mirror of
https://github.com/YuzuZensai/Termix.git
synced 2026-11-12 11:21:55 +00:00
+17


![dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>](/assets/img/avatar_default.png)






Luke Gustafson
GitHub
ZacharyZcR
Angad Singh
Angad Singh
Neo
dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Wali Lambert
Nasif Rahman
Claude Opus 5
vietanhtwdk
inontz
inontz
Max Serov
Max
ssmurfgg04-gif
ssmurfgg04-gif
ZacharyZcR
slsgzs-cloud
anshtsolanki-sketch
Cursor
tcezarl
Anton Priestley
Hakim M
copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Adel Alzubeir
Copilot Autofix powered by AI
fef8a5f28a
* Fix private AI custom endpoints (#1299) * Fix Proxmox credential guest imports (#1300) * Fix Fleet command results layout (#1301) * Fix synced client tunnel endpoints (#1302) * Fix Proxmox sync jump host persistence (#1303) * Fix command palette keyboard navigation (#1304) * Add accessible interface font choices (#1306) * Add selectable host temperature sensors (#1307) * Improve file manager navigation and compact layout (#1308) * Add configurable global hotkeys (#1305) * fix: restore split layout selection (#1310) * fix: support macOS VNC connections (#1311) * fix: use matching Undici fetch for private AI providers (#1309) Co-authored-by: Angad Singh <angad@singhangad.in> * feat: support additional TOTP authenticators (#1312) * feat: add VNC display zoom controls (#1314) * feat: add host context menu actions (#1315) * fix: force classic auth for macOS VNC (#1313) * fix: harden HTTP trust boundaries (#1316) * fix: harden application trust boundaries (#1317) * fix: verify OPKSSH binary integrity (#1318) * Fix remote desktop connection timeout (#1319) * chore(deps): bump node in /docker in the docker-major-updates group (#1321) Bumps the docker-major-updates group in /docker with 1 update: node. Updates `node` from 24-slim to 26-slim --- updated-dependencies: - dependency-name: node dependency-version: 26-slim dependency-type: direct:production dependency-group: docker-major-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-patch-updates group with 15 updates (#1322) Bumps the dev-patch-updates group with 15 updates: | Package | From | To | | --- | --- | --- | | [@codemirror/view](https://github.com/codemirror/view) | `6.43.7` | `6.43.9` | | [@commitlint/cli](https://github.com/conventional-changelog/commitlint/tree/HEAD/@commitlint/cli) | `21.2.1` | `21.2.2` | | [@commitlint/config-conventional](https://github.com/conventional-changelog/commitlint/tree/HEAD/@commitlint/config-conventional) | `21.2.0` | `21.2.2` | | [@testing-library/jest-dom](https://github.com/testing-library/jest-dom) | `7.0.0` | `7.0.1` | | [@testing-library/user-event](https://github.com/testing-library/user-event) | `14.6.1` | `14.6.5` | | [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) | `4.1.10` | `4.1.11` | | [@vitest/ui](https://github.com/vitest-dev/vitest/tree/HEAD/packages/ui) | `4.1.10` | `4.1.11` | | [concurrently](https://github.com/open-cli-tools/concurrently) | `10.0.4` | `10.0.5` | | [cytoscape](https://github.com/cytoscape/cytoscape.js) | `3.34.0` | `3.34.1` | | [eslint](https://github.com/eslint/eslint) | `10.8.0` | `10.8.1` | | [eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) | `0.5.3` | `0.5.4` | | [react-i18next](https://github.com/i18next/react-i18next) | `17.0.11` | `17.0.12` | | [sonner](https://github.com/emilkowalski/sonner) | `2.0.7` | `2.0.8` | | [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) | `8.2.0` | `8.2.2` | | [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `4.1.10` | `4.1.11` | Updates `@codemirror/view` from 6.43.7 to 6.43.9 - [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/view/commits) Updates `@commitlint/cli` from 21.2.1 to 21.2.2 - [Release notes](https://github.com/conventional-changelog/commitlint/releases) - [Changelog](https://github.com/conventional-changelog/commitlint/blob/master/@commitlint/cli/CHANGELOG.md) - [Commits](https://github.com/conventional-changelog/commitlint/commits/v21.2.2/@commitlint/cli) Updates `@commitlint/config-conventional` from 21.2.0 to 21.2.2 - [Release notes](https://github.com/conventional-changelog/commitlint/releases) - [Changelog](https://github.com/conventional-changelog/commitlint/blob/master/@commitlint/config-conventional/CHANGELOG.md) - [Commits](https://github.com/conventional-changelog/commitlint/commits/v21.2.2/@commitlint/config-conventional) Updates `@testing-library/jest-dom` from 7.0.0 to 7.0.1 - [Release notes](https://github.com/testing-library/jest-dom/releases) - [Changelog](https://github.com/testing-library/jest-dom/blob/main/CHANGELOG.md) - [Commits](https://github.com/testing-library/jest-dom/compare/v7.0.0...v7.0.1) Updates `@testing-library/user-event` from 14.6.1 to 14.6.5 - [Release notes](https://github.com/testing-library/user-event/releases) - [Changelog](https://github.com/testing-library/user-event/blob/main/CHANGELOG.md) - [Commits](https://github.com/testing-library/user-event/compare/v14.6.1...v14.6.5) Updates `@vitest/coverage-v8` from 4.1.10 to 4.1.11 - [Release notes](https://github.com/vitest-dev/vitest/releases) - [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md) - [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.11/packages/coverage-v8) Updates `@vitest/ui` from 4.1.10 to 4.1.11 - [Release notes](https://github.com/vitest-dev/vitest/releases) - [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md) - [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.11/packages/ui) Updates `concurrently` from 10.0.4 to 10.0.5 - [Release notes](https://github.com/open-cli-tools/concurrently/releases) - [Commits](https://github.com/open-cli-tools/concurrently/compare/v10.0.4...v10.0.5) Updates `cytoscape` from 3.34.0 to 3.34.1 - [Release notes](https://github.com/cytoscape/cytoscape.js/releases) - [Commits](https://github.com/cytoscape/cytoscape.js/compare/v3.34.0...v3.34.1) Updates `eslint` from 10.8.0 to 10.8.1 - [Release notes](https://github.com/eslint/eslint/releases) - [Commits](https://github.com/eslint/eslint/compare/v10.8.0...v10.8.1) Updates `eslint-plugin-react-refresh` from 0.5.3 to 0.5.4 - [Release notes](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/releases) - [Changelog](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/blob/main/CHANGELOG.md) - [Commits](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/compare/v0.5.3...v0.5.4) Updates `react-i18next` from 17.0.11 to 17.0.12 - [Changelog](https://github.com/i18next/react-i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/react-i18next/compare/v17.0.11...v17.0.12) Updates `sonner` from 2.0.7 to 2.0.8 - [Release notes](https://github.com/emilkowalski/sonner/releases) - [Commits](https://github.com/emilkowalski/sonner/compare/v2.0.7...v2.0.8) Updates `vite` from 8.2.0 to 8.2.2 - [Release notes](https://github.com/vitejs/vite/releases) - [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite/commits/v8.2.2/packages/vite) Updates `vitest` from 4.1.10 to 4.1.11 - [Release notes](https://github.com/vitest-dev/vitest/releases) - [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md) - [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.11/packages/vitest) --- updated-dependencies: - dependency-name: "@codemirror/view" dependency-version: 6.43.9 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@commitlint/cli" dependency-version: 21.2.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@commitlint/config-conventional" dependency-version: 21.2.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@testing-library/jest-dom" dependency-version: 7.0.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@testing-library/user-event" dependency-version: 14.6.5 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@vitest/coverage-v8" dependency-version: 4.1.11 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@vitest/ui" dependency-version: 4.1.11 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: concurrently dependency-version: 10.0.5 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: cytoscape dependency-version: 3.34.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: eslint dependency-version: 10.8.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: eslint-plugin-react-refresh dependency-version: 0.5.4 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: react-i18next dependency-version: 17.0.12 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: sonner dependency-version: 2.0.8 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: vite dependency-version: 8.2.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: vitest dependency-version: 4.1.11 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump the prod-patch-updates group with 5 updates (#1324) Bumps the prod-patch-updates group with 5 updates: | Package | From | To | | --- | --- | --- | | [@tanstack/react-virtual](https://github.com/TanStack/virtual/tree/HEAD/packages/react-virtual) | `3.14.9` | `3.14.10` | | [better-sqlite3](https://github.com/WiseLibs/better-sqlite3) | `13.0.2` | `13.0.3` | | [jose](https://github.com/panva/jose) | `6.2.8` | `6.2.9` | | [mysql2](https://github.com/sidorares/node-mysql2) | `3.23.2` | `3.23.4` | | [ws](https://github.com/websockets/ws) | `8.21.1` | `8.21.3` | Updates `@tanstack/react-virtual` from 3.14.9 to 3.14.10 - [Release notes](https://github.com/TanStack/virtual/releases) - [Changelog](https://github.com/TanStack/virtual/blob/main/packages/react-virtual/CHANGELOG.md) - [Commits](https://github.com/TanStack/virtual/commits/@tanstack/react-virtual@3.14.10/packages/react-virtual) Updates `better-sqlite3` from 13.0.2 to 13.0.3 - [Release notes](https://github.com/WiseLibs/better-sqlite3/releases) - [Commits](https://github.com/WiseLibs/better-sqlite3/compare/v13.0.2...v13.0.3) Updates `jose` from 6.2.8 to 6.2.9 - [Release notes](https://github.com/panva/jose/releases) - [Changelog](https://github.com/panva/jose/blob/main/CHANGELOG.md) - [Commits](https://github.com/panva/jose/compare/v6.2.8...v6.2.9) Updates `mysql2` from 3.23.2 to 3.23.4 - [Release notes](https://github.com/sidorares/node-mysql2/releases) - [Changelog](https://github.com/sidorares/node-mysql2/blob/master/Changelog.md) - [Commits](https://github.com/sidorares/node-mysql2/compare/v3.23.2...v3.23.4) Updates `ws` from 8.21.1 to 8.21.3 - [Release notes](https://github.com/websockets/ws/releases) - [Commits](https://github.com/websockets/ws/compare/8.21.1...8.21.3) --- updated-dependencies: - dependency-name: "@tanstack/react-virtual" dependency-version: 3.14.10 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: better-sqlite3 dependency-version: 13.0.3 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: jose dependency-version: 6.2.9 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: mysql2 dependency-version: 3.23.4 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: ws dependency-version: 8.21.3 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump motion in the major-updates group (#1326) Bumps the major-updates group with 1 update: [motion](https://github.com/motiondivision/motion). Updates `motion` from 12.43.0 to 13.1.1 - [Changelog](https://github.com/motiondivision/motion/blob/main/CHANGELOG.md) - [Commits](https://github.com/motiondivision/motion/compare/v12.43.0...v13.1.1) --- updated-dependencies: - dependency-name: motion dependency-version: 13.1.1 dependency-type: direct:production update-type: version-update:semver-major dependency-group: major-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * feat: add semantic motion system (#1320) * feat: add semantic motion system * feat: animate session workspace transitions * feat: refine motion accessibility and transfer feedback * feat: enforce RBAC and harden collaboration features (#1327) * feat: enforce RBAC and harden collaboration features - Mount requirePermission on hosts/snippets/credentials/automations/AI routes - Seed and backfill system role permissions on every dialect at startup - Support personal credential overrides for RDP/VNC/Telnet shared hosts - Broadcast participant presence in shared terminal sessions - Make audit log forwarding configurable from the admin panel - Add role members endpoint and snippet folder sharing * fix: enforce RBAC across split routes * fix: reject malformed Guacamole tokens safely (#1329) * fix: allow approved private notification hosts (#1330) * feat: collaboration rooms with switchable presenter (#1328) * feat: add collaboration rooms with switchable presenter Rooms are a group of members watching one stage - the live SSH/RDP/VNC session the current presenter shares. Any member can take over the stage; the host can invite, force-stop and end the meeting. Stages reuse session_shares (new room share type), so gating, recording, expiry and the global sharing toggle all apply unchanged. * feat: add stage control handoff to collaboration rooms The presenter or host can grant any member write access to the live stage and take it back; members can raise a hand to ask. SSH flips the participant's permission on the live gate; RDP/VNC re-mint the viewer's join token. Control clears on every stage switch. * feat: guest links, role invites and invite awareness for collab rooms - Anonymous guest link per room (host toggles/rotates), followed by polling the public resolve endpoint; SSH guests join over the terminal WS with roomGuestToken, guac guests get read-only join tokens - Invite by role (expands to current members, snapshot semantics) - Toast when a room you were invited to appears - Stale stages are cleared lazily when the presenter is gone - Telnet presenting, expired-tab fallback, documented single-instance and guac-kick limits - Tests for the collab routes, room hub, share access and control flip * fix: keep remote desktop collaboration read-only * fix: restore RDP clipboard paste across browsers (#1331) * fix: show the full command line in the process inspector (#1334) The CMD column rendered ps's comm field, which the kernel caps at 15 characters, so anything longer looked truncated no matter how wide the column was. The full args were already collected; show them. * fix: harden collaboration room access (#1332) * fix: harden collaboration room access * fix: confirm guest link lifecycle changes * fix: make RDP drive redirection writable on the stock deployment (#1333) * fix: make RDP drive redirection writable on the stock deployment The default drive-path was /drive on the guacd side, which the official guacd image cannot create as its non-root user, so every upload was refused with guacd's raw "FAIL (CANNOT OPEN)" ack. Default to GUACD_DRIVE_PATH (set to the shared termix-data volume in compose) with one folder per user, and explain guacd's refusal in the file browser. * style: format RDP drive settings * feat: quick connect for RDP and VNC (#1335) The Quick Connect panel gets a protocol switch. RDP/VNC quick hosts are built like SSH ones (never saved) and opened as regular remote desktop tabs; GuacamoleApp mints their token from the typed fields through the existing /guacamole/token endpoint instead of a host-row lookup. * fix: authenticate unwatched hosts during the status probe (#1337) With metrics enabled, the status probe left SSH authentication to the metrics poll - which only runs while someone is viewing the host. An unwatched host therefore never left "reachable", while a host with metrics disabled (whose probe always authenticates) showed online. The probe now authenticates whenever no metrics poll will. * feat: compact snippet list option (#1339) A "Show Commands" toggle in the snippets settings menu hides the command text under each snippet name, for people who dock the panel on the narrow right rail and only need the names. Local preference, on by default. * fix: guide users to Auto-Tmux when a persisted session expires (#1336) * fix: guide users to Auto-Tmux when a persisted session expires A timed-out terminal session silently reconnected to a fresh shell, so people running long jobs lost them with no explanation and never learned about Auto-Tmux. Explain the expiry with a one-click Enable Auto-Tmux action, let admins default it for new hosts and tune the persistence timeout from the UI, and move the setting up with copy that says what it does. The global default stays off. * style: format terminal expiry notice * feat: improve collaboration rooms (#1338) * feat: Step CA SSH certificates as a host authentication type (#1340) * feat: Step CA SSH certificates as a host authentication type Issue short-lived SSH user certificates from a smallstep CA through its OIDC provisioner, over the CA's HTTP API rather than the step binary. Everything after issuance reuses the OPKSSH plumbing: the same encrypted per-user/host token store, WebSocket dialog and ssh2 certificate injection, with the connect paths branching on a shared usesIssuedCertificate() predicate. Instance-wide CA settings live in the admin panel, with a private-host allowlist for the SSRF guard. * fix: harden Step CA callback flow * style: format Step CA changes * feat: 1Password Connect secret sources for SSH credentials (#1341) * feat: 1Password Connect secret sources for SSH credentials Hosts and credentials can hold op://vault/item/field references instead of secrets; they are resolved at connect time from the user's secret source (1Password Connect) at the single point where every subsystem receives plaintext credentials, so terminal, SFTP, Docker, metrics and tunnels all work without per-subsystem changes. Sources are per user, optionally shared, with the access token encrypted under the owner's data key; resolved values are cached briefly in memory. * style: format secret source changes * feat: share credentials with users and roles, inherit data on account deletion (#1342) * feat: share credentials with users and roles, inherit data on account deletion Credentials can be shared at "use" or "manage" level. Recipients get a copy re-encrypted under their own data key (shared_credential_secrets), kept in step with the owner's row through the same lifecycle hooks as shared host secrets. One gate, findUsableCredential(), replaces the private-namespace lookups so a shared credential works wherever a private one does. Deleting a user now hands their hosts and credentials to a successor (the deleting admin by default) instead of revoking everything they shared. * fix: harden credential ownership transfer * feat: folder shares apply to hosts added later (#1343) * feat: folder shares apply to hosts added later Sharing a folder only fanned grants out to the hosts in it at the time. The share is now also kept as a standing rule on the folder, and a host created in or moved into it (or a subfolder) inherits the same access and secret snapshots. Rules follow folder renames and can be stopped from the share dialog. * fix: stabilize folder access migrations * fix: package sharp for both macOS architectures (#1344) * fix: prompt shared RDP users for credentials (#1345) * feat: add terminal copy-on-select option (#1346) * fix: retry protected file reads with sudo (#1349) * fix: stop SSH-authenticating hosts during routine status polling (#1347) * fix: preserve omitted host protocol settings (#1350) * fix: surface remote sync reauthentication failures (#1351) * fix: harden file reads and timer cleanup (#1352) * fix: harden file reads and timer cleanup * fix: preserve literal file path escapes * fix: enforce SSH pool connection limits (#1353) * fix: enforce SSH pool connection limits * fix: discard stale pooled connections * fix: harden connection, payload, and persisted state handling (#1354) * fix: clean up Cloudflare tunnel timeouts * fix: couple tunnel socket lifecycle * fix: validate Docker console messages * fix: bound homepage proxy responses * fix: bound reconnect and response failures * fix: harden persisted and socket state * fix: support local connections to shared hosts * fix: recover expired dashboard metrics sessions (#1355) * fix: upload files to redirected RDP drives (#1356) * fix: unify connection toolbar visibility (#1357) * fix: reset host virtualizer after editing (#1358) * test: update Guacamole toolbar display mock (#1360) * fix: reflect live SSH sessions in host status (#1359) * fix: support Vault auth in file manager (#1361) * fix: allow exec on shared hosts (#1362) * fix(file-manager): align chunked upload contract (#1371) * fix(file-manager): make bulk uploads resilient (#1373) * fix(terminal): disable local echo on alternate screen (#1372) * fix(homepage): validate clock widget timezones (#1374) An invalid timezone in a clock widget's config reached toLocaleTimeString unchecked, throwing RangeError during render and taking the homepage canvas down with it. The edit dialog accepted any string, so "America/New York" - a space where IANA wants an underscore - was easy to save, and the homepage stayed broken on every later load because the value is reloaded from the database. The edit dialog now flags an unusable zone the way FolderMetadataDialog flags a duplicate folder name: inline message, aria-invalid, and a disabled Save. Whitespace is normalized to underscores on save, so the space spelling is stored as America/New_York rather than rejected. ClockWidget falls back to local time for any config already holding an invalid zone. Related to Termix-SSH/Support#1238 * fix(hosts): preserve connection origin in editor (#1376) * fix(remote-sync): expose local login notification (#1375) * fix(auth): allow passkeys in desktop login (#1378) * fix(proxmox): elevate guest discovery commands (#1379) * Fix permanent file-transfer completion toasts (#1383) * fix(file-manager): expire completed progress toasts * test(file-manager): use valid transfer status * fix(hosts): allow clearing SSH key type (#1384) * fix(terminal): suppress local echo for contextual password prompts (#1387) * fix(desktop): surface a failed embedded backend start (#1382) * fix(desktop): surface a failed embedded backend start When the embedded backend's HTTP port was already taken, the desktop app sat on the "Loading..." spinner forever with nothing in the UI to say why. The backend logged the conflict and exited 1, and startBackendServer resolved false, but that verdict never reached the renderer: the get-embedded-server-status channel was not exposed in preload and nothing called it. The renderer, by design, treats every connection failure as "the embedded backend is still booting" and retries indefinitely -- in main.tsx's verifying phase, in Auth's desktop auto-session, and in FullScreenAppWrapper. That holds while the backend is merely slow to boot, but not once the process has exited, and nothing distinguished the two. Classify why the child died from its exit code and a bounded tail of its stderr, report it through get-embedded-server-status, and have each retry loop keep waiting only while no failure is reported. A port conflict names the port, since that is what the user has to act on -- most often a Termix container on the same ports, or a backend orphaned by a hard-kill that reapOrphanedBackendProcess could not claim. A deliberate shutdown is not reported as a crash, and a backend that is only slow to start still gets retried as before. Fixes Termix-SSH/Support#1254 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(desktop): treat every unrequested backend exit as a failure The classifier exempted a clean exit and SIGTERM/SIGINT, calling those a deliberate shutdown. It has no evidence for that: its only caller already sits behind backendStopRequested, so it is reached only for exits stopBackendServer() did not ask for. A backend that exited 0 on its own, or was terminated by the OS or an external signal, therefore reported no failure at all -- leaving all three renderer loops waiting forever for a process that is gone, which is the exact hang this change set exists to remove. Every exit reaching the classifier is now a failure, port-in-use when stderr carries EADDRINUSE and crashed otherwise, with backendStopRequested left as the sole deliberate-shutdown guard. That makes the exit code and signal irrelevant to the verdict, so the classifier now takes only the stderr tail rather than carrying two parameters it no longer reads. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> * Add white label branding settings (#1386) * feat(admin): add white label branding settings Admins can configure a custom app name, logo and tagline from the Admin Settings panel. The values apply to the login screen and the browser tab title/favicon at runtime. * fix(admin): restore default icons on logo reset, validate upload MIME type Resetting the logo now restores the bundled favicon/apple-touch-icon instead of leaving the previous custom one until a reload. The admin upload also validates file.type up front instead of only failing later on save. * fix(admin): restore default favicons and reject invalid logo types Capture bundled icon hrefs before the first custom logo is applied so a reset does not leave the previous upload in the tab, and reject non-image uploads before they are read into branding state. * test(admin): cover branding routes and logo validation Add backend tests for the public GET, admin-only PATCH, unknown-field rejection, and parseBrandingLogoDataUrl so invalid images cannot land in settings without a failing test. * fix(backend): report port conflicts on the service ports (#1388) Express's app.listen(port, host, callback) registers that callback as the server's error handler as well as its listening handler: if (typeof args[args.length - 1] === 'function') { var done = args[args.length - 1] = once(args[args.length - 1]) server.once('error', done) } so a bind failure invoked the service's "started" callback with an EADDRINUSE error as its only argument and emitted nothing. None of the services read that argument, which made a failed bind indistinguishable from a successful one: the service logged that it had started, ran its initialisation, and served nothing. With one of 30003-30012 occupied the backend still reported backend_init_complete, the app loaded, and the affected feature was dead for the session with no error anywhere in the logs -- searching the backend log, the Electron main log and stdout for EADDRINUSE returned nothing, as did uncaughtException and unhandledRejection probes. This is also why only the main port behaved sensibly: database.ts does not use app.listen(), it builds the server and attaches a real error handler, so 30001 was the one port whose conflict was ever detected. listenOnServicePort() builds the server so that listening and error stay separate, and treats a conflict the way database.ts already does -- name the port, then exit -- rather than running on with one feature missing. Exiting also hands the desktop app the classified failure it already surfaces, so the user is told which port to free. Services that must own their server, such as the tunnel service with its WebSocket upgrade handler, get the same handler via attachServicePortConflictHandler(). Note that adding .on("error") to the services would not have worked: express consumes the event through once('error', done) before any later handler runs. The callback has to stop being passed to listen() at all. Fixes Termix-SSH/Support#1260 Co-authored-by: Claude Opus 5 <noreply@anthropic.com> * feat(desktop): allow RDP/VNC/Telnet to originate from this device (#1389) The desktop pinned rdp/vnc/telnet to the remote server, so a host the user's own machine could reach but the Termix server could not was impossible to open: the app answered "Remote server required" even when no remote server was wanted. The embedded backend already runs the Guacamole websocket server and guacd's address is already configurable globally and per host, so what was missing was the choice. resolveConnectionOrigin now honours an explicit per-host origin for these protocols. Left on Default they still resolve to remote: they need a guacd, which the desktop does not ship, so originating locally only works once the user has pointed Termix at one of their own. Keeping that opt-in means an upgrade never moves a working connection onto a guacd that is not there. Serial and non-Electron behaviour are unchanged. Three call paths had the same assumption baked in and would have quietly ignored the setting: - The Guacamole call sites resolved the origin without passing the host's own override, so it could never take effect. - guacamole-api sent every token, connect-host and status call to the remote server whenever running under Electron, and remapped the host id onto the remote server's id -- which would address the wrong row, or fail outright with no server configured. - GuacamoleDisplay minted its token before resolving the origin, so the token could come from a different backend than the socket dialled. The origin is a required parameter on those API functions rather than a defaulted one. A default silently sent a missed call site to the remote server: the guacd status check in fetchToken was one, and it failed with a bare "Network Error" on a desktop with no server configured. Making it required means the compiler names every caller instead. That also covers CollabRoomTab, which now resolves from the host it already holds, so a locally-originated host stays local when presented into a room. Finally, the Connection Origin control was gated on SSH alone, so a host enabling only these protocols could never reach the setting. That gate is now a named predicate covering every protocol the control applies to. Verified end to end on Linux against a local guacd: with a host set to "This device", guacd accepted the connection and reached the target, which answered for itself. With guacd stopped, the guacd status check that has run before every connection since v2.3.0 -- now asking the backend the session will actually use -- reports it clearly before a socket is opened. Refs Termix-SSH/Support#1240 Co-authored-by: Claude Opus 5 <noreply@anthropic.com> * feat(local-terminal): add copy/paste support (#1391) * feat(local-terminal): add copy/paste support Local terminal had no clipboard wiring, so selected text couldn't be copied. Extracted the SSH terminal's copy/paste shortcut and right-click handling into a shared terminal-clipboard module and wired it into both terminals, removing duplicated logic in the process. * fix(local-terminal): stop language changes from restarting the shell session The session effect that starts the local PTY depended on `t`, whose identity changes on every language switch (react-i18next). That tore down the running shell and spawned a new one just from changing the UI language. Read translations through a ref instead so localization stays decoupled from the PTY lifecycle. Also adds regression coverage for the extracted terminal-clipboard.ts helpers: copy with/without selection, explicit vs native paste, right-click preference, and Ctrl+right-click passthrough. * fix(file-manager): keep name column visible on narrow viewports in list view (#1402) Rebased onto dev-2.8.0 (the density refactor kept the same 3 list-view grid patterns). Use minmax(140px, 1fr) for the name track so it cannot collapse to 0px on narrow viewports; the table scrolls horizontally instead of hiding names and icons. Co-authored-by: inontz <inontz@users.noreply.github.com> * feat(desktop): local filesystem and transfer bridge for the file manager (#1392) * feat(desktop): local filesystem and transfer bridge for the file manager Adds the Electron main-process side of the upcoming Local | Remote dual-pane file manager, with no UI yet: - electron/local-files.cjs: IPC handlers to browse the local disk (home, list, mkdir, createFile, rename, trash, ensureDir, walk, reveal, open) and to stream files between the local disk and the file-manager backend (uploadLocalFile / downloadToLocal with progress events and cancellation). Streams go through Electron's `net` so the session cookie / remembered JWT is attached the same way as the renderer's own requests. - electron/preload.js: exposes them as `window.electronAPI.localFs` and `window.electronAPI.localTransfer`; the existing `invoke` allowlist is untouched. - src/types/electron.d.ts: typings for the new surface. - electron/main.cjs: registers the handlers. Follow-up PRs add the renderer side (local pane, drag-and-drop transfers, context menu). * fix(desktop): harden the local transfer bridge (origin allowlist, collision policy) Addresses the review on the transfer boundary: - The renderer no longer supplies a URL or headers. It sends `{ origin: "local" | "remote", route, deviceId }` and the main process resolves the target itself: fixed route allowlist (`uploadFileStream`, `downloadFileStream`), local = the embedded backend base, remote = the remote-sync config's URL (http/https only) with the stored JWT. Anything else is rejected before a request is made. `deviceId` is validated. - Downloads never rename or replace silently. The destination is checked first and `EEXIST` is returned unless the caller passes `overwrite: true`. Each transfer writes to its own `<dest>.<transferId>.termix-part` opened with `wx`, and publishes with `fs.link` / `COPYFILE_EXCL` (rename only when overwriting), so concurrent transfers to the same path cannot share or clobber a partial (`EBUSY` for the second). Partials are removed on failure or cancel. - New `local-fs:exists` handler so the renderer can ask before starting. - `createLocalFileHandlers` / `createTargetResolver` take their dependencies (net, shell, remote-sync getters) as parameters so the boundary is unit-testable without Electron. - src/backend/tests/electron/local-files.test.ts: target resolution and off-origin refusal, EEXIST / EBUSY / overwrite paths, unique partials and cleanup, upload multipart integrity (parsed with Busboy). * fix(desktop): Windows-safe replace for overwrite downloads `publishDownload()` used `rename(partial, dest)` for the explicit overwrite path. POSIX replaces the destination, but on Windows rename() onto an existing name commonly fails (EEXIST / EPERM, always while the file is open), so "Replace" did not actually work there. The overwrite path no longer renames onto an occupied name: 1. the current file is moved aside to a transfer-unique sibling (`<dest>.<transferId>.termix-replaced`) - renaming to a fresh name is safe on every platform; 2. the partial is published exclusively under the now-free name (the same `link` / `COPYFILE_EXCL` primitive the non-overwrite path uses); 3. the aside copy is deleted (retried once; if another process still holds it open on Windows it is left in place and logged rather than failing the transfer). Failure handling preserves the original: if step 1 fails (file in use) nothing has changed and the caller gets `EBUSY`; if step 2 fails the aside copy is moved back under its name and the error propagates. Replacing a folder with a file is refused with `EISDIR`; a destination that vanished mid-transfer falls back to the exclusive publish. The publish primitives take their filesystem operations as an injectable `publishFs` (default: real fs), and the tests drive them with a Windows-like fs whose rename() refuses to overwrite - so the strategy is verified without relying on POSIX rename-over-existing semantics: successful swap with no rename ever targeting an occupied name, original restored byte-for-byte when publishing fails, EBUSY with nothing touched when the file cannot be moved aside, EISDIR for folders, vanished destination, and the end-to-end overwrite through the download handler. --------- Co-authored-by: Max <maxim@cogitate.ai> * chore: update package lock * feat(file-manager): Termius-style Local | Remote dual pane with drag-and-drop transfers (desktop) Renderer side of the dual-pane file manager, built on the local filesystem bridge added in the previous PR. Desktop app only; the web build is unchanged (the toggle is hidden when `window.electronAPI.localFs` is absent). - New Local pane (LocalFilePane) next to the remote grid, toggled from the toolbar (Laptop icon); path, visibility and width are remembered in localStorage (`termix:file-manager:local-pane:*`). Grid and list views, hidden files toggle, breadcrumb navigation, New Folder. - Drag files/folders from the Local pane onto the remote grid to upload, and from the remote grid onto the Local pane to download. Both directions stream through the main process (`useLocalTransfers`) with a single progress toast per batch (speed, ETA, cancel). Finder drops onto the remote grid keep working as before. - Collision policy for downloads: destinations are checked first; if any exist the user is asked Replace / Skip for the batch. Skip, dismiss and timeout all mean skip - nothing is ever replaced without an explicit click, and the main process enforces the same rule (`EEXIST` unless `overwrite` is set). - Drag MIME contract: `application/x-termix-local-files` for local drags, `application/x-termix-remote-files` marker on the remote grid's internal drags, so each pane can tell the two apart from Finder drops. - Transfer targets are described as `{ origin, route, deviceId }` (`getSessionOrigin` in main-axios) - the renderer never hands the main process a URL. - i18n: new `fileManager.local*` keys in en.json only (other locales via Crowdin). - Tests: LocalFilePane rendering/navigation, local-transfer-utils (relative-path planning, size formatting). - Modified column uses the same `Mon DD HH:MM` / `Mon DD YYYY` (ls -l style) format as the remote grid, so both panes read alike. * docs: point security note to the docs root (old /security page is gone) (#1400) * chore: sync Crowdin translations * chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325) Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg). Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0 - [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases) - [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md) - [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0) Updates `js-yaml` from 5.2.3 to 5.3.0 - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0) Updates `pg` from 8.22.0 to 8.23.0 - [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md) - [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg) --- updated-dependencies: - dependency-name: "@anthropic-ai/sdk" dependency-version: 0.120.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: js-yaml dependency-version: 5.3.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: pg dependency-version: 8.23.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323) Bumps the dev-minor-updates group with 10 updates in the / directory: | Package | From | To | | --- | --- | --- | | [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` | | [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` | | [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` | | [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` | | [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` | | [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` | | [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` | | [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` | | [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` | | [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` | Updates `@codemirror/commands` from 6.10.4 to 6.11.0 - [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/commands/commits) Updates `@types/node` from 26.1.2 to 26.2.0 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0 - [Release notes](https://github.com/vitejs/vite-plugin-react/releases) - [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react) Updates `electron` from 43.2.0 to 43.4.1 - [Release notes](https://github.com/electron/electron/releases) - [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1) Updates `globals` from 17.9.0 to 17.11.0 - [Release notes](https://github.com/sindresorhus/globals/releases) - [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0) Updates `i18next` from 26.3.6 to 26.4.0 - [Release notes](https://github.com/i18next/i18next/releases) - [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0) Updates `lucide-react` from 1.28.0 to 1.33.0 - [Release notes](https://github.com/lucide-icons/lucide/releases) - [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react) Updates `react-hook-form` from 7.84.0 to 7.85.0 - [Release notes](https://github.com/react-hook-form/react-hook-form/releases) - [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md) - [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0) Updates `react-pdf` from 10.4.1 to 10.5.0 - [Release notes](https://github.com/wojtekmaj/react-pdf/releases) - [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf) Updates `typescript-eslint` from 8.66.0 to 8.67.0 - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint) --- updated-dependencies: - dependency-name: "@codemirror/commands" dependency-version: 6.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@types/node" dependency-version: 26.2.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@vitejs/plugin-react" dependency-version: 6.1.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: electron dependency-version: 43.4.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: globals dependency-version: 17.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: i18next dependency-version: 26.4.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: lucide-react dependency-version: 1.33.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-hook-form dependency-version: 7.85.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-pdf dependency-version: 10.5.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: typescript-eslint dependency-version: 8.67.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore: sync Crowdin translations * Update redirect-issues workflow configuration Updated the workflow to change the runner and modify the issue response message. * chore: sync Crowdin translations * Add Hetzner logo and referral link to README Added Hetzner logo with a referral link to README. * Fix Hetzner logo URL in README.md * docs: point security note to the feature security page The old /security page is gone and the docs root redirects to /install/, which loses the encryption context the sentence promises. Point the per-user secret and database encryption note at the canonical docs.termix.site/features/authentication/security/ page instead. Applied across all README locales. --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: ssmurfgg04-gif <232103099+ssmurfgg04-gif@users.noreply.github.com> Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com> * fix: use i18n for host status tooltip labels (#1403) * chore: sync Crowdin translations * chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325) Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg). Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0 - [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases) - [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md) - [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0) Updates `js-yaml` from 5.2.3 to 5.3.0 - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0) Updates `pg` from 8.22.0 to 8.23.0 - [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md) - [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg) --- updated-dependencies: - dependency-name: "@anthropic-ai/sdk" dependency-version: 0.120.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: js-yaml dependency-version: 5.3.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: pg dependency-version: 8.23.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323) Bumps the dev-minor-updates group with 10 updates in the / directory: | Package | From | To | | --- | --- | --- | | [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` | | [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` | | [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` | | [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` | | [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` | | [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` | | [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` | | [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` | | [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` | | [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` | Updates `@codemirror/commands` from 6.10.4 to 6.11.0 - [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/commands/commits) Updates `@types/node` from 26.1.2 to 26.2.0 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0 - [Release notes](https://github.com/vitejs/vite-plugin-react/releases) - [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react) Updates `electron` from 43.2.0 to 43.4.1 - [Release notes](https://github.com/electron/electron/releases) - [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1) Updates `globals` from 17.9.0 to 17.11.0 - [Release notes](https://github.com/sindresorhus/globals/releases) - [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0) Updates `i18next` from 26.3.6 to 26.4.0 - [Release notes](https://github.com/i18next/i18next/releases) - [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0) Updates `lucide-react` from 1.28.0 to 1.33.0 - [Release notes](https://github.com/lucide-icons/lucide/releases) - [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react) Updates `react-hook-form` from 7.84.0 to 7.85.0 - [Release notes](https://github.com/react-hook-form/react-hook-form/releases) - [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md) - [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0) Updates `react-pdf` from 10.4.1 to 10.5.0 - [Release notes](https://github.com/wojtekmaj/react-pdf/releases) - [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf) Updates `typescript-eslint` from 8.66.0 to 8.67.0 - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint) --- updated-dependencies: - dependency-name: "@codemirror/commands" dependency-version: 6.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@types/node" dependency-version: 26.2.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@vitejs/plugin-react" dependency-version: 6.1.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: electron dependency-version: 43.4.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: globals dependency-version: 17.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: i18next dependency-version: 26.4.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: lucide-react dependency-version: 1.33.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-hook-form dependency-version: 7.85.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-pdf dependency-version: 10.5.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: typescript-eslint dependency-version: 8.67.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore: sync Crowdin translations * Update redirect-issues workflow configuration Updated the workflow to change the runner and modify the issue response message. * chore: sync Crowdin translations * fix: use i18n for host status tooltip labels (#1265) * fix: add missing hosts.status.* locale keys (fixes #1265) * fix: add hosts.status.* translation keys for i18n tooltip The buildStatusTooltip function calls t("hosts.status.available"), t("hosts.status.reachable"), t("hosts.status.offline"), and t("hosts.status.monitoringDisabled"), but the locale file only had "status": "Status" as a flat string. Replaced with a status object containing all four keys plus a "label" key preserving the original "Status" string. * fix: restore final newline in en.json Requested by ZacharyZcR in review feedback. * test: assert translated labels in buildStatusTooltip Per review feedback from ZacharyZcR: add focused tests that exercise buildStatusTooltip with a translator and assert the rendered labels rather than key paths. Covers all three status values, monitoring disabled, protocol list, and the no-key-path regression guard. --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com> * fix(workspaces): fall back when randomUUID is unavailable (#1397) * fix(terminal): preserve macOS Alt digit characters (#1398) * fix(ssh): verify resolved server host identity (#1419) * fix: add principals to Termix ID certificates (#1421) * chore: sync Crowdin translations * chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325) Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg). Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0 - [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases) - [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md) - [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0) Updates `js-yaml` from 5.2.3 to 5.3.0 - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0) Updates `pg` from 8.22.0 to 8.23.0 - [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md) - [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg) --- updated-dependencies: - dependency-name: "@anthropic-ai/sdk" dependency-version: 0.120.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: js-yaml dependency-version: 5.3.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: pg dependency-version: 8.23.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323) Bumps the dev-minor-updates group with 10 updates in the / directory: | Package | From | To | | --- | --- | --- | | [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` | | [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` | | [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` | | [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` | | [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` | | [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` | | [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` | | [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` | | [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` | | [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` | Updates `@codemirror/commands` from 6.10.4 to 6.11.0 - [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/commands/commits) Updates `@types/node` from 26.1.2 to 26.2.0 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0 - [Release notes](https://github.com/vitejs/vite-plugin-react/releases) - [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react) Updates `electron` from 43.2.0 to 43.4.1 - [Release notes](https://github.com/electron/electron/releases) - [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1) Updates `globals` from 17.9.0 to 17.11.0 - [Release notes](https://github.com/sindresorhus/globals/releases) - [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0) Updates `i18next` from 26.3.6 to 26.4.0 - [Release notes](https://github.com/i18next/i18next/releases) - [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0) Updates `lucide-react` from 1.28.0 to 1.33.0 - [Release notes](https://github.com/lucide-icons/lucide/releases) - [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react) Updates `react-hook-form` from 7.84.0 to 7.85.0 - [Release notes](https://github.com/react-hook-form/react-hook-form/releases) - [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md) - [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0) Updates `react-pdf` from 10.4.1 to 10.5.0 - [Release notes](https://github.com/wojtekmaj/react-pdf/releases) - [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf) Updates `typescript-eslint` from 8.66.0 to 8.67.0 - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint) --- updated-dependencies: - dependency-name: "@codemirror/commands" dependency-version: 6.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@types/node" dependency-version: 26.2.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@vitejs/plugin-react" dependency-version: 6.1.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: electron dependency-version: 43.4.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: globals dependency-version: 17.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: i18next dependency-version: 26.4.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: lucide-react dependency-version: 1.33.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-hook-form dependency-version: 7.85.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-pdf dependency-version: 10.5.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: typescript-eslint dependency-version: 8.67.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore: sync Crowdin translations * Update redirect-issues workflow configuration Updated the workflow to change the runner and modify the issue response message. * chore: sync Crowdin translations * Add Hetzner logo and referral link to README Added Hetzner logo with a referral link to README. * Fix Hetzner logo URL in README.md * chore: pull sponsor logos from the docs site * fix: add principals to Termix ID certificates --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com> * fix(deps): resolve transitive security advisories (#1412) * chore: sync Crowdin translations * chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325) Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg). Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0 - [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases) - [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md) - [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0) Updates `js-yaml` from 5.2.3 to 5.3.0 - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0) Updates `pg` from 8.22.0 to 8.23.0 - [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md) - [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg) --- updated-dependencies: - dependency-name: "@anthropic-ai/sdk" dependency-version: 0.120.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: js-yaml dependency-version: 5.3.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: pg dependency-version: 8.23.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323) Bumps the dev-minor-updates group with 10 updates in the / directory: | Package | From | To | | --- | --- | --- | | [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` | | [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` | | [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` | | [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` | | [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` | | [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` | | [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` | | [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` | | [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` | | [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` | Updates `@codemirror/commands` from 6.10.4 to 6.11.0 - [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/commands/commits) Updates `@types/node` from 26.1.2 to 26.2.0 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0 - [Release notes](https://github.com/vitejs/vite-plugin-react/releases) - [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react) Updates `electron` from 43.2.0 to 43.4.1 - [Release notes](https://github.com/electron/electron/releases) - [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1) Updates `globals` from 17.9.0 to 17.11.0 - [Release notes](https://github.com/sindresorhus/globals/releases) - [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0) Updates `i18next` from 26.3.6 to 26.4.0 - [Release notes](https://github.com/i18next/i18next/releases) - [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0) Updates `lucide-react` from 1.28.0 to 1.33.0 - [Release notes](https://github.com/lucide-icons/lucide/releases) - [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react) Updates `react-hook-form` from 7.84.0 to 7.85.0 - [Release notes](https://github.com/react-hook-form/react-hook-form/releases) - [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md) - [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0) Updates `react-pdf` from 10.4.1 to 10.5.0 - [Release notes](https://github.com/wojtekmaj/react-pdf/releases) - [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf) Updates `typescript-eslint` from 8.66.0 to 8.67.0 - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint) --- updated-dependencies: - dependency-name: "@codemirror/commands" dependency-version: 6.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@types/node" dependency-version: 26.2.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@vitejs/plugin-react" dependency-version: 6.1.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: electron dependency-version: 43.4.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: globals dependency-version: 17.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: i18next dependency-version: 26.4.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: lucide-react dependency-version: 1.33.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-hook-form dependency-version: 7.85.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-pdf dependency-version: 10.5.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: typescript-eslint dependency-version: 8.67.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore: sync Crowdin translations * Update redirect-issues workflow configuration Updated the workflow to change the runner and modify the issue response message. * chore: sync Crowdin translations * Add Hetzner logo and referral link to README Added Hetzner logo with a referral link to README. * Fix Hetzner logo URL in README.md * chore: pull sponsor logos from the docs site * fix(deps): resolve transitive security advisories --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> * fix(sync): map nested host parent references (#1418) * fix(metrics): surface SSH host key changes (#1404) * fix(guacamole): coalesce VNC wheel floods and label meta keys by device (#1385) High-latency proxies like Cloudflare queue guacamole-common-js scroll clicks so the desktop keeps crawling after the user stops. Cap in-flight wheel buttons, and show Super/Cmd in the VNC toolbar on non-Windows clients. Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> * fix(file-manager): keep downloaded files inside the selected local folder Remote file names were turned into local destinations by splitting the relative remote path on "/" and concatenating each name with the platform separator. A POSIX file name may contain "\", ":" or end in a dot, so on Windows a remote "..\outside.txt" downloaded into C:\Downloads\selected was normalised to C:\Downloads\outside.txt - outside the folder the user picked, even with overwrite disabled. The main process only normalised destPath and never checked it against the selected root. Two independent layers now enforce containment: Renderer (local-transfer-utils.ts) - `assertSafeLocalComponent(name, separator)` validates each remote path component for the destination platform: never empty, "." or "..", never "/" or NUL; on Windows (separator "\") additionally no "\ : * ? " < > |", no control characters, no trailing dot/space, no reserved device names (CON, NUL, COM1...). Backslashes stay legal on macOS/Linux, where they are ordinary file-name characters and the result remains inside the folder. - `buildLocalDestination(localDir, relativePath, separator)` joins the validated components and asserts the result is strictly under localDir (case-insensitive on Windows). - useLocalTransfers builds every file and directory destination through it. Items that fail are skipped before any filesystem call and reported ("Skipped N item(s) whose names cannot be used on this computer"). Main process (electron/local-files.cjs) - `assertWithinRoot(rootPath, candidate, pathImpl)` resolves + normalises both paths and refuses anything that is the root itself, escapes it (".." after normalisation), is absolute relative to it (another drive, UNC) or contains empty/".." segments. `pathImpl` is injectable so the Windows rules run in tests on any OS. - downloadToLocal requires `rootPath` (the selected folder) and checks the destination before the request is made or any file is created; the ensure-dir handler applies the same check when a root is passed (used for the directory skeleton of downloaded trees). - LocalDownloadRequest / downloadSessionFileToLocal / ensureLocalDirectory carry the root. Tests - Renderer: ordinary nested folders on Windows; backslash traversal in a POSIX name; absolute, drive-qualified and UNC names; reserved names, trailing dots/spaces, control chars; POSIX traversal rejected while a POSIX-legal backslash name is kept inside the folder. - Main process (path.win32): nested destinations accepted incl. case differences; "selected\..\outside.txt" refused; other drive / UNC / sibling folder refused; missing root refused; end-to-end handler test that a POSIX "../outside.txt" download and an escaping ensure-dir are refused before any network traffic or disk write. * feat(file-manager): right-click context menu for the local pane Mirrors the remote grid's menu for the user's own disk. On an entry (or the current multi-selection): Open / Open folder, Upload to server, Reveal in Finder/Explorer, Rename (inline, F2), Copy Path, Move to Trash (confirmation toast, Del). On the background: New Folder, New File, Reveal, Show/Hide hidden files, Refresh (F5). Enter opens, Cmd/Ctrl+A selects all, Escape clears the selection. Deletion goes through shell.trashItem so it lands in the OS Trash and is recoverable; rename and create refuse names containing path separators and never overwrite an existing entry. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W * feat(file-manager): resizable list-view columns in both panes Drag the boundary at the left edge of a column header (Modified, Owner, Size, Permissions on the remote grid; Modified, Size, Kind in the local pane) to change its width; the Name column takes whatever is left. Double-click a handle to reset that column. Widths are remembered per pane in localStorage. Finishing a drag over a sortable header no longer toggles the sort. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W * feat(file-manager): pinned ".." parent entry in both panes Both the remote grid (list, grid and empty-folder states) and the local pane show a Termius-style ".." row pinned above the entries whenever the current folder has a parent. Double-clicking it goes up one level. It is also a drop target: local files dropped on it upload into the parent folder, remote rows dragged onto it move there, and remote items dropped on the local pane's ".." download into the parent folder. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W * feat(file-manager): show/hide list-view columns from the header Right-click a list-view header (remote grid or local pane) to open a Columns menu and tick/untick Modified, Owner, Size, Permissions (remote) or Modified, Size, Kind (local). Hidden columns leave the grid template entirely so the Name column gets the space back; at least one optional column always stays on. The choice is remembered per pane alongside the column widths. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W * feat(file-manager): sidebar toggle works on desktop too The toolbar's sidebar button now shows/hides the directories panel on desktop (persisted), while below md it still opens the mobile overlay. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W * feat(file-manager): resizable directories sidebar The Trash/Directories sidebar can now be resized by dragging its right edge (160px minimum, up to 40% of the row); double-click the handle to restore the default 224px. The width is remembered. The same handle and persisted-width hook now also drive the local pane divider, replacing the inline implementation. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W * fix(metrics): support macOS/WIN hosts in stats collection (#1430) * fix(metrics): support macOS hosts in stats collection Host metrics collectors only ever ran Linux commands (/proc/*, ip, GNU df flags), so any macOS host always reported 0%/null for cpu, memory, uptime, network and disk. Detect the host platform once per poll and use vm_stat, sysctl, top, ifconfig and netstat on Darwin hosts instead. * fix(metrics): support Windows hosts in stats collection RDP/VNC hosts running Windows hit the same problem as macOS did: no /proc, no BSD tools, not even uname. Route CPU, memory, uptime, network and disk through PowerShell (WMI/CIM) when the host is detected as Windows, using -EncodedCommand so there's no cmd.exe quoting to fight with. * fix(metrics): use real macOS df/mount for disk collection BSD df's -T flag filters by filesystem type instead of printing one like GNU df does, so the previous macOS disk path was still running a GNU-only command and coming back empty. Now uses df -Pk plus mount output to build the filesystem type/percent list, filtering out the noisy APFS system volumes and devfs/autofs mounts. Verified on an M4 MacBook running the latest macOS - disk usage now reports correctly. * feat(file-manager): Termius-style Local | Remote dual pane with drag-and-drop transfers (desktop) (#1413) Integrate the reviewed change and its maintainer fixes into dev-2.8.0. Validated with focused regression tests, type-check, lint, formatting, build, and the PR Check database jobs. * fix(terminal): persist Ctrl+/- font zoom so it survives option refreshes (#1399) Integrate the reviewed change and its maintainer fixes into dev-2.8.0. Validated with focused regression tests, type-check, lint, formatting, build, and the PR Check database jobs. * Fix macOS terminal packaging and keyboard shortcuts. (#1417) Integrate the reviewed change and its maintainer fixes into dev-2.8.0. Validated with focused regression tests, type-check, lint, formatting, build, and the PR Check database jobs. * fix(auth): skip TOTP only after verified WebAuthn user verification (#1420) Integrate the reviewed change and its maintainer fixes into dev-2.8.0. Validated with focused regression tests, type-check, lint, formatting, build, and the PR Check database jobs. * feat(hosts): add per-host Web Endpoints (direct or SSH-tunnelled web UIs) (#1416) * test: provide an in-memory localStorage for the vitest environment jsdom in this project ships without a localStorage global, so every suite that touched storage threw "Cannot read properties of undefined" during setup and failed wholesale -- 119 tests across 15 files, none of them actual product defects. Node only supplies localStorage with --localstorage-file, which persists to disk and is shared across test files. A per-process in-memory Storage is what tests want, so define one (plus sessionStorage) when the global is absent, alongside the existing matchMedia shim. Full suite goes from 15 failed files / 119 failed tests to 400 files and 2888 tests passing. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Fdjjsdaz6aFMyJr4h3Y6qj * feat(web-endpoints): add endpoint types and URL resolution First step of per-host Web Endpoints: a host declares web UIs it serves and opens them either directly at the host's address or through an SSH forward Termix establishes on demand. This commit is pure logic with no I/O, so it needs no mocks to test. resolveWebEndpointUrl expects an already-normalized path -- normalization is the storage boundary's job (a later commit), and duplicating it here would invite the two copies to drift. separatedTunnelHost is the one part that is a security control rather than a convenience. Cookies are keyed by host and ignore the port, and SameSite computes "site" as scheme + registrable domain -- also ignoring the port. A forward reached at the host string serving Termix is therefore same-site with Termix, which leaks the session both ways: the framed service receives the jwt cookie, and a Set-Cookie it returns lands in the jar Termix's own API calls read from. So a tunnel URL resolves to a different loopback spelling than the page's, and refuses outright when no alias exists. Only loopback literals qualify -- a same-registrable-domain alias could still answer Set-Cookie with a Domain attribute that reaches Termix. The cookie-separation tests were verified to fail against a resolver that returns the page host (4 failures), so they cannot pass vacuously. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(web-endpoints): validate and normalize endpoint config normalizeWebEndpoints is the enforcement point for values that reach an href and an iframe src, so the editor's constraints are UX rather than security. It drops any row it refuses instead of rejecting the whole host -- one bad endpoint must not make a host unsaveable or unlistable. Paths are checked for C0 controls and DEL by codepoint rather than by regex character class: "\t//evil.example" defeats a startsWith("//") guard, because the browser strips the control character and then follows the authority. bindHost lands both in a TCP listener and in a URL authority, so it is restricted to a bare host literal -- nothing carrying a scheme, port, path or credentials survives. bindHost and localPort are ignored on a direct endpoint, which never creates a forward. parseWebUiConfig never throws. A malformed stored value yields an empty endpoint list, so a half-written config cannot take out the whole host listing -- which is what dockerConfig's bare JSON.parse does today. The editor validator is a second implementation in a layer that cannot import backend route modules. Its accompanying test runs BOTH implementations over the same path and port samples, because drift here is invisible in the worst way: the editor accepts a row, the normalizer silently drops it, and the endpoint disappears on reload with no error. That agreement test was verified to fail (4 cases) when the editor's control-character check is removed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore(db): migrate the shared_credential_secrets foreign key rename Running `npm run schema:migrations` on an UNCHANGED schema emits these, so they are pre-existing drift between schema.ts and drizzle/, not something this branch introduced. Landing them alone, before the web-endpoint columns, so the feature's own migration is reviewable without an unrelated table rebuild sitting in the middle of it. Both forms are a foreign-key constraint rename only. Postgres drops and re-adds the constraint under a shorter name. SQLite has no ALTER for that, so drizzle emits the standard table rebuild -- verified data-preserving: CREATE lists 14 columns, INSERT...SELECT copies the same 14 in the same order, and both indexes are recreated. The SQLite file is in practice dead code: runRemoteMigrations throws for sqlite, which builds its schema from db/index.ts instead. It is kept rather than hand-trimmed because drizzle derives the meta snapshot from schema.ts regardless, so trimming the .sql while the snapshot advances would make the drift permanently invisible -- no future `generate` would re-emit it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(db): add enable_web_ui and web_ui_config columns Two columns on ssh_data mirroring the Docker pair. No show_web_ui_in_sidebar: every existing showXInSidebar column is vestigial -- they appear only in defaults, the export payload and tests, and gate no rendering -- so a fourth dead column plus a migration buys nothing. web_ui_config stores an object rather than a bare array so host-level web settings can be added later without a second migration. The column has to be declared in FOUR places, not one. SQLite never runs the drizzle migrations at all (runRemoteMigrations throws for sqlite), so the live default-dialect schema comes from hand-written DDL: 1. db/schema.ts, then the two generated dialect schemas and the migrations 2. db/index.ts CREATE TABLE -- fresh databases 3. db/index.ts addColumnIfNotExists -- existing databases 4. database.ts CREATE TABLE and its positional INSERT -- encrypted export Missing 2 or 3 breaks every host write on the default dialect while the migration file sits there looking correct. Two guards, both watched failing first. bootstrap-matches-schema-columns boots a real database and compares PRAGMA table_info against the drizzle definition for every table -- it reported ssh_data.enable_web_ui and ssh_data.web_ui_config missing before item 2/3 landed. A grep-based guard could not: db/index.ts names columns as snake_case strings, never the camelCase the schema uses. export-ddl-matches-schema-columns covers database.ts, which no booted database reaches. It caught a real defect while being written: the two new columns went into the INSERT list but the VALUES list still held 53 placeholders for 55 columns. Being positional, that shifts every later value by one. The placeholder-count assertion is now permanent. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(hosts): thread web endpoint config through host read and write paths A host field has to be enumerated by hand in nine places here, and "added a column, missed one update path" is this codebase's most repeated bug -- during the first attempt at this feature a field was missed at one of these points six separate times, each surfacing as a different mystery: endpoints that saved but never appeared, config that vanished on reload. Backend: host-normalizers (input type, CONNECT_LEVEL_FIELDS, boolean normalization, parse block), host.ts (create, update, both read paths, quick-connect defaults), host-bulk-routes (bulk update, import, reset). Renderer: host-export-payload, HostManagerData's sshHostToHost, tabUtils' hostToSSHHost, HostEditorData's form seed and payload builder. The three renderer mappers copy field by field, so an unlisted field is silently dropped -- which is how endpoints saved correctly and never appeared. webUiConfig is parsed with parseWebUiConfig rather than a bare JSON.parse. dockerConfig on the adjacent line uses a bare one, so a single malformed value takes out the whole host listing; that is a bug to avoid copying, not a convention to follow. All three write paths now clear webUiConfig when the feature is disabled. They disagreed before, and the export payload ships the config unconditionally -- so a host disabled without clearing still exported its endpoint list (internal hostnames, ports, paths) while the UI read as off, and re-enabling resurrected stale endpoints. webUiConfig is shared with connect-level recipients, unlike dockerConfig. A connect-level recipient is already authorized to open these tunnels, so withholding the config only breaks discovery while the flag advertises the feature. Docker's precedent does not transfer: its tab works without its config, whereas a web endpoint IS its config. The enumeration guard asserts every one of the nine files mentions the web endpoint field beside its Docker counterpart, and checks the Docker anchor is present too so it cannot pass vacuously if a file is restructured. The clear-on-disable assertion was rewritten after the first version passed with the guard deleted -- a loose regex matched unrelated sites. Both halves are now anchored on exact text and were watched failing. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(tunnel): report the real bound port, support idle close, reserve web: Three changes the web endpoint open route depends on, plus the name reservation that makes the scheme safe. Real bound port. Under sourcePort 0 the kernel assigns the port, but the runtime recorded the requested value -- so it advertised 0 and any caller reusing it failed. It now records tcpServer.address().port. Idle close, behind the new tunnelConfig.idleTimeoutMs. Web endpoint tunnels are opened on demand and must not outlive their use. The timer lives inside establishDirectTunnel because the socket set is only visible from that closure, polls at min(30s, timeout) so "empty for N" means roughly that rather than "empty at the instant of one N-spaced tick", and unrefs so it cannot hold the process open. It calls cleanupTunnelResources rather than close(): close() stops the listener but leaves the entry in activeTunnelRuntimes, so the open route would keep handing out a port nothing is listening on. Reserved names skip retry. handleDisconnect returns early for a "web:" name after a forced cleanup. maxRetries: 0 would NOT achieve this -- the retry path reads `maxRetries || 3`, so 0 falls through to 3. The cleanup is forced because cleanupTunnelResources no-ops while tunnelConnecting holds the name, and a web tunnel has no retry pass to self-heal a leaked runtime. That early return carries an identity guard, which is the subtle one. sourceClient.end() only STARTS an async teardown, so the SSH "close" event lands after a reopen may already have registered a NEW runtime under the same name. Acting by name alone would tear down the successor rather than the stale tunnel -- surfacing as a 200 with a good port followed by a silent connection reset and no error anywhere. handleDisconnect now takes the closing Client and returns early when the registered runtime belongs to someone else. The idle timer carries the same guard for the same reason. /ssh/tunnel/connect now rejects a user-supplied "web:" name with 400. validateTunnelConfig is no defence here: it returns true unconditionally for any name that is not the legacy 6-part format, so an authenticated user could otherwise create a real retry-configured tunnel that collides with a live web endpoint forward and silently loses its own reconnect behaviour. The manager tests run against a real TCP listener and real timers -- mixing fake timers with real socket I/O is a known route to a hanging test. Both were watched failing: reverting the bound port fails the port test, and swapping cleanupTunnelResources for close() fails the idle test, which asserts the ENTRY is gone rather than merely that the listener stopped. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(tunnel): add the web endpoint open route POST /ssh/tunnel/web-endpoint/open { hostId, endpointId } -> { port }. The host is resolved through the user-scoped resolveHostById, so an authenticated user cannot obtain a forward to a host id they do not own. The endpoint is re-normalized out of storage rather than trusted: the stored value predates any later tightening of the rules, and this is what a forward gets built from. An enabled flag is required as well as a present endpoint -- a bulk update that sends only { webUiConfig } can leave a configured endpoint on a host whose UI reads as off everywhere. Not gated to the desktop. The forward binds wherever this backend runs, as the server tunnels feature does, and the endpoint's own bindHost decides whether that is reachable from a browser. endpointHost: "127.0.0.1" is load-bearing, not cosmetic. connectSSHTunnel picks its strategy via shouldEstablishDirectTunnel -> isSingleHostTunnel, which keys on endpointHost -- setting only targetHost selects a different path and the forward never binds locally. connectSSHTunnel never rejects, and its promise resolves right after conn.connect() -- long before the SSH "ready" event populates activeTunnelRuntimes. Awaited is not connected, so waitForTunnelSettled polls the maps the manager already exports. Polling rather than adding a promise-returning variant: every existing caller is fire-and-forget by design, and changing that contract for one new caller is the larger blast radius. A probe forwardOut runs before returning 200. Without it the route succeeds the moment listen() does, and forwardOut is only attempted per inbound socket where failure is swallowed -- so the likeliest real error, nothing listening on the endpoint's port, reached the user as a blank frame and no message. Staleness is validated at open, never on save: host save lives in the database service and the runtimes live in the tunnel service, with no push between them. On reuse the route compares a fingerprint covering the endpoint's target AND the host's SSH identity, and reopens when it differs. An absent fingerprint means reuse, not staleness -- a reserved-prefixed runtime can only have been created here. Deletion, disabling and host removal then need no handling: nothing reopens the tunnel, so it idles out. Also closes an authorization gap this feature would otherwise have created. /ssh/tunnel/disconnect and /ssh/tunnel/cancel checked ownership only inside `if (config && config.sourceHostId)`, and web tunnels are deliberately absent from tunnelConfigs -- so the check never ran for them. Host ids are small sequential integers and endpoint ids are client-supplied, so the name is guessable and any authenticated user could force-close another user's tunnel. authorizeTunnelAction recovers the host id from the name and fails closed when it cannot; the tests were watched failing against the old behaviour. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(hosts): add the web endpoint client and per-origin certificate allowance The client posts a path relative to tunnelApi's base, which already includes /ssh -- a leading "/ssh" here resolves to /ssh/ssh/... and 404s on every call. The test asserts that on the captured runtime argument rather than by scanning source, so quoting style and indirection cannot fool it. Backend error messages are preserved rather than collapsed. 502 is this route's likeliest real failure and carries the actionable cause -- SSH auth rejected, host unreachable, nothing listening on the target port -- and handleApiError would replace all three with "Server error occurred". It stays as the fallback for bodies that carry no string reason, so a body shaped { error: <object> } cannot reach the user as "[object Object]". openWebEndpointExternally applies the same refusal gate as the embedded tab. Opening in the real browser is not the safer path: the cookie jar is the browser's either way, so a tunnel URL on the page's own host string leaks the session exactly as a frame would. The refusal happens before the forward is opened -- binding the port and then declining to navigate would be no protection. Certificate allowance covers the one case Electron's existing handling misses: direct access to a HOSTNAME over https. isPrivateNetworkHost matches IP literals only and sshData.ip has no IP validation, so https://nas.local:8006 fails the check and renders blank inside an iframe with no click-through -- Chromium offers no proceed option for subframes. Three properties of that allowance are deliberate and now pinned by tests, because each would otherwise be undone by a reasonable-looking simplification: - it is NOT wired into isInvalidCertificateAllowedForUrl, which also governs this process's own outbound TLS via getTlsVerificationOptions; - it is https-only, in both the check and the IPC handler, since a non-TLS origin in a TLS-error allowlist is meaningless and file:/ftp: must never be storable; and - entries carry a five-minute TTL refreshed on each registration. Main has no host-database access and cannot verify the renderer's claim that an origin is a configured endpoint, so the residual risk has to be a momentary window rather than one lasting until the app restarts. The handler stores the parsed origin, never the caller's string, so a path or wildcard cannot widen the allowance. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(hosts): add the Web UI editor tab Mounted as a Web UI sub-tab inside the SSH group, beside Docker, Tunnels, Files and Host Metrics, and laid out as two SectionCards following the tunnels editor: settings first, then the list it governs. There is a deliberate asymmetry with the sidebar here. The sidebar entry will appear on enableWebUi alone, because a direct endpoint needs no SSH -- but Web UI is an SSH sub-tab, so a host with SSH disabled cannot configure endpoints at all. That is the accepted behaviour and both halves are pinned by tests, so neither gets "fixed" into agreement later. tunnelAvailable is enableSsh && originIsLocal, resolved inside HostWebUiTab rather than in HostEditor.tsx, which is already ~2600 lines. It is NOT gated on isElectron(): the forward binds wherever the backend runs, exactly as the server tunnels feature does. resolveConnectionOrigin is called with connectionType "ssh" deliberately -- a tunnel endpoint always rides SSH, and "ssh" avoids the guacamole special case that forces "remote" for RDP/VNC/Telnet. Three input details that each prevent a silent data loss: - the id generator falls back off crypto.randomUUID, which is undefined outside a secure context -- a plain-http web deployment is a first-class target for direct+external and would otherwise throw on "Add endpoint"; - a new row gets a de-duplicated label, since labels are what identify an endpoint in the sidebar picker; and - the port field commits only a value the normalizer would keep. Number("") is 0, which the normalizer rejects, so clearing the field would otherwise write an endpoint that vanishes on save with no error. The tunnel fields carry three warnings: a non-loopback bind exposes the target's web UI unauthenticated to anyone who can reach the port; a loopback bind on a remote backend cannot be reached from a browser at all; and a tunnel reached at Termix's own hostname would hand the tunnelled service this session. All three are shown while configuring rather than only when the tab fails to load. The unavailable-tunnel reason is shown whenever tunnelling is unavailable, not only once a row asks for it -- a disabled dropdown option with no stated reason reads as the control being broken. Copy is reused verbatim from the previous iteration's reviewed strings rather than reworded. One test was written and then removed rather than kept: its name promised that switching to tunnel access clears ignoreCert, but Radix Select needs pointer APIs jsdom lacks, so the body only asserted the control existed. The clearing is covered where it is enforced, in the normalizer. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(hosts): open web endpoints from the sidebar and in a tab One sidebar entry per host, never one per endpoint: a host may declare up to 16, and a row of 16 identical globes is unusable. With a single endpoint the entry wears its label and acts directly; with several it carries no endpointId and the click opens a picker -- a DropdownMenu in the tray, a DropdownMenuSub in the Connect submenu. The entry is gated on enableWebUi ALONE, unlike every neighbouring action, which requires enableSsh. A direct endpoint needs no SSH; SSH matters only per-endpoint, for tunnel access, which the open route enforces. openTab gains a fourth optional parameter rather than overloading `restore`, which means something else. What was actually broken for two endpoints on one host was the LABEL -- tab ids are already `${name}-${type}-${Date.now()}`, so they never collided. All existing call sites keep working. The tab is passed the endpoint ID, not the endpoint object, so one deleted while its tab is open renders a plain message instead of throwing. Reload re-resolves and REMOUNTS. A direct endpoint's URL never changes and a live tunnel returns the same port on every open, so setUrl(resolved) would be a same-value setState that React bails out of, leaving the frame untouched -- Reload would silently do nothing in the two most common cases. A generation counter folded into the iframe key fixes that and doubles as the staleness guard for two resolutions landing out of order. The test captures the DOM node before and after, and was watched failing against a url-only key. PERSISTENT_TAB_TYPES is hoisted to module scope and exported so it can be asserted on -- it was a local const inside the component and therefore untestable. web-endpoint is deliberately excluded: an idle tunnel re-binds a fresh kernel-assigned port, so a restored tab could never hold a valid URL. Two notes on verification. `tsc -p tsconfig.json` passes vacuously in this repo -- tsconfig.json is a solution file with project references and does nothing without -b -- so `npm run type-check` (tsc -b --force) is the real check; it caught two insertions that had landed in the wrong function. And the one full-suite failure seen along the way was vault-signer-core, which passes in isolation and on re-run, is untouched by this branch, and is a flake under parallel load. Lint: 0 errors, 102 warnings, identical to the baseline on a clean tree. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(tunnel): register the web endpoint route under its /ssh path Every route in routes.ts registers the full "/ssh/tunnel/..." path -- nginx proxies /ssh through with the path intact -- and the client resolves "/tunnel/web-endpoint/open" against a baseURL that already ends in /ssh. The unprefixed registration therefore 404'd every call. No handler unit test could catch this: they call handleWebEndpointOpen directly and never touch registration. It surfaced only on opening a real tunnel against a deployed build, which is why that step exists. Added a registration test that captures the paths passed to app.post, so the invariant is checked without needing a server. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(hosts): apply session-cookie isolation to direct web endpoints The cookie guard only covered tunnel access. `unreachableTunnelReason` returned null for every `access: direct` endpoint, so WebEndpointTab framed the host's own address unconditionally. With Termix served at https://termix.example/ and a direct endpoint at https://termix.example:8443/, the browser attaches Termix's `jwt` to the framed request -- cookies are keyed by host and ignore the port -- and a `Set-Cookie` from that service lands in the jar both auth middlewares read before the Authorization header. Renames the helper to `webEndpointRefusalReason` so its scope is no longer tunnel-only, and gives it the endpoint's target host. A direct endpoint is now refused in a browser when that host shares Termix's cookie site, checked BEFORE any navigation in both open paths (embedded tab and external window) -- refusing after framing would leak on the first request. `sharesCookieSiteWithPage` treats an equal host as same-site (the jwt is set host-only, so the port is irrelevant) and also a parent/sub domain, which a `Set-Cookie: Domain=` from the target crosses. The suffix test is anchored on a dot boundary so `eviltermix.example` does not pass as `termix.example`. A precise eTLD+1 test would also catch sibling subdomains, but needs a public suffix list this app does not bundle. The desktop stays exempt: its session is Bearer-only with no `jwt` in the jar. Also drops "or change this endpoint to Direct" from the tunnel refusal copy, which pointed at the path that had this same leak. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com> * fix(tunnel): preserve local status when remote names collide (#1431) * fix(desktop): honor remote sync certificate setting (#1432) * fix(file-manager): interpolate preview download filename (#1433) * fix(automations): dispatch SSH login events to triggers (#1434) * fix(hosts): preserve imported settings and remap jump hosts (#1435) * fix(hosts): preserve terminal switches across JSON transfer * fix(hosts): remap imported jump-host dependencies * fix(ssh): preserve agent framing after unsupported extensions (#1436) * fix(guacamole): return tokens before awaiting the client handshake (#1437) * fix(sidebar): unmount the host tree while its panel is hidden (#1438) * fix(terminal): leave macOS Option characters enabled by default (#1439) * fix(dashboard): open the enabled remote desktop protocol (#1440) * fix(version): preserve local version when update checks fail (#1441) * fix(sftp): create uploaded directories without shell access (#1442) * fix(desktop): honor explicit GPU acceleration opt-out (#1443) * fix(desktop): exclude remote-only host IDs from local tab persistence (#1444) * Enhance SFTP and terminal flows, stabilize desktop sync (#1377) * feat: add electron sftp c2s and terminal ai flows * fix: stabilize desktop sync and c2s tunnels * Improve remote tunnels and SFTP transfer feedback * chore: sync Crowdin translations * chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325) Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg). Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0 - [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases) - [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md) - [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0) Updates `js-yaml` from 5.2.3 to 5.3.0 - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0) Updates `pg` from 8.22.0 to 8.23.0 - [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md) - [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg) --- updated-dependencies: - dependency-name: "@anthropic-ai/sdk" dependency-version: 0.120.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: js-yaml dependency-version: 5.3.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: pg dependency-version: 8.23.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323) Bumps the dev-minor-updates group with 10 updates in the / directory: | Package | From | To | | --- | --- | --- | | [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` | | [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` | | [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` | | [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` | | [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` | | [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` | | [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` | | [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` | | [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` | | [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` | Updates `@codemirror/commands` from 6.10.4 to 6.11.0 - [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/commands/commits) Updates `@types/node` from 26.1.2 to 26.2.0 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0 - [Release notes](https://github.com/vitejs/vite-plugin-react/releases) - [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react) Updates `electron` from 43.2.0 to 43.4.1 - [Release notes](https://github.com/electron/electron/releases) - [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1) Updates `globals` from 17.9.0 to 17.11.0 - [Release notes](https://github.com/sindresorhus/globals/releases) - [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0) Updates `i18next` from 26.3.6 to 26.4.0 - [Release notes](https://github.com/i18next/i18next/releases) - [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0) Updates `lucide-react` from 1.28.0 to 1.33.0 - [Release notes](https://github.com/lucide-icons/lucide/releases) - [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react) Updates `react-hook-form` from 7.84.0 to 7.85.0 - [Release notes](https://github.com/react-hook-form/react-hook-form/releases) - [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md) - [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0) Updates `react-pdf` from 10.4.1 to 10.5.0 - [Release notes](https://github.com/wojtekmaj/react-pdf/releases) - [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf) Updates `typescript-eslint` from 8.66.0 to 8.67.0 - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint) --- updated-dependencies: - dependency-name: "@codemirror/commands" dependency-version: 6.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@types/node" dependency-version: 26.2.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@vitejs/plugin-react" dependency-version: 6.1.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: electron dependency-version: 43.4.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: globals dependency-version: 17.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: i18next dependency-version: 26.4.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: lucide-react dependency-version: 1.33.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-hook-form dependency-version: 7.85.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-pdf dependency-version: 10.5.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: typescript-eslint dependency-version: 8.67.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore: sync Crowdin translations * Update redirect-issues workflow configuration Updated the workflow to change the runner and modify the issue response message. * test(sftp): verify local collection limit boundaries --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com> * chore: increment ver * fix: allow any origin by default when CORS_ALLOWED_ORIGINS is unset * feat(file-manager): parallel local transfers (#1446) Uploads from the Local pane (and downloads to it) ran strictly one file after another. Batches of many small files were bound by per-file latency rather than bandwidth. - `runWithConcurrency(items, limit, worker, shouldStop)`: a bounded worker pool that dispatches in order, keeps at most `limit` transfers in flight, and stops dispatching once cancelled while letting in-flight items finish. Worker errors are handled by the worker (one failure never aborts the batch). - useLocalTransfers: both directions go through the pool. Remote / local directory skeletons are still created up front, so file order does not matter. The batch runner now tracks a set of in-flight transfer ids (Cancel cancels all of them), sums bytes across in-flight transfers plus settled ones for the progress bar / speed, and shows how many files are moving at once. - New preference "Simultaneous File Transfers" (1-8, default 4) in the profile settings, stored in localStorage (`termix:file-manager:transfer-concurrency`) and part of the storage snapshot. 1 restores the previous sequential behaviour; the hint suggests lowering it for servers that limit SFTP channels. - Remote directories are created with the now-idempotent mkdir (#1442) without swallowing its errors, so a real failure stops the batch up front instead of surfacing as N per-file failures. When files do fail, the summary toast carries the first underlying reason (e.g. the backend's 401 message) instead of a bare "Upload failed". - Tests: pool never exceeds the limit and drains everything, stops on cancel, tolerates a failing item, handles empty input; preference clamping and persistence; bridge-level concurrent uploads/downloads with a mid-flight cancel leave every other file intact and no partials. Co-authored-by: Max <maxim@cogitate.ai> * fix(sftp): complete streamed uploads and stop pre-parsing chunk bodies * fix(desktop): stop setting Content-Length on local download requests * fix(file-manager): keep drop overlays in view when the list is scrolled * fix(file-manager): let remote rows be dropped on the local pane * fix(desktop): authenticate local transfers with the renderer's token * chore: update release notes * chore: remove unused gitlab ci and argocd deploy configs * chore: remove unused files * feat: improve loading animation * fix(shell): stop tab reorder from resetting terminals and tab indicator Keep the tab-content portal order stable so reordering tabs doesn't retrigger React's offscreen pass and dispose live terminals. Also stop the active tab indicator from teleporting during a drag, and fix the drag ghost's size/border mismatch. * fix(shell): hand-roll the tab indicator instead of a shared layoutId Framer's layoutId could measure the wrong tab's rect during a reorder and land on an inactive tab, or leave a stray line visible mid-drag. Now it reads the active tab's own DOM rect directly and hides while dragging. * fix(hosts): fix right-click menu position and unwanted tray expand * chore: update release notes * fix(terminal): stop autosuggestion ghost text overlapping typed input Position was computed from cursorX before server echo landed, causing a stale read that overlapped just-typed characters on fast local input. * chore: update release notes for v2.8.0 * fix(sftp): rebuild transfer tab for web, fix menu offset bug Drop the electron-only local mode and dead code, i18n all strings, fix double progress toasts and a wrong pane refresh on move. Fix context menus rendering offset due to a lingering CSS transform from the tab-switch animation. Move SFTP next to SSH Tools in the rail. * fix(file-manager): shrink oversized .. entry, navigate on single click * fix: make select2 component use rounded corners * fix: rebuild terminal AI assistant on the real backend Removes the Electron-only Agent Mode/AI Command Helper that bypassed admin/user gating and ran commands with no approval step. Replaces it with a terminal-docked panel on the same gated backend as the AI tab, adds a per-host toggle (off by default), moves it into the toolbar, and fixes proposal ordering and run-in-terminal execution. * fix(file-manager): remove duplicate borders in toolbar view toggle Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix: separate registration toggle from step ca settings * fix: collab room bugs and add room deletion Accent-colored new room button, fix fullscreen guest view layout and duplicate view-only badges, self-heal stale presenter state, add delete room for persistent rooms. * refactor: move host-identity helpers to hosts core Used by docker, file-manager, and terminal alike, so it belongs at the hosts root instead of under terminal/. * refactor: move host-session-status singleton to hosts core metrics subscribed to terminal's private online/offline pub-sub module. Moved to hosts core so both sides depend on a shared module instead of metrics reaching into terminal. Marked the subscribe call with PLUGIN-EVENT for the future event bus. * refactor: split generic automation event notify out of metrics notifyAutomationInternalEvent was in hosts/metrics/automation-bridge.ts but is used by tunnel, host routes, user routes, and automations engine itself, not just metrics. Moved it to hosts/automation-events.ts so those callers depend on a shared module instead of metrics internals. Left the metrics-specific notifiers in place. * feat: add plugin system schema and repositories Adds plugins, plugin_permission_grants, plugin_registries, and plugin_install_counts tables plus their repositories. No routes or UI yet. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat: add runtime rail item and tab component registries for plugins * feat: support runtime-registered permission groups Adds register/unregister for plugin permission groups so the RBAC catalog and validation can grow beyond the static list. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat: add plugin-api nginx route and dispatcher stub * feat: add plugin manifest schema and validator * chore: update release notes * chore: update i18n for local/remote file manager * feat: add toggle to show/hide app rail pin button * feat(host-metrics): add NVIDIA GPU metrics card (#1452) * feat(host-metrics): add NVIDIA GPU metrics card Collect per-GPU utilization, VRAM, temperature, power, fan speed and the processes using each GPU over SSH with nvidia-smi. The collector exits immediately when nvidia-smi is missing, so hosts without a GPU pay almost nothing per poll. The GPU card is opt-in: it is available from the Add card tray but is not part of new-host defaults or any UI preset. It shows live sparklines for utilization and VRAM per GPU. Adaptive polling now also watches GPU readings and the GPU process count, so it no longer backs off on hosts where only the GPU is busy. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01F2ctuPwiesLzhF6XQiozm8 * fix(host-metrics): draw sparklines from the first metrics sample The first sample fetched when the tab connects was shown but never added to the sparkline history, so every sparkline (CPU, memory, disk, GPU) stayed empty until the second poll, a full metrics interval later (about 35 s with the default 30 s interval). Record the first sample like every later one, so the lines appear as soon as the tab loads. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01F2ctuPwiesLzhF6XQiozm8 * Fix logical condition for memory percentage calculation Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * fix: annotate local transfer plan type to fix CI type-check * fix: move connection toolbar settings to bottom of host editor general tab * chore: add debug logging for macOS sharp packaging failure Temporary diagnostic to find which phase drops @img/sharp-darwin-x64 from the packaged app. Revert once root cause is found. * fix: correct macOS sharp verify script for universal build layout electron-builder uses mergeASARs: false, so universal builds ship app-x64.asar.unpacked and app-arm64.asar.unpacked side by side instead of a single app.asar.unpacked. The verify script only checked the single-asar path, so it always failed on universal/mas artifacts even when packaging was correct. * fix: update sharp verify test fixtures for universal build layout The test built fake apps using the single app.asar.unpacked layout, which doesn't match how universal builds are actually packaged now (app-x64.asar.unpacked / app-arm64.asar.unpacked side by side). * chore: update readme * fix: guard against missing rooms array in collab list response * fix: distinct guac connection log stages, RDP black screen before failure * fix: proxy /collab routes in nginx configs * fix: stop tab-switch flash and host metrics/proxmox reconnect Tab DOM visibility now syncs before paint instead of after, and switching tabs no longer tears down live metrics connections. * fix: tab bar flashing, growing, and merged separators Terminal tabs no longer flash when switching, the enter animation no longer nudges layout size, and a stray transform on resting tabs no longer causes the border between tabs to vanish at some zoom levels. * fix: match select trigger height to inputs in web UI editor * chore: lint, format, and bump version to 2.8.0 * chore: sync Crowdin translations for 2.8.0 --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> Co-authored-by: Angad Singh <7099405+singhangadin@users.noreply.github.com> Co-authored-by: Angad Singh <angad@singhangad.in> Co-authored-by: Neo <54811660+neooriginal@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Wali Lambert <98448225+YatoVoid@users.noreply.github.com> Co-authored-by: Nasif Rahman <44437976+nasif-naseef@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: vietanhtwdk <vietanhtruongwdk@gmail.com> Co-authored-by: inontz <inontz@icloud.com> Co-authored-by: inontz <inontz@users.noreply.github.com> Co-authored-by: Max Serov <133950708+maxser0v@users.noreply.github.com> Co-authored-by: Max <maxim@cogitate.ai> Co-authored-by: ssmurfgg04-gif <ssmurfgg04@gmail.com> Co-authored-by: ssmurfgg04-gif <232103099+ssmurfgg04-gif@users.noreply.github.com> Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com> Co-authored-by: slsgzs-cloud <slsgzs@gmail.com> Co-authored-by: anshtsolanki-sketch <anshtsolanki@gmail.com> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: tcezarl <tomescu.cezar.laurentiu@gmail.com> Co-authored-by: Anton Priestley <anton@priestley.me> Co-authored-by: Hakim M <hakimmarsudi@outlook.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Adel Alzubeir <14052842+Adelzu@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
3071 lines
93 KiB
TypeScript
3071 lines
93 KiB
TypeScript
import type { AuthenticatedRequest } from "../../../types/index.js";
|
|
import express, { type Request, type Response } from "express";
|
|
import bcrypt from "bcryptjs";
|
|
import crypto from "crypto";
|
|
import { nanoid } from "nanoid";
|
|
import { authLogger } from "../../utils/logger.js";
|
|
import { AuthManager } from "../../utils/auth-manager.js";
|
|
import { DatabaseSaveTrigger } from "../../utils/database-save-trigger.js";
|
|
import { DataCrypto } from "../../utils/data-crypto.js";
|
|
import {
|
|
getDeviceId,
|
|
parseUserAgent,
|
|
generateDeviceFingerprint,
|
|
} from "../../utils/user-agent-parser.js";
|
|
import { loginRateLimiter } from "../../utils/login-rate-limiter.js";
|
|
import { getRequestOriginWithForceHTTPS } from "../../utils/request-origin.js";
|
|
import {
|
|
getDesktopOidcCallbackUrl,
|
|
isOidcTokenCallback,
|
|
} from "../../utils/oidc-desktop-callback.js";
|
|
import { deleteUserAndRelatedData } from "./delete-user-data.js";
|
|
import {
|
|
isLoopbackRequest,
|
|
extractBearerOrCookieToken,
|
|
isNativeTokenExportRequest,
|
|
resolveDesktopAutoSessionUser,
|
|
} from "./desktop-auto-session.js";
|
|
import { shouldShowDonationModal } from "./donation-modal-utils.js";
|
|
import { PermissionManager } from "../../utils/permission-manager.js";
|
|
import {
|
|
getOIDCConfigFromEnv,
|
|
isOIDCUserAllowed,
|
|
OIDCTokenFormatError,
|
|
verifyOIDCToken,
|
|
extractOidcGroupsFromSources,
|
|
parseOidcRoleMap,
|
|
resolveOidcMappedRoles,
|
|
loadProviderConfig,
|
|
buildFetchOptions,
|
|
resolveProviderByIssuer,
|
|
validateLogoutToken,
|
|
} from "./user-oidc-utils.js";
|
|
import { registerUserApiKeyRoutes } from "./user-api-key-routes.js";
|
|
import { registerUserImageStorageRoutes } from "./user-image-storage-routes.js";
|
|
import { registerBrandingRoutes } from "./branding-routes.js";
|
|
import { registerUserSettingsRoutes } from "./user-settings-routes.js";
|
|
import { registerTouchInputSettingsRoutes } from "./touch-input-settings-routes.js";
|
|
import { registerAcmeSSLRoutes } from "./acme-ssl-routes.js";
|
|
import { registerUserTotpRoutes } from "./user-totp-routes.js";
|
|
import { registerUserWebAuthnRoutes } from "./user-webauthn-routes.js";
|
|
import { registerUserSessionRoutes } from "./user-session-routes.js";
|
|
import { registerUserOidcAccountRoutes } from "./user-oidc-account-routes.js";
|
|
import { registerUserPasswordResetRoutes } from "./user-password-reset-routes.js";
|
|
import { registerUserAdminRoutes } from "./user-admin-routes.js";
|
|
import { registerUserDataAccessRoutes } from "./user-data-access-routes.js";
|
|
import { registerSSOProviderRoutes } from "./sso-provider-routes.js";
|
|
import { registerLDAPAuthRoutes } from "./ldap-auth-routes.js";
|
|
import { logAudit, getRequestMeta } from "../../utils/audit-logger.js";
|
|
import { notifyAutomationInternalEvent } from "../../hosts/automation-events.js";
|
|
import {
|
|
createCurrentSettingsRepository,
|
|
getCurrentSettingValue,
|
|
createCurrentRoleRepository,
|
|
createCurrentSsoProviderRepository,
|
|
createCurrentUserRepository,
|
|
} from "../repositories/factory.js";
|
|
import type { UserRecord } from "../repositories/user-repository.js";
|
|
import {
|
|
getTrustedProxyAuthConfig,
|
|
isTrustedProxyAddress,
|
|
isTrustedProxyAuthEnabled,
|
|
resolveTrustedProxyRoles,
|
|
} from "../../utils/trusted-proxy-auth.js";
|
|
|
|
const authManager = AuthManager.getInstance();
|
|
|
|
const router = express.Router();
|
|
|
|
router.use((req, res, next) => {
|
|
if (isTrustedProxyAuthEnabled() && req.path.startsWith("/oidc")) {
|
|
return res.status(409).json({
|
|
error: "OIDC is disabled while trusted proxy authentication is enabled",
|
|
});
|
|
}
|
|
next();
|
|
});
|
|
|
|
async function syncSharedCredentialsForUserRoles(
|
|
userId: string,
|
|
operation: string,
|
|
) {
|
|
try {
|
|
const { SharedHostSecretsManager } =
|
|
await import("../../utils/shared-host-secrets-manager.js");
|
|
await SharedHostSecretsManager.getInstance().snapshotForUserRoles(userId);
|
|
const { SharedCredentialSecretsManager } =
|
|
await import("../../utils/shared-credential-secrets-manager.js");
|
|
await SharedCredentialSecretsManager.getInstance().snapshotForUserRoles(
|
|
userId,
|
|
);
|
|
} catch (error) {
|
|
authLogger.warn("Failed to sync role shared host secrets", {
|
|
operation,
|
|
userId,
|
|
error,
|
|
});
|
|
}
|
|
}
|
|
|
|
function isNonEmptyString(val: unknown): val is string {
|
|
return typeof val === "string" && val.trim().length > 0;
|
|
}
|
|
|
|
function isRegistrationAllowed(): boolean {
|
|
const envVal = process.env.ALLOW_REGISTRATION;
|
|
if (envVal !== undefined) return envVal.trim().toLowerCase() === "true";
|
|
try {
|
|
const value = getCurrentSettingValue("allow_registration");
|
|
return value ? value === "true" : true;
|
|
} catch {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
function isPasswordLoginAllowed(): boolean {
|
|
const envVal = process.env.ALLOW_PASSWORD_LOGIN;
|
|
if (envVal !== undefined) return envVal.trim().toLowerCase() === "true";
|
|
try {
|
|
const value = getCurrentSettingValue("allow_password_login");
|
|
return value ? value === "true" : true;
|
|
} catch {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
function isPasswordResetAllowed(): boolean {
|
|
const envVal = process.env.ALLOW_PASSWORD_RESET;
|
|
if (envVal !== undefined) return envVal.trim().toLowerCase() === "true";
|
|
try {
|
|
const value = getCurrentSettingValue("allow_password_reset");
|
|
return value ? value === "true" : true;
|
|
} catch {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
function getOidcSilentLoginDefaultFromEnv(): boolean | undefined {
|
|
const envVal = process.env.OIDC_SILENT_LOGIN_DEFAULT;
|
|
if (envVal === undefined) return undefined;
|
|
return envVal.trim().toLowerCase() === "true";
|
|
}
|
|
|
|
function isNativeAppRequest(req: Request): boolean {
|
|
return (
|
|
(req.get("User-Agent") || "").startsWith("Termix-Mobile/") ||
|
|
req.get("X-Electron-App") === "true"
|
|
);
|
|
}
|
|
|
|
async function findCurrentUser(userId: string): Promise<UserRecord | null> {
|
|
return createCurrentUserRepository().findById(userId);
|
|
}
|
|
|
|
async function requireCurrentAdmin(userId: string): Promise<UserRecord | null> {
|
|
const user = await findCurrentUser(userId);
|
|
return user?.isAdmin ? user : null;
|
|
}
|
|
|
|
// RFC 7636 PKCE: 43-128 char unreserved-character string.
|
|
function generatePkceCodeVerifier(): string {
|
|
return crypto.randomBytes(64).toString("base64url");
|
|
}
|
|
|
|
function generatePkceCodeChallenge(verifier: string): string {
|
|
return crypto.createHash("sha256").update(verifier).digest("base64url");
|
|
}
|
|
|
|
async function deleteOIDCStateSettings(state: string): Promise<void> {
|
|
const settingsRepository = createCurrentSettingsRepository();
|
|
await settingsRepository.delete(`oidc_state_${state}`);
|
|
await settingsRepository.delete(`oidc_backend_callback_${state}`);
|
|
await settingsRepository.delete(`oidc_frontend_origin_${state}`);
|
|
await settingsRepository.delete(`oidc_remember_me_${state}`);
|
|
await settingsRepository.delete(`oidc_provider_${state}`);
|
|
await settingsRepository.delete(`oidc_pkce_verifier_${state}`);
|
|
}
|
|
|
|
const authenticateJWT = authManager.createAuthMiddleware();
|
|
const requireAdmin = authManager.createAdminMiddleware();
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/create:
|
|
* post:
|
|
* summary: Create a new user
|
|
* description: Creates a new user with a username and password.
|
|
* tags:
|
|
* - Users
|
|
* requestBody:
|
|
* required: true
|
|
* content:
|
|
* application/json:
|
|
* schema:
|
|
* type: object
|
|
* properties:
|
|
* username:
|
|
* type: string
|
|
* password:
|
|
* type: string
|
|
* responses:
|
|
* 200:
|
|
* description: User created successfully.
|
|
* 400:
|
|
* description: Username and password are required.
|
|
* 403:
|
|
* description: Registration is currently disabled.
|
|
* 409:
|
|
* description: Username already exists.
|
|
* 500:
|
|
* description: Failed to create user.
|
|
*/
|
|
router.post("/create", async (req, res) => {
|
|
if (!isRegistrationAllowed()) {
|
|
return res
|
|
.status(403)
|
|
.json({ error: "Registration is currently disabled" });
|
|
}
|
|
|
|
const { username, password } = req.body;
|
|
authLogger.info("User registration attempt", {
|
|
operation: "user_register_attempt",
|
|
username,
|
|
});
|
|
|
|
if (!isNonEmptyString(username) || !isNonEmptyString(password)) {
|
|
authLogger.warn(
|
|
"Invalid user creation attempt - missing username or password",
|
|
{
|
|
operation: "user_create",
|
|
hasUsername: !!username,
|
|
hasPassword: !!password,
|
|
},
|
|
);
|
|
return res
|
|
.status(400)
|
|
.json({ error: "Username and password are required" });
|
|
}
|
|
|
|
try {
|
|
const userRepository = createCurrentUserRepository();
|
|
const existing = await userRepository.findByUsername(username);
|
|
if (existing) {
|
|
authLogger.warn("Registration failed - username exists", {
|
|
operation: "user_register_failed",
|
|
username,
|
|
reason: "username_exists",
|
|
});
|
|
return res.status(409).json({ error: "Username already exists" });
|
|
}
|
|
|
|
const password_hash = await bcrypt.hash(password, 10);
|
|
const id = nanoid();
|
|
|
|
const { isFirstUser } = await userRepository.createFirstLocalUser({
|
|
id,
|
|
username,
|
|
passwordHash: password_hash,
|
|
isOidc: false,
|
|
clientId: "",
|
|
clientSecret: "",
|
|
issuerUrl: "",
|
|
authorizationUrl: "",
|
|
tokenUrl: "",
|
|
identifierPath: "",
|
|
namePath: "",
|
|
scopes: "openid email profile",
|
|
totpSecret: null,
|
|
totpEnabled: false,
|
|
totpBackupCodes: null,
|
|
});
|
|
|
|
try {
|
|
const defaultRoleName = isFirstUser ? "admin" : "user";
|
|
const assigned = await createCurrentRoleRepository().assignRoleNameToUser(
|
|
{
|
|
userId: id,
|
|
roleName: defaultRoleName,
|
|
grantedBy: id,
|
|
},
|
|
);
|
|
|
|
if (!assigned) {
|
|
authLogger.warn("Default role not found during user registration", {
|
|
operation: "assign_default_role",
|
|
userId: id,
|
|
roleName: defaultRoleName,
|
|
});
|
|
}
|
|
} catch (roleError) {
|
|
authLogger.error("Failed to assign default role", roleError, {
|
|
operation: "assign_default_role",
|
|
userId: id,
|
|
});
|
|
}
|
|
|
|
try {
|
|
await authManager.registerUser(id, password);
|
|
} catch (encryptionError) {
|
|
await userRepository.delete(id);
|
|
authLogger.error(
|
|
"Failed to setup user encryption, user creation rolled back",
|
|
encryptionError,
|
|
{
|
|
operation: "user_create_encryption_failed",
|
|
userId: id,
|
|
},
|
|
);
|
|
return res.status(500).json({
|
|
error: "Failed to setup user security - user creation cancelled",
|
|
});
|
|
}
|
|
|
|
try {
|
|
await DatabaseSaveTrigger.forceSave("user_create_explicit_save");
|
|
} catch (saveError) {
|
|
authLogger.error("Failed to persist user to disk", saveError, {
|
|
operation: "user_create_save_failed",
|
|
userId: id,
|
|
});
|
|
}
|
|
|
|
authLogger.success("User registration successful", {
|
|
operation: "user_register_success",
|
|
userId: id,
|
|
username,
|
|
isAdmin: isFirstUser,
|
|
});
|
|
|
|
const { ipAddress, userAgent } = getRequestMeta(req);
|
|
await logAudit({
|
|
userId: id,
|
|
username,
|
|
action: "create_user",
|
|
resourceType: "user",
|
|
resourceId: id,
|
|
resourceName: username,
|
|
ipAddress,
|
|
userAgent,
|
|
success: true,
|
|
});
|
|
|
|
res.json({
|
|
message: "User created",
|
|
is_admin: isFirstUser,
|
|
toast: { type: "success", message: `User created: ${username}` },
|
|
});
|
|
} catch (err) {
|
|
authLogger.error("Failed to create user", err);
|
|
res.status(500).json({ error: "Failed to create user" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/oidc-config:
|
|
* post:
|
|
* summary: Configure OIDC provider
|
|
* description: Creates or updates the OIDC provider configuration.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: OIDC configuration updated.
|
|
* 403:
|
|
* description: Not authorized.
|
|
* 500:
|
|
* description: Failed to update OIDC config.
|
|
*/
|
|
router.post("/oidc-config", authenticateJWT, async (req, res) => {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
try {
|
|
const user = await requireCurrentAdmin(userId);
|
|
if (!user) {
|
|
return res.status(403).json({ error: "Not authorized" });
|
|
}
|
|
|
|
const {
|
|
client_id,
|
|
client_secret,
|
|
issuer_url,
|
|
authorization_url,
|
|
token_url,
|
|
userinfo_url,
|
|
identifier_path,
|
|
name_path,
|
|
scopes,
|
|
allowed_users,
|
|
admin_group,
|
|
group_claim,
|
|
} = req.body;
|
|
|
|
const isDisableRequest =
|
|
(client_id === "" || client_id === null || client_id === undefined) &&
|
|
(client_secret === "" ||
|
|
client_secret === null ||
|
|
client_secret === undefined) &&
|
|
(issuer_url === "" || issuer_url === null || issuer_url === undefined) &&
|
|
(authorization_url === "" ||
|
|
authorization_url === null ||
|
|
authorization_url === undefined) &&
|
|
(token_url === "" || token_url === null || token_url === undefined);
|
|
|
|
const isEnableRequest =
|
|
isNonEmptyString(client_id) &&
|
|
isNonEmptyString(client_secret) &&
|
|
isNonEmptyString(issuer_url) &&
|
|
isNonEmptyString(authorization_url) &&
|
|
isNonEmptyString(token_url) &&
|
|
isNonEmptyString(identifier_path) &&
|
|
isNonEmptyString(name_path);
|
|
|
|
if (!isDisableRequest && !isEnableRequest) {
|
|
authLogger.warn(
|
|
"OIDC validation failed - neither disable nor enable request",
|
|
{
|
|
operation: "oidc_config_update",
|
|
userId,
|
|
isDisableRequest,
|
|
isEnableRequest,
|
|
},
|
|
);
|
|
return res
|
|
.status(400)
|
|
.json({ error: "All OIDC configuration fields are required" });
|
|
}
|
|
|
|
const settingsRepository = createCurrentSettingsRepository();
|
|
|
|
if (isDisableRequest) {
|
|
await settingsRepository.delete("oidc_config");
|
|
authLogger.info("OIDC configuration disabled", {
|
|
operation: "oidc_disable",
|
|
userId,
|
|
});
|
|
res.json({ message: "OIDC configuration disabled" });
|
|
} else {
|
|
const config = {
|
|
client_id,
|
|
client_secret,
|
|
issuer_url,
|
|
authorization_url,
|
|
token_url,
|
|
userinfo_url: userinfo_url || "",
|
|
identifier_path,
|
|
name_path,
|
|
scopes: scopes || "openid email profile",
|
|
allowed_users: allowed_users || "",
|
|
admin_group: admin_group || "",
|
|
group_claim: group_claim || "",
|
|
};
|
|
|
|
let encryptedConfig;
|
|
try {
|
|
const adminDataKey = DataCrypto.getUserDataKey(userId);
|
|
if (adminDataKey) {
|
|
const configWithId = { ...config, id: `oidc-config-${userId}` };
|
|
encryptedConfig = DataCrypto.encryptRecord(
|
|
"settings",
|
|
configWithId,
|
|
userId,
|
|
adminDataKey,
|
|
);
|
|
} else {
|
|
encryptedConfig = {
|
|
...config,
|
|
client_secret: `encrypted:${Buffer.from(client_secret).toString("base64")}`,
|
|
};
|
|
authLogger.warn(
|
|
"OIDC configuration stored with basic encoding - admin should re-save with password",
|
|
{
|
|
operation: "oidc_config_basic_encoding",
|
|
userId,
|
|
},
|
|
);
|
|
}
|
|
} catch (encryptError) {
|
|
authLogger.error(
|
|
"Failed to encrypt OIDC configuration, storing with basic encoding",
|
|
encryptError,
|
|
{
|
|
operation: "oidc_config_encrypt_failed",
|
|
userId,
|
|
},
|
|
);
|
|
encryptedConfig = {
|
|
...config,
|
|
client_secret: `encoded:${Buffer.from(client_secret).toString("base64")}`,
|
|
};
|
|
}
|
|
|
|
await settingsRepository.set(
|
|
"oidc_config",
|
|
JSON.stringify(encryptedConfig),
|
|
);
|
|
authLogger.info("OIDC configuration updated", {
|
|
operation: "oidc_update",
|
|
userId,
|
|
hasUserinfoUrl: !!userinfo_url,
|
|
});
|
|
res.json({ message: "OIDC configuration updated" });
|
|
}
|
|
} catch (err) {
|
|
authLogger.error("Failed to update OIDC config", err);
|
|
res.status(500).json({ error: "Failed to update OIDC config" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/oidc-config:
|
|
* delete:
|
|
* summary: Disable OIDC configuration
|
|
* description: Disables the OIDC provider configuration.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: OIDC configuration disabled.
|
|
* 403:
|
|
* description: Not authorized.
|
|
* 500:
|
|
* description: Failed to disable OIDC config.
|
|
*/
|
|
router.delete("/oidc-config", authenticateJWT, async (req, res) => {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
try {
|
|
const user = await requireCurrentAdmin(userId);
|
|
if (!user) {
|
|
return res.status(403).json({ error: "Not authorized" });
|
|
}
|
|
|
|
await createCurrentSettingsRepository().delete("oidc_config");
|
|
authLogger.success("OIDC configuration disabled", {
|
|
operation: "oidc_disable",
|
|
userId,
|
|
});
|
|
res.json({ message: "OIDC configuration disabled" });
|
|
} catch (err) {
|
|
authLogger.error("Failed to disable OIDC config", err);
|
|
res.status(500).json({ error: "Failed to disable OIDC config" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/oidc-config:
|
|
* get:
|
|
* summary: Get OIDC configuration
|
|
* description: Returns the public OIDC configuration.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: Public OIDC configuration.
|
|
* 500:
|
|
* description: Failed to get OIDC config.
|
|
*/
|
|
router.get("/oidc-config", async (_req, res) => {
|
|
try {
|
|
const providerResult = await loadProviderConfig(undefined);
|
|
if (!providerResult) {
|
|
return res.json(null);
|
|
}
|
|
const { config } = providerResult;
|
|
return res.json({
|
|
client_id: config.client_id,
|
|
issuer_url: config.issuer_url,
|
|
authorization_url: config.authorization_url,
|
|
scopes: config.scopes,
|
|
});
|
|
} catch (err) {
|
|
authLogger.error("Failed to get OIDC config", err);
|
|
res.status(500).json({ error: "Failed to get OIDC config" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/oidc-config/admin:
|
|
* get:
|
|
* summary: Get OIDC configuration for admin
|
|
* description: Returns the full OIDC configuration for an admin.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: Full OIDC configuration.
|
|
* 500:
|
|
* description: Failed to get OIDC config for admin.
|
|
*/
|
|
router.get("/oidc-config/admin", requireAdmin, async (req, res) => {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
try {
|
|
const value = await createCurrentSettingsRepository().get("oidc_config");
|
|
if (!value) {
|
|
const envConfig = getOIDCConfigFromEnv();
|
|
return res.json(envConfig);
|
|
}
|
|
|
|
let config = JSON.parse(value);
|
|
|
|
if (config.client_secret?.startsWith("encrypted:")) {
|
|
try {
|
|
const adminDataKey = DataCrypto.getUserDataKey(userId);
|
|
if (adminDataKey) {
|
|
config = DataCrypto.decryptRecord(
|
|
"settings",
|
|
config,
|
|
userId,
|
|
adminDataKey,
|
|
);
|
|
} else {
|
|
config.client_secret = "[ENCRYPTED - PASSWORD REQUIRED]";
|
|
}
|
|
} catch {
|
|
authLogger.warn("Failed to decrypt OIDC config for admin", {
|
|
operation: "oidc_config_decrypt_failed",
|
|
userId,
|
|
});
|
|
config.client_secret = "[ENCRYPTED - DECRYPTION FAILED]";
|
|
}
|
|
} else if (config.client_secret?.startsWith("encoded:")) {
|
|
try {
|
|
const decoded = Buffer.from(
|
|
config.client_secret.substring(8),
|
|
"base64",
|
|
).toString("utf8");
|
|
config.client_secret = decoded;
|
|
} catch {
|
|
authLogger.warn("Failed to decode OIDC config for admin", {
|
|
operation: "oidc_config_decode_failed",
|
|
userId,
|
|
});
|
|
config.client_secret = "[ENCODING ERROR]";
|
|
}
|
|
}
|
|
|
|
res.json(config);
|
|
} catch (err) {
|
|
authLogger.error("Failed to get OIDC config for admin", err);
|
|
res.status(500).json({ error: "Failed to get OIDC config for admin" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/oidc/authorize:
|
|
* get:
|
|
* summary: Get OIDC authorization URL
|
|
* description: Returns the OIDC authorization URL.
|
|
* tags:
|
|
* - Users
|
|
* parameters:
|
|
* - in: query
|
|
* name: rememberMe
|
|
* schema:
|
|
* type: boolean
|
|
* description: Whether to extend the session to 30 days instead of 2 hours.
|
|
* responses:
|
|
* 200:
|
|
* description: OIDC authorization URL.
|
|
* 404:
|
|
* description: OIDC not configured.
|
|
* 500:
|
|
* description: Failed to generate authorization URL.
|
|
*/
|
|
router.get("/oidc/authorize", async (req, res) => {
|
|
try {
|
|
const {
|
|
rememberMe,
|
|
desktopCallbackPort,
|
|
appCallbackUrl,
|
|
providerId: providerIdStr,
|
|
} = req.query;
|
|
const origin = getRequestOriginWithForceHTTPS(req);
|
|
const basePath = (process.env.BASE_PATH || "").replace(/\/+$/, "");
|
|
const backendCallbackUri = `${origin}${basePath}/users/oidc/callback`;
|
|
|
|
const resolvedProviderId = providerIdStr
|
|
? parseInt(providerIdStr as string, 10)
|
|
: null;
|
|
const providerResult = await loadProviderConfig(
|
|
resolvedProviderId || undefined,
|
|
);
|
|
if (!providerResult) {
|
|
return res.status(404).json({ error: "OIDC not configured" });
|
|
}
|
|
const { config, providerDbId } = providerResult;
|
|
const state = nanoid();
|
|
const nonce = nanoid();
|
|
|
|
const referer = req.get("Referer");
|
|
let frontendOrigin;
|
|
if (desktopCallbackPort) {
|
|
frontendOrigin = getDesktopOidcCallbackUrl(desktopCallbackPort);
|
|
if (!frontendOrigin) {
|
|
return res.status(400).json({ error: "Invalid desktop callback port" });
|
|
}
|
|
} else if (typeof appCallbackUrl === "string" && appCallbackUrl) {
|
|
let callbackUrl: URL;
|
|
try {
|
|
callbackUrl = new URL(appCallbackUrl);
|
|
} catch {
|
|
return res.status(400).json({ error: "Invalid app callback URL" });
|
|
}
|
|
if (callbackUrl.protocol !== "termix-mobile:") {
|
|
return res.status(400).json({ error: "Unsupported app callback URL" });
|
|
}
|
|
frontendOrigin = callbackUrl.toString();
|
|
} else if (referer) {
|
|
const refererUrl = new URL(referer);
|
|
frontendOrigin = `${refererUrl.protocol}//${refererUrl.host}`;
|
|
} else {
|
|
frontendOrigin = origin;
|
|
}
|
|
|
|
const codeVerifier = generatePkceCodeVerifier();
|
|
const codeChallenge = generatePkceCodeChallenge(codeVerifier);
|
|
|
|
const settingsRepository = createCurrentSettingsRepository();
|
|
await settingsRepository.set(`oidc_state_${state}`, nonce);
|
|
await settingsRepository.set(
|
|
`oidc_backend_callback_${state}`,
|
|
backendCallbackUri,
|
|
);
|
|
await settingsRepository.set(
|
|
`oidc_frontend_origin_${state}`,
|
|
frontendOrigin,
|
|
);
|
|
await settingsRepository.set(
|
|
`oidc_remember_me_${state}`,
|
|
rememberMe === "true" ? "true" : "false",
|
|
);
|
|
await settingsRepository.set(`oidc_pkce_verifier_${state}`, codeVerifier);
|
|
|
|
if (providerDbId != null) {
|
|
await settingsRepository.set(
|
|
`oidc_provider_${state}`,
|
|
String(providerDbId),
|
|
);
|
|
}
|
|
|
|
const authUrl = new URL(config.authorization_url);
|
|
authUrl.searchParams.set("client_id", config.client_id);
|
|
authUrl.searchParams.set("redirect_uri", backendCallbackUri);
|
|
authUrl.searchParams.set("response_type", "code");
|
|
authUrl.searchParams.set("scope", config.scopes);
|
|
authUrl.searchParams.set("state", state);
|
|
authUrl.searchParams.set("nonce", nonce);
|
|
authUrl.searchParams.set("code_challenge", codeChallenge);
|
|
authUrl.searchParams.set("code_challenge_method", "S256");
|
|
|
|
res.json({ auth_url: authUrl.toString(), state, nonce });
|
|
} catch (err) {
|
|
authLogger.error("Failed to generate OIDC auth URL", err);
|
|
res.status(500).json({ error: "Failed to generate authorization URL" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/oidc/callback:
|
|
* get:
|
|
* summary: OIDC callback
|
|
* description: Handles the OIDC callback, exchanges the code for a token, and creates or logs in the user.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 302:
|
|
* description: Redirects to the frontend with a success or error message.
|
|
* 400:
|
|
* description: Code and state are required.
|
|
*/
|
|
router.get("/oidc/callback", async (req, res) => {
|
|
const { code, state } = req.query;
|
|
|
|
if (!isNonEmptyString(code) || !isNonEmptyString(state)) {
|
|
return res.status(400).json({ error: "Code and state are required" });
|
|
}
|
|
|
|
const settingsRepository = createCurrentSettingsRepository();
|
|
const storedBackendCallback = await settingsRepository.get(
|
|
`oidc_backend_callback_${state}`,
|
|
);
|
|
const storedFrontendOrigin = await settingsRepository.get(
|
|
`oidc_frontend_origin_${state}`,
|
|
);
|
|
const storedRememberMeValue = await settingsRepository.get(
|
|
`oidc_remember_me_${state}`,
|
|
);
|
|
const storedCodeVerifier = await settingsRepository.get(
|
|
`oidc_pkce_verifier_${state}`,
|
|
);
|
|
|
|
if (!storedBackendCallback || !storedFrontendOrigin) {
|
|
return res
|
|
.status(400)
|
|
.json({ error: "Invalid state parameter - redirect URIs not found" });
|
|
}
|
|
|
|
const backendCallbackUri = storedBackendCallback;
|
|
const frontendOrigin = storedFrontendOrigin;
|
|
const storedRememberMe = storedRememberMeValue === "true";
|
|
|
|
try {
|
|
const storedNonce = await settingsRepository.get(`oidc_state_${state}`);
|
|
if (!storedNonce) {
|
|
return res.status(400).json({ error: "Invalid state parameter" });
|
|
}
|
|
|
|
const storedProviderId = await settingsRepository.get(
|
|
`oidc_provider_${state}`,
|
|
);
|
|
const callbackProviderId = storedProviderId
|
|
? parseInt(storedProviderId, 10)
|
|
: null;
|
|
|
|
const providerResult = await loadProviderConfig(
|
|
callbackProviderId || undefined,
|
|
);
|
|
if (!providerResult) {
|
|
return res.status(500).json({ error: "OIDC not configured" });
|
|
}
|
|
const {
|
|
config,
|
|
providerType: callbackProviderType,
|
|
providerDbId: callbackProviderDbId,
|
|
} = providerResult;
|
|
|
|
await settingsRepository.delete(`oidc_provider_${state}`);
|
|
|
|
const caCert = config.ca_cert;
|
|
const fetchOptions = buildFetchOptions(caCert);
|
|
|
|
// GitHub does not issue OIDC id_tokens; handle its token exchange separately
|
|
if (callbackProviderType === "github") {
|
|
const ghTokenResponse = await fetch(config.token_url, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
Accept: "application/json",
|
|
},
|
|
body: new URLSearchParams({
|
|
grant_type: "authorization_code",
|
|
client_id: config.client_id,
|
|
client_secret: config.client_secret,
|
|
code: code,
|
|
redirect_uri: backendCallbackUri,
|
|
}),
|
|
...fetchOptions,
|
|
});
|
|
|
|
if (!ghTokenResponse.ok) {
|
|
const errorText = await ghTokenResponse.text();
|
|
authLogger.error("GitHub token exchange failed", {
|
|
operation: "github_token_exchange_failed",
|
|
status: ghTokenResponse.status,
|
|
errorResponse: errorText,
|
|
});
|
|
return res
|
|
.status(400)
|
|
.json({ error: "Failed to exchange authorization code" });
|
|
}
|
|
|
|
const ghTokenData = (await ghTokenResponse.json()) as Record<
|
|
string,
|
|
unknown
|
|
>;
|
|
await deleteOIDCStateSettings(state);
|
|
|
|
const ghUserInfoResponse = await fetch("https://api.github.com/user", {
|
|
headers: {
|
|
Authorization: `Bearer ${ghTokenData.access_token}`,
|
|
Accept: "application/json",
|
|
"User-Agent": "Termix",
|
|
},
|
|
...fetchOptions,
|
|
});
|
|
if (!ghUserInfoResponse.ok) {
|
|
return res
|
|
.status(400)
|
|
.json({ error: "Failed to get GitHub user information" });
|
|
}
|
|
const ghUserInfo = (await ghUserInfoResponse.json()) as Record<
|
|
string,
|
|
unknown
|
|
>;
|
|
|
|
const emailRes = await fetch("https://api.github.com/user/emails", {
|
|
headers: {
|
|
Authorization: `Bearer ${ghTokenData.access_token}`,
|
|
Accept: "application/json",
|
|
"User-Agent": "Termix",
|
|
},
|
|
});
|
|
if (emailRes.ok) {
|
|
const emails = (await emailRes.json()) as Array<{
|
|
email: string;
|
|
primary: boolean;
|
|
verified: boolean;
|
|
}>;
|
|
const primary = emails.find((e) => e.primary && e.verified);
|
|
if (primary) ghUserInfo.email = primary.email;
|
|
}
|
|
|
|
const ghIdentifier = `github:${callbackProviderDbId}:${String(ghUserInfo.id ?? ghUserInfo.login)}`;
|
|
const ghName = (ghUserInfo.name ||
|
|
ghUserInfo.login ||
|
|
ghIdentifier) as string;
|
|
const deviceInfo = parseUserAgent(req);
|
|
const userRepository = createCurrentUserRepository();
|
|
|
|
let ghUserRecord =
|
|
await userRepository.findByOidcIdentifier(ghIdentifier);
|
|
if (!ghUserRecord) {
|
|
const isFirstUser = (await userRepository.countAll()) === 0;
|
|
|
|
if (!isFirstUser && config.allowed_users) {
|
|
const email = ghUserInfo.email as string | undefined;
|
|
if (!isOIDCUserAllowed(config.allowed_users, ghIdentifier, email)) {
|
|
const redirectUrl = new URL(frontendOrigin);
|
|
redirectUrl.searchParams.set("error", "user_not_allowed");
|
|
return res.redirect(redirectUrl.toString());
|
|
}
|
|
}
|
|
|
|
let ghAutoProvision = false;
|
|
try {
|
|
ghAutoProvision = await settingsRepository.getBoolean(
|
|
"oidc_auto_provision",
|
|
false,
|
|
);
|
|
} catch {
|
|
/* */
|
|
}
|
|
if (!ghAutoProvision)
|
|
ghAutoProvision =
|
|
(process.env.OIDC_ALLOW_REGISTRATION || "").trim().toLowerCase() ===
|
|
"true";
|
|
|
|
if (!isFirstUser && !ghAutoProvision) {
|
|
const redirectUrl = new URL(frontendOrigin);
|
|
redirectUrl.searchParams.set("error", "registration_disabled");
|
|
return res.redirect(redirectUrl.toString());
|
|
}
|
|
|
|
const ghId = nanoid();
|
|
const createdUser = await userRepository.createFirstLocalUser({
|
|
id: ghId,
|
|
username: ghName,
|
|
passwordHash: "",
|
|
isOidc: true,
|
|
oidcIdentifier: ghIdentifier,
|
|
ssoProviderId: callbackProviderDbId,
|
|
});
|
|
ghUserRecord = createdUser.user;
|
|
|
|
try {
|
|
const defaultRoleName = createdUser.isFirstUser ? "admin" : "user";
|
|
await createCurrentRoleRepository().assignRoleNameToUser({
|
|
userId: ghId,
|
|
roleName: defaultRoleName,
|
|
grantedBy: ghId,
|
|
});
|
|
} catch {
|
|
/* */
|
|
}
|
|
|
|
try {
|
|
const sessionDurationMs =
|
|
deviceInfo.type === "desktop" || deviceInfo.type === "mobile"
|
|
? 30 * 24 * 60 * 60 * 1000
|
|
: 24 * 60 * 60 * 1000;
|
|
await authManager.registerOIDCUser(ghId, sessionDurationMs);
|
|
} catch {
|
|
await userRepository.delete(ghId);
|
|
return res.status(500).json({
|
|
error: "Failed to setup user security - user creation cancelled",
|
|
});
|
|
}
|
|
}
|
|
|
|
try {
|
|
await authManager.authenticateOIDCUser(
|
|
ghUserRecord.id,
|
|
deviceInfo.type,
|
|
);
|
|
} catch {
|
|
/* */
|
|
}
|
|
await syncSharedCredentialsForUserRoles(
|
|
ghUserRecord.id,
|
|
"github_oidc_role_shared_credentials",
|
|
);
|
|
const ghToken = await authManager.generateJWTToken(ghUserRecord.id, {
|
|
deviceType: deviceInfo.type,
|
|
deviceInfo: deviceInfo.deviceInfo,
|
|
rememberMe: storedRememberMe,
|
|
});
|
|
const ghRedirectUrl = new URL(frontendOrigin);
|
|
ghRedirectUrl.searchParams.set("success", "true");
|
|
const ghIsTokenCallback = isOidcTokenCallback(frontendOrigin);
|
|
const ghMaxAge =
|
|
deviceInfo.type === "desktop" || deviceInfo.type === "mobile"
|
|
? 30 * 24 * 60 * 60 * 1000
|
|
: storedRememberMe
|
|
? 30 * 24 * 60 * 60 * 1000
|
|
: 24 * 60 * 60 * 1000;
|
|
res.clearCookie("jwt", authManager.getClearCookieOptions(req));
|
|
if (ghIsTokenCallback) {
|
|
ghRedirectUrl.searchParams.set("token", ghToken);
|
|
return res.redirect(ghRedirectUrl.toString());
|
|
}
|
|
return res
|
|
.cookie(
|
|
"jwt",
|
|
ghToken,
|
|
authManager.getSecureCookieOptions(req, ghMaxAge),
|
|
)
|
|
.redirect(ghRedirectUrl.toString());
|
|
}
|
|
|
|
const tokenResponse = await fetch(config.token_url, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
Accept: "application/json",
|
|
},
|
|
body: new URLSearchParams({
|
|
grant_type: "authorization_code",
|
|
client_id: config.client_id,
|
|
client_secret: config.client_secret,
|
|
code: code,
|
|
redirect_uri: backendCallbackUri,
|
|
...(storedCodeVerifier ? { code_verifier: storedCodeVerifier } : {}),
|
|
}),
|
|
...fetchOptions,
|
|
});
|
|
|
|
if (!tokenResponse.ok) {
|
|
const errorText = await tokenResponse.text();
|
|
authLogger.error("OIDC token exchange failed", {
|
|
operation: "oidc_token_exchange_failed",
|
|
status: tokenResponse.status,
|
|
statusText: tokenResponse.statusText,
|
|
backendCallbackUri,
|
|
frontendOrigin,
|
|
errorResponse: errorText,
|
|
});
|
|
return res
|
|
.status(400)
|
|
.json({ error: "Failed to exchange authorization code" });
|
|
}
|
|
|
|
const tokenData = (await tokenResponse.json()) as Record<string, unknown>;
|
|
|
|
await deleteOIDCStateSettings(state);
|
|
|
|
let userInfo: Record<string, unknown> = null;
|
|
const oidcClaimSources: Record<string, unknown>[] = [];
|
|
const userInfoUrls: string[] = [];
|
|
|
|
const normalizedIssuerUrl = config.issuer_url.endsWith("/")
|
|
? config.issuer_url.slice(0, -1)
|
|
: config.issuer_url;
|
|
const baseUrl = normalizedIssuerUrl.replace(/\/application\/o\/[^/]+$/, "");
|
|
|
|
try {
|
|
const discoveryUrl = `${normalizedIssuerUrl}/.well-known/openid-configuration`;
|
|
const discoveryResponse = await fetch(discoveryUrl, fetchOptions);
|
|
if (discoveryResponse.ok) {
|
|
const discovery = (await discoveryResponse.json()) as Record<
|
|
string,
|
|
unknown
|
|
>;
|
|
if (discovery.userinfo_endpoint) {
|
|
userInfoUrls.push(discovery.userinfo_endpoint as string);
|
|
}
|
|
}
|
|
} catch (discoveryError) {
|
|
authLogger.error(`OIDC discovery failed: ${discoveryError}`);
|
|
}
|
|
|
|
if (config.userinfo_url) {
|
|
userInfoUrls.unshift(config.userinfo_url);
|
|
}
|
|
|
|
userInfoUrls.push(
|
|
`${baseUrl}/userinfo/`,
|
|
`${baseUrl}/userinfo`,
|
|
`${normalizedIssuerUrl}/userinfo/`,
|
|
`${normalizedIssuerUrl}/userinfo`,
|
|
`${baseUrl}/oauth2/userinfo/`,
|
|
`${baseUrl}/oauth2/userinfo`,
|
|
`${normalizedIssuerUrl}/oauth2/userinfo/`,
|
|
`${normalizedIssuerUrl}/oauth2/userinfo`,
|
|
);
|
|
|
|
if (tokenData.id_token) {
|
|
try {
|
|
userInfo = await verifyOIDCToken(
|
|
tokenData.id_token as string,
|
|
config.issuer_url,
|
|
config.client_id,
|
|
caCert,
|
|
);
|
|
|
|
const expectedNonce = storedNonce;
|
|
if (userInfo.nonce !== expectedNonce) {
|
|
authLogger.warn("OIDC ID token nonce mismatch", {
|
|
operation: "oidc_nonce_mismatch",
|
|
providerId: callbackProviderId,
|
|
});
|
|
return res.status(401).json({ error: "Invalid OIDC token nonce" });
|
|
}
|
|
oidcClaimSources.push(userInfo);
|
|
} catch (error) {
|
|
// A token we cannot parse as a JWS carries no claims we could trust, so
|
|
// fall through to the userinfo endpoint instead of failing the login.
|
|
// Signature and claim failures still reject: those are real rejections.
|
|
if (!(error instanceof OIDCTokenFormatError)) throw error;
|
|
|
|
userInfo = null;
|
|
authLogger.warn(
|
|
"OIDC ID token cannot be verified, falling back to userinfo endpoint",
|
|
{
|
|
operation: "oidc_id_token_unverifiable",
|
|
providerId: callbackProviderId,
|
|
reason: error.message,
|
|
},
|
|
);
|
|
}
|
|
}
|
|
|
|
if (tokenData.access_token) {
|
|
for (const userInfoUrl of userInfoUrls) {
|
|
try {
|
|
const userInfoResponse = await fetch(userInfoUrl, {
|
|
headers: {
|
|
Authorization: `Bearer ${tokenData.access_token}`,
|
|
},
|
|
...fetchOptions,
|
|
});
|
|
|
|
if (userInfoResponse.ok) {
|
|
const fetchedUserInfo = (await userInfoResponse.json()) as Record<
|
|
string,
|
|
unknown
|
|
>;
|
|
oidcClaimSources.push(fetchedUserInfo);
|
|
userInfo = { ...userInfo, ...fetchedUserInfo };
|
|
break;
|
|
} else {
|
|
authLogger.error(
|
|
`Userinfo endpoint ${userInfoUrl} failed with status: ${userInfoResponse.status}`,
|
|
);
|
|
}
|
|
} catch (error) {
|
|
authLogger.error(`Userinfo endpoint ${userInfoUrl} failed:`, error);
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!userInfo) {
|
|
authLogger.error("Failed to get user information from all sources");
|
|
authLogger.error(`Tried userinfo URLs: ${userInfoUrls.join(", ")}`);
|
|
authLogger.error(`Token data keys: ${Object.keys(tokenData).join(", ")}`);
|
|
authLogger.error(`Has id_token: ${!!tokenData.id_token}`);
|
|
authLogger.error(`Has access_token: ${!!tokenData.access_token}`);
|
|
return res.status(400).json({ error: "Failed to get user information" });
|
|
}
|
|
|
|
const getNestedValue = (
|
|
obj: Record<string, unknown>,
|
|
path: string,
|
|
): unknown => {
|
|
if (!path || !obj) return null;
|
|
return path.split(".").reduce((current, key) => current?.[key], obj);
|
|
};
|
|
|
|
const identifier = (getNestedValue(userInfo, config.identifier_path) ||
|
|
userInfo[config.identifier_path] ||
|
|
userInfo.sub ||
|
|
userInfo.email ||
|
|
userInfo.preferred_username) as string;
|
|
|
|
const name = (getNestedValue(userInfo, config.name_path) ||
|
|
userInfo[config.name_path] ||
|
|
userInfo.name ||
|
|
userInfo.given_name ||
|
|
identifier) as string;
|
|
|
|
if (!identifier) {
|
|
authLogger.error(
|
|
`Identifier not found at path: ${config.identifier_path}`,
|
|
);
|
|
authLogger.error(`Available fields: ${Object.keys(userInfo).join(", ")}`);
|
|
return res.status(400).json({
|
|
error: `User identifier not found at path: ${config.identifier_path}. Available fields: ${Object.keys(userInfo).join(", ")}`,
|
|
});
|
|
}
|
|
|
|
const deviceInfo = parseUserAgent(req);
|
|
const userRepository = createCurrentUserRepository();
|
|
let userRecord = await userRepository.findByOidcIdentifier(identifier);
|
|
|
|
let isFirstUser = false;
|
|
if (!userRecord) {
|
|
isFirstUser = (await userRepository.countAll()) === 0;
|
|
|
|
if (!isFirstUser && config.allowed_users) {
|
|
const email = userInfo.email as string | undefined;
|
|
if (!isOIDCUserAllowed(config.allowed_users, identifier, email)) {
|
|
authLogger.warn("OIDC user not in allowed list", {
|
|
operation: "oidc_user_not_allowed",
|
|
identifier,
|
|
email,
|
|
});
|
|
const redirectUrl = new URL(frontendOrigin);
|
|
redirectUrl.searchParams.set("error", "user_not_allowed");
|
|
return res.redirect(redirectUrl.toString());
|
|
}
|
|
}
|
|
|
|
let oidcAutoProvision = false;
|
|
try {
|
|
oidcAutoProvision = await settingsRepository.getBoolean(
|
|
"oidc_auto_provision",
|
|
false,
|
|
);
|
|
} catch {
|
|
// fall through to env var check
|
|
}
|
|
|
|
if (!oidcAutoProvision) {
|
|
oidcAutoProvision =
|
|
(process.env.OIDC_ALLOW_REGISTRATION || "").trim().toLowerCase() ===
|
|
"true";
|
|
}
|
|
|
|
if (!isFirstUser && !oidcAutoProvision) {
|
|
authLogger.warn(
|
|
"OIDC user attempted to register but auto-provisioning is disabled",
|
|
{
|
|
operation: "oidc_registration_disabled",
|
|
identifier,
|
|
name,
|
|
},
|
|
);
|
|
const redirectUrl = new URL(frontendOrigin);
|
|
redirectUrl.searchParams.set("error", "registration_disabled");
|
|
return res.redirect(redirectUrl.toString());
|
|
}
|
|
|
|
const id = nanoid();
|
|
const createdUser = await userRepository.createFirstLocalUser({
|
|
id,
|
|
username: name,
|
|
passwordHash: "",
|
|
isOidc: true,
|
|
oidcIdentifier: identifier,
|
|
ssoProviderId: callbackProviderDbId,
|
|
});
|
|
isFirstUser = createdUser.isFirstUser;
|
|
userRecord = createdUser.user;
|
|
|
|
try {
|
|
const defaultRoleName = isFirstUser ? "admin" : "user";
|
|
const assigned =
|
|
await createCurrentRoleRepository().assignRoleNameToUser({
|
|
userId: id,
|
|
roleName: defaultRoleName,
|
|
grantedBy: id,
|
|
});
|
|
|
|
if (!assigned) {
|
|
authLogger.warn(
|
|
"Default role not found during OIDC user registration",
|
|
{
|
|
operation: "assign_default_role_oidc",
|
|
userId: id,
|
|
roleName: defaultRoleName,
|
|
},
|
|
);
|
|
}
|
|
} catch (roleError) {
|
|
authLogger.error(
|
|
"Failed to assign default role to OIDC user",
|
|
roleError,
|
|
{
|
|
operation: "assign_default_role_oidc",
|
|
userId: id,
|
|
},
|
|
);
|
|
}
|
|
|
|
try {
|
|
const sessionDurationMs =
|
|
deviceInfo.type === "desktop" || deviceInfo.type === "mobile"
|
|
? 30 * 24 * 60 * 60 * 1000
|
|
: 24 * 60 * 60 * 1000;
|
|
await authManager.registerOIDCUser(id, sessionDurationMs);
|
|
} catch (encryptionError) {
|
|
await userRepository.delete(id);
|
|
authLogger.error(
|
|
"Failed to setup OIDC user encryption, user creation rolled back",
|
|
encryptionError,
|
|
{
|
|
operation: "oidc_user_create_encryption_failed",
|
|
userId: id,
|
|
},
|
|
);
|
|
return res.status(500).json({
|
|
error: "Failed to setup user security - user creation cancelled",
|
|
});
|
|
}
|
|
|
|
try {
|
|
await DatabaseSaveTrigger.forceSave("oidc_user_create_explicit_save");
|
|
} catch (saveError) {
|
|
authLogger.error("Failed to persist OIDC user to disk", saveError, {
|
|
operation: "oidc_user_create_save_failed",
|
|
userId: id,
|
|
});
|
|
}
|
|
} else {
|
|
if (config.allowed_users) {
|
|
const email = userInfo.email as string | undefined;
|
|
if (!isOIDCUserAllowed(config.allowed_users, identifier, email)) {
|
|
authLogger.warn("OIDC user not in allowed list (existing user)", {
|
|
operation: "oidc_user_not_allowed_existing",
|
|
identifier,
|
|
email,
|
|
userId: userRecord.id,
|
|
});
|
|
const redirectUrl = new URL(frontendOrigin);
|
|
redirectUrl.searchParams.set("error", "user_not_allowed");
|
|
return res.redirect(redirectUrl.toString());
|
|
}
|
|
}
|
|
|
|
const isDualAuth =
|
|
userRecord.passwordHash && userRecord.passwordHash.trim() !== "";
|
|
|
|
if (!isDualAuth) {
|
|
userRecord =
|
|
(await userRepository.update(userRecord.id, { username: name })) ??
|
|
userRecord;
|
|
}
|
|
}
|
|
|
|
// Sync admin status based on OIDC group membership
|
|
if (config.admin_group) {
|
|
const groups = extractOidcGroupsFromSources(
|
|
oidcClaimSources,
|
|
config.group_claim,
|
|
);
|
|
|
|
authLogger.info(
|
|
`Evaluating OIDC admin group sync. parsedGroups: ${JSON.stringify(groups)}, configuredAdminGroup: ${config.admin_group}, groupClaim: ${config.group_claim || "(default)"}, availableUserInfoKeys: ${Object.keys(userInfo).join(",")}`,
|
|
{
|
|
operation: "oidc_admin_group_sync_eval",
|
|
userId: userRecord.id,
|
|
},
|
|
);
|
|
|
|
const shouldBeAdmin = groups.includes(config.admin_group);
|
|
if (!!userRecord.isAdmin !== shouldBeAdmin) {
|
|
authLogger.info("Syncing admin status based on OIDC group membership", {
|
|
operation: "oidc_admin_group_sync",
|
|
userId: userRecord.id,
|
|
group: config.admin_group,
|
|
isAdmin: shouldBeAdmin,
|
|
});
|
|
userRecord =
|
|
(await userRepository.update(userRecord.id, {
|
|
isAdmin: shouldBeAdmin,
|
|
})) ?? userRecord;
|
|
try {
|
|
const newRoleName = shouldBeAdmin ? "admin" : "user";
|
|
const oldRoleName = shouldBeAdmin ? "user" : "admin";
|
|
await createCurrentRoleRepository().switchUserRoleName({
|
|
userId: userRecord.id,
|
|
addRoleName: newRoleName,
|
|
removeRoleName: oldRoleName,
|
|
grantedBy: userRecord.id,
|
|
});
|
|
} catch {
|
|
/* non-fatal */
|
|
}
|
|
authLogger.info("OIDC admin status synced", {
|
|
operation: "oidc_admin_group_sync",
|
|
userId: userRecord.id,
|
|
group: config.admin_group,
|
|
isAdmin: shouldBeAdmin,
|
|
});
|
|
}
|
|
}
|
|
|
|
// Sync RBAC roles from provider group membership (OIDC_ROLE_MAP).
|
|
//
|
|
// This is what makes environment-scoped access work without hand-assigning
|
|
// roles: map a provider group to a Termix role, grant that role access to a
|
|
// set of hosts once, and membership follows the identity provider.
|
|
//
|
|
// Only roles named in the map are touched. Roles assigned by hand, and the
|
|
// admin/user pair maintained by the admin-group sync above, are never
|
|
// removed here — otherwise this would fight that block on every login.
|
|
//
|
|
// Non-fatal by design: a role-sync failure must not block a valid login.
|
|
try {
|
|
const roleMap = parseOidcRoleMap(
|
|
config.role_map ?? process.env.OIDC_ROLE_MAP,
|
|
);
|
|
|
|
if (roleMap.size > 0) {
|
|
const groups = extractOidcGroupsFromSources(
|
|
oidcClaimSources,
|
|
config.group_claim,
|
|
);
|
|
const { desired, managed } = resolveOidcMappedRoles(groups, roleMap);
|
|
|
|
const roleRepository = createCurrentRoleRepository();
|
|
const currentRoles = await roleRepository.listUserRoles(userRecord.id);
|
|
const currentNames = new Set(currentRoles.map((r) => r.roleName));
|
|
|
|
const toAdd = [...desired].filter((name) => !currentNames.has(name));
|
|
const toRemove = currentRoles.filter(
|
|
(r) => managed.has(r.roleName) && !desired.has(r.roleName),
|
|
);
|
|
|
|
authLogger.info(
|
|
`Evaluating OIDC role map sync. parsedGroups: ${JSON.stringify(groups)}, desiredRoles: ${JSON.stringify([...desired])}, managedRoles: ${JSON.stringify([...managed])}, groupClaim: ${config.group_claim || "(default)"}`,
|
|
{
|
|
operation: "oidc_role_map_sync_eval",
|
|
userId: userRecord.id,
|
|
},
|
|
);
|
|
|
|
for (const roleName of toAdd) {
|
|
const assigned = await roleRepository.assignRoleNameToUser({
|
|
userId: userRecord.id,
|
|
roleName,
|
|
grantedBy: userRecord.id,
|
|
});
|
|
if (!assigned) {
|
|
authLogger.warn(
|
|
"OIDC role map references a role that does not exist",
|
|
{
|
|
operation: "oidc_role_map_missing_role",
|
|
userId: userRecord.id,
|
|
roleName,
|
|
},
|
|
);
|
|
}
|
|
}
|
|
|
|
for (const role of toRemove) {
|
|
await roleRepository.removeRoleFromUser(userRecord.id, role.roleId);
|
|
}
|
|
|
|
if (toAdd.length > 0 || toRemove.length > 0) {
|
|
authLogger.info("OIDC roles synced from group membership", {
|
|
operation: "oidc_role_map_sync",
|
|
userId: userRecord.id,
|
|
added: toAdd,
|
|
removed: toRemove.map((r) => r.roleName),
|
|
});
|
|
// Host access is resolved through cached role permissions; drop the
|
|
// cache so the new roles apply to this session immediately.
|
|
PermissionManager.getInstance().invalidateUserPermissionCache(
|
|
userRecord.id,
|
|
);
|
|
}
|
|
}
|
|
} catch (roleSyncError) {
|
|
authLogger.error("Failed to sync OIDC roles", roleSyncError, {
|
|
operation: "oidc_role_map_sync_failed",
|
|
userId: userRecord.id,
|
|
});
|
|
}
|
|
|
|
try {
|
|
await authManager.authenticateOIDCUser(userRecord.id, deviceInfo.type);
|
|
} catch (setupError) {
|
|
authLogger.error("Failed to setup OIDC user encryption", setupError, {
|
|
operation: "oidc_user_encryption_setup_failed",
|
|
userId: userRecord.id,
|
|
});
|
|
}
|
|
|
|
await syncSharedCredentialsForUserRoles(
|
|
userRecord.id,
|
|
"oidc_role_shared_credentials",
|
|
);
|
|
|
|
const oidcSub = typeof userInfo.sub === "string" ? userInfo.sub : null;
|
|
const oidcSid = typeof userInfo.sid === "string" ? userInfo.sid : null;
|
|
|
|
const token = await authManager.generateJWTToken(userRecord.id, {
|
|
deviceType: deviceInfo.type,
|
|
deviceInfo: deviceInfo.deviceInfo,
|
|
rememberMe: storedRememberMe,
|
|
oidcSub,
|
|
oidcSid,
|
|
ssoProviderId: callbackProviderDbId ?? null,
|
|
});
|
|
|
|
authLogger.success("OIDC login successful", {
|
|
operation: "oidc_login_complete",
|
|
userId: userRecord.id,
|
|
username: userRecord.username,
|
|
});
|
|
|
|
const redirectUrl = new URL(frontendOrigin);
|
|
redirectUrl.searchParams.set("success", "true");
|
|
|
|
const isTokenCallback = isOidcTokenCallback(frontendOrigin);
|
|
|
|
const maxAge =
|
|
deviceInfo.type === "desktop" || deviceInfo.type === "mobile"
|
|
? 30 * 24 * 60 * 60 * 1000
|
|
: storedRememberMe
|
|
? 30 * 24 * 60 * 60 * 1000
|
|
: 24 * 60 * 60 * 1000;
|
|
|
|
res.clearCookie("jwt", authManager.getClearCookieOptions(req));
|
|
|
|
if (isTokenCallback) {
|
|
redirectUrl.searchParams.set("token", token);
|
|
return res.redirect(redirectUrl.toString());
|
|
}
|
|
|
|
return res
|
|
.cookie("jwt", token, authManager.getSecureCookieOptions(req, maxAge))
|
|
.redirect(redirectUrl.toString());
|
|
} catch (err) {
|
|
authLogger.error("OIDC callback failed", err);
|
|
|
|
const redirectUrl = new URL(frontendOrigin);
|
|
redirectUrl.searchParams.set("error", "OIDC authentication failed");
|
|
|
|
res.redirect(redirectUrl.toString());
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/login:
|
|
* post:
|
|
* summary: User login
|
|
* description: Authenticates a user and returns a JWT.
|
|
* tags:
|
|
* - Users
|
|
* requestBody:
|
|
* required: true
|
|
* content:
|
|
* application/json:
|
|
* schema:
|
|
* type: object
|
|
* properties:
|
|
* username:
|
|
* type: string
|
|
* password:
|
|
* type: string
|
|
* responses:
|
|
* 200:
|
|
* description: Login successful.
|
|
* 400:
|
|
* description: Invalid username or password.
|
|
* 401:
|
|
* description: Invalid username or password.
|
|
* 403:
|
|
* description: Password authentication is currently disabled.
|
|
* 429:
|
|
* description: Too many login attempts.
|
|
* 500:
|
|
* description: Login failed.
|
|
*/
|
|
router.post("/proxy-login", async (req, res) => {
|
|
let config;
|
|
try {
|
|
config = getTrustedProxyAuthConfig();
|
|
} catch (error) {
|
|
authLogger.error(
|
|
"Invalid trusted proxy authentication configuration",
|
|
error,
|
|
);
|
|
return res
|
|
.status(503)
|
|
.json({ error: "Proxy authentication is misconfigured" });
|
|
}
|
|
if (!config.enabled) return res.json({ enabled: false });
|
|
|
|
const sourceAddress = req.socket.remoteAddress;
|
|
try {
|
|
if (!isTrustedProxyAddress(sourceAddress, config.trustedProxies)) {
|
|
authLogger.warn(
|
|
"Rejected proxy authentication from an untrusted source",
|
|
{
|
|
operation: "trusted_proxy_auth_rejected",
|
|
sourceAddress,
|
|
},
|
|
);
|
|
return res.status(403).json({ error: "Untrusted authentication proxy" });
|
|
}
|
|
} catch (error) {
|
|
authLogger.error("Invalid trusted proxy allowlist", error);
|
|
return res
|
|
.status(503)
|
|
.json({ error: "Proxy authentication is misconfigured" });
|
|
}
|
|
|
|
const usernameValue = req.headers[config.usernameHeader];
|
|
const roleValue = req.headers[config.roleHeader];
|
|
const username = Array.isArray(usernameValue)
|
|
? usernameValue[0]
|
|
: usernameValue;
|
|
const roleHeader = Array.isArray(roleValue) ? roleValue[0] : roleValue;
|
|
if (!isNonEmptyString(username) || !isNonEmptyString(roleHeader)) {
|
|
return res
|
|
.status(401)
|
|
.json({ error: "Proxy authentication headers are missing" });
|
|
}
|
|
|
|
const mappedRoles = resolveTrustedProxyRoles(roleHeader, config.roleMap);
|
|
if (!mappedRoles) {
|
|
return res.status(403).json({ error: "Proxy role is not mapped" });
|
|
}
|
|
|
|
try {
|
|
const [legacyOidc, enabledProviders, userRecord] = await Promise.all([
|
|
createCurrentSettingsRepository().get("oidc_config"),
|
|
createCurrentSsoProviderRepository().listEnabled(),
|
|
createCurrentUserRepository().findByUsername(username),
|
|
]);
|
|
const hasOidc =
|
|
Boolean(getOIDCConfigFromEnv() || legacyOidc) ||
|
|
enabledProviders.some((provider) =>
|
|
["oidc", "github", "google"].includes(provider.type),
|
|
);
|
|
if (hasOidc) {
|
|
return res
|
|
.status(409)
|
|
.json({ error: "Proxy authentication cannot be used with OIDC" });
|
|
}
|
|
if (!userRecord) {
|
|
return res.status(403).json({ error: "Proxy user must already exist" });
|
|
}
|
|
if (userRecord.isOidc || userRecord.totpEnabled) {
|
|
return res.status(409).json({
|
|
error: "Proxy authentication cannot be used with OIDC or TOTP users",
|
|
});
|
|
}
|
|
|
|
const roleRepository = createCurrentRoleRepository();
|
|
const managedRoles = new Set([...config.roleMap.values()].flat());
|
|
for (const roleName of managedRoles) {
|
|
if (!(await roleRepository.findRoleByName(roleName))) {
|
|
authLogger.error("Trusted proxy role map references a missing role", {
|
|
operation: "trusted_proxy_auth_missing_role",
|
|
roleName,
|
|
});
|
|
return res
|
|
.status(503)
|
|
.json({ error: "Proxy role mapping is misconfigured" });
|
|
}
|
|
}
|
|
|
|
const currentRoles = await roleRepository.listUserRoles(userRecord.id);
|
|
const currentNames = new Set(currentRoles.map((role) => role.roleName));
|
|
for (const roleName of mappedRoles) {
|
|
if (!currentNames.has(roleName)) {
|
|
await roleRepository.assignRoleNameToUser({
|
|
userId: userRecord.id,
|
|
roleName,
|
|
grantedBy: userRecord.id,
|
|
});
|
|
}
|
|
}
|
|
for (const role of currentRoles) {
|
|
if (
|
|
managedRoles.has(role.roleName) &&
|
|
!mappedRoles.includes(role.roleName)
|
|
) {
|
|
await roleRepository.removeRoleFromUser(userRecord.id, role.roleId);
|
|
}
|
|
}
|
|
PermissionManager.getInstance().invalidateUserPermissionCache(
|
|
userRecord.id,
|
|
);
|
|
|
|
const deviceInfo = parseUserAgent(req);
|
|
if (
|
|
!(await authManager.authenticateWebAuthnUser(
|
|
userRecord.id,
|
|
deviceInfo.type,
|
|
))
|
|
) {
|
|
return res
|
|
.status(409)
|
|
.json({ error: "User encryption data is unavailable" });
|
|
}
|
|
await syncSharedCredentialsForUserRoles(
|
|
userRecord.id,
|
|
"trusted_proxy_login_role_shared_credentials",
|
|
);
|
|
const token = await authManager.generateJWTToken(userRecord.id, {
|
|
deviceType: deviceInfo.type,
|
|
deviceInfo: deviceInfo.deviceInfo,
|
|
});
|
|
const payload = await authManager.verifyJWTToken(token);
|
|
const { ipAddress, userAgent } = getRequestMeta(req);
|
|
await logAudit({
|
|
userId: userRecord.id,
|
|
username: userRecord.username,
|
|
action: "trusted_proxy_login",
|
|
resourceType: "session",
|
|
ipAddress,
|
|
userAgent,
|
|
success: true,
|
|
});
|
|
authLogger.success("Trusted proxy login successful", {
|
|
operation: "trusted_proxy_login",
|
|
userId: userRecord.id,
|
|
sessionId: payload?.sessionId,
|
|
mappedRoles,
|
|
});
|
|
|
|
return res
|
|
.cookie("jwt", token, authManager.getSecureCookieOptions(req))
|
|
.json({
|
|
enabled: true,
|
|
success: true,
|
|
username: userRecord.username,
|
|
userId: userRecord.id,
|
|
is_admin: !!userRecord.isAdmin,
|
|
...(isNativeAppRequest(req) ? { token } : {}),
|
|
});
|
|
} catch (error) {
|
|
authLogger.error("Trusted proxy login failed", error);
|
|
return res.status(500).json({ error: "Proxy authentication failed" });
|
|
}
|
|
});
|
|
|
|
router.post("/login", async (req, res) => {
|
|
if (isTrustedProxyAuthEnabled()) {
|
|
return res.status(403).json({
|
|
error:
|
|
"Password login is disabled while trusted proxy authentication is enabled",
|
|
});
|
|
}
|
|
const { username, password, rememberMe } = req.body;
|
|
const clientIp = req.ip || req.socket.remoteAddress || "unknown";
|
|
authLogger.info("User login request received", {
|
|
operation: "user_login_request",
|
|
username,
|
|
});
|
|
|
|
if (!isNonEmptyString(username) || !isNonEmptyString(password)) {
|
|
authLogger.warn("Invalid traditional login attempt", {
|
|
operation: "user_login",
|
|
hasUsername: !!username,
|
|
hasPassword: !!password,
|
|
});
|
|
return res.status(400).json({ error: "Invalid username or password" });
|
|
}
|
|
|
|
const lockStatus = loginRateLimiter.isLocked(clientIp, username);
|
|
if (lockStatus.locked) {
|
|
authLogger.warn("Login attempt blocked due to rate limiting", {
|
|
operation: "user_login_blocked",
|
|
username,
|
|
ip: clientIp,
|
|
remainingTime: lockStatus.remainingTime,
|
|
});
|
|
return res.status(429).json({
|
|
error: "Too many login attempts. Please try again later.",
|
|
remainingTime: lockStatus.remainingTime,
|
|
});
|
|
}
|
|
|
|
if (!isPasswordLoginAllowed()) {
|
|
return res
|
|
.status(403)
|
|
.json({ error: "Password authentication is currently disabled" });
|
|
}
|
|
|
|
try {
|
|
const userRecord =
|
|
await createCurrentUserRepository().findByUsername(username);
|
|
|
|
if (!userRecord) {
|
|
loginRateLimiter.recordFailedAttempt(clientIp, username);
|
|
authLogger.warn(`Login failed: user not found`, {
|
|
operation: "user_login",
|
|
username,
|
|
ip: clientIp,
|
|
remainingAttempts: loginRateLimiter.getRemainingAttempts(
|
|
clientIp,
|
|
username,
|
|
),
|
|
});
|
|
return res.status(401).json({ error: "Invalid username or password" });
|
|
}
|
|
|
|
if (
|
|
userRecord.isOidc &&
|
|
(!userRecord.passwordHash || userRecord.passwordHash.trim() === "")
|
|
) {
|
|
authLogger.warn("OIDC-only user attempted traditional login", {
|
|
operation: "user_login",
|
|
username,
|
|
userId: userRecord.id,
|
|
});
|
|
return res
|
|
.status(403)
|
|
.json({ error: "This user uses external authentication" });
|
|
}
|
|
|
|
const isMatch = await bcrypt.compare(password, userRecord.passwordHash);
|
|
if (!isMatch) {
|
|
loginRateLimiter.recordFailedAttempt(clientIp, username);
|
|
authLogger.warn(`Login failed: incorrect password`, {
|
|
operation: "user_login",
|
|
username,
|
|
userId: userRecord.id,
|
|
ip: clientIp,
|
|
remainingAttempts: loginRateLimiter.getRemainingAttempts(
|
|
clientIp,
|
|
username,
|
|
),
|
|
});
|
|
return res.status(401).json({ error: "Invalid username or password" });
|
|
}
|
|
|
|
const deviceInfo = parseUserAgent(req);
|
|
|
|
let authenticated = false;
|
|
if (userRecord.isOidc) {
|
|
authenticated = await authManager.authenticateOIDCUser(
|
|
userRecord.id,
|
|
deviceInfo.type,
|
|
);
|
|
} else {
|
|
authenticated = await authManager.authenticateUser(
|
|
userRecord.id,
|
|
password,
|
|
deviceInfo.type,
|
|
);
|
|
}
|
|
|
|
if (!authenticated) {
|
|
return res.status(401).json({ error: "Incorrect password" });
|
|
}
|
|
|
|
await syncSharedCredentialsForUserRoles(
|
|
userRecord.id,
|
|
"login_role_shared_credentials",
|
|
);
|
|
|
|
if (userRecord.totpEnabled) {
|
|
const deviceFingerprint = generateDeviceFingerprint(
|
|
deviceInfo,
|
|
getDeviceId(req),
|
|
);
|
|
|
|
const isTrusted = deviceFingerprint
|
|
? await authManager.isTrustedDevice(userRecord.id, deviceFingerprint)
|
|
: false;
|
|
|
|
if (isTrusted) {
|
|
authLogger.info("TOTP bypassed for trusted device", {
|
|
operation: "totp_bypass",
|
|
userId: userRecord.id,
|
|
deviceFingerprint,
|
|
});
|
|
} else {
|
|
const tempToken = await authManager.generateJWTToken(userRecord.id, {
|
|
pendingTOTP: true,
|
|
expiresIn: "10m",
|
|
});
|
|
return res.json({
|
|
success: true,
|
|
requires_totp: true,
|
|
temp_token: tempToken,
|
|
rememberMe: !!rememberMe,
|
|
});
|
|
}
|
|
}
|
|
|
|
const token = await authManager.generateJWTToken(userRecord.id, {
|
|
rememberMe: !!rememberMe,
|
|
deviceType: deviceInfo.type,
|
|
deviceInfo: deviceInfo.deviceInfo,
|
|
});
|
|
|
|
loginRateLimiter.resetAttempts(clientIp, username);
|
|
|
|
const payload = await authManager.verifyJWTToken(token);
|
|
authLogger.success("User login successful", {
|
|
operation: "user_login_complete",
|
|
userId: userRecord.id,
|
|
username,
|
|
sessionId: payload?.sessionId,
|
|
});
|
|
|
|
const { ipAddress: loginIp, userAgent: loginUa } = getRequestMeta(req);
|
|
await logAudit({
|
|
userId: userRecord.id,
|
|
username,
|
|
action: "login",
|
|
resourceType: "session",
|
|
ipAddress: loginIp,
|
|
userAgent: loginUa,
|
|
success: true,
|
|
});
|
|
|
|
notifyAutomationInternalEvent("user_login", userRecord.id, undefined, {
|
|
username,
|
|
ipAddress: loginIp,
|
|
});
|
|
|
|
const response: Record<string, unknown> = {
|
|
success: true,
|
|
is_admin: !!userRecord.isAdmin,
|
|
username: userRecord.username,
|
|
...(isNativeAppRequest(req) ? { token } : {}),
|
|
};
|
|
|
|
const sessionTimeoutHoursValue =
|
|
await createCurrentSettingsRepository().get("session_timeout_hours");
|
|
const timeoutHours = sessionTimeoutHoursValue
|
|
? parseInt(sessionTimeoutHoursValue, 10) || 24
|
|
: 24;
|
|
const maxAge = rememberMe
|
|
? 30 * 24 * 60 * 60 * 1000
|
|
: timeoutHours * 60 * 60 * 1000;
|
|
|
|
return res
|
|
.cookie("jwt", token, authManager.getSecureCookieOptions(req, maxAge))
|
|
.json(response);
|
|
} catch (err) {
|
|
authLogger.error("Failed to log in user", err);
|
|
return res.status(500).json({ error: "Login failed" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/logout:
|
|
* post:
|
|
* summary: User logout
|
|
* description: Logs out the user and clears the JWT cookie.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: Logged out successfully.
|
|
* 500:
|
|
* description: Logout failed.
|
|
*/
|
|
router.post("/logout", authenticateJWT, async (req, res) => {
|
|
try {
|
|
const authReq = req as AuthenticatedRequest;
|
|
const userId = authReq.userId;
|
|
|
|
if (userId) {
|
|
const sessionId = authReq.sessionId;
|
|
|
|
await authManager.logoutUser(userId, sessionId);
|
|
authLogger.info("User logged out", {
|
|
operation: "user_logout",
|
|
userId,
|
|
sessionId,
|
|
});
|
|
}
|
|
|
|
return res
|
|
.clearCookie("jwt", authManager.getClearCookieOptions(req))
|
|
.json({ success: true, message: "Logged out successfully" });
|
|
} catch (err) {
|
|
authLogger.error("Logout failed", err);
|
|
return res.status(500).json({ error: "Logout failed" });
|
|
}
|
|
});
|
|
|
|
const seenLogoutJti = new Map<string, number>();
|
|
const LOGOUT_JTI_TTL_MS = 5 * 60 * 1000;
|
|
|
|
function pruneLogoutJti(now: number): void {
|
|
for (const [key, expiry] of seenLogoutJti) {
|
|
if (expiry <= now) seenLogoutJti.delete(key);
|
|
}
|
|
}
|
|
|
|
function isReplayedJti(jti: string): boolean {
|
|
const now = Date.now();
|
|
pruneLogoutJti(now);
|
|
return seenLogoutJti.has(jti);
|
|
}
|
|
|
|
function markLogoutJti(jti: string): void {
|
|
const now = Date.now();
|
|
pruneLogoutJti(now);
|
|
seenLogoutJti.set(jti, now + LOGOUT_JTI_TTL_MS);
|
|
}
|
|
|
|
router.post("/oidc/backchannel-logout", async (req, res) => {
|
|
res.setHeader("Cache-Control", "no-store");
|
|
|
|
try {
|
|
const logoutToken = (req.body as Record<string, unknown> | undefined)
|
|
?.logout_token;
|
|
if (typeof logoutToken !== "string" || !logoutToken) {
|
|
return res.status(400).json({ error: "missing logout_token" });
|
|
}
|
|
|
|
let issuer: string | null = null;
|
|
try {
|
|
const parts = logoutToken.split(".");
|
|
if (parts.length === 3) {
|
|
const claims = JSON.parse(Buffer.from(parts[1], "base64").toString());
|
|
issuer = typeof claims.iss === "string" ? claims.iss : null;
|
|
}
|
|
} catch {
|
|
issuer = null;
|
|
}
|
|
|
|
if (!issuer) {
|
|
return res.status(400).json({ error: "invalid logout_token" });
|
|
}
|
|
|
|
const provider = await resolveProviderByIssuer(issuer);
|
|
if (!provider) {
|
|
authLogger.warn("Back-channel logout for unknown issuer", { issuer });
|
|
return res.status(400).json({ error: "unknown issuer" });
|
|
}
|
|
|
|
const claims = await validateLogoutToken(logoutToken, provider.config);
|
|
|
|
if (claims.jti && isReplayedJti(claims.jti)) {
|
|
return res.status(200).json({ ok: true });
|
|
}
|
|
|
|
try {
|
|
await authManager.revokeSessionsByOidc({
|
|
ssoProviderId: provider.providerDbId,
|
|
sub: claims.sub,
|
|
sid: claims.sid,
|
|
});
|
|
} catch (err) {
|
|
authLogger.error("OIDC back-channel session revocation failed", err);
|
|
return res.status(500).json({ error: "logout processing failed" });
|
|
}
|
|
|
|
markLogoutJti(claims.jti);
|
|
|
|
return res.status(200).json({ ok: true });
|
|
} catch (err) {
|
|
authLogger.error("OIDC back-channel logout failed", err);
|
|
return res.status(400).json({ error: "invalid logout_token" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/me:
|
|
* get:
|
|
* summary: Get current user's info
|
|
* description: Retrieves information about the currently authenticated user.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: User information.
|
|
* 401:
|
|
* description: Invalid userId or user not found.
|
|
* 500:
|
|
* description: Failed to get username.
|
|
*/
|
|
router.get("/me", authenticateJWT, async (req: Request, res: Response) => {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
|
|
if (!isNonEmptyString(userId)) {
|
|
authLogger.warn("Invalid userId in JWT for /users/me");
|
|
return res.status(401).json({ error: "Invalid userId" });
|
|
}
|
|
try {
|
|
const user = await findCurrentUser(userId);
|
|
if (!user) {
|
|
authLogger.warn(`User not found for /users/me: ${userId}`);
|
|
return res.status(401).json({ error: "User not found" });
|
|
}
|
|
|
|
const hasPassword = user.passwordHash && user.passwordHash.trim() !== "";
|
|
const hasOidc = user.isOidc && user.oidcIdentifier;
|
|
const isDualAuth = hasPassword && hasOidc;
|
|
|
|
const showDonationModal = shouldShowDonationModal(
|
|
user.registeredAt,
|
|
!!user.donationModalDismissed,
|
|
);
|
|
|
|
res.json({
|
|
userId: user.id,
|
|
username: user.username,
|
|
is_admin: !!user.isAdmin,
|
|
is_oidc: !!user.isOidc,
|
|
is_dual_auth: isDualAuth,
|
|
totp_enabled: !!user.totpEnabled,
|
|
show_donation_modal: showDonationModal,
|
|
});
|
|
} catch (err) {
|
|
authLogger.error("Failed to get username", err);
|
|
res.status(500).json({ error: "Failed to get username" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/me/dismiss-donation-modal:
|
|
* post:
|
|
* summary: Permanently dismiss the donation reminder modal
|
|
* description: Marks the donation reminder modal as dismissed for the currently authenticated user so it is never shown to them again.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: Donation modal dismissed.
|
|
* 401:
|
|
* description: Invalid userId or user not found.
|
|
* 500:
|
|
* description: Failed to dismiss donation modal.
|
|
*/
|
|
router.post(
|
|
"/me/dismiss-donation-modal",
|
|
authenticateJWT,
|
|
async (req: Request, res: Response) => {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
|
|
if (!isNonEmptyString(userId)) {
|
|
return res.status(401).json({ error: "Invalid userId" });
|
|
}
|
|
try {
|
|
const updated = await createCurrentUserRepository().update(userId, {
|
|
donationModalDismissed: true,
|
|
});
|
|
if (!updated) {
|
|
return res.status(401).json({ error: "User not found" });
|
|
}
|
|
return res.json({ success: true });
|
|
} catch (err) {
|
|
authLogger.error("Failed to dismiss donation modal", err);
|
|
return res
|
|
.status(500)
|
|
.json({ error: "Failed to dismiss donation modal" });
|
|
}
|
|
},
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/me/token:
|
|
* get:
|
|
* summary: Get current session token
|
|
* description: Returns the JWT for the currently authenticated native Mobile or Desktop client. Browser sessions cannot export their HTTP-only cookie.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: Current session token.
|
|
* content:
|
|
* application/json:
|
|
* schema:
|
|
* type: object
|
|
* properties:
|
|
* token:
|
|
* type: string
|
|
* 401:
|
|
* description: Not authenticated.
|
|
* 403:
|
|
* description: Token export is not available to browser clients.
|
|
*/
|
|
router.get("/me/token", authenticateJWT, (req: Request, res: Response) => {
|
|
if (!isNativeTokenExportRequest(req)) {
|
|
return res
|
|
.status(403)
|
|
.json({ error: "Token export is limited to native clients" });
|
|
}
|
|
|
|
// authenticateJWT accepts either the jwt cookie or an Authorization:
|
|
// Bearer header (see auth-manager.ts's createAuthMiddleware) -- this must
|
|
// check both too, or a request that only carried the header (e.g. the
|
|
// Electron renderer's own axios interceptor, which always attaches a
|
|
// stored localStorage JWT as a Bearer header) would pass authentication
|
|
// here but still get back a null token.
|
|
res.json({ token: extractBearerOrCookieToken(req) ?? null });
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/setup-required:
|
|
* get:
|
|
* summary: Check if setup is required
|
|
* description: Checks if the system requires initial setup (i.e., no users exist).
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: Setup status.
|
|
* 500:
|
|
* description: Failed to check setup status.
|
|
*/
|
|
router.get("/setup-required", async (req, res) => {
|
|
try {
|
|
const count = await createCurrentUserRepository().countAll();
|
|
|
|
res.json({
|
|
setup_required: count === 0,
|
|
});
|
|
} catch (err) {
|
|
authLogger.error("Failed to check setup status", err);
|
|
res.status(500).json({ error: "Failed to check setup status" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/internal/auto-session:
|
|
* post:
|
|
* summary: Mint a session for the sole local desktop user
|
|
* description: Used by the Electron desktop app to skip the login form entirely when running standalone against the embedded local backend. Only available over loopback. Logs in as the sole local user regardless of its credentials; if the local database has more than one user (e.g. repeated manual registration), deterministically logs in as the admin account, or the earliest-registered account if none is admin -- a login form must never appear for the local backend under any circumstance. Only declines if zero local users exist at all, which normal desktop provisioning never produces. Provisions the resolved user's data-encryption key if missing before minting the session, matching every other login path -- self-heals an account that previously ended up with a valid session but no usable encryption key.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: Session created.
|
|
* 403:
|
|
* description: Forbidden, or no local users exist.
|
|
* 500:
|
|
* description: Failed to create session.
|
|
*/
|
|
router.post("/internal/auto-session", async (req, res) => {
|
|
try {
|
|
if (!isLoopbackRequest(req)) {
|
|
authLogger.warn(
|
|
"Rejected non-loopback attempt to access auto-session endpoint",
|
|
{ source: req.ip },
|
|
);
|
|
return res.status(403).json({ error: "Forbidden" });
|
|
}
|
|
|
|
const userRepository = createCurrentUserRepository();
|
|
const allUsers = await userRepository.listAll();
|
|
const userRecord = resolveDesktopAutoSessionUser(allUsers);
|
|
if (!userRecord) {
|
|
return res.status(403).json({
|
|
error: "No local users exist",
|
|
});
|
|
}
|
|
await authManager.registerUser(userRecord.id);
|
|
const existingToken = extractBearerOrCookieToken(req);
|
|
if (existingToken) {
|
|
const existingPayload = await authManager.verifyJWTToken(existingToken);
|
|
if (existingPayload?.userId === userRecord.id) {
|
|
return res.json({
|
|
success: true,
|
|
is_admin: !!userRecord.isAdmin,
|
|
username: userRecord.username,
|
|
token: existingToken,
|
|
});
|
|
}
|
|
}
|
|
|
|
const token = await authManager.generateJWTToken(userRecord.id, {
|
|
deviceType: "desktop",
|
|
deviceInfo: "Termix Desktop (local)",
|
|
rememberMe: true,
|
|
});
|
|
|
|
const response = {
|
|
success: true,
|
|
is_admin: !!userRecord.isAdmin,
|
|
username: userRecord.username,
|
|
token,
|
|
};
|
|
|
|
return res
|
|
.cookie(
|
|
"jwt",
|
|
token,
|
|
authManager.getSecureCookieOptions(req, 30 * 24 * 60 * 60 * 1000),
|
|
)
|
|
.json(response);
|
|
} catch (err) {
|
|
authLogger.error("Failed to create auto-session", err);
|
|
res.status(500).json({ error: "Failed to create auto-session" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/count:
|
|
* get:
|
|
* summary: Count users
|
|
* description: Returns the total number of users in the system.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: User count.
|
|
* 403:
|
|
* description: Admin access required.
|
|
* 500:
|
|
* description: Failed to count users.
|
|
*/
|
|
router.get("/count", authenticateJWT, async (req, res) => {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
try {
|
|
const user = await requireCurrentAdmin(userId);
|
|
if (!user) {
|
|
return res.status(403).json({ error: "Admin access required" });
|
|
}
|
|
|
|
const count = await createCurrentUserRepository().countAll();
|
|
res.json({ count });
|
|
} catch (err) {
|
|
authLogger.error("Failed to count users", err);
|
|
res.status(500).json({ error: "Failed to count users" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/db-health:
|
|
* get:
|
|
* summary: Database health check
|
|
* description: Checks if the database is accessible.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: Database is accessible.
|
|
* 500:
|
|
* description: Database not accessible.
|
|
*/
|
|
router.get("/db-health", requireAdmin, async (req, res) => {
|
|
try {
|
|
await createCurrentUserRepository().countAll();
|
|
res.json({ status: "ok" });
|
|
} catch (err) {
|
|
authLogger.error("DB health check failed", err);
|
|
res.status(500).json({ error: "Database not accessible" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/registration-allowed:
|
|
* get:
|
|
* summary: Get registration status
|
|
* description: Checks if user registration is currently allowed.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: Registration status.
|
|
* 500:
|
|
* description: Failed to get registration allowed status.
|
|
*/
|
|
router.get("/registration-allowed", async (req, res) => {
|
|
try {
|
|
res.json({ allowed: isRegistrationAllowed() });
|
|
} catch (err) {
|
|
authLogger.error("Failed to get registration allowed", err);
|
|
res.status(500).json({ error: "Failed to get registration allowed" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/registration-allowed:
|
|
* patch:
|
|
* summary: Set registration status
|
|
* description: Enables or disables user registration.
|
|
* tags:
|
|
* - Users
|
|
* requestBody:
|
|
* required: true
|
|
* content:
|
|
* application/json:
|
|
* schema:
|
|
* type: object
|
|
* properties:
|
|
* allowed:
|
|
* type: boolean
|
|
* responses:
|
|
* 200:
|
|
* description: Registration status updated.
|
|
* 400:
|
|
* description: Invalid value for allowed.
|
|
* 403:
|
|
* description: Not authorized.
|
|
* 500:
|
|
* description: Failed to set registration allowed status.
|
|
*/
|
|
router.patch("/registration-allowed", authenticateJWT, async (req, res) => {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
try {
|
|
const user = await requireCurrentAdmin(userId);
|
|
if (!user) {
|
|
return res.status(403).json({ error: "Not authorized" });
|
|
}
|
|
const { allowed } = req.body;
|
|
if (typeof allowed !== "boolean") {
|
|
return res.status(400).json({ error: "Invalid value for allowed" });
|
|
}
|
|
await createCurrentSettingsRepository().set(
|
|
"allow_registration",
|
|
allowed ? "true" : "false",
|
|
);
|
|
res.json({ allowed });
|
|
} catch (err) {
|
|
authLogger.error("Failed to set registration allowed", err);
|
|
res.status(500).json({ error: "Failed to set registration allowed" });
|
|
}
|
|
});
|
|
|
|
router.get("/oidc-auto-provision", async (_req, res) => {
|
|
try {
|
|
res.json({
|
|
enabled: await createCurrentSettingsRepository().getBoolean(
|
|
"oidc_auto_provision",
|
|
false,
|
|
),
|
|
});
|
|
} catch (err) {
|
|
authLogger.error("Failed to get OIDC auto-provision setting", err);
|
|
res
|
|
.status(500)
|
|
.json({ error: "Failed to get OIDC auto-provision setting" });
|
|
}
|
|
});
|
|
|
|
router.patch("/oidc-auto-provision", authenticateJWT, async (req, res) => {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
try {
|
|
const user = await requireCurrentAdmin(userId);
|
|
if (!user) {
|
|
return res.status(403).json({ error: "Not authorized" });
|
|
}
|
|
const { enabled } = req.body;
|
|
if (typeof enabled !== "boolean") {
|
|
return res.status(400).json({ error: "Invalid value for enabled" });
|
|
}
|
|
await createCurrentSettingsRepository().set(
|
|
"oidc_auto_provision",
|
|
enabled ? "true" : "false",
|
|
);
|
|
res.json({ enabled });
|
|
} catch (err) {
|
|
authLogger.error("Failed to set OIDC auto-provision", err);
|
|
res.status(500).json({ error: "Failed to set OIDC auto-provision" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/oidc-silent-login-default:
|
|
* get:
|
|
* summary: Get OIDC silent login default setting
|
|
* description: Returns whether silent OIDC login is enabled as the default behavior. Can be pinned via the OIDC_SILENT_LOGIN_DEFAULT env var.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: Silent login default setting.
|
|
* 500:
|
|
* description: Failed to get setting.
|
|
*/
|
|
router.get("/oidc-silent-login-default", async (_req, res) => {
|
|
try {
|
|
const envVal = getOidcSilentLoginDefaultFromEnv();
|
|
if (envVal !== undefined) {
|
|
res.json({ enabled: envVal, locked: true });
|
|
return;
|
|
}
|
|
res.json({
|
|
enabled: await createCurrentSettingsRepository().getBoolean(
|
|
"oidc_silent_login_default",
|
|
false,
|
|
),
|
|
locked: false,
|
|
});
|
|
} catch (err) {
|
|
authLogger.error("Failed to get OIDC silent login default", err);
|
|
res.status(500).json({ error: "Failed to get OIDC silent login default" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/oidc-silent-login-default:
|
|
* patch:
|
|
* summary: Set OIDC silent login default setting
|
|
* description: Enables or disables silent OIDC login as the default behavior on the login page.
|
|
* tags:
|
|
* - Users
|
|
* requestBody:
|
|
* required: true
|
|
* content:
|
|
* application/json:
|
|
* schema:
|
|
* type: object
|
|
* properties:
|
|
* enabled:
|
|
* type: boolean
|
|
* responses:
|
|
* 200:
|
|
* description: Setting updated.
|
|
* 400:
|
|
* description: Invalid value.
|
|
* 403:
|
|
* description: Not authorized.
|
|
* 409:
|
|
* description: Setting is pinned by the OIDC_SILENT_LOGIN_DEFAULT env var.
|
|
* 500:
|
|
* description: Failed to update setting.
|
|
*/
|
|
router.patch(
|
|
"/oidc-silent-login-default",
|
|
authenticateJWT,
|
|
async (req, res) => {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
try {
|
|
const user = await requireCurrentAdmin(userId);
|
|
if (!user) {
|
|
return res.status(403).json({ error: "Not authorized" });
|
|
}
|
|
if (getOidcSilentLoginDefaultFromEnv() !== undefined) {
|
|
return res.status(409).json({
|
|
error:
|
|
"OIDC silent login default is set via the OIDC_SILENT_LOGIN_DEFAULT env var and cannot be changed here",
|
|
});
|
|
}
|
|
const { enabled } = req.body;
|
|
if (typeof enabled !== "boolean") {
|
|
return res.status(400).json({ error: "Invalid value for enabled" });
|
|
}
|
|
await createCurrentSettingsRepository().set(
|
|
"oidc_silent_login_default",
|
|
enabled ? "true" : "false",
|
|
);
|
|
res.json({ enabled });
|
|
} catch (err) {
|
|
authLogger.error("Failed to set OIDC silent login default", err);
|
|
res
|
|
.status(500)
|
|
.json({ error: "Failed to set OIDC silent login default" });
|
|
}
|
|
},
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/password-login-allowed:
|
|
* get:
|
|
* summary: Get password login status
|
|
* description: Checks if password-based login is currently allowed.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: Password login status.
|
|
* 500:
|
|
* description: Failed to get password login allowed status.
|
|
*/
|
|
router.get("/password-login-allowed", async (req, res) => {
|
|
try {
|
|
res.json({ allowed: isPasswordLoginAllowed() });
|
|
} catch (err) {
|
|
authLogger.error("Failed to get password login allowed", err);
|
|
res.status(500).json({ error: "Failed to get password login allowed" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/password-login-allowed:
|
|
* patch:
|
|
* summary: Set password login status
|
|
* description: Enables or disables password-based login.
|
|
* tags:
|
|
* - Users
|
|
* requestBody:
|
|
* required: true
|
|
* content:
|
|
* application/json:
|
|
* schema:
|
|
* type: object
|
|
* properties:
|
|
* allowed:
|
|
* type: boolean
|
|
* responses:
|
|
* 200:
|
|
* description: Password login status updated.
|
|
* 400:
|
|
* description: Invalid value for allowed.
|
|
* 403:
|
|
* description: Not authorized.
|
|
* 500:
|
|
* description: Failed to set password login allowed status.
|
|
*/
|
|
router.patch("/password-login-allowed", authenticateJWT, async (req, res) => {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
try {
|
|
const user = await requireCurrentAdmin(userId);
|
|
if (!user) {
|
|
return res.status(403).json({ error: "Not authorized" });
|
|
}
|
|
const { allowed } = req.body;
|
|
if (typeof allowed !== "boolean") {
|
|
return res.status(400).json({ error: "Invalid value for allowed" });
|
|
}
|
|
if (!allowed) {
|
|
const totpEnabledCount =
|
|
await createCurrentUserRepository().countTotpEnabled();
|
|
if (totpEnabledCount > 0) {
|
|
return res.status(409).json({
|
|
error:
|
|
"Cannot disable password login while 2FA is enabled for one or more users. Disable 2FA first.",
|
|
});
|
|
}
|
|
}
|
|
await createCurrentSettingsRepository().set(
|
|
"allow_password_login",
|
|
allowed ? "true" : "false",
|
|
);
|
|
res.json({ allowed });
|
|
} catch (err) {
|
|
authLogger.error("Failed to set password login allowed", err);
|
|
res.status(500).json({ error: "Failed to set password login allowed" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/password-reset-allowed:
|
|
* get:
|
|
* summary: Get password reset status
|
|
* description: Checks if password reset is currently allowed.
|
|
* tags:
|
|
* - Users
|
|
* responses:
|
|
* 200:
|
|
* description: Password reset status.
|
|
* 500:
|
|
* description: Failed to get password reset allowed status.
|
|
*/
|
|
router.get("/password-reset-allowed", async (req, res) => {
|
|
try {
|
|
res.json({ allowed: isPasswordResetAllowed() });
|
|
} catch (err) {
|
|
authLogger.error("Failed to get password reset allowed", err);
|
|
res.status(500).json({ error: "Failed to get password reset allowed" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/password-reset-allowed:
|
|
* patch:
|
|
* summary: Set password reset status
|
|
* description: Enables or disables password reset.
|
|
* tags:
|
|
* - Users
|
|
* requestBody:
|
|
* required: true
|
|
* content:
|
|
* application/json:
|
|
* schema:
|
|
* type: object
|
|
* properties:
|
|
* allowed:
|
|
* type: boolean
|
|
* responses:
|
|
* 200:
|
|
* description: Password reset status updated.
|
|
* 400:
|
|
* description: Invalid value for allowed.
|
|
* 403:
|
|
* description: Not authorized.
|
|
* 500:
|
|
* description: Failed to set password reset allowed status.
|
|
*/
|
|
router.patch("/password-reset-allowed", authenticateJWT, async (req, res) => {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
try {
|
|
const user = await requireCurrentAdmin(userId);
|
|
if (!user) {
|
|
return res.status(403).json({ error: "Not authorized" });
|
|
}
|
|
const { allowed } = req.body;
|
|
if (typeof allowed !== "boolean") {
|
|
return res.status(400).json({ error: "Invalid value for allowed" });
|
|
}
|
|
await createCurrentSettingsRepository().set(
|
|
"allow_password_reset",
|
|
allowed ? "true" : "false",
|
|
);
|
|
res.json({ allowed });
|
|
} catch (err) {
|
|
authLogger.error("Failed to set password reset allowed", err);
|
|
res.status(500).json({ error: "Failed to set password reset allowed" });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/delete-account:
|
|
* delete:
|
|
* summary: Delete user account
|
|
* description: Deletes the authenticated user's account.
|
|
* tags:
|
|
* - Users
|
|
* requestBody:
|
|
* required: true
|
|
* content:
|
|
* application/json:
|
|
* schema:
|
|
* type: object
|
|
* properties:
|
|
* password:
|
|
* type: string
|
|
* responses:
|
|
* 200:
|
|
* description: Account deleted successfully.
|
|
* 400:
|
|
* description: Password is required.
|
|
* 401:
|
|
* description: Incorrect password.
|
|
* 403:
|
|
* description: Cannot delete external authentication accounts or the last admin user.
|
|
* 404:
|
|
* description: User not found.
|
|
* 500:
|
|
* description: Failed to delete account.
|
|
*/
|
|
router.delete("/delete-account", authenticateJWT, async (req, res) => {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
const { password } = req.body;
|
|
|
|
if (!isNonEmptyString(password)) {
|
|
return res
|
|
.status(400)
|
|
.json({ error: "Password is required to delete account" });
|
|
}
|
|
|
|
try {
|
|
const userRecord = await findCurrentUser(userId);
|
|
if (!userRecord) {
|
|
return res.status(404).json({ error: "User not found" });
|
|
}
|
|
|
|
if (userRecord.isOidc) {
|
|
return res.status(403).json({
|
|
error:
|
|
"Cannot delete external authentication accounts through this endpoint",
|
|
});
|
|
}
|
|
|
|
const isMatch = await bcrypt.compare(password, userRecord.passwordHash);
|
|
if (!isMatch) {
|
|
authLogger.warn(
|
|
`Incorrect password provided for account deletion: ${userRecord.username}`,
|
|
);
|
|
return res.status(401).json({ error: "Incorrect password" });
|
|
}
|
|
|
|
if (userRecord.isAdmin) {
|
|
const adminCount = await createCurrentUserRepository().countAdmins();
|
|
if (adminCount <= 1) {
|
|
return res
|
|
.status(403)
|
|
.json({ error: "Cannot delete the last admin user" });
|
|
}
|
|
}
|
|
|
|
await createCurrentUserRepository().delete(userId);
|
|
|
|
authLogger.success(`User account deleted: ${userRecord.username}`);
|
|
res.json({ message: "Account deleted successfully" });
|
|
} catch (err) {
|
|
authLogger.error("Failed to delete user account", err);
|
|
res.status(500).json({ error: "Failed to delete account" });
|
|
}
|
|
});
|
|
|
|
registerUserPasswordResetRoutes(router, { authManager });
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/change-password:
|
|
* post:
|
|
* summary: Change user password
|
|
* description: Changes the authenticated user's password.
|
|
* tags:
|
|
* - Users
|
|
* requestBody:
|
|
* required: true
|
|
* content:
|
|
* application/json:
|
|
* schema:
|
|
* type: object
|
|
* properties:
|
|
* oldPassword:
|
|
* type: string
|
|
* newPassword:
|
|
* type: string
|
|
* responses:
|
|
* 200:
|
|
* description: Password changed successfully.
|
|
* 400:
|
|
* description: Old and new passwords are required.
|
|
* 401:
|
|
* description: Incorrect current password.
|
|
* 500:
|
|
* description: Failed to update password and re-encrypt data.
|
|
*/
|
|
router.post("/change-password", authenticateJWT, async (req, res) => {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
const { oldPassword, newPassword } = req.body;
|
|
authLogger.info("Password change request", {
|
|
operation: "password_change_request",
|
|
userId,
|
|
});
|
|
|
|
if (!userId) {
|
|
return res.status(401).json({ error: "User not authenticated" });
|
|
}
|
|
|
|
if (!oldPassword || !newPassword) {
|
|
return res
|
|
.status(400)
|
|
.json({ error: "Old and new passwords are required." });
|
|
}
|
|
|
|
const user = await findCurrentUser(userId);
|
|
if (!user) {
|
|
return res.status(404).json({ error: "User not found" });
|
|
}
|
|
|
|
const isMatch = await bcrypt.compare(oldPassword, user.passwordHash);
|
|
if (!isMatch) {
|
|
authLogger.warn("Password change failed - old password incorrect", {
|
|
operation: "password_change_failed",
|
|
userId,
|
|
reason: "old_password_wrong",
|
|
});
|
|
return res.status(401).json({ error: "Incorrect current password" });
|
|
}
|
|
|
|
const success = await authManager.changeUserPassword(
|
|
userId,
|
|
oldPassword,
|
|
newPassword,
|
|
);
|
|
if (!success) {
|
|
return res
|
|
.status(500)
|
|
.json({ error: "Failed to update password and re-encrypt data." });
|
|
}
|
|
|
|
const password_hash = await bcrypt.hash(newPassword, 10);
|
|
await createCurrentUserRepository().update(userId, {
|
|
passwordHash: password_hash,
|
|
});
|
|
|
|
authManager.logoutUser(userId);
|
|
authLogger.success("Password changed successfully", {
|
|
operation: "password_change_complete",
|
|
userId,
|
|
});
|
|
|
|
const { ipAddress: pwIp, userAgent: pwUa } = getRequestMeta(req);
|
|
await logAudit({
|
|
userId,
|
|
username: user.username ?? userId,
|
|
action: "change_password",
|
|
resourceType: "user",
|
|
resourceId: userId,
|
|
ipAddress: pwIp,
|
|
userAgent: pwUa,
|
|
success: true,
|
|
});
|
|
|
|
res.json({ message: "Password changed successfully. Please log in again." });
|
|
});
|
|
|
|
registerUserAdminRoutes(router, authenticateJWT);
|
|
|
|
registerUserTotpRoutes(router, {
|
|
authenticateJWT,
|
|
authManager,
|
|
isNativeAppRequest,
|
|
});
|
|
|
|
registerUserWebAuthnRoutes(router, {
|
|
authenticateJWT,
|
|
authManager,
|
|
isNativeAppRequest,
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /users/delete-user:
|
|
* delete:
|
|
* summary: Delete user (admin only)
|
|
* description: Allows an admin to delete another user and all related data.
|
|
* tags:
|
|
* - Users
|
|
* requestBody:
|
|
* required: true
|
|
* content:
|
|
* application/json:
|
|
* schema:
|
|
* type: object
|
|
* properties:
|
|
* username:
|
|
* type: string
|
|
* responses:
|
|
* 200:
|
|
* description: User deleted successfully.
|
|
* 400:
|
|
* description: Username is required or cannot delete yourself.
|
|
* 403:
|
|
* description: Not authorized or cannot delete last admin.
|
|
* 404:
|
|
* description: User not found.
|
|
* 500:
|
|
* description: Failed to delete user.
|
|
*/
|
|
router.delete("/delete-user", authenticateJWT, async (req, res) => {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
const { username } = req.body;
|
|
|
|
if (!isNonEmptyString(username)) {
|
|
return res.status(400).json({ error: "Username is required" });
|
|
}
|
|
|
|
try {
|
|
const userRepository = createCurrentUserRepository();
|
|
const adminUser = await userRepository.findById(userId);
|
|
if (!adminUser?.isAdmin) {
|
|
return res.status(403).json({ error: "Not authorized" });
|
|
}
|
|
|
|
if (adminUser.username === username) {
|
|
return res.status(400).json({ error: "Cannot delete your own account" });
|
|
}
|
|
|
|
const targetUser = await userRepository.findByUsername(username);
|
|
if (!targetUser) {
|
|
return res.status(404).json({ error: "User not found" });
|
|
}
|
|
|
|
if (targetUser.isAdmin) {
|
|
if ((await userRepository.countAdmins()) <= 1) {
|
|
return res
|
|
.status(403)
|
|
.json({ error: "Cannot delete the last admin user" });
|
|
}
|
|
}
|
|
|
|
const targetUserId = targetUser.id;
|
|
|
|
// Inherit rather than drop: the deleting admin takes over the hosts and
|
|
// credentials unless another successor is named; "none" discards them.
|
|
const { successorUserId: requestedSuccessor } = req.body ?? {};
|
|
let successorUserId: string | undefined = userId;
|
|
if (requestedSuccessor === "none") {
|
|
successorUserId = undefined;
|
|
} else if (isNonEmptyString(requestedSuccessor)) {
|
|
const successor = await userRepository.findById(requestedSuccessor);
|
|
if (!successor || successor.id === targetUserId) {
|
|
return res.status(400).json({ error: "Invalid successor user" });
|
|
}
|
|
successorUserId = successor.id;
|
|
}
|
|
|
|
await deleteUserAndRelatedData(targetUserId, { successorUserId });
|
|
|
|
authLogger.warn("User account deleted by admin", {
|
|
operation: "admin_delete_user",
|
|
adminId: userId,
|
|
targetUserId,
|
|
targetUsername: username,
|
|
});
|
|
|
|
const { ipAddress: deleteIp, userAgent: deleteUa } = getRequestMeta(req);
|
|
await logAudit({
|
|
userId,
|
|
username: adminUser.username ?? userId,
|
|
action: "delete_user",
|
|
resourceType: "user",
|
|
resourceId: targetUserId,
|
|
resourceName: username,
|
|
ipAddress: deleteIp,
|
|
userAgent: deleteUa,
|
|
success: true,
|
|
});
|
|
|
|
res.json({ message: `User ${username} deleted successfully` });
|
|
} catch (err) {
|
|
authLogger.error("Failed to delete user", err);
|
|
|
|
if (err && typeof err === "object" && "code" in err) {
|
|
if (err.code === "SQLITE_CONSTRAINT_FOREIGNKEY") {
|
|
res.status(400).json({
|
|
error:
|
|
"Cannot delete user: User has associated data that cannot be removed",
|
|
});
|
|
} else {
|
|
res.status(500).json({ error: `Database error: ${err.code}` });
|
|
}
|
|
} else {
|
|
res.status(500).json({ error: "Failed to delete account" });
|
|
}
|
|
}
|
|
});
|
|
|
|
registerUserDataAccessRoutes(router, {
|
|
authenticateJWT,
|
|
authManager,
|
|
});
|
|
|
|
registerUserSessionRoutes(router, {
|
|
authenticateJWT,
|
|
authManager,
|
|
});
|
|
|
|
registerUserOidcAccountRoutes(router, {
|
|
authenticateJWT,
|
|
authManager,
|
|
});
|
|
|
|
registerUserSettingsRoutes(router, authenticateJWT);
|
|
registerTouchInputSettingsRoutes(router, authenticateJWT);
|
|
registerAcmeSSLRoutes(router, authenticateJWT);
|
|
|
|
registerUserApiKeyRoutes(router, requireAdmin);
|
|
registerUserImageStorageRoutes(router, requireAdmin);
|
|
registerBrandingRoutes(router, requireAdmin);
|
|
|
|
registerSSOProviderRoutes(router);
|
|
registerLDAPAuthRoutes(router);
|
|
|
|
export default router;
|