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>
This commit is contained in:
@@ -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};
|
||||
@@ -1,8 +1,8 @@
|
||||
'use strict';
|
||||
|
||||
// model-redis backing (same store the other stack apps use). Table is the
|
||||
// base class; getRedis() exposes the underlying node-redis client for the
|
||||
// counters and sorted-set index in models/metrics.js and models/audit_event.js.
|
||||
// model-redis backing (same store the sibling apps use). Table is the base
|
||||
// class; getRedis() exposes the underlying node-redis client for the counters
|
||||
// and sorted-set index in models/metrics.js and models/audit_event.js.
|
||||
|
||||
const conf = require('@simpleworkjs/conf');
|
||||
const { setUpTable } = require('model-redis');
|
||||
@@ -31,5 +31,8 @@ async function 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');
|
||||
|
||||
@@ -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};
|
||||
@@ -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;
|
||||
@@ -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};
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
})();
|
||||
Reference in New Issue
Block a user