Compare commits

...

7 Commits

Author SHA1 Message Date
wmantly 23d99980ce Merge pull request #3 from theta42/feature/web-ui-rework
Rebuild web UI on the shared theta42 stack; OIDC + local-admin auth
2026-07-23 20:58:54 -04:00
wmantly aa3b3ed515 feat: rebuild web UI on the shared theta42 app stack; OIDC + local admin auth
The web management UI was a bespoke minimal theme with LDAP-bind login.
Rebuild it to match the SSO Manager and Proxy — same stack, same look/feel,
same auth model. The SSH bridge, audit, metrics, and access logic are
unchanged; this is purely the web layer.

Frontend (mirrors proxy/sso):
- Express + EJS with the shared top.ejs/bottom.ejs shell, Bootstrap 5,
  jQuery, jq-repeat, FontAwesome, Socket.IO, and the shared app-base.js /
  val.js client framework (copied verbatim). Vendor libs served from
  node_modules via /static-modules; app assets via /static.
- Dashboard / Sessions / Audit pages render in the common look/feel,
  loading data through the authenticated /api/* endpoints.

Auth (mirrors proxy):
- OIDC against the SSO (utils/oidc.js + routes/auth.js + models/oidc_state)
  plus a local anti-lockout admin (models/user_redis.js, bootstrapped from
  auth.adminUsers[0] / auth.localAdminPass). AuthToken sessions carry the
  group snapshot; middleware gates the data API on adminGroups or the local
  admin. New config: oidc{} + auth.adminUsers/localAdminPass.
- /api/user/me drives the client login state; "Log in with SSO" hidden when
  oidc.enabled is false.

Verified end to end: local admin login -> token -> /api/user/me isAdmin,
metrics/sessions/audit 200 with token / 401 without / 401 bad password;
static + page shells serve; 26 tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 20:57:34 -04:00
wmantly eb8e5b409e Release 1.0.1 — CI portability (test glob + redis service)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 16:26:50 -04:00
wmantly eb2354a7ab Merge pull request #2 from theta42/docs/pages
docs: GitHub Pages site
2026-07-23 16:23:31 -04:00
wmantly 3f8f56ee35 ci: add redis service (audit/metrics/session models need it on import)
model-redis opens a client when models/index is required, so with no
redis the integration test saw ECONNREFUSED as a post-test unhandled
rejection. Provide redis:7 at 127.0.0.1:6379 in CI (mirrors how
sso-manager-node tests run).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 16:22:26 -04:00
wmantly 9ee5b4bbe0 fix: use shell-expanded globs in test scripts (CI portability)
node's own '**' glob expansion for --test worked on local node 22.23 but
not in CI (node 20/22 runners) — 'Could not find test/**/*.test.js'. Use
plain single-star globs the shell expands instead; test files are exactly
one level under test/unit and test/integration.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 16:20:58 -04:00
wmantly 5968722dc0 docs: GitHub Pages site (index, connecting, architecture, installation)
Mirrors the proxy/sso-manager docs-site layout (Jekyll + Bootstrap
default layout, theta42 assets). Documents the username grammar, the TUI
picker, SFTP/WinSCP, how auth/access/key-injection/bridging work, and the
three install paths + the required sshPublicKey write-ACL.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 16:15:47 -04:00
48 changed files with 3340 additions and 374 deletions
+13
View File
@@ -13,6 +13,19 @@ jobs:
name: Run Tests name: Run Tests
runs-on: ubuntu-latest runs-on: ubuntu-latest
# The audit/metrics/session models are redis-backed (model-redis opens a
# client on import), so the tests need a reachable redis at 127.0.0.1:6379.
services:
redis:
image: redis:7-alpine
ports:
- 6379:6379
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s
--health-timeout 3s
--health-retries 10
strategy: strategy:
matrix: matrix:
node-version: [20.x, 22.x] node-version: [20.x, 22.x]
+11
View File
@@ -4,6 +4,17 @@ All notable changes to this project are documented here. Format loosely
follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions
correspond to git tags (`vX.Y.Z`) and `nodejs/package.json`'s `version`. correspond to git tags (`vX.Y.Z`) and `nodejs/package.json`'s `version`.
## [1.1.0] - 2026-07-23
### Changed
- **Rebuilt the web UI on the shared theta42 app stack** so it looks and behaves like the SSO Manager and Proxy: Express + EJS with the same `top.ejs`/`bottom.ejs` shell, Bootstrap 5, jQuery, jq-repeat, FontAwesome, the shared `app-base.js` client framework, and Socket.IO — replacing the bespoke minimal theme. Dashboard, Sessions, and Audit pages now render in the common look/feel.
- **Web-UI auth is now OIDC + a local anti-lockout admin** (the proxy's model), replacing the direct LDAP-bind login. Normal users log in through the SSO ("Log in with SSO"); a local `auth.adminUsers` account (bootstrapped on first boot, password from `auth.localAdminPass`) still works if the SSO is unreachable. Admin access is gated by `auth.adminGroups` or the local admin account. New config: `oidc` block + `auth.adminUsers`/`localAdminPass`. **Note:** the SSH bridge and its own LDAP auth are unchanged — this only affects the web management UI.
## [1.0.1] - 2026-07-23
### Fixed
- Test scripts use shell-expanded globs and CI provides a redis service, so `npm test` runs green on the Node 20/22 CI runners (the `node --test` `**` glob and the redis-backed models only worked locally before). No runtime change.
## [1.0.0] - 2026-07-23 ## [1.0.0] - 2026-07-23
### Added ### Added
+7 -3
View File
@@ -91,9 +91,13 @@ The default SSH port is **2222** so the service needs no privilege. To listen on
## Web UI / API ## Web UI / API
`https://jump.example.com/` (behind the proxy) — admin login uses your LDAP `https://jump.example.com/` (behind the proxy) — built on the same
credentials and requires membership in `auth.adminGroups` (default Express + EJS + Bootstrap stack as the [SSO Manager](https://theta42.github.io/sso-manager-node/)
`app_sso_admin`). and [Proxy](https://theta42.github.io/proxy/), so it looks and behaves like the
rest of the stack. Login is **OIDC against the SSO** (the "Log in with SSO"
button) plus a **local anti-lockout admin** that works even if the SSO is
unreachable. Admin access requires membership in `auth.adminGroups` (default
`app_sso_admin`) or being the local `auth.adminUsers` account.
- `GET /health` — open; `{status, activeSessions, version}` - `GET /health` — open; `{status, activeSessions, version}`
- `GET /api/sessions` — active sessions - `GET /api/sessions` — active sessions
+24
View File
@@ -0,0 +1,24 @@
# Documentation
This directory is the GitHub Pages documentation site for the Jump Host project.
**Live site:** https://theta42.github.io/jump-host/
## Pages
- `index.md` — overview and quick start
- `connecting.md` — usage: the username grammar, the TUI picker, SFTP/WinSCP
- `architecture.md` — how auth, access resolution, key injection, and bridging work
- `installation.md` — Docker, bare-metal, and theta-env install; the LDAP write-ACL
## Local preview
```bash
gem install jekyll bundler
cd docs && jekyll serve
# http://localhost:4000/jump-host/
```
## Updating
Edit the markdown, push to `master`, and GitHub Pages rebuilds automatically.
+41
View File
@@ -0,0 +1,41 @@
title: Jump Host
description: An SSH jump host for the theta42 stack — LDAP-authenticated, directory-driven host bridging with audit and metrics.
url: "https://theta42.github.io"
baseurl: "/jump-host"
logo: /assets/img/theta42.svg
lang: en_US
plugins:
- jekyll-seo-tag
- jekyll-sitemap
github:
repository_url: https://github.com/theta42/jump-host
zip_url: https://github.com/theta42/jump-host/archive/refs/heads/master.zip
tar_url: https://github.com/theta42/jump-host/archive/refs/heads/master.tar.gz
repository_name: theta42/jump-host
nav:
- title: Home
page: /
icon: fa-house
- title: Connecting
page: /connecting.html
icon: fa-terminal
- title: Architecture
page: /architecture.html
icon: fa-sitemap
- title: Installation
page: /installation.html
icon: fa-download
- title: Changelog
url: https://github.com/theta42/jump-host/blob/master/CHANGELOG.md
icon: fa-list
defaults:
- scope:
path: ""
type: "pages"
values:
layout: default
image: /assets/img/theta42.svg
+82
View File
@@ -0,0 +1,82 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="icon" type="image/svg+xml" href="{{ '/assets/img/favicon.svg' | relative_url }}">
{% seo title=false %}
<title>{% if page.title %}{{ page.title }} &middot; {% endif %}{{ site.title }}</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
<link rel="stylesheet" href="{{ '/assets/css/style.css' | relative_url }}">
</head>
<body class="d-flex flex-column min-vh-100">
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
<div class="container-fluid px-3">
<a class="navbar-brand d-flex align-items-center" href="{{ '/' | relative_url }}">
<img src="{{ '/assets/img/theta42.svg' | relative_url }}" height="28" class="me-2" alt="">
{{ site.title }}
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navMain" aria-controls="navMain" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse justify-content-end" id="navMain">
<ul class="navbar-nav">
{% for item in site.nav %}
<li class="nav-item">
{% if item.page %}
<a class="nav-link{% if page.url == item.page %} active{% endif %}" href="{{ item.page | relative_url }}">
{% if item.icon %}<i class="fa-solid {{ item.icon }}"></i>{% endif %} {{ item.title }}
</a>
{% else %}
<a class="nav-link" href="{{ item.url }}" target="_blank" rel="noopener">
{% if item.icon %}<i class="fa-solid {{ item.icon }}"></i>{% endif %} {{ item.title }}
</a>
{% endif %}
</li>
{% endfor %}
</ul>
</div>
</div>
</nav>
<main class="flex-grow-1" style="margin-top: 4.5rem;">
<div class="container-fluid py-4 py-md-5">
<div class="row justify-content-center">
<div class="col-12 col-lg-10 col-xl-8">
<div class="card shadow-lg">
<div class="card-body p-4 p-md-5 site-content">
{{ content }}
</div>
</div>
</div>
</div>
</div>
</main>
<footer class="py-3 bg-dark text-light mt-auto">
<div class="container-fluid d-flex flex-wrap justify-content-between align-items-center small gap-2 px-3">
<span class="d-flex align-items-center gap-2">
<a href="https://theta42.com" target="_blank" rel="noopener">
<img width="40" src="{{ '/assets/img/theta42.svg' | relative_url }}" alt="theta42">
</a>
&copy; {{ 'now' | date: '%Y' }} theta42 &middot;
<a href="{{ site.github.repository_url }}/blob/master/LICENSE" target="_blank" rel="noopener" class="text-light">MIT License</a>
</span>
<span class="d-flex align-items-center gap-3">
<a href="{{ site.github.repository_url }}" target="_blank" rel="noopener" class="text-light text-decoration-none">
<i class="fa-brands fa-github"></i> GitHub
</a>
<a href="{{ site.github.repository_url }}/blob/master/CHANGELOG.md" target="_blank" rel="noopener" class="text-light text-decoration-none">
<i class="fa-solid fa-list"></i> Changelog
</a>
</span>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
+125
View File
@@ -0,0 +1,125 @@
---
layout: default
title: Architecture
description: How the jump host authenticates users, resolves reachable hosts from the directory, injects per-user keys, and bridges SSH — plus the web UI and audit model.
---
# Architecture
The jump host is a Node.js service (using [`ssh2`](https://github.com/mscdex/ssh2)
as both an SSH **server** and **client**) with two faces: the SSH front door
(default `:2222`) and a web UI/API (`:3002`). It holds no user database of its
own — identity, authorization, and onward credentials all come from the shared
directory.
```
┌────────────────────── jump host ──────────────────────┐
ssh │ ssh2 Server (:2222) │ ssh2 Client
─────┼─▶ 1. authenticate user ──▶ LDAP (sshPublicKey / bind) │ ───────────▶ downstream
user │ 2. resolve target ──▶ SSO /api/discovery │ sshd (as the
│ 3. inject key ──▶ LDAP (add sshPublicKey) │ real user)
│ 4. bridge channels ◀───────────────────────────────▶ │
│ web UI/API (:3002) ──▶ audit + metrics (redis) │
└───────────────────────────────────────────────────────┘
```
## 1. Inbound authentication
When a user connects, the jump host authenticates them against LDAP:
- **Public key** — it looks up the user's `sshPublicKey` values in the directory
and matches the offered key (handling ssh2's probe-then-sign two-phase
publickey auth). The jump host's *own* injected key (identified by its comment
marker) is deliberately excluded from this match — only the jump host may hold
that private key, so accepting it inbound would be a bypass.
- **Password** — an LDAP simple bind as the user's DN. Policy is configurable:
`off` (keys only — recommended for a public host), `local` (passwords only
from loopback/RFC1918 clients, keys-only from the internet), or `all`.
Every attempt — success or failure, with method and reason — is audited.
## 2. Access & target resolution
The hosts a user may reach are computed from the directory, not a local list:
1. The user's LDAP group memberships (`(&(objectClass=groupOfNames)(member=…))`).
2. For each group, the SSO's
`GET /api/discovery/resources?group=<cn>` (authenticated with an API token),
unioned and filtered to `kind: host`.
Each host's dial address is `metadata.ip` (or the hostname from
`metadata.address`) and port `metadata.sshPort` (default 22). Results are cached
briefly per user and shared by both the grammar path and the TUI picker.
Target matching tries, in order: exact slug → `host_`-prefixed slug → display
name → IP → address hostname. A raw IP that isn't an accessible directory host
is refused unless explicitly allowed.
> The directory auto-creates `<slug>_access` / `<slug>_admin` groups for every
> host and service (see the SSO's
> [Directory & Inventory](https://theta42.github.io/sso-manager-node/directory.html)
> docs), which is exactly what this authorization reads.
## 3. Per-user key injection {#per-user-key-injection}
The jump host holds **one** keypair. To connect downstream *as the user*
without asking them for anything, it must present a key the downstream `sshd`
will accept for that user. Downstream hosts (joined via
[ldap-client](https://github.com/theta42/ldap-client)) serve authorized keys
straight from LDAP via `AuthorizedKeysCommand`. So on a user's first connection,
the jump host appends its own public key to that user's `sshPublicKey` attribute
in LDAP — comment-marked so it's recognizable — then connects downstream with
its private key.
- Idempotent: the key is added once; a redis flag skips the LDAP round-trip
afterwards.
- The jump host's bind account therefore needs **write access to the
`sshPublicKey` attribute** on user entries (an OpenLDAP ACL — see the README).
In the bundled theta-env deployment this is handled for you.
- Because the marker key is excluded from inbound auth (step 1), it grants only
the jump host's onward path, never inbound impersonation.
## 4. Bridging
Once the upstream connection is ready, the jump host splices SSH channels
between the two connections:
- **shell / exec** — piped both ways, with window-change and exit-status
forwarded.
- **SFTP subsystem** — the two subsystem channels are raw-piped as opaque bytes;
no SFTP protocol parsing is needed, which is why WinSCP and `sftp` work
unchanged.
- Channel requests that arrive before the upstream is ready are buffered and
replayed, so nothing is dropped during the connect.
- The downstream host key's SHA256 fingerprint is recorded in the audit event
(trust-on-use in v1).
Byte counts per direction are tallied cheaply for the audit record.
## Web UI, API & audit
An Express + EJS + Bootstrap app on `:3002` — the same front-end stack and
look/feel as the SSO Manager and Proxy. Login is OIDC against the SSO plus a
local anti-lockout admin (`auth.adminUsers`), with admin access gated by
`auth.adminGroups`. It exposes:
- `GET /health` — open; `{status, activeSessions, version}`
- `GET /api/sessions` — active sessions
- `GET /api/audit?page=&uid=&target=&status=` — the paged audit log
- `GET /api/metrics` — counters (total, failures, top users/hosts)
Audit events and counters live in redis. Each event captures: user, auth method,
mode (grammar/picker), target slug/address/port, channel type, client IP,
success + failure reason, downstream host-key fingerprint, timing, and bytes in/out.
## Where it sits in the stack
- **[SSO Manager](https://theta42.github.io/sso-manager-node/)** — provides the
OpenLDAP directory (users, groups, `sshPublicKey`) and the inventory API this
jump host reads.
- **[ldap-client](https://github.com/theta42/ldap-client)** — enrolls the
downstream Linux hosts (SSSD/PAM + `AuthorizedKeysCommand`) that the jump host
connects into.
- **[Proxy](https://theta42.github.io/proxy/)** — fronts the jump host's web UI
under TLS.
- **[theta-env](https://theta42.github.io/theta-env/)** — wires it all together.
+116
View File
@@ -0,0 +1,116 @@
/* theta42 docs site — shares the in-app dark navbar/footer + card look
(Bootstrap 5 + Font Awesome, same as the running apps) rather than a
generic Jekyll theme. */
body {
background-color: #f4f5f6;
}
.navbar-brand img {
filter: drop-shadow(0 0 2px rgba(0, 0, 0, .4));
}
.navbar-nav .nav-link.active {
color: #fff;
font-weight: 600;
}
/* Markdown content typography, scoped to the card body so it doesn't leak
into the nav/footer. */
.site-content h1:first-child {
margin-top: 0;
}
.site-content h1,
.site-content h2,
.site-content h3 {
font-weight: 700;
}
.site-content h2 {
margin-top: 2.5rem;
padding-bottom: .4rem;
border-bottom: 1px solid #e9ecef;
}
.site-content h3 {
margin-top: 1.75rem;
}
.site-content a {
color: #a3671f;
text-decoration-color: rgba(163, 103, 31, .35);
}
.site-content a:hover {
color: #8a5a16;
}
.site-content pre {
background-color: #212529;
color: #f8f9fa;
padding: 1rem 1.25rem;
border-radius: .375rem;
overflow-x: auto;
}
.site-content code {
color: #a3671f;
background-color: #f4f0e8;
padding: .15em .4em;
border-radius: .25rem;
font-size: .875em;
}
.site-content pre code {
color: inherit;
background: none;
padding: 0;
}
.site-content table {
display: block;
overflow-x: auto;
width: 100%;
border-collapse: collapse;
margin: 1.25rem 0;
}
.site-content table th,
.site-content table td {
border: 1px solid #dee2e6;
padding: .5rem .75rem;
text-align: left;
}
.site-content table th {
background-color: #f8f9fa;
}
.site-content blockquote {
border-left: 4px solid #C59341;
padding: .5rem 1rem;
margin: 1.25rem 0;
background-color: #f8f6f1;
color: #495057;
}
.site-content img {
max-width: 100%;
height: auto;
}
/* Screenshot grids in the markdown use width="49%" inline attrs for a
two-up desktop layout -- stack them on narrow screens instead of
squeezing to illegibility. */
@media (max-width: 576px) {
.site-content img[width] {
width: 100% !important;
margin-bottom: .75rem;
}
}
.site-content hr {
margin: 2rem 0;
border-top: 1px solid #e9ecef;
}
+17
View File
@@ -0,0 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<!-- Background circle -->
<circle cx="50" cy="50" r="48" fill="#1a1a1a" stroke="#4a9eff" stroke-width="3"/>
<!-- Network nodes -->
<circle cx="30" cy="30" r="8" fill="#4a9eff"/>
<circle cx="70" cy="30" r="8" fill="#4a9eff"/>
<circle cx="50" cy="50" r="10" fill="#66b3ff"/>
<circle cx="30" cy="70" r="8" fill="#4a9eff"/>
<circle cx="70" cy="70" r="8" fill="#4a9eff"/>
<!-- Connection lines -->
<line x1="30" y1="30" x2="50" y2="50" stroke="#4a9eff" stroke-width="2"/>
<line x1="70" y1="30" x2="50" y2="50" stroke="#4a9eff" stroke-width="2"/>
<line x1="30" y1="70" x2="50" y2="50" stroke="#4a9eff" stroke-width="2"/>
<line x1="70" y1="70" x2="50" y2="50" stroke="#4a9eff" stroke-width="2"/>
</svg>

After

Width:  |  Height:  |  Size: 788 B

+51
View File
@@ -0,0 +1,51 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400" width="100%" height="100%">
<defs>
<linearGradient id="gold-grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#C59341" />
<stop offset="20%" stop-color="#E4B869" />
<stop offset="40%" stop-color="#FBF0B9" />
<stop offset="60%" stop-color="#DFB260" />
<stop offset="80%" stop-color="#BC8837" />
<stop offset="100%" stop-color="#A36F28" />
</linearGradient>
<linearGradient id="text-grad" x1="0%" y1="100%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#FFFFFF" />
<stop offset="40%" stop-color="#F5E3B5" />
<stop offset="70%" stop-color="#D4A343" />
<stop offset="100%" stop-color="#8A5A16" />
</linearGradient>
<filter id="drop-shadow" x="-20%" y="-20%" width="140%" height="140%">
<feDropShadow dx="0" dy="8" stdDeviation="6" flood-color="#000000" flood-opacity="0.4"/>
</filter>
</defs>
<g filter="url(#drop-shadow)">
<g fill="url(#gold-grad)">
<path d="M 200,40
C 290,40 350,110 350,200
C 350,290 290,360 200,360
C 110,360 50,290 50,200
C 50,110 110,40 200,40 Z
M 200,75
C 130,75 88,130 88,200
C 88,270 130,325 200,325
C 270,325 312,270 312,200
C 312,130 270,75 200,75 Z"
fill-rule="evenodd" />
<path d="M 88,190 L 140,190 C 140,190 142,210 140,210 L 88,210 Z" />
<path d="M 260,190 L 312,190 C 312,190 310,210 260,210 Z" />
</g>
<text x="200" y="222"
font-family="system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif"
font-size="78"
font-weight="900"
fill="url(#text-grad)"
text-anchor="middle"
letter-spacing="-2">42</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

+101
View File
@@ -0,0 +1,101 @@
---
layout: default
title: Connecting
description: How to reach downstream hosts through the jump host — the username grammar, the interactive picker, SFTP/WinSCP, and what access you get.
---
# Connecting
You reach a downstream host two ways: name the target in your username, or log
in plain and pick it from a menu. Either way you authenticate **once**, to the
jump host, with your directory credentials.
## The username grammar
```
{uid}_-_{target}
```
- `{uid}` — your directory username.
- `_-_` — the separator (legal in an SSH username everywhere, including WinSCP).
- `{target}` — the host to reach: a directory **slug** (`host_web01` or just
`web01`), the host's **display name**, its **IP**, or the hostname in its
directory `address`.
```bash
ssh alice_-_web01@jump.example.com # by slug (host_ prefix optional)
ssh alice_-_10.0.0.10@jump.example.com # by IP (must be a host you can reach)
```
If the target matches a host your directory groups grant, you're bridged
straight to its `sshd` — same as if you'd SSH'd directly, but through the
audited jump host.
## SFTP / WinSCP / scp
Because the whole route is encoded in the username, file transfer tools that
only take one connection string work with no extra configuration:
```bash
sftp -P 2222 alice_-_web01@jump.example.com
scp -P 2222 file.txt alice_-_web01@jump.example.com:/tmp/
```
**WinSCP:** set Host name to `jump.example.com`, Port to `2222`, and User name
to `alice_-_web01`. SFTP is bridged as an opaque byte stream, so all operations
(browse, upload, download, rename) work normally.
## The interactive picker
Log in with just your username and you get a TUI list of every host you can
reach:
```bash
ssh alice@jump.example.com
```
- **↑ / ↓** move the selection
- **type** to filter the list incrementally
- **Enter** connect to the highlighted host
- **number keys** jump straight to that row
- **q** or **Ctrl-C** to quit
Pick a host and you're bridged into it. The picker only ever lists hosts your
directory access allows — it doubles as "what can I reach from here?"
## What you can reach
The set of hosts is computed per login: your LDAP group memberships intersected
with the SSO directory's hosts (via the `host_<name>_access` groups the
directory auto-creates for each machine). To get access to a new host, an admin
adds you to that host's access group in the SSO — nothing on the jump host
changes.
Targets that don't resolve to a host you're allowed to reach are refused (and
audited). Raw IPs that aren't a known directory host are denied by default.
## Authentication
The jump host authenticates **you** against the directory:
- **Public key** — matched against your `sshPublicKey` entries in LDAP. Use your
normal SSH key; the client picks it automatically.
- **Password** — your directory password (LDAP bind). Password auth is often
restricted to local networks or disabled entirely on a public jump host
(keys-only) — check with your operator.
You never manage a separate credential for the downstream host: the jump host
handles onward authentication for you (see
[Architecture](architecture.html#per-user-key-injection)).
## First connection to a host
The very first time you reach a given downstream host, the jump host provisions
its access key for you behind the scenes. If that first attempt races the
directory's key-cache refresh you may see a brief
```
jump-host: first-time key propagation, retrying…
```
and it reconnects automatically. Subsequent connections are immediate.
+104
View File
@@ -0,0 +1,104 @@
---
layout: default
title: Home
description: An SSH jump host for the theta42 stack — one public host, LDAP login, and directory-driven access to every downstream machine you're entitled to.
---
# Jump Host
An SSH jump host for the [theta42](https://github.com/theta42) self-hosted
stack. Users SSH into **one** public host and land on any downstream host
they're entitled to — authenticated against the shared LDAP directory,
authorized from the [SSO Manager](https://theta42.github.io/sso-manager-node/)'s
inventory graph, and audited end to end.
No per-host accounts, no distributing keys, no VPN. The same people who log in
to your SSO are the people who can reach your machines — and only the machines
their directory groups grant.
Part of the theta42 self-hosted identity stack, alongside
[SSO Manager](https://theta42.github.io/sso-manager-node/) and
[Proxy](https://theta42.github.io/proxy/), composable with one command via
[theta-env](https://theta42.github.io/theta-env/).
## Two ways to connect
**Direct (WinSCP/SFTP-friendly):**
```bash
ssh alice_-_web01@jump.example.com
sftp -P 2222 alice_-_web01@jump.example.com
```
The username grammar is `{uid}_-_{target}``target` is a directory host slug
(with or without the `host_` prefix), a bare hostname, or an IP. One username
string, no interactive step, so it works cleanly in WinSCP and scripts.
**Interactive picker:**
```bash
ssh alice@jump.example.com
```
A plain login shows a TUI list of the hosts you can reach; arrow-key or type to
filter, Enter to connect.
See **[Connecting](connecting.html)** for the full usage guide.
## Why a jump host (and why this one)
A bastion/jump host is the standard way to give SSH access to internal machines
through a single audited entry point. What's usually painful is *authorization*
and *credentials*: who may reach which host, and how the bastion authenticates
onward without you copying keys everywhere.
This jump host answers both from your directory:
- **Authorization is your directory graph.** The hosts you can reach are the
union of your LDAP groups × the SSO's inventory (the `host_<name>_access`
groups the directory already auto-creates). Add someone to a group; they can
reach the host. No bastion-side allow-list to maintain.
- **Onward auth is automatic.** The jump host holds one key and injects its
public half into your `sshPublicKey` on first use, then connects downstream
**as you**. Downstream hosts already serve keys from LDAP (via
[ldap-client](https://github.com/theta42/ldap-client)'s
`AuthorizedKeysCommand`), so nothing downstream needs configuring.
## Features
- **Username-grammar routing** (`uid_-_target`) — straight-through to the host,
SFTP included (WinSCP works)
- **Interactive TUI host picker** on plain login, scoped to your access
- **LDAP inbound auth** — public key or password (keys-only policy recommended
for a public host)
- **Directory-driven access** — reachable hosts come from the SSO inventory, not
a static list
- **Per-user key injection** — no downstream changes, no key distribution
- **Shell, exec, and SFTP** bridging
- **Web UI + HTTP API** for auditing and metrics — active sessions, a searchable
audit log, per-user/per-host counters
- **Full audit trail** — who, target, method, result, bytes, duration, and the
downstream host-key fingerprint
- Packaged like the rest of the stack: one-command Docker, idempotent bare-metal
installer, or bundled in theta-env
## Get it
```bash
git clone https://github.com/theta42/jump-host.git
cd jump-host
cp secrets.js.example config/jump-secrets.js # then edit it
docker compose up -d --build
```
That's the standalone quick start. For bare-metal and the bundled theta-env
option, see **[Installation](installation.html)**.
## Related projects
- **[SSO Manager](https://theta42.github.io/sso-manager-node/)** — the OpenLDAP
directory + OIDC provider + the inventory graph this jump host reads.
- **[Proxy](https://theta42.github.io/proxy/)** — puts your web apps behind the
same identity; fronts this jump host's web UI.
- **[theta-env](https://theta42.github.io/theta-env/)** — runs the whole stack,
jump host included, with one command.
+110
View File
@@ -0,0 +1,110 @@
---
layout: default
title: Installation
description: Install the jump host three ways — bundled in the theta-env stack, standalone Docker, or bare metal — plus the required LDAP write-ACL and port-22 options.
---
# Installation
Three ways to run the jump host, in increasing manual effort. All read their
config through [@simpleworkjs/conf](https://www.npmjs.com/package/@simpleworkjs/conf)
(`conf/base.js` < `conf/<NODE_ENV>.js` < the `CONF_SECRETS` file < `app_*` env).
## Requirements
- The [SSO Manager](https://theta42.github.io/sso-manager-node/) (OpenLDAP
directory + `/api/discovery`), v1.3.0 or newer.
- Downstream hosts joined via
[ldap-client](https://github.com/theta42/ldap-client) (SSSD +
`AuthorizedKeysCommand`).
- An LDAP bind account with **write access to the `sshPublicKey` attribute** on
user entries (see below).
- An SSO API token (`sso_…`) for the directory queries.
## 1. Unified theta-env stack (recommended)
Enable it in `theta-env/setup.env`:
```bash
CFG_JUMP_HOST_ENABLED=true
CFG_JUMP_HOST=jump.example.com
JUMP_SSH_PORT=2222
```
Re-run `./setup.sh`. The stack builds the submodule (behind the `jump-host`
compose profile), mints the directory API token, writes
`./config/jump-secrets.js`, grants the `sshPublicKey` write-ACL, registers the
jump host in the proxy, and seeds a directory entry. Forward the public host's
`:22` (or `:2222`) to the container's published `JUMP_SSH_PORT`.
## 2. Standalone Docker
```bash
cp secrets.js.example config/jump-secrets.js
$EDITOR config/jump-secrets.js # LDAP bind (+ sshPublicKey write ACL), SSO url + token
docker compose up -d --build
```
Host keys persist in the `jump-data` volume. The web UI is on `:3002`; front it
with your own TLS/proxy.
## 3. Bare metal
```bash
curl -fsSL https://raw.githubusercontent.com/theta42/jump-host/master/ops/install.sh | sudo bash
sudo $EDITOR /etc/jump-host/secrets.js
sudo systemctl restart jump-host
journalctl -u jump-host -f
```
`ops/install.sh` installs Node 22 + Redis, hard-resets the checkout at
`/opt/theta42/jump-host` to the remote branch, symlinks the systemd unit, and
runs `npm ci`. Idempotent — re-run to update. Overridable via `REPO_DIR=`,
`BRANCH=`, `SECRETS_FILE=`.
## The LDAP write-ACL (required)
The jump host injects its public key into each user's `sshPublicKey`, so its
bind account must be able to **write** that attribute. In the bundled OpenLDAP:
```
access to attrs=sshPublicKey
by dn.exact="cn=ldapclient,ou=people,dc=example,dc=com" write
by self write
by * read
```
In the theta-env bundle this is handled for you (the jump host binds as the LDAP
admin). For a hardened standalone deployment, use a dedicated bind account with
exactly this attribute-scoped ACL. Without write access, key injection fails and
every bridge attempt is audited `key-inject-failed`.
## Listening on port 22
The default SSH port is **2222** so the service needs no privilege. To listen on
22, set `ssh.listenPort: 22` and either:
- **systemd:** uncomment `AmbientCapabilities=CAP_NET_BIND_SERVICE` in the unit;
- **Docker:** publish `22:22`; or
- **firewall:** DNAT `22 → 2222`.
## Configuration reference
Every key is documented in
[`secrets.js.example`](https://github.com/theta42/jump-host/blob/master/secrets.js.example):
`ldap` (bind + bases + TLS), `sso` (url + apiToken), `ssh`
(`listenPort`, `passwordAuth`, `allowRawIPs`, `keyComment`, timeouts,
`maxSessions`), `web.port`, `oidc` (web-UI SSO login), `auth`
(`adminGroups` / `adminUsers` / `localAdminPass`), and `redis`.
## Verifying
```bash
ssh -p 2222 youruid@jump.example.com # TUI picker
ssh -p 2222 youruid_-_somehost@jump.example.com # direct
sftp -P 2222 youruid_-_somehost@jump.example.com # WinSCP path
curl -s http://localhost:3002/health
```
Watch `journalctl -u jump-host -f` (or `docker logs -f jump-host`) and the audit
log at `/audit` in the web UI.
+4
View File
@@ -0,0 +1,4 @@
User-agent: *
Allow: /
Sitemap: https://theta42.github.io/proxy/sitemap.xml
+26 -21
View File
@@ -1,37 +1,42 @@
'use strict'; 'use strict';
const path = require('path');
const express = require('express'); const express = require('express');
const conf = require('@simpleworkjs/conf'); const compression = require('compression');
const registry = require('./services/session_registry'); require('./models'); // wire model-redis + register models
const { requireAdmin } = require('./middleware/auth');
const buildInfo = require('./models/build_info');
const app = express(); const app = express();
app.set('view engine', 'ejs'); app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views')); app.set('views', require('path').join(__dirname, 'views'));
app.use('/public', express.static(path.join(__dirname, 'public')));
// Open health check — no auth (used by Docker/compose + the proxy). app.use(compression());
app.get('/health', (req, res) => { app.use(express.json());
res.json({ status: 'ok', activeSessions: registry.count(), version: buildInfo.version, commit: buildInfo.commit }); app.use(express.urlencoded({extended: false}));
// Page shells + static assets + /health (mostly unauthenticated; the client
// gates itself on /api/user/me and redirects to /login).
app.use('/', require('./routes/render'));
// API — auth handled per-router inside (see routes/api.js).
app.use('/api', require('./routes/api'));
// 404
app.use((req, res, next) => {
const error = new Error('Not Found');
error.status = 404;
next(error);
}); });
// Login routes (no session required). // Error handler — JSON for API, redirect to login for pages on 401.
app.use('/', require('./routes/auth'));
// Everything else requires an admin session.
app.use(requireAdmin);
app.use('/api', require('./routes/api'));
app.use('/', require('./routes/index'));
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => { app.use((err, req, res, next) => {
console.error(err); const status = err.status || 500;
if (req.path.startsWith('/api/')) return res.status(500).json({ error: err.message }); if(status >= 500) console.error(err);
res.status(500).render('login', { error: 'Internal error.', name: conf.name }); if(req.path.startsWith('/api/')){
return res.status(status).json({name: err.name || 'Error', message: err.message || 'Error'});
}
res.status(status).send(err.message || 'Error');
}); });
module.exports = app; module.exports = app;
+13 -4
View File
@@ -2,24 +2,33 @@
'use strict'; 'use strict';
// Boots BOTH faces of the jump host: the SSH front door (services/ssh_server) // Boots BOTH faces of the jump host: the SSH front door (services/ssh_server)
// and the web UI/API (app.js). One process, one redis, shared audit store. // and the web UI/API (app.js + Socket.IO). One process, one redis, shared
// audit store.
const http = require('http'); const http = require('http');
const conf = require('@simpleworkjs/conf'); const conf = require('@simpleworkjs/conf');
const { Server } = require('socket.io');
require('../models'); // wire model-redis + register models require('../models');
const app = require('../app'); const app = require('../app');
const middleware = require('../middleware/auth');
const sshServer = require('../services/ssh_server'); const sshServer = require('../services/ssh_server');
// Web server
const webPort = (conf.web && conf.web.port) || 3002; const webPort = (conf.web && conf.web.port) || 3002;
const server = http.createServer(app); const server = http.createServer(app);
// Socket.IO — the client framework (app-base.js) opens an authenticated socket.
// We don't push anything yet, but serving /socket.io keeps the shared front-end
// working exactly as it does in the sibling apps.
const io = new Server(server);
io.use(middleware.authIO);
app.io = io;
server.listen(webPort, () => { server.listen(webPort, () => {
console.log(`[web] jump-host UI/API on :${server.address().port}`); console.log(`[web] jump-host UI/API on :${server.address().port}`);
}); });
// SSH server
sshServer.start(); sshServer.start();
function shutdown() { function shutdown() {
+25 -3
View File
@@ -7,6 +7,7 @@
module.exports = { module.exports = {
name: 'Jump Host', name: 'Jump Host',
logo: '/static/img/theta42.svg',
// LDAP directory the users live in (same directory the SSO manages). // LDAP directory the users live in (same directory the SSO manages).
// bindDN needs: read on ou=people (users + sshPublicKey) and ou=groups, // bindDN needs: read on ou=people (users + sshPublicKey) and ou=groups,
@@ -59,11 +60,32 @@ module.exports = {
port: 3002, port: 3002,
}, },
// Web UI/API login. Same model as the proxy: OIDC against the SSO for
// normal users, plus a local anti-lockout admin that works even if the SSO
// is unreachable. OIDC endpoints + clientId/clientSecret live in the
// secrets file; enabled:false hides the "Log in with SSO" button.
oidc: {
enabled: false,
issuer: '',
authorizationEndpoint: '',
tokenEndpoint: '',
userinfoEndpoint: '',
clientId: '',
clientSecret: '',
redirectUri: '',
scopes: ['openid', 'profile', 'email', 'groups'],
groupsClaim: 'groups',
usernameClaim: 'preferred_username',
},
auth: { auth: {
// LDAP groups whose members may use the web UI/API. // OIDC group memberships that grant web UI/API admin access.
adminGroups: ['app_sso_admin'], adminGroups: ['app_sso_admin'],
// Web session lifetime (ms). // Local anti-lockout admin: the first name here is bootstrapped as a
sessionTTLms: 12 * 60 * 60 * 1000, // redis-backed user on first boot (password from localAdminPass, or a
// random one printed to the log once). Lets you in even with OIDC down.
adminUsers: ['jumpadmin'],
localAdminPass: '',
}, },
redis: { redis: {
+45 -27
View File
@@ -1,36 +1,54 @@
'use strict'; 'use strict';
// Web UI/API auth: a signed-in admin session (cookie) whose LDAP groups // Web UI/API auth, mirroring the sibling apps: a browser session token
// intersect conf.auth.adminGroups. /health and the login routes are exempt // (`auth-token: <AuthToken uuid>`) established via local login or the OIDC
// (mounted before this middleware). // callback. The token carries the group snapshot captured at login.
const conf = require('@simpleworkjs/conf'); const conf = require('@simpleworkjs/conf');
const Session = require('../models/session'); const { Auth } = require('../models/auth');
function parseCookies(header) { async function auth(req, res, next){
const out = {}; try{
(header || '').split(';').forEach((p) => { req.token = await Auth.checkToken(req.header('auth-token'));
const i = p.indexOf('='); req.user = req.token.user;
if (i > -1) out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); req.groups = typeof req.token.groupsArray === 'function' ? req.token.groupsArray() : [];
}); return next();
return out; }catch(error){
next(error);
}
} }
async function requireAdmin(req, res, next) { // Is the authenticated request an admin? Admin = a session whose OIDC groups
const token = parseCookies(req.headers.cookie).jump_session; // intersect conf.auth.adminGroups, OR the local anti-lockout admin
const session = await Session.verify(token); // (conf.auth.adminUsers). The whole web UI is admin-only (audit + metrics).
if (!session) { function isAdmin(req){
if (req.path.startsWith('/api/')) return res.status(401).json({ error: 'unauthorized' }); const adminGroups = (conf.auth && conf.auth.adminGroups) || [];
return res.redirect('/login'); const adminUsers = (conf.auth && conf.auth.adminUsers) || [];
} const username = req.user && req.user.username;
const groups = JSON.parse(session.groups || '[]'); if(username && adminUsers.includes(username)) return true;
const admin = (conf.auth.adminGroups || []).some((g) => groups.includes(g)); return (req.groups || []).some(g => adminGroups.includes(g));
if (!admin) {
if (req.path.startsWith('/api/')) return res.status(403).json({ error: 'forbidden' });
return res.status(403).render('login', { error: 'Your account is not a jump-host admin.', name: conf.name });
}
req.jumpUser = { uid: session.uid, groups };
next();
} }
module.exports = { requireAdmin, parseCookies }; async function requireAdmin(req, res, next){
if(isAdmin(req)) return next();
const error = new Error('Forbidden');
error.name = 'Forbidden';
error.status = 403;
error.message = 'Admin access required.';
next(error);
}
// Socket.IO handshake auth (app-base.js connects with the session token).
async function authIO(socket, next){
try{
const tok = socket.handshake.auth && socket.handshake.auth.token;
if(!tok) return next(Auth.errors.login());
const token = await Auth.checkToken(tok);
socket.user = token.user;
next();
}catch(error){
next(error);
}
}
module.exports = { auth, requireAdmin, authIO, isAdmin };
+118
View File
@@ -0,0 +1,118 @@
'use strict';
const Table = require('../models');
const {User, AuthToken} = Table.models;
/**
* Auth Model
*
* Handles authentication operations for the application.
* Manages user login, token validation, and logout processes.
*
* Dependencies:
* - User model: Validates user credentials
* - AuthToken model: Creates and manages authentication tokens
*
* All methods throw standardized login errors on failure to avoid
* leaking information about whether usernames exist or tokens are valid.
*/
class Auth{
/**
* Standardized error responses for authentication failures.
* Returns generic "Invalid Credentials" message for security.
*/
static errors = {
login: function(){
let error = new Error('LoginFailed');
error.name = 'LoginFailed';
error.message = `Invalid Credentials, login failed.`;
error.status = 401;
return error;
}
}
/**
* Authenticate user and create session token.
*
* @param {Object} data - Login credentials {username, password}
* @returns {Object} {user, token} - User object and auth token
* @throws {Error} Generic login error on any failure
*
* Flow:
* 1. Validate credentials via User.login()
* 2. Create new AuthToken for the user
* 3. Return both user data and token
*/
static async login(data){
try{
let user = await User.login(data);
// Backends may attach group membership to the user (LDAP); default
// to none for local/redis users.
let groups = Array.isArray(user.groups) ? user.groups : [];
let token = await AuthToken.create({username: user.username, groups});
return {user, token}
}catch(error){
console.log('login error', error);
throw this.errors.login();
}
}
/**
* Establish a session for an OIDC-authenticated identity: JIT-provision the
* local user (redis-backed) and mint an AuthToken carrying the SSO groups.
*
* @param {Object} identity - {username, groups} from utils/oidc claims
* @returns {Object} {user, token}
*/
static async oidcSession(identity){
let user = typeof User.upsertOidc === 'function'
? await User.upsertOidc(identity)
: await User.get(identity.username);
let token = await AuthToken.create({
username: user.username,
groups: identity.groups || [],
});
return {user, token};
}
/**
* Validate an authentication token.
*
* @param {string} token - Token string to validate
* @returns {Object} Token object if valid
* @throws {Error} Generic login error if token invalid or expired
*
* Checks:
* 1. Token exists in database
* 2. Token has not expired (via token.check())
*/
static async checkToken(token){
try{
token = await AuthToken.get(token);
if(token && token.check()) return token;
throw this.errors.login();
}catch(error){
console.log('check error', error);
throw this.errors.login();
}
}
/**
* Destroy an authentication token (logout).
*
* @param {string} data - Token string to destroy
* @returns {void}
*
* Removes token from database, invalidating the session.
*/
static async logout(data){
let token = await AuthToken.get(data);
await token.destroy();
}
}
module.exports = {Auth};
+7 -4
View File
@@ -1,8 +1,8 @@
'use strict'; 'use strict';
// model-redis backing (same store the other stack apps use). Table is the // model-redis backing (same store the sibling apps use). Table is the base
// base class; getRedis() exposes the underlying node-redis client for the // class; getRedis() exposes the underlying node-redis client for the counters
// counters and sorted-set index in models/metrics.js and models/audit_event.js. // and sorted-set index in models/metrics.js and models/audit_event.js.
const conf = require('@simpleworkjs/conf'); const conf = require('@simpleworkjs/conf');
const { setUpTable } = require('model-redis'); const { setUpTable } = require('model-redis');
@@ -31,5 +31,8 @@ async function getRedis() {
module.exports.getRedis = getRedis; module.exports.getRedis = getRedis;
require('./session'); // Register models (order matters: User before AuthToken's relation resolves).
require('./user_redis');
require('./token');
require('./oidc_state');
require('./audit_event'); require('./audit_event');
+31
View File
@@ -0,0 +1,31 @@
'use strict';
const Table = require('.');
/**
* OidcState
*
* Short-lived store for an in-flight OpenID Connect authorization request.
* Keyed by the random `state` value; holds the PKCE `code_verifier` and the
* post-login redirect target until the SSO calls us back.
*
* The record auto-expires via model-redis per-key TTL (static _ttl), so an
* abandoned login attempt leaves nothing behind and there is no cleanup job.
*/
class OidcState extends Table{
static _key = 'state';
// Auth round-trips are quick; 5 minutes is plenty and bounds replay.
static _ttl = 300;
static _keyMap = {
'created_on': {default: function(){return (new Date).getTime()}},
'state': {isRequired: true, type: 'string', min: 8, max: 500},
'codeVerifier': {isRequired: true, type: 'string', min: 8, max: 500},
'redirect': {default: '/', isRequired: false, type: 'string'},
}
}
OidcState.register();
module.exports = {OidcState};
-42
View File
@@ -1,42 +0,0 @@
'use strict';
// Web UI sessions — a signed-in admin's browser token. model-redis Table with
// a TTL so entries expire and survive restarts.
const crypto = require('crypto');
const Table = require('.');
class Session extends Table {
static _key = 'token';
static _keyMap = {
'token': {default: function(){ return crypto.randomUUID() }, type: 'string'},
'uid': {isRequired: true, type: 'string'},
'groups': {default: '[]', type: 'string'},
'created_on': {default: function(){ return (new Date).getTime() }},
'expires_at': {default: 0, type: 'number'},
}
}
Session.register();
Session.start = async function (uid, groups, ttlMs) {
return Session.create({
uid,
groups: JSON.stringify(groups || []),
expires_at: Date.now() + ttlMs,
}, { ttl: Math.ceil(ttlMs / 1000) });
};
Session.verify = async function (token) {
if (!token) return null;
let session;
try {
session = await Session.get(token);
} catch (_) {
return null;
}
if (!session || session.expires_at < Date.now()) return null;
return session;
};
module.exports = Session;
+64
View File
@@ -0,0 +1,64 @@
'use strict';
const Table = require('.');
const UUID = function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)};
class Token extends Table{
static _key = 'token';
static _keyMap = {
'created_by': {isRequired: true, type: 'string', min: 3, max: 500},
'created_on': {default: function(){return (new Date).getTime()}},
'updated_on': {default: function(){return (new Date).getTime()}, always: true},
'token': {default: UUID, type: 'string', min: 36, max: 36, isPrivate: true},
'is_valid': {default: true, type: 'boolean'},
}
constructor(...args){
super(...args);
}
async check(){
try{
return this.is_valid;
}catch(error){
return false
}
}
}
Token.register();
class AuthToken extends Token{
static _keyMap = {
...super._keyMap,
user: {model: 'User', rel: 'one', localKey: 'created_by'},
// Group memberships captured at login (OIDC `groups` claim or LDAP
// group membership), stored as a JSON string. Drives authorization for
// the life of the session without re-querying the IdP on every request.
groups: {default: '[]', isRequired: false, type: 'string'},
}
static async create(data){
data.created_by = data.username;
if(Array.isArray(data.groups)){
data.groups = JSON.stringify(data.groups);
}
return super.create(data)
}
// Parse the stored groups JSON back into an array, tolerating bad/missing
// data so authorization never crashes on a malformed token.
groupsArray(){
try{
let parsed = JSON.parse(this.groups);
return Array.isArray(parsed) ? parsed : [];
}catch(error){
return [];
}
}
}
AuthToken.register();
module.exports = {Token, AuthToken};
+123
View File
@@ -0,0 +1,123 @@
'use strict';
const Table = require('.');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
const conf = require('@simpleworkjs/conf');
const saltRounds = 10;
class User extends Table{
static _key = 'username';
static _keyMap = {
'created_by': {isRequired: true, type: 'string', min: 3, max: 500},
'created_on': {default: function(){return (new Date).getTime()}},
'updated_by': {default:"__NONE__", isRequired: false, type: 'string',},
'updated_on': {default: function(){return (new Date).getTime()}, always: true},
'username': {isRequired: true, type: 'string', min: 3, max: 500},
'password': {isRequired: true, type: 'string', min: 3, max: 500, isPrivate: true},
'backing': {default:"redis", isRequired: false, type: 'string',},
}
static backing = 'redis'
static async create(data) {
try{
data['password'] = await bcrypt.hash(data['password'], saltRounds);
data['backing'] = data['backing'] || 'redis';
return await super.create(data)
}catch(error){
throw error;
}
}
async setPassword(data){
try{
data['password'] = await bcrypt.hash(data['password'], saltRounds);
return this.update(data);
}catch(error){
throw error;
}
}
/**
* Just-in-time provisioning for an OIDC-authenticated user. Creates the
* local user on first login so relations (tokens, created_by, grants) have
* something to point at. OIDC users get a random, unusable password — they
* authenticate through the SSO, never the local password form.
*
* @param {Object} data - {username, ...} from the OIDC userinfo claims
* @returns {User} the existing or newly created user
*/
static async upsertOidc(data){
try{
return await User.get(data.username);
}catch(error){
return await User.create({
username: data.username,
password: crypto.randomBytes(24).toString('hex'),
created_by: data.username,
backing: 'oidc',
});
}
}
static async login(data){
try{
let user = await User.get(data);
let auth = await bcrypt.compare(data.password, user.password);
if(auth){
return user
}else{
throw this.errors.login();
}
}catch(error){
console.error('!!!!!!!!!!', error)
if (error == 'Authentication failure'){
throw this.errors.login()
}
throw error;
}
};
}
User.register();
(async function(){
// The anti-lockout local admin: the first entry in conf.auth.adminUsers
// (default 'jumpadmin'). A local login that works even if the SSO/OIDC is
// unreachable — the whole point of "OIDC + internal users".
var defaultUser = (conf.auth && conf.auth.adminUsers && conf.auth.adminUsers[0]) || 'jumpadmin';
// Optional: an orchestrator (e.g. theta-env's setup.sh) can set
// auth.localAdminPass in jump-secrets.js to a generated password so this
// bootstrap account isn't left at a well-known default. Only used on first
// creation -- once the account exists this is never read again, so it's
// safe to leave set. If unset, a random password is generated and printed
// once; save it from the log or set auth.localAdminPass explicitly.
var defaultPass = (conf.auth && conf.auth.localAdminPass);
if (!defaultPass) {
defaultPass = crypto.randomBytes(16).toString('hex');
console.warn(`====================================================================`);
console.warn(`Bootstrap admin "${defaultUser}" created with random password:`);
console.warn(`${defaultPass}`);
console.warn(`Set auth.localAdminPass in your secrets file to make this deterministic.`);
console.warn(`====================================================================`);
}
try{
let user = await User.get(defaultUser);
}catch(error){
try{
let user = await User.create({
username:defaultUser,
password: defaultPass,
created_by: defaultUser
});
console.log(defaultUser, 'created');
}catch(error){
console.error(error)
}
}
})();
+485 -2
View File
@@ -1,20 +1,30 @@
{ {
"name": "t42-jump-host", "name": "t42-jump-host",
"version": "1.0.0", "version": "1.1.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "t42-jump-host", "name": "t42-jump-host",
"version": "1.0.0", "version": "1.1.0",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@fortawesome/fontawesome-free": "^7.3.0",
"@simpleworkjs/conf": "^1.2.0", "@simpleworkjs/conf": "^1.2.0",
"bcrypt": "^6.0.0",
"bootstrap": "^5.3.8",
"compression": "^1.8.1",
"ejs": "^3.1.10", "ejs": "^3.1.10",
"express": "^5.2.1", "express": "^5.2.1",
"express-rate-limit": "^8.5.2",
"jq-repeat": "^2.2.0",
"jquery": "^3.7.1",
"ldapts": "^8.1.2", "ldapts": "^8.1.2",
"model-redis": "^1.6.0", "model-redis": "^1.6.0",
"moment": "^2.30.1",
"mustache": "^4.2.0",
"redis": "^4.7.0", "redis": "^4.7.0",
"socket.io": "^4.8.3",
"ssh2": "^1.16.0" "ssh2": "^1.16.0"
}, },
"devDependencies": { "devDependencies": {
@@ -24,6 +34,26 @@
"node": ">=20.14" "node": ">=20.14"
} }
}, },
"node_modules/@fortawesome/fontawesome-free": {
"version": "7.3.1",
"resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-free/-/fontawesome-free-7.3.1.tgz",
"integrity": "sha512-wmglKKPDIkgV3aWlZzWECCPoGIkYCulzBwxG9+w7rc5BGapZ6cPMpoPOT8k36J0Ni7PPX6c/rsoMWfS4d1MUMg==",
"license": "(CC-BY-4.0 AND OFL-1.1 AND MIT)",
"engines": {
"node": ">=6"
}
},
"node_modules/@popperjs/core": {
"version": "2.11.8",
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz",
"integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==",
"license": "MIT",
"peer": true,
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/popperjs"
}
},
"node_modules/@redis/bloom": { "node_modules/@redis/bloom": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-1.2.0.tgz", "resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-1.2.0.tgz",
@@ -95,6 +125,39 @@
"node": ">=16.0.0" "node": ">=16.0.0"
} }
}, },
"node_modules/@socket.io/component-emitter": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
"license": "MIT"
},
"node_modules/@types/cors": {
"version": "2.8.19",
"resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz",
"integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/node": {
"version": "26.1.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.1.tgz",
"integrity": "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw==",
"license": "MIT",
"dependencies": {
"undici-types": "~8.3.0"
}
},
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
"integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/accepts": { "node_modules/accepts": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
@@ -143,6 +206,29 @@
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/base64id": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz",
"integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==",
"license": "MIT",
"engines": {
"node": "^4.5.0 || >= 5.9"
}
},
"node_modules/bcrypt": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-6.0.0.tgz",
"integrity": "sha512-cU8v/EGSrnH+HnxV2z0J7/blxH8gq7Xh2JFT6Aroax7UohdmiJJlxApMxtKfuI7z68NvvVcmR78k2LbT6efhRg==",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"node-addon-api": "^8.3.0",
"node-gyp-build": "^4.8.4"
},
"engines": {
"node": ">= 18"
}
},
"node_modules/bcrypt-pbkdf": { "node_modules/bcrypt-pbkdf": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
@@ -202,6 +288,25 @@
"url": "https://opencollective.com/express" "url": "https://opencollective.com/express"
} }
}, },
"node_modules/bootstrap": {
"version": "5.3.8",
"resolved": "https://registry.npmjs.org/bootstrap/-/bootstrap-5.3.8.tgz",
"integrity": "sha512-HP1SZDqaLDPwsNiqRqi5NcP0SSXciX2s9E+RyqJIIqGo+vJeN5AJVM98CXmW/Wux0nQ5L7jeWUdplCEf0Ee+tg==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/twbs"
},
{
"type": "opencollective",
"url": "https://opencollective.com/bootstrap"
}
],
"license": "MIT",
"peerDependencies": {
"@popperjs/core": "^2.11.8"
}
},
"node_modules/brace-expansion": { "node_modules/brace-expansion": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.2.tgz", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.2.tgz",
@@ -305,6 +410,60 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/compressible": {
"version": "2.0.18",
"resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz",
"integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==",
"license": "MIT",
"dependencies": {
"mime-db": ">= 1.43.0 < 2"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/compression": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/compression/-/compression-1.8.1.tgz",
"integrity": "sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==",
"license": "MIT",
"dependencies": {
"bytes": "3.1.2",
"compressible": "~2.0.18",
"debug": "2.6.9",
"negotiator": "~0.6.4",
"on-headers": "~1.1.0",
"safe-buffer": "5.2.1",
"vary": "~1.1.2"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/compression/node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/compression/node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT"
},
"node_modules/compression/node_modules/negotiator": {
"version": "0.6.4",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.4.tgz",
"integrity": "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/content-disposition": { "node_modules/content-disposition": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
@@ -345,6 +504,23 @@
"node": ">=6.6.0" "node": ">=6.6.0"
} }
}, },
"node_modules/cors": {
"version": "2.8.6",
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
"integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",
"license": "MIT",
"dependencies": {
"object-assign": "^4",
"vary": "^1"
},
"engines": {
"node": ">= 0.10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/cpu-features": { "node_modules/cpu-features": {
"version": "0.0.10", "version": "0.0.10",
"resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz", "resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz",
@@ -429,6 +605,79 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/engine.io": {
"version": "6.6.9",
"resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.9.tgz",
"integrity": "sha512-clKkw4C7nJ22mGgoVcCg6V/W/TxdNyIOTr89k2ONZu81qqkddPFDF0LXcbAwhzPD8DjkiRCjzuiO6Y+fkpD4vg==",
"license": "MIT",
"dependencies": {
"@types/cors": "^2.8.12",
"@types/node": ">=10.0.0",
"@types/ws": "^8.5.12",
"accepts": "~1.3.4",
"base64id": "2.0.0",
"cookie": "~0.7.2",
"cors": "~2.8.5",
"debug": "~4.4.1",
"engine.io-parser": "~5.2.1",
"ws": "~8.21.0"
},
"engines": {
"node": ">=10.2.0"
}
},
"node_modules/engine.io-parser": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
"integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/engine.io/node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
"license": "MIT",
"dependencies": {
"mime-types": "~2.1.34",
"negotiator": "0.6.3"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/engine.io/node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/engine.io/node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/engine.io/node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/es-define-property": { "node_modules/es-define-property": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
@@ -517,6 +766,25 @@
"url": "https://opencollective.com/express" "url": "https://opencollective.com/express"
} }
}, },
"node_modules/express-rate-limit": {
"version": "8.6.0",
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.6.0.tgz",
"integrity": "sha512-XKJXDsASUOo0LLtFwW5hCcQGH0N4WQc/Rn8/Pvoia+TJFOkkFPvrtW9lZOeeNcxQJspvOIERMwiRLsVFlhHEkA==",
"license": "MIT",
"dependencies": {
"debug": "^4.4.3",
"ip-address": "^10.2.0"
},
"engines": {
"node": ">= 16"
},
"funding": {
"url": "https://github.com/sponsors/express-rate-limit"
},
"peerDependencies": {
"express": ">= 4.11"
}
},
"node_modules/extend": { "node_modules/extend": {
"version": "3.0.2", "version": "3.0.2",
"resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
@@ -762,6 +1030,15 @@
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC" "license": "ISC"
}, },
"node_modules/ip-address": {
"version": "10.2.0",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",
"integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",
"license": "MIT",
"engines": {
"node": ">= 12"
}
},
"node_modules/ipaddr.js": { "node_modules/ipaddr.js": {
"version": "1.9.1", "version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
@@ -840,6 +1117,25 @@
"node": ">=10" "node": ">=10"
} }
}, },
"node_modules/jq-repeat": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/jq-repeat/-/jq-repeat-2.2.1.tgz",
"integrity": "sha512-1M0jRo7rJKO2mHbeENNjUx9YMOCobUuG4XElKt2NWDc4+j22wrZELqt7Twy95BBEkZQuwDteoPTd1etupZZPtQ==",
"license": "MIT",
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"jquery": ">=3.0.0",
"mustache": ">=4.0.0"
}
},
"node_modules/jquery": {
"version": "3.7.1",
"resolved": "https://registry.npmjs.org/jquery/-/jquery-3.7.1.tgz",
"integrity": "sha512-m4avr8yL8kmFN8psrbFFFmB/If14iN5o9nw/NgnnM+kybDJpRsAynV2BsfpTYrTRysYUdADVD7CkUUizgkpLfg==",
"license": "MIT"
},
"node_modules/ldapts": { "node_modules/ldapts": {
"version": "8.2.0", "version": "8.2.0",
"resolved": "https://registry.npmjs.org/ldapts/-/ldapts-8.2.0.tgz", "resolved": "https://registry.npmjs.org/ldapts/-/ldapts-8.2.0.tgz",
@@ -1016,12 +1312,30 @@
"node": ">= 20.0.0" "node": ">= 20.0.0"
} }
}, },
"node_modules/moment": {
"version": "2.30.1",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.30.1.tgz",
"integrity": "sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how==",
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/ms": { "node_modules/ms": {
"version": "2.1.3", "version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/mustache": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz",
"integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==",
"license": "MIT",
"bin": {
"mustache": "bin/mustache"
}
},
"node_modules/nan": { "node_modules/nan": {
"version": "2.28.0", "version": "2.28.0",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.28.0.tgz", "resolved": "https://registry.npmjs.org/nan/-/nan-2.28.0.tgz",
@@ -1038,6 +1352,26 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/node-addon-api": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.0.tgz",
"integrity": "sha512-ekZMeaaIzSQTSpr7X2X3iJM7lTzgnx8ahAG9pJfT/7+14mlEM8ZYQ9cgCDvSSRbReFK0oHli3WrZdCiRsgAT9Q==",
"license": "MIT",
"engines": {
"node": "^18 || ^20 || >= 21"
}
},
"node_modules/node-gyp-build": {
"version": "4.8.4",
"resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",
"integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==",
"license": "MIT",
"bin": {
"node-gyp-build": "bin.js",
"node-gyp-build-optional": "optional.js",
"node-gyp-build-test": "build-test.js"
}
},
"node_modules/nodemon": { "node_modules/nodemon": {
"version": "3.1.14", "version": "3.1.14",
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.14.tgz", "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.14.tgz",
@@ -1116,6 +1450,15 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/object-inspect": { "node_modules/object-inspect": {
"version": "1.13.4", "version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
@@ -1140,6 +1483,15 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/on-headers": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz",
"integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/once": { "node_modules/once": {
"version": "1.4.0", "version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
@@ -1297,6 +1649,26 @@
"node": ">= 18" "node": ">= 18"
} }
}, },
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/safer-buffer": { "node_modules/safer-buffer": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
@@ -1452,6 +1824,90 @@
"node": ">=10" "node": ">=10"
} }
}, },
"node_modules/socket.io": {
"version": "4.8.3",
"resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.3.tgz",
"integrity": "sha512-2Dd78bqzzjE6KPkD5fHZmDAKRNe3J15q+YHDrIsy9WEkqttc7GY+kT9OBLSMaPbQaEd0x1BjcmtMtXkfpc+T5A==",
"license": "MIT",
"dependencies": {
"accepts": "~1.3.4",
"base64id": "~2.0.0",
"cors": "~2.8.5",
"debug": "~4.4.1",
"engine.io": "~6.6.0",
"socket.io-adapter": "~2.5.2",
"socket.io-parser": "~4.2.4"
},
"engines": {
"node": ">=10.2.0"
}
},
"node_modules/socket.io-adapter": {
"version": "2.5.8",
"resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.8.tgz",
"integrity": "sha512-6Oy52pbg+kvdCVvjcN+FnY7BvxZ7cIHNScbvztT/It5d0vbwoJoVZmF2gjJmnV0/4WlXRfG15zc45ySk9Ah8bw==",
"license": "MIT",
"dependencies": {
"debug": "~4.4.1",
"ws": "~8.21.0"
}
},
"node_modules/socket.io-parser": {
"version": "4.2.7",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.7.tgz",
"integrity": "sha512-IH/iSeO9T6gz1KkFleGDWkG9N3dl4jXVYUtMhIqH10Md0ttMer8nUNWiP1DKuNrybD2xBrixLJdCC9J6ECoYkg==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/socket.io/node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
"license": "MIT",
"dependencies": {
"mime-types": "~2.1.34",
"negotiator": "0.6.3"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/socket.io/node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/socket.io/node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/socket.io/node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/ssh2": { "node_modules/ssh2": {
"version": "1.17.0", "version": "1.17.0",
"resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz", "resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz",
@@ -1573,6 +2029,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/undici-types": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
"license": "MIT"
},
"node_modules/unpipe": { "node_modules/unpipe": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
@@ -1597,6 +2059,27 @@
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC" "license": "ISC"
}, },
"node_modules/ws": {
"version": "8.21.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.1.tgz",
"integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/yallist": { "node_modules/yallist": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
+14 -4
View File
@@ -1,6 +1,6 @@
{ {
"name": "t42-jump-host", "name": "t42-jump-host",
"version": "1.0.0", "version": "1.1.0",
"description": "SSH jump host for the theta42 stack — LDAP-authenticated, directory-driven host bridging with audit and metrics", "description": "SSH jump host for the theta42 stack — LDAP-authenticated, directory-driven host bridging with audit and metrics",
"author": [ "author": [
{ {
@@ -14,17 +14,27 @@
"scripts": { "scripts": {
"start": "node ./bin/www", "start": "node ./bin/www",
"dev": "npx nodemon --ignore public/ ./bin/www", "dev": "npx nodemon --ignore public/ ./bin/www",
"test": "NODE_ENV=test node --test --test-force-exit 'test/**/*.test.js'", "test": "NODE_ENV=test node --test --test-force-exit test/unit/*.test.js test/integration/*.test.js",
"test:unit": "NODE_ENV=test node --test --test-force-exit 'test/unit/**/*.test.js'", "test:unit": "NODE_ENV=test node --test --test-force-exit test/unit/*.test.js",
"test:integration": "NODE_ENV=test node --test --test-force-exit 'test/integration/**/*.test.js'" "test:integration": "NODE_ENV=test node --test --test-force-exit test/integration/*.test.js"
}, },
"dependencies": { "dependencies": {
"@fortawesome/fontawesome-free": "^7.3.0",
"@simpleworkjs/conf": "^1.2.0", "@simpleworkjs/conf": "^1.2.0",
"bcrypt": "^6.0.0",
"bootstrap": "^5.3.8",
"compression": "^1.8.1",
"ejs": "^3.1.10", "ejs": "^3.1.10",
"express": "^5.2.1", "express": "^5.2.1",
"express-rate-limit": "^8.5.2",
"jq-repeat": "^2.2.0",
"jquery": "^3.7.1",
"ldapts": "^8.1.2", "ldapts": "^8.1.2",
"model-redis": "^1.6.0", "model-redis": "^1.6.0",
"moment": "^2.30.1",
"mustache": "^4.2.0",
"redis": "^4.7.0", "redis": "^4.7.0",
"socket.io": "^4.8.3",
"ssh2": "^1.16.0" "ssh2": "^1.16.0"
}, },
"devDependencies": { "devDependencies": {
-31
View File
@@ -1,31 +0,0 @@
:root { --bg:#0f1115; --panel:#181b22; --line:#272b34; --fg:#e6e8ec; --mut:#8b93a1; --acc:#4f9cf9; --bad:#ff6b6b; --ok:#4ec9a5; }
* { box-sizing: border-box; }
body { margin:0; font:14px/1.5 -apple-system,Segoe UI,Roboto,sans-serif; background:var(--bg); color:var(--fg); }
a { color:var(--acc); text-decoration:none; } a:hover { text-decoration:underline; }
.nav { display:flex; align-items:center; gap:16px; padding:12px 20px; background:var(--panel); border-bottom:1px solid var(--line); }
.brand { font-weight:600; } .brand small { color:var(--mut); font-weight:400; }
.nav .spacer { flex:1; } .nav .who { color:var(--mut); }
.wrap { max-width:1100px; margin:0 auto; padding:24px 20px; }
h1 { font-size:20px; margin:0 0 16px; } h2 { font-size:15px; margin:24px 0 8px; }
.tiles { display:flex; gap:16px; flex-wrap:wrap; }
.tile { background:var(--panel); border:1px solid var(--line); border-radius:10px; padding:16px 20px; min-width:150px; }
.tile .n { display:block; font-size:28px; font-weight:600; } .tile .l { color:var(--mut); }
.cols { display:grid; grid-template-columns:2fr 1fr; gap:24px; }
@media (max-width:800px){ .cols { grid-template-columns:1fr; } }
table { width:100%; border-collapse:collapse; margin-top:8px; }
th,td { text-align:left; padding:7px 10px; border-bottom:1px solid var(--line); }
th { color:var(--mut); font-weight:500; font-size:12px; text-transform:uppercase; letter-spacing:.03em; }
td.r,th.r { text-align:right; }
tr.bad td { color:var(--bad); }
.muted { color:var(--mut); }
.more { font-size:12px; font-weight:400; margin-left:8px; }
.foot { max-width:1100px; margin:0 auto; padding:16px 20px; color:var(--mut); font-size:12px; }
.filters { display:flex; gap:8px; margin-bottom:12px; flex-wrap:wrap; }
.filters input,.filters select,.login input { background:#0c0e12; border:1px solid var(--line); color:var(--fg); border-radius:7px; padding:7px 10px; }
button { background:var(--acc); color:#fff; border:0; border-radius:7px; padding:8px 14px; cursor:pointer; font:inherit; }
button.link { background:none; color:var(--acc); padding:0; }
.inline { display:inline; } .pager { display:flex; gap:16px; align-items:center; margin-top:16px; color:var(--mut); }
.center { display:grid; place-items:center; min-height:100vh; }
.card.login { background:var(--panel); border:1px solid var(--line); border-radius:12px; padding:28px; width:320px; display:flex; flex-direction:column; gap:12px; }
.card.login h1 { margin:0 0 8px; } .card.login label { display:flex; flex-direction:column; gap:4px; font-size:13px; color:var(--mut); }
.card.login .hint { color:var(--mut); font-size:12px; margin:4px 0 0; } .err { color:var(--bad); margin:0; }
+20
View File
@@ -0,0 +1,20 @@
nav.navbar{
padding-left: 1em;
padding-right: 1em;
}
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
#spa-shell {
margin-top: 4.5rem;
padding-bottom: 1em;
flex-grow: 1;
}
.card-title{
font-weight: bold;
}
+17
View File
@@ -0,0 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<!-- Background circle -->
<circle cx="50" cy="50" r="48" fill="#1a1a1a" stroke="#4a9eff" stroke-width="3"/>
<!-- Network nodes -->
<circle cx="30" cy="30" r="8" fill="#4a9eff"/>
<circle cx="70" cy="30" r="8" fill="#4a9eff"/>
<circle cx="50" cy="50" r="10" fill="#66b3ff"/>
<circle cx="30" cy="70" r="8" fill="#4a9eff"/>
<circle cx="70" cy="70" r="8" fill="#4a9eff"/>
<!-- Connection lines -->
<line x1="30" y1="30" x2="50" y2="50" stroke="#4a9eff" stroke-width="2"/>
<line x1="70" y1="30" x2="50" y2="50" stroke="#4a9eff" stroke-width="2"/>
<line x1="30" y1="70" x2="50" y2="50" stroke="#4a9eff" stroke-width="2"/>
<line x1="70" y1="70" x2="50" y2="50" stroke="#4a9eff" stroke-width="2"/>
</svg>

After

Width:  |  Height:  |  Size: 788 B

+51
View File
@@ -0,0 +1,51 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400" width="100%" height="100%">
<defs>
<linearGradient id="gold-grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#C59341" />
<stop offset="20%" stop-color="#E4B869" />
<stop offset="40%" stop-color="#FBF0B9" />
<stop offset="60%" stop-color="#DFB260" />
<stop offset="80%" stop-color="#BC8837" />
<stop offset="100%" stop-color="#A36F28" />
</linearGradient>
<linearGradient id="text-grad" x1="0%" y1="100%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#FFFFFF" />
<stop offset="40%" stop-color="#F5E3B5" />
<stop offset="70%" stop-color="#D4A343" />
<stop offset="100%" stop-color="#8A5A16" />
</linearGradient>
<filter id="drop-shadow" x="-20%" y="-20%" width="140%" height="140%">
<feDropShadow dx="0" dy="8" stdDeviation="6" flood-color="#000000" flood-opacity="0.4"/>
</filter>
</defs>
<g filter="url(#drop-shadow)">
<g fill="url(#gold-grad)">
<path d="M 200,40
C 290,40 350,110 350,200
C 350,290 290,360 200,360
C 110,360 50,290 50,200
C 50,110 110,40 200,40 Z
M 200,75
C 130,75 88,130 88,200
C 88,270 130,325 200,325
C 270,325 312,270 312,200
C 312,130 270,75 200,75 Z"
fill-rule="evenodd" />
<path d="M 88,190 L 140,190 C 140,190 142,210 140,210 L 88,210 Z" />
<path d="M 260,190 L 312,190 C 312,190 310,210 260,210 Z" />
</g>
<text x="200" y="222"
font-family="system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif"
font-size="78"
font-weight="900"
fill="url(#text-grad)"
text-anchor="middle"
letter-spacing="-2">42</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

+21
View File
@@ -0,0 +1,21 @@
'use strict';
// Jump-host page controllers. app.api / app.auth come from app-base.js (the
// shared client framework); this adds the jump-host data calls and the small
// render helpers each page uses.
app.jump = (function(app){
function metrics(cb){ app.api.get('metrics', cb); }
function sessions(cb){ app.api.get('sessions', cb); }
function audit(query, cb){
var qs = $.param(query || {});
app.api.get('audit' + (qs ? '?' + qs : ''), cb);
}
return {metrics: metrics, sessions: sessions, audit: audit};
})(app);
// Shared render helpers.
app.jump.fmtTime = function(ts){ return ts ? moment(Number(ts)).format('YYYY-MM-DD HH:mm:ss') : '—'; };
app.jump.esc = function(s){ return $('<div>').text(s == null ? '' : String(s)).html(); };
app.jump.result = function(e){ return e.success ? '<span class="badge bg-success">ok</span>'
: '<span class="badge bg-danger">' + app.jump.esc(e.failReason || 'fail') + '</span>'; };
+552
View File
@@ -0,0 +1,552 @@
var app = {};
app.pubsub = (function(){
app.topics = {};
app.subscribe = function(topic, listener){
if(topic instanceof RegExp){
listener.match = topic;
topic = "__REGEX__";
}
// create the topic if not yet created
if(!app.topics[topic]) app.topics[topic] = [];
// add the listener
app.topics[topic].push(listener);
}
app.matchTopics = function(topic){
topic = topic || '';
var matches = [... app.topics[topic] ? app.topics[topic] : []];
if(!app.topics['__REGEX__']) return matches;
for(var listener of app.topics['__REGEX__']){
if(topic.match(listener.match)) matches.push(listener);
}
return matches;
}
app.publish = function(topic, data){
// send the event to all listeners
app.matchTopics(topic).forEach(function(listener){
setTimeout(function(data, topic){
listener(data || {}, topic);
}, 0, data, topic);
});
}
return this;
})(app);
app.socket = (function(app){
// $.getScript('/socket.io/socket.io.js')
// <script type="text/javascript" src="/socket.io/socket.io.js"></script>
var socket;
$(document).ready(function(){
socket = io({
auth: {
token: app.auth.getToken()
}
});
// socket.emit('chat message', $('#m').val());
socket.on('P2PSub', function(msg){
msg.data.__noSocket = true;
app.publish(msg.topic, msg.data);
});
app.subscribe(/./g, function(data, topic){
// console.log('local_pubs', data, topic)
if(data.__noSocket) return;
// console.log('local_pubs 2', data, topic)
socket.emit('P2PSub', { topic, data });
});
})
return socket;
})(app);
app.api = (function(app){
var baseURL = '/api/'
function post(url, data, callback){
if(typeof callback !== 'function') callback = callback2;
return $.ajax({
type: 'POST',
url: baseURL+url,
headers:{
'auth-token': app.auth.getToken()
},
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function(res, text){
callback ? callback(
text !== 'success' ? res.statusText : null,
JSON.parse(res.responseText),
res.status
) : function(){}
}
});
}
function put(url, data, callback){
if(typeof callback !== 'function') callback = callback2;
return $.ajax({
type: 'PUT',
url: baseURL+url,
headers:{
'auth-token': app.auth.getToken()
},
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function(res, text){
callback ? callback(
text !== 'success' ? res.statusText : null,
JSON.parse(res.responseText),
res.status
) : function(){}
}
});
}
function remove(url, callback, callback2){
if(typeof callback !== 'function') callback = callback2;
return $.ajax({
type: 'delete',
url: baseURL+url,
headers:{
'auth-token': app.auth.getToken()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function(res, text){
callback ? callback(
text !== 'success' ? res.statusText : null,
JSON.parse(res.responseText),
res.status
) : function(){}
}
});
}
function options(url, callback){
return $.ajax({
type: 'OPTIONS',
url: baseURL+url,
headers:{
'auth-token': app.auth.getToken()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function(res, text){
callback ? callback(
text !== 'success' ? res.statusText : null,
JSON.parse(res.responseText),
res.status
) : function(){}
}
});
}
function get(url, callback){
return $.ajax({
type: 'GET',
url: baseURL+url,
headers:{
'auth-token': app.auth.getToken()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function(res, text){
callback ? callback(
text !== 'success' ? res.statusText : null,
JSON.parse(res.responseText),
res.status
) : function(){}
}
});
}
return {post: post, get: get, put: put, delete: remove, options: options,}
})(app)
app.auth = (function(app){
var user = {}
function setToken(token){
localStorage.setItem('APIToken', token);
}
function getToken(){
return localStorage.getItem('APIToken');
}
function isLoggedIn(callback){
if(getToken()){
return app.api.get('user/me', function(error, data){
// data now carries effective rights (isAdmin, global, domains).
if(!error) app.auth.user = app.auth.perms = data;
return callback(error, data);
});
}else{
callback(null, false);
}
}
// Constrain a redirect target to a same-origin absolute path. Rejects
// absolute URLs (open redirect), protocol-relative "//host" and "/\host",
// and non-path schemes like "javascript:" (XSS). Falls back to "/".
function safeInternalPath(path){
if(typeof path !== 'string' || path.charAt(0) !== '/'
|| path.charAt(1) === '/' || path.charAt(1) === '\\'){
return '/';
}
return path;
}
// Consume an app token handed back by the OIDC callback via the URL
// fragment (#token=…&redirect=…). Stores it, strips the fragment, and
// forwards to the intended page. Returns true if a token was consumed.
function consumeTokenFragment(){
if(!location.hash) return false;
var params = new URLSearchParams(location.hash.replace(/^#/, ''));
var token = params.get('token');
if(!token) return false;
setToken(token);
// redirect comes from the URL fragment (attacker-controllable); only
// allow a same-origin path so it can't become an open redirect / XSS.
var redirect = safeInternalPath(params.get('redirect') || '/');
// Drop the token from the address bar before navigating on.
history.replaceState(null, '', location.pathname + location.search);
window.location.href = redirect;
return true;
}
// True when the logged-in user is a global admin (per user/me).
function isAdmin(){
return !!(app.auth.perms && app.auth.perms.isAdmin);
}
function logIn(args, callback){
app.api.post('auth/login', args, function(error, data){
if(data.login){
setToken(data.token);
}
callback(error, !!data.token);
});
}
function logOut(callback){
localStorage.removeItem('APIToken');
callback();
}
function forceLogin(){
// jQuery 4 removed $.holdReady; rely on the redirect below to keep an
// unauthenticated user off the page instead of pausing document ready.
app.auth.isLoggedIn(function(error, isLoggedIn){
if(error || !isLoggedIn){
app.auth.logOut(function(){})
location.replace(`/login${location.href.replace(location.origin, '')}`);
}
});
}
function logInRedirect(){
window.location.href = safeInternalPath(location.href.replace(location.origin+'/login', '') || '/')
}
return {
getToken: getToken,
setToken: setToken,
isLoggedIn: isLoggedIn,
consumeTokenFragment: consumeTokenFragment,
isAdmin: isAdmin,
perms: null,
logIn: logIn,
logOut: logOut,
forceLogin,
logInRedirect,
}
})(app);
app.user = (function(app){
function list(callback){
app.api.get('user/?detail=true', function(error, data){
callback(error, data);
})
}
function add(args, callback){
app.api.post('user/', args, function(error, data){
callback(error, data);
});
}
function remove(args, callback){
app.api.delete('user/'+ args.username, function(error, data){
callback(error, data);
});
}
function changePassword(args, callback){
app.api.put('users/'+ arg.username || '', args, function(error, data){
callback(error, data);
});
}
return {list, remove};
})(app);
app.permission = (function(app){
function list(callback){
app.api.get('permission/', function(error, data){
callback(error, data);
});
}
function subjects(callback){
app.api.get('permission/subjects', function(error, data){
callback(error, data);
});
}
function add(args, callback){
app.api.post('permission/', args, function(error, data){
callback(error, data);
});
}
function remove(id, callback){
app.api.delete('permission/' + encodeURIComponent(id), function(error, data){
callback(error, data);
});
}
return {list, subjects, add, remove};
})(app);
app.group = (function(app){
function list(callback){
app.api.get('group/', function(error, data){
callback(error, data);
});
}
function add(args, callback){
app.api.post('group/', args, function(error, data){
callback(error, data);
});
}
function remove(name, callback){
app.api.delete('group/' + encodeURIComponent(name), function(error, data){
callback(error, data);
});
}
function addMember(name, username, callback){
app.api.post('group/' + encodeURIComponent(name) + '/members', {username}, function(error, data){
callback(error, data);
});
}
function removeMember(name, username, callback){
app.api.delete('group/' + encodeURIComponent(name) + '/members/' + encodeURIComponent(username), function(error, data){
callback(error, data);
});
}
return {list, add, remove, addMember, removeMember};
})(app);
app.util = (function(app){
function getUrlParameter(name){
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
function actionMessage(message, $target, type, callback){
message = message || '';
$target = $target.closest('div.card').find('.actionMessage');
type = type || 'info';
callback = callback || function(){};
if($target.html() === message) return;
if($target.html()){
$target.slideUp('fast', function(){
$target.html('')
$target.removeClass (function(index, className){
return (className.match (/(^|\s)bg-\S+/g) || []).join(' ');
});
if(message) return actionMessage(message, $target, type, callback);
$target.hide()
})
}else{
if(type) $target.addClass('bg-' + type);
message = '<span class="align-middle">' + message + '</span><button class="action-close btn btn-sm btn-outline-dark float-end"><i class="fa-solid fa-xmark"></i></button>'
$target.html(message).slideDown('fast');
}
setTimeout(callback,10)
}
$.fn.serializeObject = function() {
var obj = {};
// Get the form values and work over them
for (let {name, value} of $(this).serializeArray()) {
console.log(name, value)
if (obj[name] === undefined) {
if (!value
&& !$(this).parent().find(`[name="${name}"]`).attr('value')
// Keep empty <textarea>s so a cleared field is submitted (and
// can reset a list, e.g. the per-host IP/header controls).
&& !$(this).filter(`textarea[name="${name}"]`).length
){
continue;
}
obj[name] = value;
let type = $(this).parent().find(`[name="${name}"]`).attr('type');
if (['number', 'range'].includes(type)) {
obj[name] = Number(value);
}
if (['radio'].includes(type) && ['true', 'false'].includes(value)) {
obj[name] = value == 'true' ? true : false;
}
} else {
if (!(obj[name] instanceof Array)) {
obj[name] = [obj[name]];
}
obj[name].push(value);
}
}
return obj;
};
function downloadFile(filename, text){
// https://stackoverflow.com/a/18197341
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
return {
downloadFile: downloadFile,
getUrlParameter: getUrlParameter,
actionMessage: actionMessage
}
})(app);
$( document ).ready(function(){
$('div.row').fadeIn('slow'); //show the page
//panel button's
$('.fa-arrows-v').click(function(){
$(this).closest('.card').find('.card-body').slideToggle('fast');
});
$('.fa-circle-minus').click(function(){
let $body = $(this).closest('.card').find('.card-body');
if($body.hasClass('d-none')){
$body.removeClass("d-none").removeClass('d-md-block');
if($body.is(":visible")) $body.hide();
}
$body.slideToggle('fast');
});
$('.fa-circle-xmark').click(function(){
$(this).closest('.card').slideUp('fast');
});
$('.actionMessage').on('click', 'button.action-close', function(event){
app.util.actionMessage(null, $(this));
});
setInterval(()=>{
$('.momentFromNow').each((idx, el)=>{
var $el = $(el);
try{
$el.html(moment($(el).data('date')).fromNow());
}catch{}
})
}, 30000,);
});
(function($){
$.fn.scrollTo = function(){
const yOffset = Number($('#spa-shell').css('margin-top').replace('px', ''));
const y = this[0].getBoundingClientRect().top + window.scrollY - yOffset;
console.log('y', y)
window.scrollTo({top: y, behavior: 'smooth'});
};
})(jQuery);
//ajax form submit
function formAJAX(btn){
event.preventDefault(btn); // avoid to execute the actual submit of the form.
var $form = $(btn || event.target).closest('[action]'); // gets the 'form' parent
var formData = $form.find('[name]').serializeObject(); // builds query formDataing
var method = ($form.attr('method') || 'post').toLowerCase();
if($form.validate && !$form.validate()){
app.util.actionMessage('Please fix the form errors.', $form, 'danger');
return false;
}
app.util.actionMessage(
'<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>',
$form,
'info'
);
app.api[method]($form.attr('action'), formData, function(error, data){
app.util.actionMessage(data.message, $form, error ? 'danger' : 'success'); //re-populate table
$form.validateClear();
if(!error){
$form.trigger("reset");
eval($form.attr('evalAJAX')); //gets JS to run after completion
}else{
console.log('formAJAX res error', error, data)
if(data && data.name === 'ObjectValidateError'){
app.util.actionMessage('Please fix the form errors', $form, 'danger'); //re-populate table
}
if(data && data.keys){
console.log('form key errors', data.keys)
for(let keyError of data.keys){
$form.find(`[name=${keyError.key}]`).validateMessage(keyError.message);
}
}
}
});
}
+201
View File
@@ -0,0 +1,201 @@
( function( $ ) {
var settings = {
rule: {
eq: function(value, options){
var compare = $('[name=' + options + ']').val();
if ( value != compare ) {
return "Miss-match";
}
}
},
};
$.fn.validate = function(event) {
// let thisSettings = $.extend(true, settings, settingsObj);
let hasErrors = false;
if(this.is('[validate]')) return this.validateField(event);
if(!this.attr('isValid')){
console.log('adding reset event')
this.on('reset', function(){
$(this).attr('isValid', false);
$(this).validateClear();
})
}
this.find('[validate]').each(function(){
if(!$(this).validateField()) hasErrors = true;
});
this.attr('isValid', !hasErrors);
if(hasErrors && event) event.preventDefault();
return !hasErrors;
};
$.fn.validateClear = function(){
$(this).find('input').each(function(){
$(this).removeClass('is-invalid');
$(this).removeClass('is-valid');
})
}
$.fn.validateField = function(){
var attr = this.attr('validate').split(':'); //array of params
var rule = attr[0];
var options = attr[1];
var value = this.val(); //link to input value
var message;
if(this.prop('disabled')) return true;
//checks if field is required, and length
if(!isNaN(options) && value.length < options){
message = `Must be ${options} characters`;
}
//checks if empty to stop processing
if(!isNaN(options) && value.length === 0) {
}else if(rule in settings.rule){
message = settings.rule[rule].apply(this, [value, options]);
}
this.validateMessage(message)
return !message;
}
$.fn.validateMessage = function(message){
if(message && message !== true){
this.closest('.form-group').find('b.invalid-feedback').html(message);
this.addClass('is-invalid');
}else{
this.removeClass('is-invalid');
this.addClass('is-valid');
}
return this;
};
jQuery.extend({
validateSettings: function( settingsObj ) {
$.extend( true, settings, settingsObj );
},
validateInit: function( ettingsObj ) {
$( '[action]' ).on( 'submit', function ( event, settingsObj ){
$( this ).validate( settingsObj, event );
});
}
});
}( jQuery ));
// Host / target validation, mirrored from the backend (utils/hostname_validate.js):
// a bare hostname or IPv4 address, no protocol / "/" / ":" / whitespace. The
// incoming host may be a wildcard ("*.example.com"); the target may not.
(function(){
var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
// Either one bare label (Docker service names, /etc/hosts entries) or a
// dotted hostname with an alphabetic TLD.
var HOSTNAME = /^(?=.{1,253}$)(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}|[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)$/i;
var FORBIDDEN = /[\s/:]/;
function isIPv4( value ) {
var parts = value.split( '.' );
if ( parts.length !== 4 ) return false;
return parts.every( function( p ) {
return /^(0|[1-9]\d{0,2})$/.test( p ) && Number( p ) <= 255;
});
}
// Incoming-host pattern: labels may be normal, "*" (one fragment), or "**"
// (any number of fragments, incl. a bare "**" global catch-all).
function isHostPattern( value ) {
if ( value.length > 253 ) return false;
return value.split( '.' ).every( function( l ) {
return l === '*' || l === '**' || LABEL.test( l );
});
}
function forbidden( value ) {
return FORBIDDEN.test( value ) || value.includes( '://' );
}
// Incoming host: IPv4 or a wildcard host pattern.
function checkHost( value ) {
if ( typeof value !== 'string' || value.length === 0 ) return "Required";
if ( forbidden( value ) ) return 'No protocol, "/", or ":"';
if ( isIPv4( value ) || isHostPattern( value ) ) return;
return "Enter a valid host or wildcard (*, **)";
}
// Downstream target: IPv4 or a strict hostname, no wildcard.
function checkTarget( value ) {
if ( typeof value !== 'string' || value.length === 0 ) return "Required";
if ( forbidden( value ) ) return 'No protocol, "/", or ":"';
if ( isIPv4( value ) || HOSTNAME.test( value ) ) return;
return "Enter a valid hostname or IP";
}
$.validateSettings({
rule:{
ip: function( value ) {
value = value.split( '.' );
if ( value.length != 4 ) {
return "Malformed IP";
}
$.each( value, function( key, value ) {
if( value > 255 || value < 0 ) {
return "Malformed IP";
}
});
},
// Incoming host name — hostname, IPv4, or wildcard pattern (*, **).
host: function( value ) {
return checkHost( value );
},
// Downstream target — hostname or IPv4, no wildcard.
target: function( value ) {
return checkTarget( value );
},
// Back-compat alias (no wildcard).
hostname: function( value ) {
return checkTarget( value );
},
user: function( value ) {
var reg = /^[a-z0-9\_\-\@\.]{1,32}$/;
if ( reg.test( value ) === false ) {
return "Invalid";
}
},
// Mirrors utils/password_policy.js: >= 8 chars, and either 12+ chars
// or at least 3 of {lowercase, uppercase, number, symbol}.
password: function( value ) {
if ( typeof value !== 'string' || value.length < 8 ) {
return "Password must be at least 8 characters";
}
if ( value.length >= 12 ) return;
var classes = 0;
if ( /[a-z]/.test( value ) ) classes++;
if ( /[A-Z]/.test( value ) ) classes++;
if ( /[0-9]/.test( value ) ) classes++;
if ( /[^A-Za-z0-9]/.test( value ) ) classes++;
if ( classes < 3 ) {
return "Use 3 of: lowercase, uppercase, number, symbol (or 12+ chars)";
}
}
}
});
})();
+8 -29
View File
@@ -1,36 +1,15 @@
'use strict'; 'use strict';
// Auditing + metrics API (admin-gated by middleware/auth in app.js). const router = require('express').Router();
const middleware = require('../middleware/auth');
const express = require('express'); // Authentication (local login + OIDC handshake). Unauthenticated by design.
const audit = require('../models/audit_event'); router.use('/auth', require('./auth'));
const metrics = require('../models/metrics');
const registry = require('../services/session_registry');
const router = express.Router(); // Who am I — needs a valid session but no admin gate (drives the login state).
router.use('/user', middleware.auth, require('./user'));
router.get('/sessions', (req, res) => { // Jump-host data — admin only (audit log, active sessions, metrics).
res.json({ results: registry.list(), active: registry.count() }); router.use('/', middleware.auth, middleware.requireAdmin, require('./jump'));
});
router.get('/audit', async (req, res, next) => {
try {
const page = Math.max(0, parseInt(req.query.page, 10) || 0);
const data = await audit.list({
page,
pageSize: Math.min(200, parseInt(req.query.pageSize, 10) || 50),
uid: req.query.uid || undefined,
target: req.query.target || undefined,
status: req.query.status || undefined,
});
res.json(data);
} catch (err) { next(err); }
});
router.get('/metrics', async (req, res, next) => {
try {
res.json({ ...(await metrics.summary()), active: registry.count() });
} catch (err) { next(err); }
});
module.exports = router; module.exports = router;
Regular → Executable
+98 -29
View File
@@ -1,42 +1,111 @@
'use strict'; 'use strict';
// Web login: LDAP bind as the user, require an adminGroups membership, mint a const router = require('express').Router();
// session cookie. (OIDC against the SSO is a follow-up.) const { rateLimit } = require('express-rate-limit');
const express = require('express');
const conf = require('@simpleworkjs/conf'); const conf = require('@simpleworkjs/conf');
const userLdap = require('../models/user_ldap'); const { Auth } = require('../models/auth');
const Session = require('../models/session'); const { OidcState } = require('../models/oidc_state');
const oidc = require('../utils/oidc');
const { safeInternalPath } = require('../utils/safe_redirect');
const router = express.Router(); // Throttle unauthenticated auth endpoints (credential login + the OIDC
// handshake) to blunt brute-force / callback abuse. Keyed per IP.
router.get('/login', (req, res) => { const authLimiter = rateLimit({
res.render('login', { error: null, name: conf.name }); windowMs: 15 * 60 * 1000, // 15 minutes
max: 60, // 60 attempts per IP per window
standardHeaders: true,
legacyHeaders: false,
message: {name: 'TooManyRequests', message: 'Too many attempts, please try again later.'},
}); });
router.post('/login', express.urlencoded({ extended: false }), async (req, res) => {
const { uid, password } = req.body || {};
const fail = (msg) => res.status(401).render('login', { error: msg, name: conf.name });
try {
const user = await userLdap.getUser(uid);
if (!user) return fail('Invalid credentials.');
const ok = await userLdap.checkPassword(user.dn, password);
if (!ok) return fail('Invalid credentials.');
const groups = await userLdap.getGroups(user.dn);
const admin = (conf.auth.adminGroups || []).some((g) => groups.includes(g));
if (!admin) return fail('Your account is not a jump-host admin.');
const session = await Session.start(user.uid, groups, conf.auth.sessionTTLms); router.post('/login', authLimiter, async function(req, res, next){
res.setHeader('Set-Cookie', `jump_session=${session.token}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${Math.floor(conf.auth.sessionTTLms / 1000)}`); try{
res.redirect('/'); let auth = await Auth.login(req.body);
} catch (err) { return res.json({
return fail('Login failed.'); login: true,
token: auth.token.token,
message:`${req.body.username} logged in!`,
});
}catch(error){
next(error);
} }
}); });
router.post('/logout', (req, res) => { router.all('/logout', async function(req, res, next){
res.setHeader('Set-Cookie', 'jump_session=; HttpOnly; Path=/; Max-Age=0'); try{
res.redirect('/login'); if(req.user){
await req.user.logout();
}
res.json({message: 'Bye'})
}catch(error){
next(error);
}
});
/**
* OIDC login start: create a PKCE + state challenge, persist it (auto-expiring
* via OidcState TTL), and redirect the browser to the SSO authorize endpoint.
*/
router.get('/oidc/start', authLimiter, async function(req, res, next){
try{
if(!conf.oidc || !conf.oidc.enabled){
let error = new Error('OidcDisabled');
error.status = 404;
error.message = 'OIDC login is not enabled.';
throw error;
}
let {state, codeVerifier, codeChallenge} = oidc.createAuthRequest();
await OidcState.create({
state,
codeVerifier,
// Sanitize now so a hostile ?redirect= can't be stored and later
// reflected into the login page's navigation.
redirect: safeInternalPath(req.query.redirect || '/'),
});
return res.redirect(oidc.buildAuthUrl(state, codeChallenge));
}catch(error){
next(error);
}
});
/**
* OIDC callback: validate state (consuming the one-time record), exchange the
* code for tokens, read identity from userinfo, establish a session, and hand
* the app token back to the browser via a URL fragment for the login page to
* store in localStorage.
*/
router.get('/oidc/callback', authLimiter, async function(req, res, next){
try{
let {code, state} = req.query;
if(!code || !state){
let error = new Error('OidcCallbackInvalid');
error.status = 400;
error.message = 'Missing code or state.';
throw error;
}
// get() throws if the state is unknown or has expired — this both binds
// the callback to our request and bounds replay.
let saved = await OidcState.get(state);
await saved.remove();
let tokens = await oidc.exchangeCode(code, saved.codeVerifier);
let claims = await oidc.fetchUserInfo(tokens.access_token);
let identity = oidc.claimsToIdentity(claims);
let {token} = await Auth.oidcSession(identity);
let redirect = safeInternalPath(saved.redirect || '/');
return res.redirect(
`/login#token=${encodeURIComponent(token.token)}&redirect=${encodeURIComponent(redirect)}`
);
}catch(error){
next(error);
}
}); });
module.exports = router; module.exports = router;
-39
View File
@@ -1,39 +0,0 @@
'use strict';
const express = require('express');
const audit = require('../models/audit_event');
const metrics = require('../models/metrics');
const registry = require('../services/session_registry');
const buildInfo = require('../models/build_info');
const conf = require('@simpleworkjs/conf');
const router = express.Router();
router.get('/', async (req, res, next) => {
try {
const [m, recent] = await Promise.all([
metrics.summary(),
audit.list({ page: 0, pageSize: 10 }),
]);
res.render('dashboard', {
name: conf.name, buildInfo, user: req.jumpUser,
metrics: { ...m, active: registry.count() },
active: registry.list(),
recent: recent.results,
});
} catch (err) { next(err); }
});
router.get('/sessions', (req, res) => {
res.render('sessions', { name: conf.name, buildInfo, user: req.jumpUser, active: registry.list() });
});
router.get('/audit', async (req, res, next) => {
try {
const page = Math.max(0, parseInt(req.query.page, 10) || 0);
const data = await audit.list({ page, pageSize: 50, uid: req.query.uid, target: req.query.target, status: req.query.status });
res.render('audit', { name: conf.name, buildInfo, user: req.jumpUser, data, query: req.query });
} catch (err) { next(err); }
});
module.exports = router;
+35
View File
@@ -0,0 +1,35 @@
'use strict';
// Jump-host data API: active sessions, the audit log, and metrics. Admin-gated
// (mounted behind middleware.auth + requireAdmin in routes/api.js).
const router = require('express').Router();
const audit = require('../models/audit_event');
const metrics = require('../models/metrics');
const registry = require('../services/session_registry');
router.get('/sessions', (req, res) => {
res.json({results: registry.list(), active: registry.count()});
});
router.get('/audit', async (req, res, next) => {
try{
const page = Math.max(0, parseInt(req.query.page, 10) || 0);
const data = await audit.list({
page,
pageSize: Math.min(200, parseInt(req.query.pageSize, 10) || 50),
uid: req.query.uid || undefined,
target: req.query.target || undefined,
status: req.query.status || undefined,
});
res.json(data);
}catch(error){ next(error); }
});
router.get('/metrics', async (req, res, next) => {
try{
res.json({...(await metrics.summary()), active: registry.count()});
}catch(error){ next(error); }
});
module.exports = router;
+46
View File
@@ -0,0 +1,46 @@
'use strict';
const path = require('path');
const express = require('express');
const router = require('express').Router();
const conf = require('@simpleworkjs/conf');
const buildInfo = require('../models/build_info');
const registry = require('../services/session_registry');
const values = {
title: conf.environment !== 'production' ? 'dev' : '',
titleIcon: conf.environment !== 'production' ? '<i class="fa-brands fa-dev"></i>' : '',
name: conf.name,
logo: conf.logo,
...buildInfo,
};
// Serve front-end vendor libraries straight from node_modules (same convention
// as the sibling apps), and the app's own JS/CSS/img from public/.
const frontEndModules = ['bootstrap', 'mustache', 'jquery', '@fortawesome', 'moment', 'jq-repeat'];
frontEndModules.forEach(dep => {
router.use(`/static-modules/${dep}`, express.static(path.join(__dirname, `../node_modules/${dep}`), {maxAge: '7d'}));
});
router.use('/static', express.static(path.join(__dirname, '../public'), {maxAge: '1h'}));
// Liveness probe — no auth.
router.get('/health', (req, res) => {
res.json({status: 'ok', activeSessions: registry.count(), version: buildInfo.version, commit: buildInfo.commit});
});
router.get('/', (req, res) => res.redirect(302, '/dashboard'));
// Page shells. The client framework (app-base.js + app.js) loads data via the
// authenticated /api/* endpoints and gates the UI on /api/user/me, so these
// render unauthenticated (like the sibling apps) and the client redirects to
// /login when there's no valid session.
router.get('/login', (req, res) => res.render('login', {
...values,
redirect: '/',
oidcEnabled: !!(conf.oidc && conf.oidc.enabled),
}));
router.get('/dashboard', (req, res) => res.render('dashboard', {...values}));
router.get('/sessions', (req, res) => res.render('sessions', {...values}));
router.get('/audit', (req, res) => res.render('audit', {...values}));
module.exports = router;
+17
View File
@@ -0,0 +1,17 @@
'use strict';
// Minimal user endpoint the client framework needs: GET /api/user/me tells the
// browser who it is and whether it's an admin (drives login state + nav).
const router = require('express').Router();
const { isAdmin } = require('../middleware/auth');
router.get('/me', (req, res) => {
res.json({
username: req.user && req.user.username,
groups: req.groups || [],
isAdmin: isAdmin(req),
});
});
module.exports = router;
+127
View File
@@ -0,0 +1,127 @@
'use strict';
const crypto = require('crypto');
const conf = require('@simpleworkjs/conf');
/**
* Minimal OpenID Connect authorization-code + PKCE client.
*
* The SSO publishes no jwks_uri, so we do not verify ID-token signatures;
* instead we treat the flow as opaque and read identity from the userinfo
* endpoint (the access token is exchanged server-side over TLS). Uses Node's
* global fetch (Node 18+) and crypto — no external dependency.
*
* All endpoints and client config come from conf.oidc (+ clientSecret from
* secrets.js, deep-merged by @simpleworkjs/conf).
*/
const base64url = buf => buf.toString('base64')
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
// A high-entropy random string for `state` / PKCE verifier.
function randomToken(bytes = 32){
return base64url(crypto.randomBytes(bytes));
}
// PKCE S256 challenge derived from the verifier.
function codeChallengeS256(verifier){
return base64url(crypto.createHash('sha256').update(verifier).digest());
}
// Generate the {state, codeVerifier, codeChallenge} triple for a new login.
function createAuthRequest(){
let state = randomToken(32);
let codeVerifier = randomToken(32);
let codeChallenge = codeChallengeS256(codeVerifier);
return {state, codeVerifier, codeChallenge};
}
// Build the SSO authorize URL the browser is redirected to. `redirectUri`
// overrides conf.oidc.redirectUri (per-host SSO uses a per-host callback).
function buildAuthUrl(state, codeChallenge, redirectUri){
let o = conf.oidc;
let params = new URLSearchParams({
response_type: 'code',
client_id: o.clientId,
redirect_uri: redirectUri || o.redirectUri,
scope: (o.scopes || ['openid', 'profile', 'email', 'groups']).join(' '),
state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});
return `${o.authorizationEndpoint}?${params.toString()}`;
}
// Exchange an authorization code for tokens at the token endpoint. `redirectUri`
// must match the one used in buildAuthUrl (per-host for per-host SSO).
async function exchangeCode(code, codeVerifier, redirectUri){
let o = conf.oidc;
let body = new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri || o.redirectUri,
client_id: o.clientId,
client_secret: o.clientSecret,
code_verifier: codeVerifier,
});
let res = await fetch(o.tokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
},
body: body.toString(),
});
if(!res.ok){
let text = await res.text().catch(() => '');
let error = new Error('OidcTokenExchangeFailed');
error.name = 'OidcTokenExchangeFailed';
error.message = `Token exchange failed (${res.status}): ${text}`;
error.status = 502;
throw error;
}
return res.json();
}
// Fetch the userinfo claims for an access token.
async function fetchUserInfo(accessToken){
let o = conf.oidc;
let res = await fetch(o.userinfoEndpoint, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Accept': 'application/json',
},
});
if(!res.ok){
let error = new Error('OidcUserInfoFailed');
error.name = 'OidcUserInfoFailed';
error.message = `Userinfo request failed (${res.status})`;
error.status = 502;
throw error;
}
return res.json();
}
// Pull the app username and group list out of userinfo claims per conf.
function claimsToIdentity(claims){
let o = conf.oidc;
let username = claims[o.usernameClaim || 'preferred_username'] || claims.sub;
let groups = claims[o.groupsClaim || 'groups'] || [];
if(!Array.isArray(groups)) groups = [groups].filter(Boolean);
return {username, groups, claims};
}
module.exports = {
randomToken,
codeChallengeS256,
createAuthRequest,
buildAuthUrl,
exchangeCode,
fetchUserInfo,
claimsToIdentity,
};
+23
View File
@@ -0,0 +1,23 @@
'use strict';
/**
* Constrain a post-login redirect target to a same-origin path.
*
* Rejects anything that could leave the site or execute script:
* - absolute URLs ("https://evil.com") -> not a "/" path
* - protocol-relative ("//evil.com", "/\\evil.com") -> host takeover
* - scheme targets ("javascript:...", "data:...") -> XSS
* Anything not a plain "/path" falls back to "/".
*
* The browser has its own copy of this in public/lib/js/app-base.js; keep the
* two in sync.
*/
function safeInternalPath(path){
if(typeof path !== 'string' || path.charAt(0) !== '/'
|| path.charAt(1) === '/' || path.charAt(1) === '\\'){
return '/';
}
return path;
}
module.exports = {safeInternalPath};
+58 -35
View File
@@ -1,39 +1,62 @@
<%- include('top') %> <%- include('top') %>
<h1>Audit log</h1> <script type="text/javascript">app.auth.forceLogin();</script>
<form class="filters" method="get">
<input name="uid" placeholder="user" value="<%= query.uid || '' %>">
<input name="target" placeholder="target" value="<%= query.target || '' %>">
<select name="status">
<option value="">any</option>
<option value="success" <%= query.status === 'success' ? 'selected' : '' %>>success</option>
<option value="fail" <%= query.status === 'fail' ? 'selected' : '' %>>fail</option>
</select>
<button>Filter</button>
</form>
<table> <div class="card shadow-sm">
<thead><tr><th>Time</th><th>User</th><th>Method</th><th>Mode</th><th>Target</th><th>Chan</th><th>Client</th><th>Result</th><th>Bytes</th></tr></thead> <div class="card-header"><i class="fa-solid fa-clipboard-list me-1"></i> Audit log</div>
<tbody> <div class="card-body pb-0">
<% data.results.forEach(e => { %> <form class="row g-2 mb-2" onsubmit="applyFilters(); return false;">
<tr class="<%= e.success ? '' : 'bad' %>"> <div class="col-auto"><input class="form-control form-control-sm" id="f-uid" placeholder="user"></div>
<td><%= new Date(e.ts).toLocaleString() %></td> <div class="col-auto"><input class="form-control form-control-sm" id="f-target" placeholder="target"></div>
<td><%= e.uid %></td> <div class="col-auto">
<td><%= e.authMethod %></td> <select class="form-select form-select-sm" id="f-status">
<td><%= e.mode %></td> <option value="">any result</option>
<td><%= e.targetSlug || e.targetAddr || '—' %></td> <option value="success">success</option>
<td><%= e.channel || '—' %></td> <option value="fail">fail</option>
<td><%= e.clientIp %></td> </select>
<td><%= e.success ? '✓' : '✗ ' + e.failReason %></td> </div>
<td class="r"><%= (e.bytesIn + e.bytesOut) || 0 %></td> <div class="col-auto"><button class="btn btn-sm btn-primary">Filter</button></div>
</tr> </form>
<% }) %> </div>
</tbody> <div class="table-responsive">
</table> <table class="table table-striped table-sm mb-0">
<thead><tr><th>Time</th><th>User</th><th>Method</th><th>Mode</th><th>Target</th><th>Chan</th><th>Client</th><th>Result</th><th class="text-end">Bytes</th></tr></thead>
<div class="pager"> <tbody id="audit-body"></tbody>
<% const p = data.page; %> </table>
<% if (p > 0) { %><a href="?page=<%= p-1 %>&uid=<%= query.uid||'' %>&target=<%= query.target||'' %>&status=<%= query.status||'' %>">← prev</a><% } %> </div>
<span><%= data.total %> events</span> <div class="card-footer d-flex justify-content-between align-items-center">
<% if ((p+1) * data.pageSize < data.total) { %><a href="?page=<%= p+1 %>&uid=<%= query.uid||'' %>&target=<%= query.target||'' %>&status=<%= query.status||'' %>">next →</a><% } %> <button class="btn btn-sm btn-outline-secondary" id="prev" onclick="changePage(-1)">&larr; prev</button>
<span class="text-muted small" id="page-info"></span>
<button class="btn btn-sm btn-outline-secondary" id="next" onclick="changePage(1)">next &rarr;</button>
</div>
</div> </div>
<script type="text/javascript">
var page = 0;
function filters(){ return {page: page, uid: $('#f-uid').val(), target: $('#f-target').val(), status: $('#f-status').val()}; }
function applyFilters(){ page = 0; load(); }
function changePage(d){ page = Math.max(0, page + d); load(); }
function load(){
app.jump.audit(filters(), function(error, data){
var $b = $('#audit-body').empty();
if(error || !data || !data.results.length){ $b.append('<tr><td colspan="9" class="text-muted">No events.</td></tr>'); }
else data.results.forEach(function(e){
$b.append('<tr class="' + (e.success ? '' : 'table-danger') + '">' +
'<td>' + app.jump.fmtTime(e.ts) + '</td>' +
'<td>' + app.jump.esc(e.uid) + '</td>' +
'<td>' + app.jump.esc(e.authMethod) + '</td>' +
'<td>' + app.jump.esc(e.mode) + '</td>' +
'<td>' + app.jump.esc(e.targetSlug || e.targetAddr || '—') + '</td>' +
'<td>' + app.jump.esc(e.channel || '—') + '</td>' +
'<td>' + app.jump.esc(e.clientIp) + '</td>' +
'<td>' + app.jump.result(e) + '</td>' +
'<td class="text-end">' + ((e.bytesIn + e.bytesOut) || 0) + '</td></tr>');
});
var total = data ? data.total : 0, size = data ? data.pageSize : 50;
$('#page-info').text(total + ' events · page ' + (page + 1));
$('#prev').prop('disabled', page === 0);
$('#next').prop('disabled', (page + 1) * size >= total);
});
}
$(document).ready(load);
</script>
<%- include('bottom') %> <%- include('bottom') %>
+23 -5
View File
@@ -1,6 +1,24 @@
</main> </div>
<footer class="foot">
<% if (typeof buildInfo !== 'undefined') { %><span>v<%= buildInfo.version %> · <%= buildInfo.commit %></span><% } %> <footer class="py-2 bg-dark text-light mt-4">
</footer> <div class="container-fluid d-flex flex-wrap justify-content-between align-items-center small gap-2">
</body> <span class="d-flex align-items-center gap-2">
<a href="https://theta42.com" target="_blank">
<img width="64" src="/static/img/theta42.svg"/>
</a>
&copy; <%- (new Date()).getFullYear() %> theta42 &middot;
<a href="https://github.com/theta42/jump-host/blob/master/LICENSE" target="_blank" class="text-light">MIT License</a>
</span>
<span class="d-flex align-items-center gap-3">
<a href="https://theta42.github.io/jump-host/" target="_blank" class="text-light text-decoration-none">
<i class="fa-solid fa-book"></i> Docs
</a>
<a href="https://github.com/theta42/jump-host" target="_blank" class="text-light text-decoration-none">
<i class="fa-brands fa-github"></i> GitHub
</a>
</span>
<span>v<%- version %> (<%- commit %>)</span>
</div>
</footer>
</body>
</html> </html>
+58 -45
View File
@@ -1,51 +1,64 @@
<%- include('top') %> <%- include('top') %>
<h1>Dashboard</h1> <script type="text/javascript">app.auth.forceLogin();</script>
<div class="tiles">
<div class="tile"><span class="n"><%= metrics.active %></span><span class="l">active sessions</span></div> <div class="row g-3 mb-4">
<div class="tile"><span class="n"><%= metrics.total %></span><span class="l">total connections</span></div> <div class="col-6 col-md-3">
<div class="tile"><span class="n"><%= metrics.fail %></span><span class="l">failed</span></div> <div class="card shadow-sm text-center"><div class="card-body">
<div class="display-6" id="stat-active"></div>
<div class="text-muted small text-uppercase">Active sessions</div>
</div></div>
</div>
<div class="col-6 col-md-3">
<div class="card shadow-sm text-center"><div class="card-body">
<div class="display-6" id="stat-total"></div>
<div class="text-muted small text-uppercase">Total connections</div>
</div></div>
</div>
<div class="col-6 col-md-3">
<div class="card shadow-sm text-center"><div class="card-body">
<div class="display-6 text-danger" id="stat-fail"></div>
<div class="text-muted small text-uppercase">Failed</div>
</div></div>
</div>
<div class="col-6 col-md-3">
<div class="card shadow-sm text-center"><div class="card-body">
<div class="display-6" id="stat-users"></div>
<div class="text-muted small text-uppercase">Users seen</div>
</div></div>
</div>
</div> </div>
<div class="cols"> <div class="row g-3">
<section> <div class="col-md-6">
<h2>Active sessions</h2> <div class="card shadow-sm"><div class="card-header"><i class="fa-solid fa-server me-1"></i> Top hosts</div>
<% if (!active.length) { %><p class="muted">None right now.</p><% } else { %> <table class="table table-sm mb-0"><tbody id="top-hosts"></tbody></table>
<table> </div>
<thead><tr><th>User</th><th>Target</th><th>Since</th></tr></thead> </div>
<tbody> <div class="col-md-6">
<% active.forEach(s => { %> <div class="card shadow-sm"><div class="card-header"><i class="fa-solid fa-user me-1"></i> Top users</div>
<tr><td><%= s.uid %></td><td><%= s.slug || s.target %></td><td><%= new Date(s.startedAt).toLocaleTimeString() %></td></tr> <table class="table table-sm mb-0"><tbody id="top-users"></tbody></table>
<% }) %> </div>
</tbody> </div>
</table>
<% } %>
</section>
<section>
<h2>Top hosts</h2>
<% if (!metrics.topHosts.length) { %><p class="muted">No data.</p><% } else { %>
<table><tbody>
<% metrics.topHosts.forEach(h => { %><tr><td><%= h.name %></td><td class="r"><%= h.count %></td></tr><% }) %>
</tbody></table>
<% } %>
</section>
</div> </div>
<section> <script type="text/javascript">
<h2>Recent connections <a class="more" href="/audit">view all →</a></h2> function rows(sel, list){
<table> var $b = $(sel).empty();
<thead><tr><th>Time</th><th>User</th><th>Target</th><th>Method</th><th>Result</th></tr></thead> if(!list || !list.length){ $b.append('<tr><td class="text-muted">No data.</td></tr>'); return; }
<tbody> list.forEach(function(x){
<% recent.forEach(e => { %> $b.append('<tr><td>' + app.jump.esc(x.name) + '</td><td class="text-end">' + x.count + '</td></tr>');
<tr> });
<td><%= new Date(e.ts).toLocaleString() %></td> }
<td><%= e.uid %></td> $(document).ready(function(){
<td><%= e.targetSlug || e.targetAddr || '—' %></td> app.jump.metrics(function(error, data){
<td><%= e.authMethod %> / <%= e.mode %></td> if(error || !data) return;
<td><%= e.success ? '✓' : '✗ ' + e.failReason %></td> $('#stat-active').text(data.active);
</tr> $('#stat-total').text(data.total);
<% }) %> $('#stat-fail').text(data.fail);
</tbody> $('#stat-users').text((data.topUsers || []).length);
</table> rows('#top-hosts', data.topHosts);
</section> rows('#top-users', data.topUsers);
});
});
</script>
<%- include('bottom') %> <%- include('bottom') %>
Regular → Executable
+97 -19
View File
@@ -1,19 +1,97 @@
<!doctype html> <%- include('top') %>
<html lang="en"> <script type="text/javascript">
<head>
<meta charset="utf-8"> // If we arrived from the OIDC callback with a token in the URL fragment,
<meta name="viewport" content="width=device-width, initial-scale=1"> // store it and forward on before doing anything else.
<title><%= name %> — Jump Host login</title> if(!app.auth.consumeTokenFragment()){
<link rel="stylesheet" href="/public/css/app.css"> app.auth.isLoggedIn(function(error, isLoggedIn){
</head> if(isLoggedIn){
<body class="center"> app.auth.logInRedirect();
<form method="post" action="/login" class="card login"> }else{
<h1><%= name %> <small>jump host</small></h1> // Reveal the login card once we know the user is not logged in.
<% if (error) { %><p class="err"><%= error %></p><% } %> document.getElementById('login-card-row').style.display = '';
<label>Username <input name="uid" autofocus autocomplete="username"></label> }
<label>Password <input name="password" type="password" autocomplete="current-password"></label> })
<button type="submit">Sign in</button> }
<p class="hint">Admin group required. Uses your directory (LDAP) credentials.</p>
</form> </script>
</body>
</html> <div id="login-card-row" class="row" style="display: none;">
<div class="col-md-4">
<div class="shadow-lg card">
<div class="card-header text-center">
<span class="card-icon float-start">
<i class="fa-solid fa-lock"></i>
</span>
<span class="card-title">
User Login
</span>
<span class="float-end">
<i class="fa-solid fa-circle-minus"></i>
</span>
</div>
<div class="card-header shadow actionMessage" style="display:none"></div>
<div class="card-body">
<form action="auth/login" onsubmit="formAJAX(this)" evalAJAX="
app.auth.setToken(data.token);
app.auth.logInRedirect();
">
<input type="hidden" name="redirect" value="<%= redirect %>">
<div class="mb-3">
<label></label>
<div class="input-group">
<span class="input-group-text" id="addon-wrapping"><i class="fa-solid fa-user-tie"></i></span>
<input type="text" name="username" class="form-control" placeholder="jsmith" aria-label="Username" aria-describedby="addon-wrapping">
</div>
</div>
<div class="mb-3">
<div class="input-group">
<span class="input-group-text" id="addon-wrapping"><i class="fa-solid fa-key"></i></span>
<input type="password" name="password" class="form-control" placeholder="huunteR!23" aria-label="Username" aria-describedby="addon-wrapping">
</div>
</div>
<!-- <div class="group">
<label class="control-label">User name</label>
<div class="input-group mb-3 shadow">
<div class="input-group-prepend">
<span class="input-group-text" ><i class="fa-solid fa-user-tie"></i></span>
</div>
<input type="text" name="username" class="input-control" placeholder="jsmith" />
</div>
</div>
<div class="group">
<label class="control-label">Password</label>
<div class="input-group mb-3 shadow">
<div class="input-group-prepend">
<span class="input-group-text" ><i class="fa-solid fa-key"></i></span>
</div>
<input type="password" name="password" class="input-control" placeholder="hunter123!"/>
</div>
</div> -->
<hr />
<button type="submit" class="btn btn-outline-dark"><i class="fa-solid fa-right-to-bracket"></i> Log in</button>
</form>
<% if (typeof oidcEnabled === 'undefined' || oidcEnabled) { %>
<hr />
<div class="d-grid">
<a href="/api/auth/oidc/start" class="btn btn-outline-primary">
<i class="fa-solid fa-id-badge"></i> Log in with SSO
</a>
</div>
<% } %>
</div>
</div>
</div>
</div>
<%- include('bottom') %>
+28 -11
View File
@@ -1,13 +1,30 @@
<%- include('top') %> <%- include('top') %>
<h1>Active sessions</h1> <script type="text/javascript">app.auth.forceLogin();</script>
<% if (!active.length) { %><p class="muted">No active sessions.</p><% } else { %>
<table> <div class="card shadow-sm">
<thead><tr><th>User</th><th>Target host</th><th>Address</th><th>Started</th></tr></thead> <div class="card-header d-flex justify-content-between align-items-center">
<tbody> <span><i class="fa-solid fa-plug-circle-bolt me-1"></i> Active sessions</span>
<% active.forEach(s => { %> <button class="btn btn-sm btn-outline-secondary" onclick="loadSessions()"><i class="fa-solid fa-rotate"></i></button>
<tr><td><%= s.uid %></td><td><%= s.slug || '—' %></td><td><%= s.target %></td><td><%= new Date(s.startedAt).toLocaleString() %></td></tr> </div>
<% }) %> <div class="table-responsive">
</tbody> <table class="table table-striped mb-0">
</table> <thead><tr><th>User</th><th>Target host</th><th>Address</th><th>Started</th></tr></thead>
<% } %> <tbody id="sessions-body"></tbody>
</table>
</div>
</div>
<script type="text/javascript">
function loadSessions(){
app.jump.sessions(function(error, data){
var $b = $('#sessions-body').empty();
if(error || !data || !data.results.length){ $b.append('<tr><td colspan="4" class="text-muted">No active sessions.</td></tr>'); return; }
data.results.forEach(function(s){
$b.append('<tr><td>' + app.jump.esc(s.uid) + '</td><td>' + app.jump.esc(s.slug || '—') +
'</td><td>' + app.jump.esc(s.target) + '</td><td>' + app.jump.fmtTime(s.startedAt) + '</td></tr>');
});
});
}
$(document).ready(loadSessions);
</script>
<%- include('bottom') %> <%- include('bottom') %>
+76 -19
View File
@@ -1,21 +1,78 @@
<!doctype html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title><%= name %> — Jump Host</title> <title><%- name %> <%- title %></title>
<link rel="stylesheet" href="/public/css/app.css"> <link rel="icon" type="image/svg+xml" href="/static/favicon.svg">
</head> <link rel="stylesheet" href="/static-modules/bootstrap/dist/css/bootstrap.min.css">
<body> <link rel="stylesheet" href="/static-modules/@fortawesome/fontawesome-free/css/all.min.css">
<nav class="nav"> <link rel='stylesheet' href='/static/css/styles.css' />
<span class="brand"><%= name %> <small>jump host</small></span> <script type="text/javascript" src="/socket.io/socket.io.js"></script>
<% if (typeof user !== 'undefined' && user) { %> <script type="text/javascript" src='/static-modules/jquery/dist/jquery.js'></script>
<span class="spacer"></span> <script type="text/javascript" src="/static-modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<a href="/">Dashboard</a> <script type="text/javascript" src="/static-modules/@fortawesome/fontawesome-free/js/all.min.js"></script>
<a href="/sessions">Sessions</a> <script type="text/javascript" src='/static-modules/mustache/mustache.min.js'></script>
<a href="/audit">Audit</a> <script type="text/javascript" src='/static-modules/jq-repeat/dist/js/jq-repeat.js'></script>
<span class="who"><%= user.uid %></span> <script type="text/javascript" src='/static/lib/js/val.js'></script>
<form method="post" action="/logout" class="inline"><button class="link">logout</button></form> <script type="text/javascript" src="/static-modules/moment/moment.js"></script>
<% } %> <script type="text/javascript" src="/static/lib/js/app-base.js"></script>
</nav> <script type="text/javascript" src="/static/js/app.js"></script>
<main class="wrap"> </head>
<body>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="/"><img src="<%- logo %>" height="28" class="me-2" alt=""><%- name %> <%- titleIcon %></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse justify-content-end" id="navbarSupportedContent">
<ul class="navbar-nav top-nav">
<li class="nav-item">
<a class="nav-link" href="/dashboard"><i class="fa-solid fa-gauge-high"></i> Dashboard</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/sessions"><i class="fa-solid fa-plug-circle-bolt"></i> Sessions</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/audit"><i class="fa-solid fa-clipboard-list"></i> Audit</a>
</li>
</ul>
<div class="form-inline mt-2 mt-md-0">
<span id="cl-username" class="navbar-text text-light me-3" style="display: none;">
<i class="fa-solid fa-user me-1"></i><span id="cl-username-text"></span>
</span>
<a id="cl-login-button" class="btn btn-outline-danger my-2 my-sm-0" href="/login" style="display: none;">
<i class="fas fa-sign-in"></i> Login
</a>
<button id="cl-logout-button" class="btn btn-outline-danger my-2 my-sm-0" onclick="app.auth.logOut(function(){ window.location.href='/login'; })" style="display: none;">
<i class="fas fa-sign-out"></i> Log Out
</button>
</div>
</div>
</nav>
<script type="text/javascript">
$(document).ready(function(){
$('.top-nav a').each(function(){
var $this = $(this);
$this.removeClass('active');
if($this.attr('href').toLowerCase() === window.location.pathname.toLowerCase()){
$this.addClass('active');
}
});
app.auth.isLoggedIn(function(error, data){
if(data){
$('#cl-logout-button').show();
if(data.username){
$('#cl-username-text').text(data.username);
$('#cl-username').css('display', '');
}
}else{
$('#cl-login-button').show();
}
});
});
</script>
<div id="spa-shell" class="container-fluid" style="margin-top: 4.5rem;">
+27 -2
View File
@@ -59,8 +59,33 @@ module.exports = {
web: { port: 3002 }, web: { port: 3002 },
// LDAP groups whose members may use the web UI/API. // Web UI/API login. Same model as the proxy: OIDC against the SSO for
auth: { adminGroups: ['app_sso_admin'] }, // normal users, plus a local anti-lockout admin. Set enabled:true and fill
// in the endpoints + client creds to turn on "Log in with SSO" (in the
// theta-env bundle these are provisioned for you).
oidc: {
enabled: false,
issuer: 'https://sso.example.com',
authorizationEndpoint: 'https://sso.example.com/oauth/authorize',
tokenEndpoint: 'http://sso-manager:3001/oauth/token',
userinfoEndpoint: 'http://sso-manager:3001/oauth/userinfo',
clientId: 'CHANGE_ME',
clientSecret: 'CHANGE_ME',
redirectUri: 'https://jump.example.com/api/auth/oidc/callback',
scopes: ['openid', 'profile', 'email', 'groups'],
groupsClaim: 'groups',
usernameClaim: 'preferred_username',
},
auth: {
// OIDC group memberships that grant web UI/API admin access.
adminGroups: ['app_sso_admin'],
// Local anti-lockout admin — the first name is bootstrapped as a
// redis-backed user on first boot (password from localAdminPass below,
// or a random one printed to the log once). Works even if OIDC is down.
adminUsers: ['jumpadmin'],
localAdminPass: 'CHANGE_ME',
},
redis: { redis: {
prefix: 'jump_host_', prefix: 'jump_host_',