'use strict'; const path = require('path'); const ejs = require('ejs') const express = require('express'); const compression = require('compression'); // Set up the express app. const app = express(); // Hold list of functions to run when the server is ready app.onListen = []; // Allow the express app to be exported into other files. module.exports = app; // Hold onto the auth middleware const middleware = require('./middleware/auth'); // OAuth routes const { router: oauthRouter, authRouter: oauthApiRouter, discovery } = require('./routes/oauth'); // Grab the projects PubSub app.contoller = require('./controller'); // Background services (self-initializing on require). require('./services/update_check'); require('./services/ldap_monitor'); // Push pubsub over the socket and back. app.onListen.push(function(){ app.io.use(middleware.authIO); app.contoller.ps.subscribe(/./g, function(data, topic){ app.io.emit('P2PSub', { topic, data }); }); app.io.on('connection', (socket) => { // console.log('socket', socket) var user = socket.user; socket.on('P2PSub', (msg) => { app.contoller.ps.publish(msg.topic, {...msg.data, __from:socket.user}); // socket.broadcast.emit('P2PSub', msg); }); }); // Initialize Theta Agent WebSockets. The REST router is already mounted // synchronously above (see the /api/agent mount); this hook only wires the WS. require('./routes/api_agent').initAgentWebSockets(app); }); // Gzip text responses (HTML/JS/CSS/JSON). The admin UI loads ~13 separate, // uncompressed vendor JS/CSS files on every full page navigation (a // traditional multi-page app, not an SPA) — this alone meaningfully cuts // bytes-over-the-wire and perceived load time on a real network, where it // matters far more than on localhost. app.use(compression()); // load the JSON parser middleware. Express will parse JSON into native objects // for any request that has JSON in its content type. app.use(express.json()); app.set('trust proxy', 1); // Set up the templating engine to build HTML for the front end. app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // Per-app values for the shared UI shell (views/top.ejs + views/bottom.ejs). // Set as an app local so every res.render has it, including routes that don't // spread the routers' `values` object. app.locals.ui = require('./utils/ui'); // Have express server static content( images, CSS, browser JS) from the public // local folder. maxAge is short since this is the app's own JS/CSS, which // changes on every deploy and isn't cache-busted/fingerprinted. app.use('/static', express.static(path.join(__dirname, 'public'), {maxAge: '1h'})); app.use('/resources', express.static(path.join(__dirname, 'public/resources'), {maxAge: '1h'})); // Routes for front end content. app.use('/', require('./routes/index')); // Local, in-app copy of the project's documentation (README, DEPLOYMENT, // API.md, docs/*) -- public, no auth, so it's readable even by a locked-out // admin or an air-gapped operator with no route to GitHub Pages. app.use('/docs', require('./routes/docs')); // API routes for authentication. app.use('/api/auth', require('./routes/auth')); // API routes for working with users. All endpoints need to be have valid user. app.use('/api/user', middleware.auth, require('./routes/user')); app.use('/api/token', middleware.auth, require('./routes/token')); app.use('/api/group', middleware.auth, require('./routes/group')); app.use('/api/notification', middleware.auth, require('./routes/notification')); app.use('/api/discovery', middleware.auth, require('./routes/discovery')); app.use('/api/directory-admin', middleware.auth, require('./routes/api_directory_admin')); // Multi-site join (site join keys, master export, spoke join) — mounted before // the 404 catch-all; /api/site/export is reachable by other hosts with a // Bearer site-join-key (no admin session). app.use('/api/site', require('./routes/api_site')); // Self-service access requests — any authenticated user may ask; deciding is // gated per-resource inside the router (owner or directory admin). app.use('/api/access-requests', middleware.auth, require('./routes/access_request')); app.use('/api/update-check', middleware.auth, require('./routes/update_check')); app.use('/api/tos', middleware.auth, require('./routes/tos')); app.use('/api/metrics', middleware.auth, require('./routes/api_metrics')); app.use('/api/conf', middleware.auth, require('./routes/api_conf')); // Self-service API tokens (PATs) — owner-scoped, no admin group required. app.use('/api/api-token', middleware.auth, require('./routes/api_token')); // theta-agent REST API. Mounted SYNCHRONOUSLY (before the 404 catch-all below), // not from an onListen hook — a router registered post-listen would sit behind // the terminal 404 handler and make every /api/agent/* request 404. The agent // WebSocket handler (routes/api_agent.initAgentWebSockets) still runs on onListen. app.use('/api/agent', require('./routes/api_agent')); // LDAP-over-HTTPS API (DESIGN.md §3). Bearer-authed (agent token or PAT); the // SSO performs the real LDAP bind/search against its own OpenLDAP. Mounted // synchronously for the same reason as /api/agent — it must sit before the 404 // catch-all. app.use('/api/v1/ldap', require('./routes/api_ldap')); // Agent-facing operations (DESIGN.md §5, §6): node-scoped secrets, IAM. The // caller is the agent itself (Bearer agent token), not an admin session. app.use('/api/v1/agent', require('./routes/api_agent_ops')); // OAuth 2.0 / OpenID Connect app.use('/oauth', oauthRouter); app.use('/api/oauth', middleware.auth, oauthApiRouter); app.use('/api/oauth/client', middleware.auth, require('./routes/oauth_client')); app.get('/.well-known/openid-configuration', discovery); app.use('/api/webhook', require('./routes/webhook')); // Plugin instances — loadable/unloadable, configurable plugin copies with // per-instance secrets in OpenBao (secret/plugins/*). Admin-only (gated inside // the router to app_sso_admin / app_sso_directory_admin). app.use('/api/plugins', middleware.auth, require('./routes/api_plugins')); // OpenBao vault API. The broker mints a server-side scoped token per user // (per-user user- or, for admins, sso-admin), enforces the path prefix // (scopeGuard), and injects ONLY that token into the proxied request — the // client's sso auth headers are stripped and never reach OpenBao. Non-admins // are confined to secret/users//*; admins roam all of secret/. The // admin-only app-token mint route is mounted BEFORE the proxy so it isn't // shadowed by the catch-all /api/vault proxy. const vaultBroker = require('./utils/vault_broker'); app.use('/api/vault/apps', middleware.auth, vaultBroker.mintAppRouter); app.use('/api/vault', middleware.auth, vaultBroker.scopeGuard, vaultBroker.vaultProxy()); // Shared secrets (metadata + grants; data reads go through /api/vault proxy). app.use('/api/shared-secrets', middleware.auth, require('./routes/api_shared_secrets')); // Catch 404 and forward to error handler. If none of the above routes are // used, this is what will be called. app.use(function(req, res, next) { var err = new Error('Not Found'); err.message = 'Page not found' err.status = 404; next(err); }); // Error handling app.use(function(err, req, res, next) { const SILENT_404S = ['/.well-known/']; const isSilent404 = err.status === 404 && SILENT_404S.some(p => req.url.startsWith(p)); if (!isSilent404) console.error(err.status || res.status, err.name, req.method, req.url); if(![401, 404].includes(err.status || res.status)){ console.error(err.message); console.error(err.stack); console.error('========================================='); } res.status(err.status || 500); if (req.accepts('html') && !req.originalUrl.startsWith('/api/')) { const conf = require('@simpleworkjs/conf'); const buildInfo = require('./utils/build_info'); res.render('error', { name: conf.name, title: 'Error', titleIcon: '', logo: conf.logo, error: err, ...buildInfo }); } else { res.json({name: err.name, message: err.message}); } });