Release 1.2.0: adopt shared @simpleworkjs/* packages; fix directory envelope drift
Rewire onto the shared @simpleworkjs/oidc-client, /directory-schema, /ldap, and
/app-stack packages (deleting the byte-identical local forks). utils/access.js
now fetches reachable hosts through the shared directory client, which
validates the {results} envelope and treats envelope drift as a failed group
rather than silently returning []. models/user_ldap.js is a thin wrapper over
createLdapClient (loose TLS default preserved). build_info moves to utils/ with
the shared {buildVersion,buildHash,buildYear} shape. Align ldapts ^8.1.8 and
redis ^6.1.0. Lockfile regenerated from the registry (no file:/link:).
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
+11
-8
@@ -16,20 +16,23 @@
|
||||
// unit testing.
|
||||
|
||||
const conf = require('@simpleworkjs/conf');
|
||||
const { createDirectoryClient } = require('@simpleworkjs/directory-schema');
|
||||
const userLdap = require('../models/user_ldap');
|
||||
|
||||
const CACHE_TTL_MS = 30 * 1000;
|
||||
const cache = new Map(); // uid -> {at, hosts}
|
||||
|
||||
async function fetchResourcesByGroup(group, { fetchImpl = fetch } = {}) {
|
||||
// Build a directory client bound to conf.sso. fetchImpl is injectable so the
|
||||
// unit tests can stub the transport; the shared client validates the
|
||||
// `{ results }` envelope on every call (turns the old bare-array drift into a
|
||||
// thrown error instead of a silent `[]`).
|
||||
function directoryClient({ fetchImpl = fetch } = {}) {
|
||||
const sso = conf.sso || {};
|
||||
const url = `${sso.url}/api/discovery/resources?group=${encodeURIComponent(group)}`;
|
||||
const res = await fetchImpl(url, {
|
||||
headers: { Authorization: `Bearer ${sso.apiToken}` },
|
||||
});
|
||||
if (!res.ok) throw new Error(`directory query failed (${res.status}) for group ${group}`);
|
||||
const data = await res.json();
|
||||
return (data && data.results) || [];
|
||||
return createDirectoryClient({ baseUrl: sso.url, apiToken: sso.apiToken, fetch: fetchImpl });
|
||||
}
|
||||
|
||||
async function fetchResourcesByGroup(group, { fetchImpl = fetch } = {}) {
|
||||
return directoryClient({ fetchImpl }).getResourcesByGroup(group);
|
||||
}
|
||||
|
||||
async function accessibleHosts(user, { fetchImpl = fetch, ldap = userLdap } = {}) {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
|
||||
// Unified build-info shape ({ buildVersion, buildHash, buildYear }) via the
|
||||
// shared @simpleworkjs/app-stack. Previously this lived in models/build_info.js
|
||||
// and exported { commit, version }; the shape is now aligned with sso + proxy.
|
||||
//
|
||||
// The baked commit file lives at the jump-host repo root (../../ from here in
|
||||
// utils/), matching the Dockerfile gitinfo stage. cwd is utils/ for the
|
||||
// bare-metal git fallback.
|
||||
|
||||
const path = require('path');
|
||||
const { createBuildInfo } = require('@simpleworkjs/app-stack');
|
||||
const { version } = require('../package.json');
|
||||
|
||||
module.exports = createBuildInfo({
|
||||
version,
|
||||
buildCommitPath: path.join(__dirname, '../../.build_commit'),
|
||||
cwd: __dirname,
|
||||
});
|
||||
@@ -1,127 +0,0 @@
|
||||
'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,
|
||||
};
|
||||
@@ -1,23 +0,0 @@
|
||||
'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};
|
||||
Reference in New Issue
Block a user