mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-29 14:45:24 +00:00
release-2.9.0 (#1532)
* fix(macos): skip single-instance lock in Mac App Store builds (#1454)
fix(macos): skip single-instance lock in Mac App Store builds
* Fix/backend optional sharp (#1455)
Fix/backend optional sharp
* feat: issue #1218 (#1218)
https://github.com/Termix-SSH/Support/issues/1218
* feat: Add option to use saved global custom theme under Connection Defaults (#1209)
https://github.com/Termix-SSH/Support/issues/1209
* feat: Add Fleet Sharing functionality to the UI (#1228)
https://github.com/Termix-SSH/Support/issues/1228
* feat: Add a list view to the Docker management page (#1237)
https://github.com/Termix-SSH/Support/issues/1237
* feat: issue #1264 (#1264)
https://github.com/Termix-SSH/Support/issues/1264
* feat: 2FA With FortiToken (#1288)
https://github.com/Termix-SSH/Support/issues/1288
* feat: Allow to disable showing paths to folders (#1274)
https://github.com/Termix-SSH/Support/issues/1274
* feat: Sync Network Graph between Desktop and Remote Server (#1245)
https://github.com/Termix-SSH/Support/issues/1245
* feat: Version Number on offline servers (#1291)
https://github.com/Termix-SSH/Support/issues/1291
* feat: Support OrbStack Docker socket path on macOS / Fix "Docker is not installed" on mac... (#1302)
https://github.com/Termix-SSH/Support/issues/1302
* feat: Sidebar host click should focus existing tab instead of opening a new connection (#1289)
https://github.com/Termix-SSH/Support/issues/1289
* fix: Search in side bar shows overlapping hosts when grouped by tags (#1303)
https://github.com/Termix-SSH/Support/issues/1303
* fix: I can't send a file on its own. (#1304)
https://github.com/Termix-SSH/Support/issues/1304
* fix: sudo password not autofilling (#1248)
https://github.com/Termix-SSH/Support/issues/1248
* fix: node-MainThread (#1300)
https://github.com/Termix-SSH/Support/issues/1300
* fix: Tunnel authentication with shared credentials (#1295)
https://github.com/Termix-SSH/Support/issues/1295
* fix: host key updates not syncing, metrics 404 race on first connect
Host key writes never bumped updatedAt so sync never picked them up.
Also retry the first metrics fetch briefly instead of failing right away.
* chore: increment ver
* feat: add category and icon fields to plugin manifest schema
* ci(deps): bump the github-actions group with 2 updates (#1458)
Bumps the github-actions group with 2 updates: [crowdin/github-action](https://github.com/crowdin/github-action) and [actions/github-script](https://github.com/actions/github-script).
Updates `crowdin/github-action` from 2 to 3
- [Release notes](https://github.com/crowdin/github-action/releases)
- [Commits](https://github.com/crowdin/github-action/compare/v2...v3)
Updates `actions/github-script` from 7 to 9
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](https://github.com/actions/github-script/compare/v7...v9)
---
updated-dependencies:
- dependency-name: crowdin/github-action
dependency-version: '3'
dependency-type: direct:production
update-type: version-update:semver-major
dependency-group: github-actions
- dependency-name: actions/github-script
dependency-version: '9'
dependency-type: direct:production
update-type: version-update:semver-major
dependency-group: github-actions
...
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 13 updates (#1459)
Bumps the dev-patch-updates group with 13 updates:
| Package | From | To |
| --- | --- | --- |
| [@codemirror/commands](https://github.com/codemirror/commands) | `6.11.0` | `6.11.1` |
| [@codemirror/search](https://github.com/codemirror/search) | `6.7.1` | `6.7.2` |
| [@codemirror/view](https://github.com/codemirror/view) | `6.43.9` | `6.43.12` |
| [@testing-library/dom](https://github.com/testing-library/dom-testing-library) | `10.4.1` | `10.4.2` |
| [@testing-library/react](https://github.com/testing-library/react-testing-library) | `16.3.2` | `16.3.3` |
| [@testing-library/user-event](https://github.com/testing-library/user-event) | `14.6.5` | `14.6.7` |
| [@types/ssh2](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/ssh2) | `1.15.5` | `1.15.6` |
| [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.1.0` | `6.1.1` |
| [cytoscape](https://github.com/cytoscape/cytoscape.js) | `3.34.1` | `3.34.3` |
| [eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) | `0.5.4` | `0.5.7` |
| [i18next](https://github.com/i18next/i18next) | `26.4.0` | `26.4.2` |
| [prettier](https://github.com/prettier/prettier) | `3.9.6` | `3.9.8` |
| [react-i18next](https://github.com/i18next/react-i18next) | `17.0.12` | `17.0.14` |
Updates `@codemirror/commands` from 6.11.0 to 6.11.1
- [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/commands/commits)
Updates `@codemirror/search` from 6.7.1 to 6.7.2
- [Changelog](https://github.com/codemirror/search/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/search/commits)
Updates `@codemirror/view` from 6.43.9 to 6.43.12
- [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/view/commits)
Updates `@testing-library/dom` from 10.4.1 to 10.4.2
- [Release notes](https://github.com/testing-library/dom-testing-library/releases)
- [Changelog](https://github.com/testing-library/dom-testing-library/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/dom-testing-library/compare/v10.4.1...v10.4.2)
Updates `@testing-library/react` from 16.3.2 to 16.3.3
- [Release notes](https://github.com/testing-library/react-testing-library/releases)
- [Changelog](https://github.com/testing-library/react-testing-library/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/react-testing-library/compare/v16.3.2...v16.3.3)
Updates `@testing-library/user-event` from 14.6.5 to 14.6.7
- [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.5...v14.6.7)
Updates `@types/ssh2` from 1.15.5 to 1.15.6
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/ssh2)
Updates `@vitejs/plugin-react` from 6.1.0 to 6.1.1
- [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.1/packages/plugin-react)
Updates `cytoscape` from 3.34.1 to 3.34.3
- [Release notes](https://github.com/cytoscape/cytoscape.js/releases)
- [Commits](https://github.com/cytoscape/cytoscape.js/compare/v3.34.1...v3.34.3)
Updates `eslint-plugin-react-refresh` from 0.5.4 to 0.5.7
- [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.4...v0.5.7)
Updates `i18next` from 26.4.0 to 26.4.2
- [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.4.0...v26.4.2)
Updates `prettier` from 3.9.6 to 3.9.8
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.9.6...3.9.8)
Updates `react-i18next` from 17.0.12 to 17.0.14
- [Changelog](https://github.com/i18next/react-i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/react-i18next/compare/v17.0.12...v17.0.14)
---
updated-dependencies:
- dependency-name: "@codemirror/commands"
dependency-version: 6.11.1
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: "@codemirror/search"
dependency-version: 6.7.2
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: "@codemirror/view"
dependency-version: 6.43.12
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: "@testing-library/dom"
dependency-version: 10.4.2
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: "@testing-library/react"
dependency-version: 16.3.3
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.7
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: "@types/ssh2"
dependency-version: 1.15.6
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: "@vitejs/plugin-react"
dependency-version: 6.1.1
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: cytoscape
dependency-version: 3.34.3
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.7
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: i18next
dependency-version: 26.4.2
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: prettier
dependency-version: 3.9.8
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: react-i18next
dependency-version: 17.0.14
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 6 updates (#1461)
Bumps the prod-patch-updates group with 6 updates:
| Package | From | To |
| --- | --- | --- |
| [@tanstack/react-virtual](https://github.com/TanStack/virtual/tree/HEAD/packages/react-virtual) | `3.14.10` | `3.14.13` |
| [compression](https://github.com/expressjs/compression) | `1.8.1` | `1.8.2` |
| [jose](https://github.com/panva/jose) | `6.2.9` | `6.2.12` |
| [jszip](https://github.com/Stuk/jszip) | `3.10.1` | `3.10.2` |
| [socks](https://github.com/JoshGlazebrook/socks) | `2.8.9` | `2.8.10` |
| [undici](https://github.com/nodejs/undici) | `8.10.0` | `8.10.2` |
Updates `@tanstack/react-virtual` from 3.14.10 to 3.14.13
- [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.13/packages/react-virtual)
Updates `compression` from 1.8.1 to 1.8.2
- [Release notes](https://github.com/expressjs/compression/releases)
- [Changelog](https://github.com/expressjs/compression/blob/master/HISTORY.md)
- [Commits](https://github.com/expressjs/compression/compare/v1.8.1...v1.8.2)
Updates `jose` from 6.2.9 to 6.2.12
- [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.9...v6.2.12)
Updates `jszip` from 3.10.1 to 3.10.2
- [Changelog](https://github.com/Stuk/jszip/blob/main/CHANGES.md)
- [Commits](https://github.com/Stuk/jszip/compare/v3.10.1...v3.10.2)
Updates `socks` from 2.8.9 to 2.8.10
- [Release notes](https://github.com/JoshGlazebrook/socks/releases)
- [Commits](https://github.com/JoshGlazebrook/socks/compare/2.8.9...2.8.10)
Updates `undici` from 8.10.0 to 8.10.2
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v8.10.0...v8.10.2)
---
updated-dependencies:
- dependency-name: "@tanstack/react-virtual"
dependency-version: 3.14.13
dependency-type: direct:production
update-type: version-update:semver-patch
dependency-group: prod-patch-updates
- dependency-name: compression
dependency-version: 1.8.2
dependency-type: direct:production
update-type: version-update:semver-patch
dependency-group: prod-patch-updates
- dependency-name: jose
dependency-version: 6.2.12
dependency-type: direct:production
update-type: version-update:semver-patch
dependency-group: prod-patch-updates
- dependency-name: jszip
dependency-version: 3.10.2
dependency-type: direct:production
update-type: version-update:semver-patch
dependency-group: prod-patch-updates
- dependency-name: socks
dependency-version: 2.8.10
dependency-type: direct:production
update-type: version-update:semver-patch
dependency-group: prod-patch-updates
- dependency-name: undici
dependency-version: 8.10.2
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>
* feat: add plugin worker protocol, bootstrap and plugin_storage table
Worker-side ctx proxy plus the message envelope it talks over, and the
per-plugin key/value table behind ctx.storage with migrations for all
three dialects. Rows cascade with the plugin so uninstalling leaves
nothing behind.
* feat: add allowlisted host view for plugins
An allowlist rather than a list of fields to strip. A blocklist rots:
the moment a new secret-bearing column lands on SSHHost it starts
leaking silently. With an allowlist a new field stays invisible to
plugins until someone adds it here on purpose.
* feat: add plugin loader with manifest validation and crash restart
Validates an unpacked plugin, spawns a worker_threads worker and manages
activate/deactivate/crash-restart with backoff, disabling after three
tries.
The crash counter clears only after a plugin stays up past a stability
window, not on activation. Clearing it on activation let a plugin that
activates cleanly and then dies restart forever, because every attempt
looked like the first.
loader.ts documents what the worker boundary does and does not buy you.
Node's permission model is process-wide, not per-worker, so it cannot be
enabled for plugin workers alone and is not claimed here.
* feat: route internal events through a shared plugin event bus
Formalises three ad-hoc publish paths that already existed:
automation-events.ts, metrics/automation-bridge.ts and the
hostSessionStatus singleton, now the host.session.status topic.
Both invariants the old code relied on are preserved. Publishing stays
fire-and-forget, so a failing subscriber cannot disturb a metrics poll or
a host delete. The automations engine subscribes to the bus at scheduler
start instead of being imported ad hoc, which keeps the edge
one-directional: automations may import repositories, hosts modules must
not import automations.
* feat: add plugin ctx broker with permission gate and audit
Every ctx call a plugin makes is checked against its granted
capabilities, performed by the main thread, then audited. A capability
must be both declared in the manifest and granted in the database, so
widening a plugin's reach always needs a new manifest the user can see,
never just a database row.
Audit attribution is set by the broker, not the plugin. The plugin
supplies only the details, so it cannot forge the actor.
fix: stop plugin workers seeing plaintext credentials in error messages
A failing ctx.ssh.connect handed the worker the raw error from deep in
the SSH stack, which embeds the connect config. The worker received, in
full:
Authentication failed for root using password <SECRET>
where <SECRET> was the host's real plaintext password. Any plugin with
ssh.exec could read it by catching the error, defeating the whole point
of the handle-based ssh API.
Errors crossing the boundary are now sanitised. Only PluginFacingError
and PluginPermissionError, both authored here, reach a plugin verbatim;
anything else becomes a generic message and the real one goes to the
log. This uses a marker class rather than matching on message text,
because matching would start leaking again the moment an upstream error
happened to contain a familiar phrase.
Covered by credential-isolation.test.ts, which plants a sentinel in
every secret-bearing field and asserts it appears in no message the
worker ever receives.
* feat: dispatch plugin HTTP routes and wire the runtime into startup
ctx.http.route now registers a real router on the /plugin-api/:pluginId
dispatcher, replacing its stub 404. A plugin never touches the Express
req/res: it gets a plain summary and returns a plain object, so sockets
and session cookies stay on this side of the boundary. Authorization and
cookie headers are not forwarded.
Plugins load last in the start-up sequence, after the server is fully
wired, and are terminated before the database on shutdown so none can
outlive it. A plugin that fails to load cannot stop the backend.
fix: correct the nginx plugin-api location regex
The pattern was ^/plugin-api/(/.*)?$, which needs a double slash and so
never matched /plugin-api/<id>/<route>. Every other block in the file
uses ^/prefix(/.*)?$. Left alone, plugin routes would work in dev and
404 only behind Docker.
* fix: update stale SFTP transfer test for single file destination paths
The test still asserted transferToHost was called with the destination
directory "/srv". Commit 7727fa09 (#1304) deliberately changed a single
file transfer to send the full destination path including the filename,
so the correct expectation is "/srv/remote-1.txt". The code was right
and the test was left behind.
* feat: ship the ssh terminal as a first-party in-process plugin
Adds a hardcoded process:transport-owner tier so the terminal can own its
WebSocket server and ssh2 clients, which cannot cross the worker boundary.
* feat: ship docker as a first-party in-process plugin
Moves docker backend and frontend into plugins/docker/, alongside
ssh-terminal. Adds a host editor tab seam, a dashboard card registry,
and a build step to compile plugin backends into dist.
* feat: ship host metrics as a first-party in-process plugin
* fix: harden plugin auth and add per-request identity for ctx calls
Require auth on /plugin-api, gate plugin enable/grant/revoke routes
behind admin.plugins.manage, and thread the calling user through
worker ctx.hosts/ctx.ssh calls instead of always using the install
owner. Also adds the plugin permissions grant/revoke UI.
* feat: ship the AI assistant as a first-party in-process plugin
Moves src/backend/ai and its routes into plugins/ai, mounted through a
small /ai dispatcher instead of its own port. Moves the ai-enabled and
ai-private-endpoints settings routes out of user-settings-routes.ts
into the plugin too, so it has no leftover core dependents.
* fix: remove compiled plugin JS left behind in plugins/ after build
copy-bundled-plugins.cjs compiled and rewrote plugin backend TS in
place, copied it to dist/plugins, but never deleted the .js it had
just emitted next to the .ts sources. Those files shadowed the real
source for vitest/tsx and had import paths rewritten for the dist
layout, so tests failed with "Cannot find module" once a local build
had run. Affects docker, host-metrics and ai, not just this one.
* feat: add a permission-gated backend service registry for plugins
* feat: add a permission-gated UI action registry and action slots for plugins
Moves the terminal toolbar's hardwired AI button into a slot the ssh-terminal
plugin offers and the ai plugin fills, gated on ai.services.use.
* feat: add cross-plugin secret references gated by the provider's RBAC permission
* feat: move proxmox discovery/import/sync into a first-party plugin
* feat: move remote desktop (RDP/VNC/Telnet) into a first-party plugin
Relocates guacamole backend/frontend source and tests into
plugins/remote-desktop, following the ssh-terminal/docker pattern.
* feat: wire remote-desktop plugin into core and rename i18n keys
Repoints core consumers (dispatcher, collab, session-sharing, tab
utils) at the plugin, adds isTabTypeAvailable gating for rdp/vnc/
telnet, widens hostCapability to accept an array, and renames the
guacamole i18n namespace to remoteDesktop.
* feat: move fleets into a first-party plugin
* feat: move automations into a first-party plugin
* feat: remove legacy alert rules, superseded by automations
Alert rules already auto-migrate into automations on boot and the old
engine stands down after. Deletes the rule/firing tables, routes, UI,
and AI tools; keeps notification channels since automations still use
them. Also fixes automations' notify step, which still called the
deleted repository.
* feat: move network topology into a first-party plugin
* feat: move tailscale device discovery and settings into a plugin
Adds plugins/tailscale/ with a devices sidebar tab, admin settings
section, and re-auth dialog. Host Metrics tailscale manager card and
SSH re-auth banner parsing stay in core.
* feat: move workspaces into a first-party plugin
* feat: move web endpoint into a first-party plugin
* feat: collapse plugin runtime to one tier behind a plugin SDK
* feat: make each plugin an npm workspace built by a termix-plugin CLI
* feat: give plugins their own tables, migrations and sync entities
* feat: serve plugin http and websockets from one mount instead of ports
* feat: namespace plugin permissions and keep them valid when a plugin is off
* feat: give plugins their own settings and one settings screen
* feat: load plugin frontends at runtime and remove plugin ids from the shell
* fix: mock the ai status fetch in its activate test
* feat: add auth extension points and one ssh connect pipeline
* feat: rebuild workspaces as the reference plugin
* fix: gate second factors after SSO/LDAP behind an admin setting
* feat: convert network-topology to a full plugin (B1)
* feat: move snippets backend and tables into a plugin (B2)
* feat: point core frontend snippets pickers at the plugin (B2)
* feat: add the snippets plugin (B2)
* feat: wire ai, automations, fleets and ssh-terminal to snippets (B2)
* feat: finish the tailscale plugin, including SSH auth (B3)
* feat: finish the fleets plugin, add ctx.hosts and host-commands SDK (B4)
* chore: update proxmox and host-metrics locale files for B5
* chore: regenerate drizzle migration journals for B5
* feat: add ctx.hosts create/update to the SDK, host-metrics drops proxmox
* feat: move proxmox node stats and collectors into the proxmox plugin
* feat: drop proxmox host columns, use plugin settings instead
* feat: finish the fleets plugin, add ctx.hosts and host-commands SDK (B4)
* feat: convert file manager into a plugin
* feat: convert ssh tunnels into a plugin
* feat: finish the web-endpoint plugin, add ctx.desktop (B8)
* feat: move the terminal fully into the ssh-terminal plugin (B9)
* feat: convert tmux monitoring into a plugin (B10)
* feat: convert serial console into the serial plugin
* feat: move session sharing and collab rooms into a plugin (B12)
* feat: turn session recording into a plugin (B13)
* feat: finish the remote-desktop plugin (B14)
* feat: finish the host-metrics plugin, move host status into core (B16)
* feat: finish the docker plugin (B15)
* feat: finish the automations plugin (B17)
* feat: finish the ai plugin (B18)
* feat: finish the homepage plugin, move service links and canvas out of core (B19)
* feat: convert wake-on-lan into a plugin (B20)
* feat: convert secret-sources into a plugin (B20)
* feat: move totp and passkeys into plugins (C1)
* feat: move sso and ldap logins into plugins (C2)
* feat: move opkssh and warpgate into plugins (C3)
* feat: move step-ca into a plugin (C4)
* feat: move vault ssh signing into a plugin (C5)
* feat: move termix identity into a plugin (C6)
* feat: move acme certificate automation into a plugin (C7)
* fix: finish 2.9.0 plugin moves and get every check green
* chore: lock the plugin boundary and remove 2.9.0 leftovers
* fix: harden the plugin runtime after the 2.9.0 security review
* feat: add plugin packing, signing, pinned trust and tmxplug bundling
* test: prove 2.8 to 2.9.0 upgrade is lossless and fix what it caught
* fix: give bundled plugin backends a real require for CJS deps
* feat: improve UI loading time and jitter
* feat: show credential sharing inline in the sidebar like host sharing
* feat: tailscale add host and copy ip, fix outbound fetch hang and plugin ESM warning
* feat: unify alerts into one plugin, channels, rules and inbox
* feat: rebuild desktop sync as linked server accounts, fix packaged plugin bundles and UI scaling
* fix: set blacksmith builder cache-key to stop broken gha cache fallback
* fix: link plugin-sdk workspace before npm ci in docker deps stage
* fix: link every plugin workspace before npm ci in docker deps stage
* fix(host-metrics): exclude image and firmware filesystems (#1469)
* fix(host-metrics): exclude image and firmware filesystems
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* fix(hosts): normalize imported jump host references (#1470)
* fix(hosts): normalize imported jump host references
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* fix(ci): build plugin SDK and repair MySQL settings migration (#1471)
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* fix(file-manager): keep inline rename consistent (#1476)
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* fix(file-manager): keep inline rename consistent
* fix(dashboard): reuse translated host status labels (#1475)
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* fix(dashboard): reuse translated host status labels
* docs(api): clarify local and remote version fields (#1474)
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* docs(api): clarify local and remote version fields
* fix(file-manager): preserve selected backgrounds on hover (#1473)
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* fix(file-manager): preserve selection feedback on hover
* test(ui): await dialog focus cleanup before teardown
* fix(file-manager): restore Ctrl/Cmd+F file search (#1472)
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* fix(file-manager): focus file search with Ctrl or Cmd F
* fix: keep rounded-full circular in production builds
* fix(file-manager): cancel uploads and stop remote writes (#1477)
* fix(file-manager): cancel uploads and stop remote writes
* test(css): exercise the configured PostCSS plugin chain
* fix(file-manager): apply compact density to directory tree (#1478)
* fix(file-manager): apply compact density to directory tree
* test(css): exercise the configured PostCSS plugin chain
* fix(file-manager): preserve font sizes in compact mode (#1480)
* fix(file-manager): preserve font sizes in compact mode
* test(css): exercise the configured PostCSS plugin chain
* fix(file-manager): prioritize file names in narrow lists (#1483)
* fix(file-manager): prioritize file names in narrow lists
* test(css): exercise the configured PostCSS plugin chain
* test(identity): preserve full Ed25519 public keys in fixtures
* test(remote-desktop): always mutate ciphertext in tamper test
* fix(remote-desktop): probe the saved host guacd endpoint (#1481)
* fix(remote-desktop): probe the saved host guacd endpoint
* test(css): exercise the configured PostCSS plugin chain
* test(identity): preserve full Ed25519 public keys in fixtures
* fix(homepage): check allowlisted private service reachability (#1479)
* fix(homepage): check allowlisted private service reachability
* test(css): exercise the configured PostCSS plugin chain
* fix(remote-desktop): stop unsolicited clipboard read prompts (#1482)
* fix(remote-desktop): read clipboard only on explicit paste
* test(css): exercise the configured PostCSS plugin chain
* test(identity): preserve full Ed25519 public keys in fixtures
* test(remote-desktop): always mutate ciphertext in tamper test
* chore: simplify plugin readmes, changelogs and manifest descriptions
* fix: keep plugins loaded after signing in from the login screen
* fix(file-manager): accept OS file drops over existing rows (#1484)
* fix(file-manager): accept OS file drops over existing rows
* test(file-manager): target the file label in drop tests
* test(css): exercise the configured PostCSS plugin chain
* test(identity): preserve full Ed25519 public keys in fixtures
* test(remote-desktop): always mutate ciphertext in tamper test
* fix(file-manager): pipeline SFTP download reads (#1485)
* feat: add plugin sdk build to beta release
* fix: make link-store secret check immune to random base64 matches
* fix(ldap): preserve the directory-provided bind DN (#1486)
* fix: compute beta changes across dev branches and move the beta tag
* chore: untrack plugin sdk ARCHITECTURE.md
* chore: remove references to plugin sdk ARCHITECTURE.md
* feat: merge host editor terminal tabs into one owned by ssh-terminal
* feat: add descriptions to plugin host enable toggles
* fix(file-manager): show download progress in file viewers (#1487)
* fix(electron): signal backend readiness over IPC (#1488)
* fix(split-screen): allow layout creation without randomUUID (#1490)
* fix(split-screen): allow layout creation without randomUUID
* test(credentials): avoid flaky Ed25519 key generation
* fix(sidebar): remeasure visible rows after density changes (#1489)
* fix(sidebar): remeasure visible rows after density changes
* test(credentials): avoid flaky Ed25519 key generation
* feat(split-screen): redesign split screen with free-form panes and pane picker
* feat(sidebar): add host click behavior setting, default to always opening a new tab
* feat(snippets): redesign panel to match the host list
* fix(session-recording): stop session logs panel from refetching in a loop
* feat(snippets): bring back sharing, target hosts and drag reorder
* feat(ssh-terminal): add toolbar position, start state, display and fade host settings
* feat(ssh-terminal): add host setting to turn off password prompt auto-fill
* fix(ai): stop streams getting cut off and keep tool steps across messages
* feat: improve quick connect system using plugin api
* fix: proxmox guest sync, startup snippet sync, drop dead cloudflare ssh transport
* feat: move terminal settings, look and ssh tools into ssh-terminal plugin
* feat: move snippets, keybinding actions and macros out of core into plugins
* feat: store rdp, vnc and telnet logins in a generic per-protocol table
* feat: type the plugin host record, move plugin strings out of core and add lint checks
* feat: replace core homepage widget registry with generic extension points
* feat: plugins only see their own host settings in the browser
* feat: harden plugin api for separate repos, signed updates and generic external login
* fix: keep plugin css below core utilities and version plugin assets by their css
* fix: load and save plugin host settings in the editor and tighten settings row spacing
* feat: redesign user host defaults system
* fix(remote-desktop): release held keys on focus loss (#1498)
* fix(session-sharing): replace local presentation after takeover (#1500)
* fix(file-manager): refresh disk usage with directory listing (#1503)
* fix(ssh-terminal): preserve input order during local echo reconciliation (#1505)
* feat(remote-desktop): expose display zoom controls for RDP (#1514)
* fix(file-manager): restore text selection and copying in Markdown previews (#1518)
* fix(sidebar): keep compact host addresses visible (#1524)
* fix(hosts): preserve plugin settings when reopening the editor (#1499)
* fix(ssh-terminal): close owner sockets when presentations unmount (#1501)
* fix(session-sharing): synchronize shared SSH terminal dimensions (#1502)
* fix(session-sharing): show participant presence in member terminals (#1504)
* fix(ai): sync provider configuration and keys across linked devices (#1506)
* feat(ssh-terminal): add a duplicate tab action (#1510)
* feat(file-manager): allow disabling move-to-trash confirmation (#1511)
* feat(file-manager): default to the remote login directory (#1512)
* feat(homepage): synchronize canvas layouts across devices (#1515)
* fix(shortcuts): prevent accidental double-Shift palette activation (#1519)
* feat(tmux-monitor): add a unified multi-host view (#1520)
* fix(electron): allow explicit quit with active connections (#1522)
* feat: reconnect all disconnected terminal tabs (#1523)
* fix(hosts): preserve recording and sharing settings in the dev editor (#1509)
* fix(database): preserve RDP domain during startup backfill (#1497)
* feat(sidebar): add keyboard type-ahead search for hosts (#1516)
* feat(automations): add per-host maintenance mode and recurring schedules (#1521)
* feat(tmux): add a per-host mouse toggle and preserve remote configuration (#1513)
* fix(session-sharing): use the linked server for desktop meetings and links (#1507)
* fix(tunnels): support TOTP for client tunnels and jump hosts (#1508)
* fix: type errors and lint failures from merged plugin prs
* feat(installer): make the Windows desktop shortcut optional (#1517)
* fix: ship the plugin sdk and serialport in desktop builds
* fix: prefer ipv4 when resolving ssh host names (#1365)
* fix: readable terminal selection with the light theme (#1319)
* fix: build desktop session share links on the linked server (#1350)
* fix: show meeting guests to members and hide the roster from guests (#1353)
* fix: reliable file manager saves with sudo prompt and no base64 guessing (#1335)
* fix: show disk usage for the mount being browsed (#1347)
* fix: load the linux tray icon reliably and log tray failures (#1332)
* fix: cover the gnome close path in the desktop quit test (#1332)
* fix: prompt for jump host TOTP in terminal, file manager and metrics (#1312)
* feat: optional auto reconnect for dropped ssh sessions (#1321)
* feat: tighter compact host rows with inline tags (#1325)
* feat: bring back the alert feed homepage widget
* feat: pick target terminals for snippets again
* feat: share button on connection tabs again
* feat: recent servers list when linking the desktop app
* feat: list the fixed app shortcuts in keyboard shortcuts
* fix: translate hardcoded toasts and drop em dashes from ui text
* fix: translate leftover hardcoded ui text
* fix: toolbar files button opens at the shell directory again
* fix: show the remote desktop note under connection origin again
* chore: openapi docs for host metrics manager routes
* chore: openapi docs for undocumented routes and fix two broken doc blocks
* fix: declare terminal.listSessions use for snippet targets
* revert: drop the alert feed widget, the notification center replaces it
* feat: restore the alert feed homepage widget
* fix: quick connect fills the host address from plugin auth editors like tailscale
* fix: docker container logs use the base background color
* chore: fix dependabot alerts and apply safe npm upgrades
* fix: proxmox stats tab reads its switch from plugin host settings
* fix: count plugin ssh logins toward host status and stop showing reachable as a warning
* fix: hide the built-in source pill in the host editor
* fix: host status shows online when the port answers and only warns on a failed login
* fix: drop the top border on the split layout menu
* fix: host defaults tabs sit where the host editor puts them and skip plugins with nothing to default
* fix: remote desktop auth method labels and notes for vnc and telnet
* fix: add description to the web endpoint enable switch
* fix: crowdin sync and pretranslate for plugin locales, run plugin tests on release
* feat: move telemetry out of core into a usage statistics plugin
* fix: recent activity card no longer cuts off host names early
* fix: remove duplicate top border on split screen menu
* fix: redesign session log player controls, fix tooltip overlap and drop dot separators
* fix: file manager and sftp text showing raw i18n keys
* fix: onboarding rerunning for existing users after upgrading
* fix: fleet detail buttons overflowing the sidebar
* fix: session log player scrolling off screen horizontally
* fix: network graph lag when adding hosts and on every render
* fix: maintenance index name, shared host read only view and badge polling
* fix: meeting tabs, workspace tab merging, rail panels as tabs and general ui lag
* chore: update release notes
* fix: remote desktop tabs reconnecting on every tab switch
* fix: build plugin sdk before linting in release workflow
* chore: lint, format, and bump version to 2.9.0
* chore: skip crowdin pre-translate in release for now
* chore: sync Crowdin translations for 2.9.0
---------
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Koi <38512047+datlt4@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com>
This commit is contained in:
4405 files changed
+1341026
-289722
No files matched your search
@@ -0,0 +1,52 @@
|
||||
import type { Router } from "express";
|
||||
import type { PluginContext } from "@termix/plugin-sdk/backend";
|
||||
import { providers } from "./tables.js";
|
||||
import { createProviderStore } from "./providers.js";
|
||||
import { createSsoLogin, METHOD_ID } from "./login.js";
|
||||
import { PUBLIC_PATHS, registerSsoRoutes } from "./routes.js";
|
||||
|
||||
/**
|
||||
* Whether the login page starts the first provider without a click. The
|
||||
* OIDC_SILENT_LOGIN_DEFAULT environment variable pins it either way.
|
||||
*/
|
||||
export async function silentLoginDefault(ctx: PluginContext): Promise<boolean> {
|
||||
const pinned = process.env.OIDC_SILENT_LOGIN_DEFAULT;
|
||||
if (pinned !== undefined) return pinned.trim().toLowerCase() === "true";
|
||||
return (await ctx.settings.get("silentLoginDefault")) === true;
|
||||
}
|
||||
|
||||
export async function activate(ctx: PluginContext) {
|
||||
const table = await ctx.db.define(providers);
|
||||
const store = createProviderStore(ctx, table);
|
||||
const login = createSsoLogin(ctx, store);
|
||||
|
||||
// One button per enabled provider.
|
||||
ctx.auth.registerLoginMethod({
|
||||
id: METHOD_ID,
|
||||
labelKey: "loginWithSso",
|
||||
icon: "key-round",
|
||||
kind: "redirect",
|
||||
external: true,
|
||||
describe: async () => {
|
||||
const autoStart = await silentLoginDefault(ctx);
|
||||
return (await store.listInstances()).map((instance, index) => ({
|
||||
...instance,
|
||||
enabled: true,
|
||||
...(autoStart && index === 0 ? { autoStart: true } : {}),
|
||||
}));
|
||||
},
|
||||
start: login.start,
|
||||
callback: login.callback,
|
||||
});
|
||||
|
||||
registerSsoRoutes(
|
||||
ctx.http.router<Router>({ public: PUBLIC_PATHS }),
|
||||
ctx,
|
||||
store,
|
||||
login,
|
||||
);
|
||||
}
|
||||
|
||||
export async function deactivate() {
|
||||
// Everything above was registered through ctx and is disposed by core.
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
/**
|
||||
* The OIDC, GitHub and Google sign-in. start builds the provider's authorize
|
||||
* URL; callback turns the provider's answer into a verified identity. Core
|
||||
* finds or provisions the user and issues the session.
|
||||
*/
|
||||
|
||||
import crypto from "node:crypto";
|
||||
import {
|
||||
LoginMethodError,
|
||||
type PluginContext,
|
||||
type PluginLoginRequest,
|
||||
type PluginVerifiedIdentity,
|
||||
} from "@termix/plugin-sdk/backend";
|
||||
import {
|
||||
OIDCTokenFormatError,
|
||||
buildFetchOptions,
|
||||
extractOidcGroupsFromSources,
|
||||
generatePkceCodeChallenge,
|
||||
generatePkceCodeVerifier,
|
||||
getDesktopCallbackUrl,
|
||||
getNestedValue,
|
||||
parseOidcRoleMap,
|
||||
resolveOidcMappedRoles,
|
||||
verifyOIDCToken,
|
||||
} from "./oidc-protocol.js";
|
||||
import {
|
||||
ENV_INSTANCE_ID,
|
||||
ENV_PROVIDER_ID,
|
||||
type ProviderStore,
|
||||
} from "./providers.js";
|
||||
import type { OidcConfig, ResolvedProvider } from "./types.js";
|
||||
|
||||
export const METHOD_ID = "oidc";
|
||||
export const CALLBACK_PATH = "/plugin-api/sso/callback";
|
||||
/** The redirect URI identity providers were set up with before 2.9. */
|
||||
export const LEGACY_CALLBACK_PATH = "/users/oidc/callback";
|
||||
|
||||
const STATE_TTL_MS = 10 * 60 * 1000;
|
||||
const STATE_PREFIX = "state:";
|
||||
|
||||
/** An error raised after the return address is known redirects there. */
|
||||
export class RedirectLoginError extends LoginMethodError {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly returnTo: string,
|
||||
status = 400,
|
||||
code?: string,
|
||||
) {
|
||||
super(message, status, code);
|
||||
this.name = "RedirectLoginError";
|
||||
}
|
||||
}
|
||||
|
||||
interface PendingState {
|
||||
nonce: string;
|
||||
backendCallback: string;
|
||||
frontendOrigin: string;
|
||||
rememberMe: boolean;
|
||||
providerId: number | null;
|
||||
codeVerifier: string;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
function nonEmpty(value: unknown): value is string {
|
||||
return typeof value === "string" && value.trim().length > 0;
|
||||
}
|
||||
|
||||
function header(request: PluginLoginRequest, name: string): string {
|
||||
const value = request.headers[name];
|
||||
return typeof (Array.isArray(value) ? value[0] : value) === "string"
|
||||
? String(Array.isArray(value) ? value[0] : value)
|
||||
: "";
|
||||
}
|
||||
|
||||
export function redirectUriFor(
|
||||
baseUrl: string,
|
||||
provider: Pick<ResolvedProvider, "legacyCallback">,
|
||||
): string {
|
||||
return `${baseUrl}${provider.legacyCallback ? LEGACY_CALLBACK_PATH : CALLBACK_PATH}`;
|
||||
}
|
||||
|
||||
export type SsoLogin = ReturnType<typeof createSsoLogin>;
|
||||
|
||||
export function createSsoLogin(ctx: PluginContext, store: ProviderStore) {
|
||||
async function saveState(state: string, pending: PendingState) {
|
||||
// Drop anything abandoned so the store does not grow.
|
||||
const now = Date.now();
|
||||
for (const key of await ctx.kv.list()) {
|
||||
if (!key.startsWith(STATE_PREFIX)) continue;
|
||||
const entry = (await ctx.kv.get(key)) as PendingState | undefined;
|
||||
if (!entry || now - entry.createdAt > STATE_TTL_MS) {
|
||||
await ctx.kv.delete(key);
|
||||
}
|
||||
}
|
||||
await ctx.kv.set(`${STATE_PREFIX}${state}`, pending);
|
||||
}
|
||||
|
||||
async function takeState(state: string): Promise<PendingState | null> {
|
||||
const key = `${STATE_PREFIX}${state}`;
|
||||
const entry = (await ctx.kv.get(key)) as PendingState | undefined;
|
||||
if (!entry) return null;
|
||||
await ctx.kv.delete(key);
|
||||
return Date.now() - entry.createdAt > STATE_TTL_MS ? null : entry;
|
||||
}
|
||||
|
||||
function frontendOriginFor(
|
||||
request: PluginLoginRequest,
|
||||
baseUrl: string,
|
||||
): string {
|
||||
const { desktopCallbackPort, appCallbackUrl } = request.query;
|
||||
if (desktopCallbackPort !== undefined && desktopCallbackPort !== "") {
|
||||
const url = getDesktopCallbackUrl(desktopCallbackPort);
|
||||
if (!url) {
|
||||
throw new LoginMethodError("Invalid desktop callback port", 400);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
if (typeof appCallbackUrl === "string" && appCallbackUrl) {
|
||||
let callbackUrl: URL;
|
||||
try {
|
||||
callbackUrl = new URL(appCallbackUrl);
|
||||
} catch {
|
||||
throw new LoginMethodError("Invalid app callback URL", 400);
|
||||
}
|
||||
if (callbackUrl.protocol !== "termix-mobile:") {
|
||||
throw new LoginMethodError("Unsupported app callback URL", 400);
|
||||
}
|
||||
return callbackUrl.toString();
|
||||
}
|
||||
const referer = header(request, "referer");
|
||||
if (referer) {
|
||||
try {
|
||||
const refererUrl = new URL(referer);
|
||||
return `${refererUrl.protocol}//${refererUrl.host}`;
|
||||
} catch {
|
||||
// fall through to the request's own origin
|
||||
}
|
||||
}
|
||||
return new URL(baseUrl).origin;
|
||||
}
|
||||
|
||||
async function start(
|
||||
request: PluginLoginRequest,
|
||||
instanceId: string | null,
|
||||
): Promise<{ redirectUrl: string }> {
|
||||
const requested =
|
||||
instanceId ??
|
||||
(typeof request.query.providerId === "string"
|
||||
? request.query.providerId
|
||||
: null);
|
||||
const rowId =
|
||||
requested && requested !== ENV_INSTANCE_ID
|
||||
? Number.parseInt(requested, 10)
|
||||
: null;
|
||||
if (rowId !== null && !Number.isInteger(rowId)) {
|
||||
throw new LoginMethodError("OIDC not configured", 404);
|
||||
}
|
||||
const provider = await store.resolve(rowId);
|
||||
if (!provider) throw new LoginMethodError("OIDC not configured", 404);
|
||||
|
||||
const baseUrl = ctx.http.baseUrl(request);
|
||||
const backendCallback = redirectUriFor(baseUrl, provider);
|
||||
const frontendOrigin = frontendOriginFor(request, baseUrl);
|
||||
const state = crypto.randomUUID();
|
||||
const nonce = crypto.randomUUID();
|
||||
const codeVerifier = generatePkceCodeVerifier();
|
||||
|
||||
await saveState(state, {
|
||||
nonce,
|
||||
backendCallback,
|
||||
frontendOrigin,
|
||||
rememberMe: String(request.query.rememberMe) === "true",
|
||||
providerId: provider.rowId,
|
||||
codeVerifier,
|
||||
createdAt: Date.now(),
|
||||
});
|
||||
|
||||
const authUrl = new URL(provider.config.authorization_url);
|
||||
authUrl.searchParams.set("client_id", provider.config.client_id);
|
||||
authUrl.searchParams.set("redirect_uri", backendCallback);
|
||||
authUrl.searchParams.set("response_type", "code");
|
||||
authUrl.searchParams.set("scope", provider.config.scopes);
|
||||
authUrl.searchParams.set("state", state);
|
||||
authUrl.searchParams.set("nonce", nonce);
|
||||
authUrl.searchParams.set(
|
||||
"code_challenge",
|
||||
generatePkceCodeChallenge(codeVerifier),
|
||||
);
|
||||
authUrl.searchParams.set("code_challenge_method", "S256");
|
||||
return { redirectUrl: authUrl.toString() };
|
||||
}
|
||||
|
||||
async function exchangeCode(
|
||||
config: OidcConfig,
|
||||
code: string,
|
||||
pending: PendingState,
|
||||
withVerifier: boolean,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const response = 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,
|
||||
redirect_uri: pending.backendCallback,
|
||||
...(withVerifier ? { code_verifier: pending.codeVerifier } : {}),
|
||||
}),
|
||||
...buildFetchOptions(config.ca_cert),
|
||||
} as RequestInit);
|
||||
if (!response.ok) {
|
||||
ctx.log.error(
|
||||
"Token exchange failed",
|
||||
new Error(`HTTP ${response.status}: ${await response.text()}`),
|
||||
);
|
||||
throw new LoginMethodError("Failed to exchange authorization code", 400);
|
||||
}
|
||||
return (await response.json()) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function providerKey(provider: ResolvedProvider): string {
|
||||
return provider.rowId === null ? ENV_PROVIDER_ID : String(provider.rowId);
|
||||
}
|
||||
|
||||
async function githubIdentity(
|
||||
provider: ResolvedProvider,
|
||||
code: string,
|
||||
pending: PendingState,
|
||||
): Promise<PluginVerifiedIdentity> {
|
||||
const tokenData = await exchangeCode(provider.config, code, pending, false);
|
||||
const fetchOptions = buildFetchOptions(provider.config.ca_cert);
|
||||
const headers = {
|
||||
Authorization: `Bearer ${tokenData.access_token}`,
|
||||
Accept: "application/json",
|
||||
"User-Agent": "Termix",
|
||||
};
|
||||
const userInfoResponse = await fetch("https://api.github.com/user", {
|
||||
headers,
|
||||
...fetchOptions,
|
||||
} as RequestInit);
|
||||
if (!userInfoResponse.ok) {
|
||||
throw new LoginMethodError("Failed to get GitHub user information", 400);
|
||||
}
|
||||
const userInfo = (await userInfoResponse.json()) as Record<string, unknown>;
|
||||
|
||||
const emailResponse = await fetch("https://api.github.com/user/emails", {
|
||||
headers,
|
||||
});
|
||||
if (emailResponse.ok) {
|
||||
const emails = (await emailResponse.json()) as Array<{
|
||||
email: string;
|
||||
primary: boolean;
|
||||
verified: boolean;
|
||||
}>;
|
||||
const primary = emails.find((e) => e.primary && e.verified);
|
||||
if (primary) userInfo.email = primary.email;
|
||||
}
|
||||
|
||||
const subject = String(userInfo.id ?? userInfo.login);
|
||||
const legacyIdentifier = `github:${provider.rowId}:${subject}`;
|
||||
return {
|
||||
kind: "external",
|
||||
provider: providerKey(provider),
|
||||
subject,
|
||||
email: (userInfo.email as string | undefined) ?? null,
|
||||
name: ((userInfo.name || userInfo.login) as string) || legacyIdentifier,
|
||||
allowedUsers: provider.config.allowed_users ?? null,
|
||||
legacy: { identifier: legacyIdentifier, providerRowId: provider.rowId },
|
||||
returnTo: pending.frontendOrigin,
|
||||
rememberMe: pending.rememberMe,
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchUserInfo(
|
||||
config: OidcConfig,
|
||||
accessToken: unknown,
|
||||
userInfo: Record<string, unknown> | null,
|
||||
claimSources: Record<string, unknown>[],
|
||||
): Promise<Record<string, unknown> | null> {
|
||||
const fetchOptions = buildFetchOptions(config.ca_cert);
|
||||
const issuer = config.issuer_url.endsWith("/")
|
||||
? config.issuer_url.slice(0, -1)
|
||||
: config.issuer_url;
|
||||
const base = issuer.replace(/\/application\/o\/[^/]+$/, "");
|
||||
const urls: string[] = [];
|
||||
|
||||
try {
|
||||
const discovery = await fetch(
|
||||
`${issuer}/.well-known/openid-configuration`,
|
||||
fetchOptions as RequestInit,
|
||||
);
|
||||
if (discovery.ok) {
|
||||
const document = (await discovery.json()) as Record<string, unknown>;
|
||||
if (typeof document.userinfo_endpoint === "string") {
|
||||
urls.push(document.userinfo_endpoint);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.log.warn(`OIDC discovery failed: ${String(error)}`);
|
||||
}
|
||||
|
||||
if (config.userinfo_url) urls.unshift(config.userinfo_url);
|
||||
urls.push(
|
||||
`${base}/userinfo/`,
|
||||
`${base}/userinfo`,
|
||||
`${issuer}/userinfo/`,
|
||||
`${issuer}/userinfo`,
|
||||
`${base}/oauth2/userinfo/`,
|
||||
`${base}/oauth2/userinfo`,
|
||||
`${issuer}/oauth2/userinfo/`,
|
||||
`${issuer}/oauth2/userinfo`,
|
||||
);
|
||||
|
||||
if (!accessToken) return userInfo;
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
...fetchOptions,
|
||||
} as RequestInit);
|
||||
if (response.ok) {
|
||||
const fetched = (await response.json()) as Record<string, unknown>;
|
||||
claimSources.push(fetched);
|
||||
return { ...userInfo, ...fetched };
|
||||
}
|
||||
ctx.log.warn(`Userinfo endpoint ${url} answered ${response.status}`);
|
||||
} catch (error) {
|
||||
ctx.log.warn(`Userinfo endpoint ${url} failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
return userInfo;
|
||||
}
|
||||
|
||||
async function oidcIdentity(
|
||||
provider: ResolvedProvider,
|
||||
code: string,
|
||||
pending: PendingState,
|
||||
): Promise<PluginVerifiedIdentity> {
|
||||
const { config } = provider;
|
||||
const tokenData = await exchangeCode(config, code, pending, true);
|
||||
|
||||
let userInfo: Record<string, unknown> | null = null;
|
||||
const claimSources: Record<string, unknown>[] = [];
|
||||
|
||||
if (typeof tokenData.id_token === "string") {
|
||||
try {
|
||||
userInfo = await verifyOIDCToken(
|
||||
tokenData.id_token,
|
||||
config.issuer_url,
|
||||
config.client_id,
|
||||
config.ca_cert,
|
||||
);
|
||||
if (userInfo.nonce !== pending.nonce) {
|
||||
ctx.log.warn("OIDC ID token nonce mismatch");
|
||||
throw new LoginMethodError("Invalid OIDC token nonce", 401);
|
||||
}
|
||||
claimSources.push(userInfo);
|
||||
} catch (error) {
|
||||
// A token that is not a JWS carries no claims we could trust; fall
|
||||
// through to userinfo. Signature and claim failures still reject.
|
||||
if (!(error instanceof OIDCTokenFormatError)) throw error;
|
||||
userInfo = null;
|
||||
ctx.log.warn(
|
||||
`OIDC ID token cannot be verified, using userinfo: ${error.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
userInfo = await fetchUserInfo(
|
||||
config,
|
||||
tokenData.access_token,
|
||||
userInfo,
|
||||
claimSources,
|
||||
);
|
||||
if (!userInfo) {
|
||||
throw new LoginMethodError("Failed to get user information", 400);
|
||||
}
|
||||
|
||||
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) {
|
||||
throw new LoginMethodError(
|
||||
`User identifier not found at path: ${config.identifier_path}. Available fields: ${Object.keys(userInfo).join(", ")}`,
|
||||
400,
|
||||
);
|
||||
}
|
||||
|
||||
const groups = extractOidcGroupsFromSources(
|
||||
claimSources,
|
||||
config.group_claim,
|
||||
);
|
||||
const isAdmin = config.admin_group
|
||||
? groups.includes(config.admin_group)
|
||||
: undefined;
|
||||
|
||||
let roles: { desired: string[]; managed: string[] } | undefined;
|
||||
const roleMap = parseOidcRoleMap(
|
||||
config.role_map ?? process.env.OIDC_ROLE_MAP,
|
||||
);
|
||||
if (roleMap.size > 0) {
|
||||
const { desired, managed } = resolveOidcMappedRoles(groups, roleMap);
|
||||
roles = { desired: [...desired], managed: [...managed] };
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "external",
|
||||
provider: providerKey(provider),
|
||||
subject: String(identifier),
|
||||
// An address the provider says it has not verified does not count
|
||||
// toward the allowed list.
|
||||
email:
|
||||
userInfo.email_verified === false || userInfo.email_verified === "false"
|
||||
? null
|
||||
: ((userInfo.email as string | undefined) ?? null),
|
||||
name,
|
||||
groups,
|
||||
isAdmin,
|
||||
allowedUsers: config.allowed_users ?? null,
|
||||
roles,
|
||||
logoutClaims: {
|
||||
providerId: provider.rowId,
|
||||
sub: typeof userInfo.sub === "string" ? userInfo.sub : null,
|
||||
sid: typeof userInfo.sid === "string" ? userInfo.sid : null,
|
||||
},
|
||||
legacy: { identifier: String(identifier), providerRowId: provider.rowId },
|
||||
returnTo: pending.frontendOrigin,
|
||||
rememberMe: pending.rememberMe,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The provider's callback. Throws RedirectLoginError once the return
|
||||
* address is known, and a plain LoginMethodError (answered as JSON) before.
|
||||
*/
|
||||
async function callback(
|
||||
request: PluginLoginRequest,
|
||||
): Promise<PluginVerifiedIdentity> {
|
||||
const source = { ...request.query, ...(request.body ?? {}) };
|
||||
const { code, state } = source as Record<string, unknown>;
|
||||
if (!nonEmpty(code) || !nonEmpty(state)) {
|
||||
throw new LoginMethodError("Code and state are required", 400);
|
||||
}
|
||||
const pending = await takeState(state);
|
||||
if (!pending) throw new LoginMethodError("Invalid state parameter", 400);
|
||||
|
||||
try {
|
||||
const provider = await store.resolve(pending.providerId);
|
||||
if (!provider) throw new LoginMethodError("OIDC not configured", 500);
|
||||
// GitHub does not issue OIDC id_tokens; it has its own token exchange.
|
||||
return provider.type === "github"
|
||||
? await githubIdentity(provider, code, pending)
|
||||
: await oidcIdentity(provider, code, pending);
|
||||
} catch (error) {
|
||||
if (error instanceof LoginMethodError) {
|
||||
throw new RedirectLoginError(
|
||||
error.message,
|
||||
pending.frontendOrigin,
|
||||
error.status,
|
||||
error.code,
|
||||
);
|
||||
}
|
||||
ctx.log.error(
|
||||
"OIDC callback failed",
|
||||
error instanceof Error ? error : new Error(String(error)),
|
||||
);
|
||||
throw new RedirectLoginError(
|
||||
"OIDC authentication failed",
|
||||
pending.frontendOrigin,
|
||||
500,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { start, callback };
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
/**
|
||||
* OpenID Connect protocol helpers: token verification, groups and the role
|
||||
* map, back-channel logout tokens and the provider defaults. Nothing here
|
||||
* touches storage.
|
||||
*/
|
||||
|
||||
import crypto from "node:crypto";
|
||||
import { Agent } from "undici";
|
||||
import type { OidcConfig } from "./types.js";
|
||||
|
||||
const BACKCHANNEL_LOGOUT_EVENT =
|
||||
"http://schemas.openid.net/event/backchannel-logout";
|
||||
|
||||
/**
|
||||
* Raised when a token cannot be verified because it is not a compact JWS,
|
||||
* as opposed to a signature or claim check that actually failed.
|
||||
*/
|
||||
export class OIDCTokenFormatError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "OIDCTokenFormatError";
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeIssuer(url: string): string {
|
||||
return url
|
||||
.trim()
|
||||
.replace(/\/+$/, "")
|
||||
.replace(/\/\.well-known\/openid-configuration$/, "");
|
||||
}
|
||||
|
||||
export function buildFetchOptions(caCert?: string): Record<string, unknown> {
|
||||
if (!caCert || !caCert.trim()) return {};
|
||||
return { dispatcher: new Agent({ connect: { ca: caCert } }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders why a fetch failed in a form an administrator can act on.
|
||||
*
|
||||
* undici reports every transport failure as the same "fetch failed" message
|
||||
* and puts the reason that actually matters -- ENOTFOUND, ECONNREFUSED,
|
||||
* UNABLE_TO_VERIFY_LEAF_SIGNATURE, a timeout -- on the cause. Reporting only
|
||||
* the outer message says nothing at all.
|
||||
*/
|
||||
export function describeFetchFailure(error: unknown): string {
|
||||
if (!(error instanceof Error)) return String(error);
|
||||
const cause = (error as { cause?: unknown }).cause;
|
||||
if (cause instanceof Error) {
|
||||
const code = (cause as { code?: unknown }).code;
|
||||
return code
|
||||
? `${error.message}: ${cause.message} (${code})`
|
||||
: `${error.message}: ${cause.message}`;
|
||||
}
|
||||
return cause ? `${error.message}: ${String(cause)}` : error.message;
|
||||
}
|
||||
|
||||
export function getOidcConfigFromEnv(): OidcConfig | null {
|
||||
const client_id = process.env.OIDC_CLIENT_ID;
|
||||
const client_secret = process.env.OIDC_CLIENT_SECRET;
|
||||
const issuer_url = process.env.OIDC_ISSUER_URL;
|
||||
const authorization_url = process.env.OIDC_AUTHORIZATION_URL;
|
||||
const token_url = process.env.OIDC_TOKEN_URL;
|
||||
|
||||
if (
|
||||
!client_id ||
|
||||
!client_secret ||
|
||||
!issuer_url ||
|
||||
!authorization_url ||
|
||||
!token_url
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
client_id,
|
||||
client_secret,
|
||||
issuer_url,
|
||||
authorization_url,
|
||||
token_url,
|
||||
userinfo_url: process.env.OIDC_USERINFO_URL || "",
|
||||
identifier_path: process.env.OIDC_IDENTIFIER_PATH || "sub",
|
||||
name_path: process.env.OIDC_NAME_PATH || "name",
|
||||
scopes: process.env.OIDC_SCOPES || "openid email profile",
|
||||
allowed_users: process.env.OIDC_ALLOWED_USERS || "",
|
||||
admin_group: process.env.OIDC_ADMIN_GROUP || "",
|
||||
group_claim: process.env.OIDC_GROUP_CLAIM || "",
|
||||
role_map: process.env.OIDC_ROLE_MAP || "",
|
||||
};
|
||||
}
|
||||
|
||||
export function isOIDCEnvOverrideEnabled(): boolean {
|
||||
return process.env.OIDC_ENV_OVERRIDE?.toLowerCase() === "true";
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a group name for comparison. Providers are inconsistent about
|
||||
* whether they emit bare names (`devops-interns`) or full paths
|
||||
* (`/devops-interns`, Keycloak's "Full group path" option), so leading slashes
|
||||
* are stripped and case is ignored.
|
||||
*/
|
||||
function normalizeGroupName(group: string): string {
|
||||
return group.trim().replace(/^\/+/, "").toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses `OIDC_ROLE_MAP` into a group -> role-name lookup.
|
||||
*
|
||||
* Format is a comma- or newline-separated list of `group:role` pairs, e.g.
|
||||
* `devops-interns:devops-intern,devops-seniors:devops-senior`. Group keys are
|
||||
* normalized via {@link normalizeGroupName}; role names are passed through
|
||||
* verbatim because they must match `roles.name` exactly.
|
||||
*
|
||||
* Malformed entries are skipped rather than throwing - a typo in one pair must
|
||||
* not lock every user out of login.
|
||||
*/
|
||||
export function parseOidcRoleMap(raw?: string | null): Map<string, string> {
|
||||
const map = new Map<string, string>();
|
||||
if (!raw || !raw.trim()) return map;
|
||||
|
||||
for (const entry of raw.split(/[\n,]/)) {
|
||||
const trimmed = entry.trim();
|
||||
if (!trimmed) continue;
|
||||
|
||||
// rsplit on the last ":" so group names containing a colon still work.
|
||||
const separator = trimmed.lastIndexOf(":");
|
||||
if (separator <= 0 || separator === trimmed.length - 1) continue;
|
||||
|
||||
const group = normalizeGroupName(trimmed.slice(0, separator));
|
||||
const roleName = trimmed.slice(separator + 1).trim();
|
||||
if (!group || !roleName) continue;
|
||||
|
||||
map.set(group, roleName);
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves which mapped roles a user should hold, given their provider groups.
|
||||
*
|
||||
* Returns both the `desired` roles (mapped groups the user is actually in) and
|
||||
* the full set of `managed` roles (every role named in the map). Callers must
|
||||
* only ever add/remove roles within `managed` - roles assigned by hand in
|
||||
* Termix, and the `admin`/`user` roles maintained by the admin-group sync, are
|
||||
* deliberately left alone.
|
||||
*/
|
||||
export function resolveOidcMappedRoles(
|
||||
groups: string[],
|
||||
roleMap: Map<string, string>,
|
||||
): { desired: Set<string>; managed: Set<string> } {
|
||||
const managed = new Set(roleMap.values());
|
||||
const desired = new Set<string>();
|
||||
|
||||
for (const group of groups) {
|
||||
const roleName = roleMap.get(normalizeGroupName(group));
|
||||
if (roleName) desired.add(roleName);
|
||||
}
|
||||
|
||||
return { desired, managed };
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the list of group/role names from an OIDC userInfo payload.
|
||||
*
|
||||
* When `groupClaim` is set, that claim is read first (useful for providers like
|
||||
* Zitadel that nest roles under a custom path such as
|
||||
* `urn:zitadel:iam:org:project:roles`). Otherwise the common `groups`, `roles`
|
||||
* and `group` claims are tried. Values may be an array, a comma-separated
|
||||
* string, or an object whose keys are the group names.
|
||||
*/
|
||||
export function extractOidcGroups(
|
||||
userInfo: Record<string, unknown>,
|
||||
groupClaim?: string,
|
||||
): string[] {
|
||||
let raw: unknown;
|
||||
if (groupClaim && groupClaim.trim()) {
|
||||
raw = userInfo[groupClaim.trim()];
|
||||
}
|
||||
if (raw === undefined || raw === null) {
|
||||
raw = userInfo.groups ?? userInfo.roles ?? userInfo.group;
|
||||
}
|
||||
|
||||
if (Array.isArray(raw)) {
|
||||
return raw.map(String);
|
||||
}
|
||||
if (typeof raw === "string") {
|
||||
return raw
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
if (raw && typeof raw === "object") {
|
||||
return Object.keys(raw as Record<string, unknown>);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* OIDC providers may return group claims in the ID token, userinfo response,
|
||||
* or both. Keep every verified source authoritative instead of letting a
|
||||
* sparse userinfo payload overwrite claims from the ID token.
|
||||
*/
|
||||
export function extractOidcGroupsFromSources(
|
||||
sources: Record<string, unknown>[],
|
||||
groupClaim?: string,
|
||||
): string[] {
|
||||
return [
|
||||
...new Set(
|
||||
sources.flatMap((source) => extractOidcGroups(source, groupClaim)),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
export async function verifyOIDCToken(
|
||||
idToken: string,
|
||||
issuerUrl: string,
|
||||
clientId: string,
|
||||
caCert?: string,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const segments = idToken.split(".");
|
||||
if (segments.length !== 3) {
|
||||
throw new OIDCTokenFormatError(
|
||||
segments.length === 5
|
||||
? "Token is a JWE (encrypted). Termix cannot verify encrypted tokens; disable token encryption for this client in your OIDC provider."
|
||||
: `Token is not a compact JWS: expected 3 segments, got ${segments.length}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const fetchOptions = buildFetchOptions(caCert);
|
||||
const configuredIssuerUrl = issuerUrl.trim().replace(/\/+$/, "");
|
||||
const normalizedIssuerUrl = normalizeIssuer(issuerUrl);
|
||||
const possibleIssuers = [
|
||||
normalizedIssuerUrl,
|
||||
normalizedIssuerUrl.replace(/\/application\/o\/[^/]+$/, ""),
|
||||
...(configuredIssuerUrl === normalizedIssuerUrl ? [issuerUrl] : []),
|
||||
];
|
||||
|
||||
const jwksUrls = [
|
||||
`${normalizedIssuerUrl}/.well-known/jwks.json`,
|
||||
`${normalizedIssuerUrl}/jwks/`,
|
||||
`${normalizedIssuerUrl.replace(/\/application\/o\/[^/]+$/, "")}/.well-known/jwks.json`,
|
||||
];
|
||||
|
||||
// Every attempt records why it failed. Without this the only thing an
|
||||
// administrator ever sees is "Failed to fetch JWKS from any URL", which
|
||||
// does not distinguish an issuer URL typo from a proxy, a private CA, or
|
||||
// a provider outage.
|
||||
const attempts: string[] = [];
|
||||
|
||||
const discoveryUrl = `${normalizedIssuerUrl}/.well-known/openid-configuration`;
|
||||
try {
|
||||
const discoveryResponse = await fetch(discoveryUrl, fetchOptions);
|
||||
if (!discoveryResponse.ok) {
|
||||
attempts.push(`${discoveryUrl}: HTTP ${discoveryResponse.status}`);
|
||||
} else {
|
||||
const discovery = (await discoveryResponse.json()) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
if (typeof discovery.jwks_uri === "string" && discovery.jwks_uri) {
|
||||
jwksUrls.unshift(discovery.jwks_uri);
|
||||
} else {
|
||||
attempts.push(`${discoveryUrl}: no jwks_uri in the discovery document`);
|
||||
}
|
||||
}
|
||||
} catch (discoveryError) {
|
||||
attempts.push(`${discoveryUrl}: ${describeFetchFailure(discoveryError)}`);
|
||||
}
|
||||
|
||||
let jwks: Record<string, unknown> | null = null;
|
||||
|
||||
for (const url of jwksUrls) {
|
||||
try {
|
||||
const response = await fetch(url, fetchOptions);
|
||||
if (!response.ok) {
|
||||
attempts.push(`${url}: HTTP ${response.status}`);
|
||||
continue;
|
||||
}
|
||||
const jwksData = (await response.json()) as Record<string, unknown>;
|
||||
if (jwksData && Array.isArray(jwksData.keys)) {
|
||||
jwks = jwksData;
|
||||
break;
|
||||
}
|
||||
attempts.push(`${url}: response contains no "keys" array`);
|
||||
} catch (error) {
|
||||
attempts.push(`${url}: ${describeFetchFailure(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!jwks) {
|
||||
throw new Error(
|
||||
`Failed to fetch JWKS from any URL. Attempts:\n ${attempts.join("\n ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!jwks.keys || !Array.isArray(jwks.keys)) {
|
||||
throw new Error(
|
||||
`Invalid JWKS response structure. Expected 'keys' array, got: ${JSON.stringify(jwks)}`,
|
||||
);
|
||||
}
|
||||
|
||||
const { decodeProtectedHeader, importJWK, jwtVerify } = await import("jose");
|
||||
const header = decodeProtectedHeader(idToken);
|
||||
const keyId = header.kid;
|
||||
|
||||
const publicKey = jwks.keys.find(
|
||||
(key: Record<string, unknown>) => key.kid === keyId,
|
||||
);
|
||||
if (!publicKey) {
|
||||
throw new Error(
|
||||
`No matching public key found for key ID: ${keyId}. Available keys: ${jwks.keys.map((k: Record<string, unknown>) => k.kid).join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
const algorithm =
|
||||
typeof publicKey.alg === "string" ? publicKey.alg : header.alg;
|
||||
const key = await importJWK(publicKey, algorithm);
|
||||
|
||||
const { payload } = await jwtVerify(idToken, key, {
|
||||
issuer: possibleIssuers,
|
||||
audience: clientId,
|
||||
});
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
const GOOGLE_DEFAULTS = {
|
||||
issuer_url: "https://accounts.google.com",
|
||||
authorization_url: "https://accounts.google.com/o/oauth2/v2/auth",
|
||||
token_url: "https://oauth2.googleapis.com/token",
|
||||
userinfo_url: "https://openidconnect.googleapis.com/v1/userinfo",
|
||||
identifier_path: "sub",
|
||||
name_path: "name",
|
||||
scopes: "openid email profile",
|
||||
};
|
||||
|
||||
const GITHUB_DEFAULTS = {
|
||||
issuer_url: "https://token.actions.githubusercontent.com",
|
||||
authorization_url: "https://github.com/login/oauth/authorize",
|
||||
token_url: "https://github.com/login/oauth/access_token",
|
||||
userinfo_url: "https://api.github.com/user",
|
||||
identifier_path: "id",
|
||||
name_path: "name",
|
||||
scopes: "read:user user:email",
|
||||
};
|
||||
|
||||
export function applyProviderDefaults(
|
||||
config: OidcConfig,
|
||||
providerType: string,
|
||||
): OidcConfig {
|
||||
const defaults =
|
||||
providerType === "google"
|
||||
? GOOGLE_DEFAULTS
|
||||
: providerType === "github"
|
||||
? GITHUB_DEFAULTS
|
||||
: null;
|
||||
if (!defaults) return config;
|
||||
return {
|
||||
...config,
|
||||
issuer_url: config.issuer_url || defaults.issuer_url,
|
||||
authorization_url: config.authorization_url || defaults.authorization_url,
|
||||
token_url: config.token_url || defaults.token_url,
|
||||
userinfo_url: config.userinfo_url || defaults.userinfo_url,
|
||||
identifier_path: config.identifier_path || defaults.identifier_path,
|
||||
name_path: config.name_path || defaults.name_path,
|
||||
scopes: config.scopes || defaults.scopes,
|
||||
};
|
||||
}
|
||||
|
||||
export type LogoutTokenClaims = {
|
||||
sub: string | null;
|
||||
sid: string | null;
|
||||
jti: string;
|
||||
};
|
||||
|
||||
export function validateLogoutTokenClaims(
|
||||
payload: Record<string, unknown>,
|
||||
): LogoutTokenClaims {
|
||||
if ("nonce" in payload) {
|
||||
throw new Error("logout_token must not contain a nonce claim");
|
||||
}
|
||||
|
||||
const event = (payload.events as Record<string, unknown> | undefined)?.[
|
||||
BACKCHANNEL_LOGOUT_EVENT
|
||||
];
|
||||
if (!event || typeof event !== "object" || Array.isArray(event)) {
|
||||
throw new Error("logout_token missing back-channel logout event");
|
||||
}
|
||||
|
||||
if (!Number.isInteger(payload.iat)) {
|
||||
throw new Error("logout_token missing iat claim");
|
||||
}
|
||||
|
||||
const jti = typeof payload.jti === "string" ? payload.jti.trim() : "";
|
||||
if (!jti) {
|
||||
throw new Error("logout_token missing jti claim");
|
||||
}
|
||||
|
||||
const sub = typeof payload.sub === "string" ? payload.sub : null;
|
||||
const sid = typeof payload.sid === "string" ? payload.sid : null;
|
||||
if (!sub && !sid) {
|
||||
throw new Error("logout_token must contain sub and/or sid");
|
||||
}
|
||||
|
||||
return { sub, sid, jti };
|
||||
}
|
||||
|
||||
export async function validateLogoutToken(
|
||||
logoutToken: string,
|
||||
config: OidcConfig,
|
||||
): Promise<LogoutTokenClaims> {
|
||||
const payload = await verifyOIDCToken(
|
||||
logoutToken,
|
||||
config.issuer_url,
|
||||
config.client_id,
|
||||
config.ca_cert,
|
||||
);
|
||||
|
||||
return validateLogoutTokenClaims(payload);
|
||||
}
|
||||
|
||||
export function isValidOidcIssuer(value: unknown): boolean {
|
||||
if (typeof value !== "string") return false;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return (
|
||||
["http:", "https:"].includes(url.protocol) &&
|
||||
!/\/userinfo\/?$/i.test(url.pathname)
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function getNestedValue(
|
||||
obj: Record<string, unknown>,
|
||||
path: string,
|
||||
): unknown {
|
||||
if (!path || !obj) return null;
|
||||
return path
|
||||
.split(".")
|
||||
.reduce<unknown>(
|
||||
(current, key) => (current as Record<string, unknown>)?.[key],
|
||||
obj,
|
||||
);
|
||||
}
|
||||
|
||||
// RFC 7636 PKCE: 43-128 char unreserved-character string.
|
||||
export function generatePkceCodeVerifier(): string {
|
||||
return crypto.randomBytes(64).toString("base64url");
|
||||
}
|
||||
|
||||
export function generatePkceCodeChallenge(verifier: string): string {
|
||||
return crypto.createHash("sha256").update(verifier).digest("base64url");
|
||||
}
|
||||
|
||||
/** The desktop app's loopback listener for a callback port it sent. */
|
||||
export function getDesktopCallbackUrl(value: unknown): string | null {
|
||||
if (typeof value !== "string" || !/^\d+$/.test(value)) return null;
|
||||
const port = Number(value);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
|
||||
return `http://localhost:${port}/oidc-callback`;
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
import { and, asc, desc, eq } from "drizzle-orm";
|
||||
import type { PluginContext } from "@termix/plugin-sdk/backend";
|
||||
import { applyProviderDefaults, normalizeIssuer } from "./oidc-protocol.js";
|
||||
import {
|
||||
SSO_PROVIDER_TYPES,
|
||||
type OidcConfig,
|
||||
type ProviderRow,
|
||||
type ResolvedProvider,
|
||||
type SsoProviderType,
|
||||
} from "./types.js";
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
// ctx.db.define hands the table back untyped and the drizzle handle is the
|
||||
// server's own, so both are typed at this module's edge.
|
||||
type Table = any;
|
||||
type Drizzle = any;
|
||||
/* eslint-enable @typescript-eslint/no-explicit-any */
|
||||
|
||||
/** Identities from the env-configured provider use this provider id. */
|
||||
export const ENV_PROVIDER_ID = "legacy-oidc";
|
||||
/** The login instance id of the env-configured provider. */
|
||||
export const ENV_INSTANCE_ID = "0";
|
||||
|
||||
const SECRET_FIELDS = ["client_secret"] as const;
|
||||
const LEGACY_PREFIXES = ["encoded:", "encrypted:"];
|
||||
|
||||
export function isSsoType(type: unknown): type is SsoProviderType {
|
||||
return SSO_PROVIDER_TYPES.includes(type as SsoProviderType);
|
||||
}
|
||||
|
||||
export function getOidcConfigFromEnv(): OidcConfig | null {
|
||||
const client_id = process.env.OIDC_CLIENT_ID;
|
||||
const client_secret = process.env.OIDC_CLIENT_SECRET;
|
||||
const issuer_url = process.env.OIDC_ISSUER_URL;
|
||||
const authorization_url = process.env.OIDC_AUTHORIZATION_URL;
|
||||
const token_url = process.env.OIDC_TOKEN_URL;
|
||||
if (
|
||||
!client_id ||
|
||||
!client_secret ||
|
||||
!issuer_url ||
|
||||
!authorization_url ||
|
||||
!token_url
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
client_id,
|
||||
client_secret,
|
||||
issuer_url,
|
||||
authorization_url,
|
||||
token_url,
|
||||
userinfo_url: process.env.OIDC_USERINFO_URL || "",
|
||||
identifier_path: process.env.OIDC_IDENTIFIER_PATH || "sub",
|
||||
name_path: process.env.OIDC_NAME_PATH || "name",
|
||||
scopes: process.env.OIDC_SCOPES || "openid email profile",
|
||||
allowed_users: process.env.OIDC_ALLOWED_USERS || "",
|
||||
admin_group: process.env.OIDC_ADMIN_GROUP || "",
|
||||
group_claim: process.env.OIDC_GROUP_CLAIM || "",
|
||||
role_map: process.env.OIDC_ROLE_MAP || "",
|
||||
};
|
||||
}
|
||||
|
||||
export function isEnvOverrideEnabled(): boolean {
|
||||
return process.env.OIDC_ENV_OVERRIDE?.toLowerCase() === "true";
|
||||
}
|
||||
|
||||
function envProvider(config: OidcConfig): ResolvedProvider {
|
||||
// Env providers were set up against the 2.8 callback and cannot be edited.
|
||||
return { config, type: "oidc", rowId: null, legacyCallback: true };
|
||||
}
|
||||
|
||||
export type ProviderStore = ReturnType<typeof createProviderStore>;
|
||||
|
||||
export function createProviderStore(ctx: PluginContext, table: Table) {
|
||||
const client = () => ctx.db.client<Drizzle>();
|
||||
|
||||
/** Opens a stored secret: sealed, or the 2.8 base64 forms. */
|
||||
async function openSecret(value: string): Promise<string> {
|
||||
const prefix = LEGACY_PREFIXES.find((p) => value.startsWith(p));
|
||||
if (prefix) {
|
||||
try {
|
||||
return Buffer.from(value.slice(prefix.length), "base64").toString(
|
||||
"utf8",
|
||||
);
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
const opened = await ctx.secrets.unseal(value);
|
||||
// A value seal() never wrote was stored in the clear by hand.
|
||||
return opened ?? value;
|
||||
}
|
||||
|
||||
async function parseConfig(raw: string): Promise<Record<string, unknown>> {
|
||||
let config: Record<string, unknown>;
|
||||
try {
|
||||
config = JSON.parse(raw);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
for (const field of SECRET_FIELDS) {
|
||||
const value = config[field];
|
||||
if (typeof value === "string" && value) {
|
||||
config[field] = await openSecret(value);
|
||||
}
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
async function sealConfig(config: Record<string, unknown>): Promise<string> {
|
||||
const out = { ...config };
|
||||
for (const field of SECRET_FIELDS) {
|
||||
const value = out[field];
|
||||
if (typeof value === "string" && value) {
|
||||
out[field] = await ctx.secrets.seal(value);
|
||||
}
|
||||
}
|
||||
return JSON.stringify(out);
|
||||
}
|
||||
|
||||
async function listRows(): Promise<ProviderRow[]> {
|
||||
const drizzle = await client();
|
||||
const rows = (await drizzle
|
||||
.select()
|
||||
.from(table)
|
||||
.orderBy(asc(table.displayOrder), asc(table.id))) as ProviderRow[];
|
||||
return rows.filter((row) => isSsoType(row.type));
|
||||
}
|
||||
|
||||
async function findRow(id: number): Promise<ProviderRow | null> {
|
||||
const drizzle = await client();
|
||||
const rows = (await drizzle
|
||||
.select()
|
||||
.from(table)
|
||||
.where(eq(table.id, id))
|
||||
.limit(1)) as ProviderRow[];
|
||||
const row = rows[0];
|
||||
return row && isSsoType(row.type) ? row : null;
|
||||
}
|
||||
|
||||
async function resolveRow(row: ProviderRow): Promise<ResolvedProvider> {
|
||||
const type = row.type as SsoProviderType;
|
||||
const config = applyProviderDefaults(
|
||||
(await parseConfig(row.config)) as unknown as OidcConfig,
|
||||
type,
|
||||
);
|
||||
return {
|
||||
config,
|
||||
type,
|
||||
rowId: row.id,
|
||||
legacyCallback: !!row.legacyCallback,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
parseConfig,
|
||||
sealConfig,
|
||||
listRows,
|
||||
findRow,
|
||||
|
||||
/** Login instances: env override, rows, or the env provider alone. */
|
||||
async listInstances(): Promise<
|
||||
Array<{ id: string; label: string; type: SsoProviderType }>
|
||||
> {
|
||||
const env = getOidcConfigFromEnv();
|
||||
const envInstance = {
|
||||
id: ENV_INSTANCE_ID,
|
||||
label: "SSO",
|
||||
type: "oidc" as const,
|
||||
};
|
||||
if (env && isEnvOverrideEnabled()) return [envInstance];
|
||||
const rows = (await listRows()).filter((row) => row.enabled);
|
||||
const instances = rows.map((row) => ({
|
||||
id: String(row.id),
|
||||
label: row.name,
|
||||
type: row.type as SsoProviderType,
|
||||
}));
|
||||
if (instances.length === 0 && env) instances.push(envInstance);
|
||||
return instances;
|
||||
},
|
||||
|
||||
/**
|
||||
* The provider for a login. With no id, the env provider or the first
|
||||
* enabled row, as 2.8 did.
|
||||
*/
|
||||
async resolve(rowId: number | null): Promise<ResolvedProvider | null> {
|
||||
const env = getOidcConfigFromEnv();
|
||||
if (env && isEnvOverrideEnabled()) return envProvider(env);
|
||||
if (rowId != null) {
|
||||
const row = await findRow(rowId);
|
||||
return row?.enabled ? resolveRow(row) : null;
|
||||
}
|
||||
if (env) return envProvider(env);
|
||||
const first = (await listRows()).find((row) => row.enabled);
|
||||
return first ? resolveRow(first) : null;
|
||||
},
|
||||
|
||||
/** The provider a back-channel logout token's issuer belongs to. */
|
||||
async resolveByIssuer(issuer: string): Promise<ResolvedProvider | null> {
|
||||
const target = normalizeIssuer(issuer);
|
||||
const env = getOidcConfigFromEnv();
|
||||
const envMatches =
|
||||
!!env?.issuer_url && normalizeIssuer(env.issuer_url) === target;
|
||||
if (envMatches && isEnvOverrideEnabled()) return envProvider(env!);
|
||||
for (const row of await listRows()) {
|
||||
if (!row.enabled) continue;
|
||||
const resolved = await resolveRow(row);
|
||||
if (
|
||||
resolved.config.issuer_url &&
|
||||
normalizeIssuer(resolved.config.issuer_url) === target
|
||||
) {
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
return envMatches ? envProvider(env!) : null;
|
||||
},
|
||||
|
||||
async create(input: {
|
||||
name: string;
|
||||
type: SsoProviderType;
|
||||
enabled: boolean;
|
||||
displayOrder: number;
|
||||
config: Record<string, unknown>;
|
||||
}): Promise<ProviderRow> {
|
||||
const drizzle = await client();
|
||||
const now = new Date().toISOString();
|
||||
await drizzle.insert(table).values({
|
||||
name: input.name,
|
||||
type: input.type,
|
||||
enabled: input.enabled,
|
||||
displayOrder: input.displayOrder,
|
||||
config: await sealConfig(input.config),
|
||||
legacyCallback: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
await ctx.db.persist();
|
||||
// No returning() on every engine: find the row by what was written.
|
||||
const rows = (await drizzle
|
||||
.select()
|
||||
.from(table)
|
||||
.where(and(eq(table.name, input.name), eq(table.createdAt, now)))
|
||||
.orderBy(desc(table.id))
|
||||
.limit(1)) as ProviderRow[];
|
||||
return rows[0];
|
||||
},
|
||||
|
||||
async update(
|
||||
id: number,
|
||||
values: Partial<{
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
displayOrder: number;
|
||||
config: Record<string, unknown>;
|
||||
legacyCallback: boolean;
|
||||
}>,
|
||||
): Promise<ProviderRow | null> {
|
||||
const drizzle = await client();
|
||||
const { config, ...rest } = values;
|
||||
await drizzle
|
||||
.update(table)
|
||||
.set({
|
||||
...rest,
|
||||
...(config ? { config: await sealConfig(config) } : {}),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
.where(eq(table.id, id));
|
||||
await ctx.db.persist();
|
||||
return findRow(id);
|
||||
},
|
||||
|
||||
async remove(id: number): Promise<void> {
|
||||
const drizzle = await client();
|
||||
await drizzle.delete(table).where(eq(table.id, id));
|
||||
await ctx.db.persist();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
import type { Request, Response, Router } from "express";
|
||||
import {
|
||||
LoginMethodError,
|
||||
type PluginContext,
|
||||
} from "@termix/plugin-sdk/backend";
|
||||
import {
|
||||
applyProviderDefaults,
|
||||
isValidOidcIssuer,
|
||||
validateLogoutToken,
|
||||
} from "./oidc-protocol.js";
|
||||
import { isSsoType, type ProviderStore } from "./providers.js";
|
||||
import { METHOD_ID, redirectUriFor, type SsoLogin } from "./login.js";
|
||||
import type { OidcConfig, ProviderRow, SsoProviderType } from "./types.js";
|
||||
|
||||
export const PUBLIC_PATHS = [
|
||||
"/start",
|
||||
"/callback",
|
||||
"/backchannel-logout",
|
||||
"/config",
|
||||
];
|
||||
|
||||
const LOGOUT_JTI_TTL_MS = 5 * 60 * 1000;
|
||||
const REQUIRED_OIDC_FIELDS = [
|
||||
"client_id",
|
||||
"client_secret",
|
||||
"issuer_url",
|
||||
"authorization_url",
|
||||
"token_url",
|
||||
] as const;
|
||||
|
||||
function fail(
|
||||
ctx: PluginContext,
|
||||
res: Response,
|
||||
message: string,
|
||||
error: unknown,
|
||||
) {
|
||||
ctx.log.error(
|
||||
message,
|
||||
error instanceof Error ? error : new Error(String(error)),
|
||||
);
|
||||
res.status(500).json({ error: message });
|
||||
}
|
||||
|
||||
export function registerSsoRoutes(
|
||||
router: Router,
|
||||
ctx: PluginContext,
|
||||
store: ProviderStore,
|
||||
login: SsoLogin,
|
||||
): void {
|
||||
// Replayed logout tokens are answered but not acted on twice.
|
||||
const seenLogoutJti = new Map<string, number>();
|
||||
|
||||
async function present(req: Request, row: ProviderRow) {
|
||||
const config = await store.parseConfig(row.config);
|
||||
const { client_secret: secret, ...rest } = config;
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
type: row.type,
|
||||
enabled: !!row.enabled,
|
||||
displayOrder: row.displayOrder,
|
||||
legacyCallback: !!row.legacyCallback,
|
||||
config: rest,
|
||||
hasClientSecret: typeof secret === "string" && secret.length > 0,
|
||||
redirectUri: redirectUriFor(ctx.http.baseUrl(req), {
|
||||
legacyCallback: !!row.legacyCallback,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Checks a full provider config; returns the error to show, if any. */
|
||||
function validate(type: SsoProviderType, config: Partial<OidcConfig>) {
|
||||
if (type === "oidc") {
|
||||
const missing = REQUIRED_OIDC_FIELDS.filter((field) => !config[field]);
|
||||
if (missing.length > 0) {
|
||||
return `Missing required OIDC fields: ${missing.join(", ")}`;
|
||||
}
|
||||
} else if (!config.client_id || !config.client_secret) {
|
||||
return "Client ID and Client Secret are required";
|
||||
}
|
||||
if (config.issuer_url && !isValidOidcIssuer(config.issuer_url)) {
|
||||
return "Issuer URL must be an HTTP(S) issuer and not a userinfo endpoint";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/sso/start:
|
||||
* get:
|
||||
* summary: Start an SSO login in the browser
|
||||
* description: Public. Sends the browser straight to the provider, so a link can start a login. The provider is picked by the provider query parameter, or the default one.
|
||||
* tags:
|
||||
* - SSO
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: provider
|
||||
* schema:
|
||||
* type: string
|
||||
* responses:
|
||||
* 302:
|
||||
* description: Redirect to the identity provider.
|
||||
* 404:
|
||||
* description: SSO is not configured.
|
||||
*/
|
||||
router.get("/start", async (req: Request, res: Response) => {
|
||||
try {
|
||||
const instance =
|
||||
typeof req.query.provider === "string" ? req.query.provider : null;
|
||||
const { redirectUrl } = await login.start(req as never, instance);
|
||||
res.redirect(redirectUrl);
|
||||
} catch (error) {
|
||||
if (error instanceof LoginMethodError) {
|
||||
res.status(error.status).json({ error: error.message });
|
||||
return;
|
||||
}
|
||||
fail(ctx, res, "Failed to start SSO login", error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/sso/callback:
|
||||
* get:
|
||||
* summary: SSO callback
|
||||
* description: Public. The redirect URI to register with an identity provider. Exchanges the code and redirects back to the app with a session, a second-factor step or an error.
|
||||
* tags:
|
||||
* - SSO
|
||||
* responses:
|
||||
* 302:
|
||||
* description: Back to the app.
|
||||
* post:
|
||||
* summary: SSO callback (form post)
|
||||
* description: Same as the GET form, for providers that post their answer.
|
||||
* tags:
|
||||
* - SSO
|
||||
* responses:
|
||||
* 302:
|
||||
* description: Back to the app.
|
||||
*/
|
||||
const callback = (req: Request, res: Response) =>
|
||||
ctx.auth.completeRedirectLogin(METHOD_ID, req, res);
|
||||
router.get("/callback", callback);
|
||||
router.post("/callback", callback);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/sso/backchannel-logout:
|
||||
* post:
|
||||
* summary: OIDC back-channel logout
|
||||
* description: Public. Where an identity provider sends a signed logout token. Ends the Termix sessions that came from the matching provider login.
|
||||
* tags:
|
||||
* - SSO
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/x-www-form-urlencoded:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* logout_token:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Logout processed.
|
||||
* 400:
|
||||
* description: Missing, invalid or unknown logout token.
|
||||
*/
|
||||
router.post("/backchannel-logout", async (req: Request, res: Response) => {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
const logoutToken = (req.body as Record<string, unknown> | undefined)
|
||||
?.logout_token;
|
||||
if (typeof logoutToken !== "string" || !logoutToken) {
|
||||
res.status(400).json({ error: "missing logout_token" });
|
||||
return;
|
||||
}
|
||||
|
||||
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) {
|
||||
res.status(400).json({ error: "invalid logout_token" });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const provider = await store.resolveByIssuer(issuer);
|
||||
if (!provider) {
|
||||
ctx.log.warn(`Back-channel logout for unknown issuer ${issuer}`);
|
||||
res.status(400).json({ error: "unknown issuer" });
|
||||
return;
|
||||
}
|
||||
const claims = await validateLogoutToken(logoutToken, provider.config);
|
||||
|
||||
const now = Date.now();
|
||||
for (const [key, expiry] of seenLogoutJti) {
|
||||
if (expiry <= now) seenLogoutJti.delete(key);
|
||||
}
|
||||
if (seenLogoutJti.has(claims.jti)) {
|
||||
res.status(200).json({ ok: true });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await ctx.auth.revokeSessions({
|
||||
providerId: provider.rowId,
|
||||
sub: claims.sub,
|
||||
sid: claims.sid,
|
||||
});
|
||||
} catch (error) {
|
||||
fail(ctx, res, "logout processing failed", error);
|
||||
return;
|
||||
}
|
||||
seenLogoutJti.set(claims.jti, now + LOGOUT_JTI_TTL_MS);
|
||||
res.status(200).json({ ok: true });
|
||||
} catch (error) {
|
||||
ctx.log.warn(`Back-channel logout failed: ${String(error)}`);
|
||||
res.status(400).json({ error: "invalid logout_token" });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/sso/config:
|
||||
* get:
|
||||
* summary: Default provider's public configuration
|
||||
* description: Public, for 2.8 clients. The client id, issuer, authorization URL and scopes of the default provider, or null.
|
||||
* tags:
|
||||
* - SSO
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Public configuration, or null.
|
||||
*/
|
||||
router.get("/config", async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const provider = await store.resolve(null);
|
||||
if (!provider) {
|
||||
res.json(null);
|
||||
return;
|
||||
}
|
||||
const { config } = provider;
|
||||
res.json({
|
||||
client_id: config.client_id,
|
||||
issuer_url: config.issuer_url,
|
||||
authorization_url: config.authorization_url,
|
||||
scopes: config.scopes,
|
||||
});
|
||||
} catch (error) {
|
||||
fail(ctx, res, "Failed to get OIDC config", error);
|
||||
}
|
||||
});
|
||||
|
||||
// Everything below manages providers.
|
||||
const manage = ctx.rbac.require("manage") as never;
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/sso/providers:
|
||||
* get:
|
||||
* summary: List SSO providers
|
||||
* description: Every OIDC, GitHub and Google provider with its redirect URI. Secrets are never sent, only whether one is set. Needs sso.manage.
|
||||
* tags:
|
||||
* - SSO
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Providers.
|
||||
* 403:
|
||||
* description: Missing permission.
|
||||
*/
|
||||
router.get("/providers", manage, async (req: Request, res: Response) => {
|
||||
try {
|
||||
const rows = await store.listRows();
|
||||
res.json({
|
||||
providers: await Promise.all(rows.map((row) => present(req, row))),
|
||||
newRedirectUri: redirectUriFor(ctx.http.baseUrl(req), {
|
||||
legacyCallback: false,
|
||||
}),
|
||||
});
|
||||
} catch (error) {
|
||||
fail(ctx, res, "Failed to list SSO providers", error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/sso/providers:
|
||||
* post:
|
||||
* summary: Add an SSO provider
|
||||
* description: Adds an OIDC, GitHub or Google provider. GitHub and Google fill in their own endpoints. Needs sso.manage.
|
||||
* tags:
|
||||
* - SSO
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* name:
|
||||
* type: string
|
||||
* type:
|
||||
* type: string
|
||||
* enum: [oidc, github, google]
|
||||
* enabled:
|
||||
* type: boolean
|
||||
* config:
|
||||
* type: object
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Provider added.
|
||||
* 400:
|
||||
* description: Missing or invalid fields.
|
||||
* 403:
|
||||
* description: Missing permission.
|
||||
*/
|
||||
router.post("/providers", manage, async (req: Request, res: Response) => {
|
||||
try {
|
||||
const {
|
||||
name,
|
||||
type,
|
||||
enabled = true,
|
||||
displayOrder = 0,
|
||||
config = {},
|
||||
} = req.body ?? {};
|
||||
if (typeof name !== "string" || !name.trim()) {
|
||||
res.status(400).json({ error: "Provider name is required" });
|
||||
return;
|
||||
}
|
||||
if (!isSsoType(type)) {
|
||||
res.status(400).json({ error: "Invalid provider type" });
|
||||
return;
|
||||
}
|
||||
const full = applyProviderDefaults(config as OidcConfig, type);
|
||||
const invalid = validate(type, full);
|
||||
if (invalid) {
|
||||
res.status(400).json({ error: invalid });
|
||||
return;
|
||||
}
|
||||
const row = await store.create({
|
||||
name: name.trim(),
|
||||
type,
|
||||
enabled: !!enabled,
|
||||
displayOrder: Number(displayOrder) || 0,
|
||||
config: { ...(config as Record<string, unknown>) },
|
||||
});
|
||||
await ctx.audit.record({
|
||||
action: "sso_provider_create",
|
||||
resourceType: "sso_provider",
|
||||
resourceId: String(row.id),
|
||||
resourceName: row.name,
|
||||
success: true,
|
||||
});
|
||||
res.status(201).json(await present(req, row));
|
||||
} catch (error) {
|
||||
fail(ctx, res, "Failed to create SSO provider", error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/sso/providers/{id}:
|
||||
* put:
|
||||
* summary: Update an SSO provider
|
||||
* description: Changes a provider. Config fields are merged over the stored ones; an empty client secret keeps the stored secret. legacyCallback false moves it to the new redirect URI. Needs sso.manage.
|
||||
* tags:
|
||||
* - SSO
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Provider updated.
|
||||
* 400:
|
||||
* description: Invalid fields.
|
||||
* 403:
|
||||
* description: Missing permission.
|
||||
* 404:
|
||||
* description: Provider not found.
|
||||
*/
|
||||
router.put("/providers/:id", manage, async (req: Request, res: Response) => {
|
||||
try {
|
||||
const id = Number.parseInt(String(req.params.id), 10);
|
||||
const row = Number.isInteger(id) ? await store.findRow(id) : null;
|
||||
if (!row) {
|
||||
res.status(404).json({ error: "Provider not found" });
|
||||
return;
|
||||
}
|
||||
const { name, enabled, displayOrder, config, legacyCallback } =
|
||||
req.body ?? {};
|
||||
const values: Parameters<ProviderStore["update"]>[1] = {};
|
||||
if (name !== undefined) {
|
||||
if (typeof name !== "string" || !name.trim()) {
|
||||
res.status(400).json({ error: "Provider name is required" });
|
||||
return;
|
||||
}
|
||||
values.name = name.trim();
|
||||
}
|
||||
if (enabled !== undefined) values.enabled = !!enabled;
|
||||
if (displayOrder !== undefined) {
|
||||
values.displayOrder = Number(displayOrder) || 0;
|
||||
}
|
||||
if (legacyCallback !== undefined) {
|
||||
values.legacyCallback = !!legacyCallback;
|
||||
}
|
||||
if (config && typeof config === "object") {
|
||||
const incoming = { ...(config as Record<string, unknown>) };
|
||||
if (!incoming.client_secret) delete incoming.client_secret;
|
||||
const merged = {
|
||||
...(await store.parseConfig(row.config)),
|
||||
...incoming,
|
||||
};
|
||||
const invalid = validate(
|
||||
row.type as SsoProviderType,
|
||||
applyProviderDefaults(merged as unknown as OidcConfig, row.type),
|
||||
);
|
||||
if (invalid) {
|
||||
res.status(400).json({ error: invalid });
|
||||
return;
|
||||
}
|
||||
values.config = merged;
|
||||
}
|
||||
const updated = await store.update(id, values);
|
||||
await ctx.audit.record({
|
||||
action: "sso_provider_update",
|
||||
resourceType: "sso_provider",
|
||||
resourceId: String(id),
|
||||
resourceName: updated?.name ?? row.name,
|
||||
success: true,
|
||||
});
|
||||
res.json(await present(req, updated ?? row));
|
||||
} catch (error) {
|
||||
fail(ctx, res, "Failed to update SSO provider", error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/sso/providers/{id}:
|
||||
* delete:
|
||||
* summary: Delete an SSO provider
|
||||
* description: Refused while users still sign in with it. Needs sso.manage.
|
||||
* tags:
|
||||
* - SSO
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Provider deleted.
|
||||
* 403:
|
||||
* description: Missing permission.
|
||||
* 404:
|
||||
* description: Provider not found.
|
||||
* 409:
|
||||
* description: Users are still linked to it.
|
||||
*/
|
||||
router.delete(
|
||||
"/providers/:id",
|
||||
manage,
|
||||
async (req: Request, res: Response) => {
|
||||
try {
|
||||
const id = Number.parseInt(String(req.params.id), 10);
|
||||
const row = Number.isInteger(id) ? await store.findRow(id) : null;
|
||||
if (!row) {
|
||||
res.status(404).json({ error: "Provider not found" });
|
||||
return;
|
||||
}
|
||||
if ((await ctx.auth.countLinkedUsers(String(id))) > 0) {
|
||||
res.status(409).json({
|
||||
error:
|
||||
"Users still sign in with this provider. Disable it instead, or remove those users first.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
await store.remove(id);
|
||||
await ctx.audit.record({
|
||||
action: "sso_provider_delete",
|
||||
resourceType: "sso_provider",
|
||||
resourceId: String(id),
|
||||
resourceName: row.name,
|
||||
success: true,
|
||||
});
|
||||
res.json({ message: "SSO provider deleted" });
|
||||
} catch (error) {
|
||||
fail(ctx, res, "Failed to delete SSO provider", error);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
adoptLegacyTable,
|
||||
boolean,
|
||||
defineTable,
|
||||
id,
|
||||
integer,
|
||||
text,
|
||||
timestamp,
|
||||
} from "@termix/plugin-sdk/db";
|
||||
|
||||
/**
|
||||
* Adopted from core's sso_providers, so the column names are the legacy ones
|
||||
* and the rename carries every provider across. LDAP rows are moved out to
|
||||
* the ldap plugin by core's boot migration; until then they are ignored here.
|
||||
*/
|
||||
export const providers = adoptLegacyTable(
|
||||
"sso_providers",
|
||||
defineTable("providers", {
|
||||
id: id(),
|
||||
name: text().notNull(),
|
||||
type: text().notNull(),
|
||||
enabled: boolean().notNull().default(true),
|
||||
displayOrder: integer().notNull().default(0),
|
||||
config: text().notNull(),
|
||||
createdAt: timestamp().notNull().defaultNow(),
|
||||
updatedAt: timestamp().notNull().defaultNow(),
|
||||
// Providers from before 2.9 keep sending the old redirect URI.
|
||||
legacyCallback: boolean().notNull().default(false),
|
||||
}),
|
||||
);
|
||||
|
||||
export const tables = [providers];
|
||||
@@ -0,0 +1,46 @@
|
||||
export type SsoProviderType = "oidc" | "github" | "google";
|
||||
|
||||
export const SSO_PROVIDER_TYPES: readonly SsoProviderType[] = [
|
||||
"oidc",
|
||||
"github",
|
||||
"google",
|
||||
];
|
||||
|
||||
export interface OidcConfig {
|
||||
client_id: string;
|
||||
client_secret: string;
|
||||
issuer_url: string;
|
||||
authorization_url: string;
|
||||
token_url: string;
|
||||
userinfo_url: string;
|
||||
identifier_path: string;
|
||||
name_path: string;
|
||||
scopes: string;
|
||||
allowed_users: string;
|
||||
admin_group: string;
|
||||
group_claim?: string;
|
||||
role_map?: string;
|
||||
ca_cert?: string;
|
||||
}
|
||||
|
||||
/** A provider ready to sign someone in: secrets opened, defaults applied. */
|
||||
export interface ResolvedProvider {
|
||||
config: OidcConfig;
|
||||
type: SsoProviderType;
|
||||
/** The row id, or null for the provider configured through OIDC_* env vars. */
|
||||
rowId: number | null;
|
||||
/** Sends the 2.8 redirect URI, /users/oidc/callback, which core forwards. */
|
||||
legacyCallback: boolean;
|
||||
}
|
||||
|
||||
export interface ProviderRow {
|
||||
id: number;
|
||||
name: string;
|
||||
type: string;
|
||||
enabled: boolean;
|
||||
displayOrder: number;
|
||||
config: string;
|
||||
legacyCallback: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useState } from "react";
|
||||
import { Button } from "@termix/plugin-sdk/ui";
|
||||
import {
|
||||
useTranslation,
|
||||
type LoginMethodUIProps,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
|
||||
/** One button per enabled provider. */
|
||||
export function OidcLoginButtons({
|
||||
instances,
|
||||
disabled,
|
||||
startRedirect,
|
||||
}: LoginMethodUIProps) {
|
||||
const { t } = useTranslation();
|
||||
const [loadingId, setLoadingId] = useState<string | null>(null);
|
||||
return (
|
||||
<>
|
||||
{instances.map((instance) => (
|
||||
<Button
|
||||
key={instance.id}
|
||||
onClick={async () => {
|
||||
setLoadingId(instance.id);
|
||||
try {
|
||||
await startRedirect(instance.id);
|
||||
} finally {
|
||||
setLoadingId(null);
|
||||
}
|
||||
}}
|
||||
disabled={disabled || loadingId !== null}
|
||||
className="w-full bg-accent-brand hover:bg-accent-brand/90 text-background font-bold"
|
||||
>
|
||||
{loadingId === instance.id
|
||||
? t("loading")
|
||||
: t("loginWithProvider", { name: instance.label })}
|
||||
</Button>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,580 @@
|
||||
import { useCallback, useEffect, useState, type ReactNode } from "react";
|
||||
import { Copy, Pencil, Plus, Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
Input,
|
||||
Select2,
|
||||
Switch,
|
||||
copyToClipboard,
|
||||
} from "@termix/plugin-sdk/ui";
|
||||
import { usePluginApi, useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import {
|
||||
createSsoApi,
|
||||
type SsoProvider,
|
||||
type SsoProviderInput,
|
||||
type SsoProviderType,
|
||||
} from "./sso-api";
|
||||
|
||||
const TYPE_LABELS: Record<SsoProviderType, string> = {
|
||||
oidc: "OIDC",
|
||||
github: "GitHub",
|
||||
google: "Google",
|
||||
};
|
||||
|
||||
const AUTHORIZATION_URLS: Record<"github" | "google", string> = {
|
||||
github: "https://github.com/login/oauth/authorize",
|
||||
google: "https://accounts.google.com/o/oauth2/v2/auth",
|
||||
};
|
||||
|
||||
type Fields = {
|
||||
client_id: string;
|
||||
client_secret: string;
|
||||
issuer_url: string;
|
||||
authorization_url: string;
|
||||
token_url: string;
|
||||
userinfo_url: string;
|
||||
identifier_path: string;
|
||||
name_path: string;
|
||||
scopes: string;
|
||||
allowed_users: string;
|
||||
admin_group: string;
|
||||
group_claim: string;
|
||||
ca_cert: string;
|
||||
};
|
||||
|
||||
const EMPTY_FIELDS: Fields = {
|
||||
client_id: "",
|
||||
client_secret: "",
|
||||
issuer_url: "",
|
||||
authorization_url: "",
|
||||
token_url: "",
|
||||
userinfo_url: "",
|
||||
identifier_path: "sub",
|
||||
name_path: "name",
|
||||
scopes: "openid email profile",
|
||||
allowed_users: "",
|
||||
admin_group: "",
|
||||
group_claim: "",
|
||||
ca_cert: "",
|
||||
};
|
||||
|
||||
function errorMessage(error: unknown, fallback: string): string {
|
||||
const err = error as {
|
||||
response?: { data?: { error?: string } };
|
||||
message?: string;
|
||||
};
|
||||
return err.response?.data?.error || err.message || fallback;
|
||||
}
|
||||
|
||||
const labelClass =
|
||||
"text-[10px] font-semibold text-muted-foreground uppercase tracking-widest";
|
||||
const areaClass =
|
||||
"w-full px-2 py-1.5 text-xs bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring font-mono";
|
||||
|
||||
function Field({
|
||||
label,
|
||||
required,
|
||||
hint,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
required?: boolean;
|
||||
hint?: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className={labelClass}>
|
||||
{label}
|
||||
{required && <span className="text-accent-brand ml-1">*</span>}
|
||||
</label>
|
||||
{hint && (
|
||||
<span className="text-[10px] text-muted-foreground">{hint}</span>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RedirectUri({ uri }: { uri: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<code className="flex-1 min-w-0 truncate text-[10px] font-mono text-muted-foreground bg-muted px-1.5 py-1">
|
||||
{uri}
|
||||
</code>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 text-muted-foreground hover:text-foreground"
|
||||
title={t("providers.copy")}
|
||||
onClick={async () => {
|
||||
await copyToClipboard(uri);
|
||||
toast.success(t("providers.copied"));
|
||||
}}
|
||||
>
|
||||
<Copy className="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProviderDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
provider,
|
||||
newRedirectUri,
|
||||
onSaved,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
provider: SsoProvider | null;
|
||||
newRedirectUri: string;
|
||||
onSaved: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const api = createSsoApi(usePluginApi());
|
||||
const isEdit = provider !== null;
|
||||
const [name, setName] = useState("");
|
||||
const [type, setType] = useState<SsoProviderType>("oidc");
|
||||
const [enabled, setEnabled] = useState(true);
|
||||
const [legacyCallback, setLegacyCallback] = useState(false);
|
||||
const [fields, setFields] = useState<Fields>(EMPTY_FIELDS);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setName(provider?.name ?? "");
|
||||
setType(provider?.type ?? "oidc");
|
||||
setEnabled(provider?.enabled ?? true);
|
||||
setLegacyCallback(provider?.legacyCallback ?? false);
|
||||
const config = provider?.config ?? {};
|
||||
const next = { ...EMPTY_FIELDS };
|
||||
for (const key of Object.keys(next) as Array<keyof Fields>) {
|
||||
const value = config[key];
|
||||
if (typeof value === "string") next[key] = value;
|
||||
}
|
||||
next.client_secret = "";
|
||||
setFields(next);
|
||||
}, [open, provider]);
|
||||
|
||||
const set = (key: keyof Fields) => (value: string) =>
|
||||
setFields((prev) => ({ ...prev, [key]: value }));
|
||||
const simplified = type !== "oidc";
|
||||
|
||||
async function save() {
|
||||
if (!name.trim()) {
|
||||
toast.error(t("providers.nameRequired"));
|
||||
return;
|
||||
}
|
||||
const config: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(fields)) {
|
||||
if (value.trim()) config[key] = value.trim();
|
||||
}
|
||||
const input: SsoProviderInput = {
|
||||
name: name.trim(),
|
||||
type,
|
||||
enabled,
|
||||
config,
|
||||
...(isEdit ? { legacyCallback } : {}),
|
||||
};
|
||||
setSaving(true);
|
||||
try {
|
||||
if (provider) await api.update(provider.id, input);
|
||||
else await api.create(input);
|
||||
toast.success(t("providers.saved"));
|
||||
onSaved();
|
||||
onOpenChange(false);
|
||||
} catch (error) {
|
||||
toast.error(errorMessage(error, t("providers.saveFailed")));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
const secretHint = provider?.hasClientSecret
|
||||
? t("fields.secretKeep")
|
||||
: undefined;
|
||||
const redirectUri = legacyCallback
|
||||
? (provider?.redirectUri ?? newRedirectUri)
|
||||
: newRedirectUri;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{isEdit ? t("providers.edit") : t("providers.add")}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col gap-3 pt-2">
|
||||
<Field label={t("providers.name")} required>
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder={t("providers.namePlaceholder")}
|
||||
className="text-xs"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
{!isEdit && (
|
||||
<Field label={t("providers.type")}>
|
||||
<Select2
|
||||
value={type}
|
||||
onChange={(e) => setType(e.target.value as SsoProviderType)}
|
||||
className="w-full px-2 py-1.5 text-xs bg-background border border-border text-foreground outline-none focus:ring-1 focus:ring-ring"
|
||||
>
|
||||
{(Object.keys(TYPE_LABELS) as SsoProviderType[]).map(
|
||||
(value) => (
|
||||
<option key={value} value={value}>
|
||||
{TYPE_LABELS[value]}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</Select2>
|
||||
</Field>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<label className={labelClass}>{t("providers.enabled")}</label>
|
||||
<Switch checked={enabled} onCheckedChange={setEnabled} />
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1 border-t border-border pt-3">
|
||||
<label className={labelClass}>{t("providers.redirectUri")}</label>
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{t("providers.redirectUriDesc")}
|
||||
</span>
|
||||
<RedirectUri uri={redirectUri} />
|
||||
{isEdit && provider.legacyCallback && (
|
||||
<div className="flex items-start justify-between gap-3 pt-1">
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{t("providers.legacyCallbackDesc", {
|
||||
uri: newRedirectUri,
|
||||
})}
|
||||
</span>
|
||||
<Switch
|
||||
checked={legacyCallback}
|
||||
onCheckedChange={setLegacyCallback}
|
||||
aria-label={t("providers.legacyCallback")}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 border-t border-border pt-3">
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
<a
|
||||
href={
|
||||
simplified
|
||||
? "https://docs.termix.site/features/authentication/github-google"
|
||||
: "https://docs.termix.site/features/authentication/oidc"
|
||||
}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-accent-brand hover:underline"
|
||||
>
|
||||
{t("providers.docsLink")}
|
||||
</a>
|
||||
</span>
|
||||
<Field label={t("fields.clientId")} required>
|
||||
<Input
|
||||
value={fields.client_id}
|
||||
onChange={(e) => set("client_id")(e.target.value)}
|
||||
placeholder="your-client-id"
|
||||
className="text-xs"
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label={t("fields.clientSecret")}
|
||||
required={!provider?.hasClientSecret}
|
||||
hint={secretHint}
|
||||
>
|
||||
<Input
|
||||
type="password"
|
||||
value={fields.client_secret}
|
||||
onChange={(e) => set("client_secret")(e.target.value)}
|
||||
placeholder="your-client-secret"
|
||||
className="text-xs"
|
||||
/>
|
||||
</Field>
|
||||
{simplified ? (
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{t("providers.authorizationUrl", {
|
||||
url: AUTHORIZATION_URLS[type as "github" | "google"],
|
||||
})}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<Field label={t("fields.issuerUrl")} required>
|
||||
<Input
|
||||
value={fields.issuer_url}
|
||||
onChange={(e) => set("issuer_url")(e.target.value)}
|
||||
placeholder="https://provider"
|
||||
className="text-xs"
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("fields.authUrl")} required>
|
||||
<Input
|
||||
value={fields.authorization_url}
|
||||
onChange={(e) => set("authorization_url")(e.target.value)}
|
||||
placeholder="https://provider/oauth2/auth"
|
||||
className="text-xs"
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("fields.tokenUrl")} required>
|
||||
<Input
|
||||
value={fields.token_url}
|
||||
onChange={(e) => set("token_url")(e.target.value)}
|
||||
placeholder="https://provider/oauth2/token"
|
||||
className="text-xs"
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("fields.userIdentifier")} required>
|
||||
<Input
|
||||
value={fields.identifier_path}
|
||||
onChange={(e) => set("identifier_path")(e.target.value)}
|
||||
placeholder="sub"
|
||||
className="text-xs"
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("fields.displayName")} required>
|
||||
<Input
|
||||
value={fields.name_path}
|
||||
onChange={(e) => set("name_path")(e.target.value)}
|
||||
placeholder="name"
|
||||
className="text-xs"
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("fields.scopes")} required>
|
||||
<Input
|
||||
value={fields.scopes}
|
||||
onChange={(e) => set("scopes")(e.target.value)}
|
||||
placeholder="openid email profile"
|
||||
className="text-xs"
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("fields.userinfoUrl")}>
|
||||
<Input
|
||||
value={fields.userinfo_url}
|
||||
onChange={(e) => set("userinfo_url")(e.target.value)}
|
||||
placeholder="https://provider/oauth2/userinfo"
|
||||
className="text-xs"
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label={t("fields.groupClaim")}
|
||||
hint={t("fields.groupClaimDesc")}
|
||||
>
|
||||
<Input
|
||||
value={fields.group_claim}
|
||||
onChange={(e) => set("group_claim")(e.target.value)}
|
||||
placeholder="groups"
|
||||
className="text-xs"
|
||||
/>
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
<Field
|
||||
label={t("fields.allowedUsers")}
|
||||
hint={t("fields.allowedUsersDesc")}
|
||||
>
|
||||
<textarea
|
||||
value={fields.allowed_users}
|
||||
onChange={(e) => set("allowed_users")(e.target.value)}
|
||||
placeholder={"user@example.com\nanother@example.com"}
|
||||
rows={3}
|
||||
className={areaClass}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label={t("fields.adminGroup")}
|
||||
hint={t("fields.adminGroupDesc")}
|
||||
>
|
||||
<Input
|
||||
value={fields.admin_group}
|
||||
onChange={(e) => set("admin_group")(e.target.value)}
|
||||
placeholder="admin"
|
||||
className="text-xs"
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("fields.caCert")} hint={t("fields.caCertDesc")}>
|
||||
<textarea
|
||||
value={fields.ca_cert}
|
||||
onChange={(e) => set("ca_cert")(e.target.value)}
|
||||
placeholder={
|
||||
"-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----"
|
||||
}
|
||||
rows={4}
|
||||
className={areaClass}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 justify-end pt-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-xs"
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
{t("providers.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
|
||||
onClick={save}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? t("providers.saving") : t("providers.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The "providers" custom field on the plugin's admin settings page: the
|
||||
* provider list with an editor, which a schema field cannot express.
|
||||
*/
|
||||
export function ProvidersSetting() {
|
||||
const { t } = useTranslation();
|
||||
const api = createSsoApi(usePluginApi());
|
||||
const [providers, setProviders] = useState<SsoProvider[] | null>(null);
|
||||
const [newRedirectUri, setNewRedirectUri] = useState("");
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<SsoProvider | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const result = await api.list();
|
||||
setProviders(result.providers);
|
||||
setNewRedirectUri(result.newRedirectUri);
|
||||
} catch (error) {
|
||||
setProviders([]);
|
||||
toast.error(errorMessage(error, t("providers.loadFailed")));
|
||||
}
|
||||
// api is rebuilt each render from the same client.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
async function toggleEnabled(provider: SsoProvider) {
|
||||
try {
|
||||
await api.update(provider.id, { enabled: !provider.enabled });
|
||||
await load();
|
||||
} catch (error) {
|
||||
toast.error(errorMessage(error, t("providers.saveFailed")));
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(provider: SsoProvider) {
|
||||
if (!window.confirm(t("providers.deleteConfirm"))) return;
|
||||
try {
|
||||
await api.remove(provider.id);
|
||||
toast.success(t("providers.deleted"));
|
||||
await load();
|
||||
} catch (error) {
|
||||
toast.error(errorMessage(error, t("providers.deleteFailed")));
|
||||
}
|
||||
}
|
||||
|
||||
if (providers === null) return null;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
<a
|
||||
href="https://docs.termix.site/features/authentication/sso-providers"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-accent-brand hover:underline"
|
||||
>
|
||||
{t("providers.docsLink")}
|
||||
</a>
|
||||
</span>
|
||||
{providers.length === 0 ? (
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{t("providers.none")}
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{providers.map((provider) => (
|
||||
<div
|
||||
key={provider.id}
|
||||
className="flex flex-col gap-1.5 p-2 border border-border bg-background"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex-1 min-w-0 flex items-center gap-1.5">
|
||||
<span className="text-xs font-medium truncate">
|
||||
{provider.name}
|
||||
</span>
|
||||
<span className="text-[9px] px-1 py-0.5 bg-muted text-muted-foreground font-mono uppercase">
|
||||
{TYPE_LABELS[provider.type] ?? provider.type}
|
||||
</span>
|
||||
</div>
|
||||
<Switch
|
||||
checked={provider.enabled}
|
||||
onCheckedChange={() => void toggleEnabled(provider)}
|
||||
aria-label={t("providers.enabled")}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => {
|
||||
setEditing(provider);
|
||||
setDialogOpen(true);
|
||||
}}
|
||||
title={t("providers.edit")}
|
||||
>
|
||||
<Pencil className="size-3" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => void remove(provider)}
|
||||
title={t("providers.delete")}
|
||||
>
|
||||
<Trash2 className="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<RedirectUri uri={provider.redirectUri} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="self-start text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setDialogOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="size-3" />
|
||||
{t("providers.add")}
|
||||
</Button>
|
||||
<ProviderDialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
provider={editing}
|
||||
newRedirectUri={newRedirectUri}
|
||||
onSaved={() => void load()}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { TermixApp } from "@termix/plugin-sdk/frontend";
|
||||
import { OidcLoginButtons } from "./OidcLoginButtons";
|
||||
import { ProvidersSetting } from "./ProvidersSetting";
|
||||
|
||||
export function activate(app: TermixApp): void {
|
||||
app.registerLoginMethod({
|
||||
id: "oidc",
|
||||
titleKey: "loginWithSso",
|
||||
component: OidcLoginButtons,
|
||||
});
|
||||
app.registerSettingsComponent("providers", ProvidersSetting);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { PluginApiClient } from "@termix/plugin-sdk/frontend";
|
||||
|
||||
export type SsoProviderType = "oidc" | "github" | "google";
|
||||
|
||||
export interface SsoProvider {
|
||||
id: number;
|
||||
name: string;
|
||||
type: SsoProviderType;
|
||||
enabled: boolean;
|
||||
displayOrder: number;
|
||||
legacyCallback: boolean;
|
||||
config: Record<string, unknown>;
|
||||
hasClientSecret: boolean;
|
||||
redirectUri: string;
|
||||
}
|
||||
|
||||
export interface SsoProviderInput {
|
||||
name?: string;
|
||||
type?: SsoProviderType;
|
||||
enabled?: boolean;
|
||||
legacyCallback?: boolean;
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Paths are relative to /plugin-api/sso/. */
|
||||
export function createSsoApi(api: PluginApiClient) {
|
||||
return {
|
||||
async list() {
|
||||
const { data } = await api.get<{
|
||||
providers: SsoProvider[];
|
||||
newRedirectUri: string;
|
||||
}>("/providers");
|
||||
return data;
|
||||
},
|
||||
async create(input: SsoProviderInput) {
|
||||
return (await api.post<SsoProvider>("/providers", input)).data;
|
||||
},
|
||||
async update(id: number, input: SsoProviderInput) {
|
||||
return (await api.put<SsoProvider>(`/providers/${id}`, input)).data;
|
||||
},
|
||||
async remove(id: number) {
|
||||
await api.delete(`/providers/${id}`);
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user