fase(25-26): keyboard shortcuts, mobile responsive, enterprise SSO/audit

- Phase 25.4: N shortcut for new exploration on dashboard (react-hotkeys-hook)
- Phase 25.5: overflow-x-auto on tables, responsive padding (p-4 md:p-6)
- Phase 26: SAML/OIDC/LDAP providers (build-fixed), TOTP/MFA service
- Phase 26: KyselySSOConfigRepository + KyselyTOTPRepository
- Phase 26: SSO HTTP controller (config CRUD + MFA setup/verify/disable)
- Phase 26: Audit module index.ts + SSO module index.ts
- Phase 26: Session management endpoints (findByUserId, deleteById, list/revoke)
- Phase 26: SSO and audit routes feature-gated (auth:sso, audit:logs)
- Phase 26: Frontend SSOSection (SAML/OIDC/LDAP config + TOTP setup)
- Phase 26: Frontend SessionsSection (list/revoke active sessions)
- Phase 26: Settings navigation updated with SSO & Sessions sections

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
debian
2026-03-08 13:38:25 -04:00
parent c3911bafe8
commit 08011d22d5
58 changed files with 2689 additions and 23 deletions

View File

@@ -0,0 +1,147 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSSORouter = createSSORouter;
/**
* SSO Controller — manages SSO provider configurations and TOTP/MFA.
* Feature-gated: enterprise license required.
*/
const express_1 = require("express");
const SSOConfig_1 = require("../../domain/entities/SSOConfig");
const TOTPSecret_1 = require("../../domain/entities/TOTPSecret");
function createSSORouter(deps) {
const router = (0, express_1.Router)();
const { ssoConfigRepository, totpRepository, totpService } = deps;
// GET /api/sso/config — get SSO config for the current org
router.get('/config', async (req, res, next) => {
try {
const user = req.user;
if (!user?.orgId)
return res.status(400).json({ error: 'No organization' });
const config = await ssoConfigRepository.findByOrganizationId(user.orgId);
if (!config)
return res.json(null);
res.json({
id: config.id.toString(),
provider: config.provider,
enabled: config.enabled,
config: config.config,
createdAt: config.createdAt.toISOString(),
});
}
catch (err) {
next(err);
}
});
// PUT /api/sso/config — create or update SSO config
router.put('/config', async (req, res, next) => {
try {
const user = req.user;
if (!user?.orgId)
return res.status(400).json({ error: 'No organization' });
const { provider, enabled, config } = req.body;
if (!['saml', 'oidc', 'ldap'].includes(provider)) {
return res.status(400).json({ error: 'Invalid provider' });
}
const existing = await ssoConfigRepository.findByOrganizationId(user.orgId);
if (existing) {
if (enabled !== undefined) {
enabled ? existing.enable() : existing.disable();
}
// Merge config fields
Object.assign(existing.config, config ?? {});
await ssoConfigRepository.save(existing);
return res.json({ id: existing.id.toString(), provider: existing.provider, enabled: existing.enabled });
}
const ssoConfig = SSOConfig_1.SSOConfig.create({
organizationId: user.orgId,
provider,
enabled: enabled ?? true,
config: config ?? {},
createdAt: new Date(),
});
await ssoConfigRepository.save(ssoConfig);
res.status(201).json({ id: ssoConfig.id.toString(), provider, enabled: ssoConfig.enabled });
}
catch (err) {
next(err);
}
});
// DELETE /api/sso/config — remove SSO config (disables SSO)
router.delete('/config', async (req, res, next) => {
try {
const user = req.user;
if (!user?.orgId)
return res.status(400).json({ error: 'No organization' });
const config = await ssoConfigRepository.findByOrganizationId(user.orgId);
if (!config)
return res.status(404).json({ error: 'Not found' });
config.disable();
await ssoConfigRepository.save(config);
res.json({ success: true });
}
catch (err) {
next(err);
}
});
// POST /api/sso/mfa/setup — generate TOTP secret for current user
router.post('/mfa/setup', async (req, res, next) => {
try {
const user = req.user;
const { otpauthUrl, secret } = totpService.generateSecret(user.id, user.email);
// Save unverified secret
const totpSecret = TOTPSecret_1.TOTPSecret.create({
userId: user.id,
secret,
verified: false,
createdAt: new Date(),
});
await totpRepository.save(totpSecret);
res.json({ otpauthUrl, secret });
}
catch (err) {
next(err);
}
});
// POST /api/sso/mfa/verify — verify TOTP token and mark as verified
router.post('/mfa/verify', async (req, res, next) => {
try {
const user = req.user;
const { token } = req.body;
const stored = await totpRepository.findByUserId(user.id);
if (!stored)
return res.status(400).json({ error: 'MFA not set up' });
if (!totpService.verify(stored.secret, token)) {
return res.status(400).json({ error: 'Invalid token' });
}
stored.verify();
await totpRepository.save(stored);
res.json({ verified: true });
}
catch (err) {
next(err);
}
});
// DELETE /api/sso/mfa — remove MFA for current user
router.delete('/mfa', async (req, res, next) => {
try {
const user = req.user;
await totpRepository.delete(user.id);
res.json({ success: true });
}
catch (err) {
next(err);
}
});
// GET /api/sso/mfa/status — check MFA status
router.get('/mfa/status', async (req, res, next) => {
try {
const user = req.user;
const stored = await totpRepository.findByUserId(user.id);
res.json({ enabled: !!stored, verified: stored?.verified ?? false });
}
catch (err) {
next(err);
}
});
return router;
}

View File

@@ -0,0 +1,81 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LDAPProvider = void 0;
/**
* LDAP/Active Directory authentication provider.
*/
const ldapjs_1 = __importDefault(require("ldapjs"));
class LDAPProvider {
constructor(config) {
this.config = config;
}
async authenticate(username, password) {
return new Promise((resolve, reject) => {
const client = ldapjs_1.default.createClient({
url: this.config.url,
tlsOptions: this.config.tlsOptions,
});
client.on('error', (err) => {
reject(err);
});
const escaped = username.replace(/[\\*()\x00]/g, (c) => `\\${c.charCodeAt(0).toString(16).padStart(2, '0')}`);
const filter = (this.config.userSearchFilter ?? '(uid={username})')
.replace('{username}', escaped);
// Bind with service account if provided
const bindDN = this.config.bindDN ?? '';
const bindPwd = this.config.bindPassword ?? '';
client.bind(bindDN, bindPwd, (err) => {
if (err) {
client.destroy();
return resolve(null);
}
client.search(this.config.baseDN, { filter, scope: 'sub', attributes: ['dn', 'mail', 'displayName', 'memberOf'] }, (searchErr, res) => {
if (searchErr) {
client.destroy();
return reject(searchErr);
}
let foundEntry = null;
res.on('searchEntry', (entry) => {
foundEntry = entry;
});
res.on('error', (resErr) => {
client.destroy();
reject(resErr);
});
res.on('end', () => {
if (!foundEntry) {
client.destroy();
return resolve(null);
}
const entry = foundEntry;
const userDN = entry.objectName ?? '';
// Authenticate as the found user
client.bind(userDN, password, (authErr) => {
client.destroy();
if (authErr) {
return resolve(null);
}
const obj = entry.pojo;
const getAttr = (name) => {
const attr = obj.attributes.find((a) => a.type === name);
return attr?.values[0];
};
resolve({
dn: userDN,
email: getAttr('mail'),
displayName: getAttr('displayName'),
groups: obj.attributes
.find((a) => a.type === 'memberOf')
?.values ?? [],
});
});
});
});
});
});
}
}
exports.LDAPProvider = LDAPProvider;

View File

@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OIDCProvider = void 0;
/**
* OIDC (OpenID Connect) SSO provider.
* Supports Okta, Azure AD, Google Workspace.
*/
const openid_client_1 = require("openid-client");
class OIDCProvider {
constructor(config) {
this.config = config;
}
async generateAuthUrl() {
const issuerUrl = new URL(this.config.issuer);
const oidcConfig = await (0, openid_client_1.discovery)(issuerUrl, this.config.clientId, this.config.clientSecret);
const state = (0, openid_client_1.randomState)();
const params = new URLSearchParams({
client_id: this.config.clientId,
redirect_uri: this.config.redirectUri,
response_type: 'code',
scope: (this.config.scopes ?? ['openid', 'email', 'profile']).join(' '),
state,
});
const url = (0, openid_client_1.buildAuthorizationUrl)(oidcConfig, params);
return { url: url.href, state, codeVerifier: '' };
}
async handleCallback(params, expectedState, _codeVerifier) {
const issuerUrl = new URL(this.config.issuer);
const oidcConfig = await (0, openid_client_1.discovery)(issuerUrl, this.config.clientId, this.config.clientSecret);
const currentUrl = new URL(`${this.config.redirectUri}?${params.toString()}`);
const tokens = await (0, openid_client_1.authorizationCodeGrant)(oidcConfig, currentUrl, {
expectedState,
});
const claims = tokens.claims();
if (!claims) {
throw new Error('OIDC: no claims in token response');
}
return {
sub: String(claims['sub'] ?? ''),
email: typeof claims['email'] === 'string' ? claims['email'] : undefined,
name: typeof claims['name'] === 'string' ? claims['name'] : undefined,
};
}
}
exports.OIDCProvider = OIDCProvider;

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SAMLProvider = void 0;
/**
* SAML 2.0 SSO provider.
* Uses @node-saml/node-saml for SP-initiated SSO.
*/
const node_saml_1 = require("@node-saml/node-saml");
class SAMLProvider {
constructor(config) {
const samlConfig = {
entryPoint: config.entryPoint,
issuer: config.issuer,
idpCert: config.cert,
callbackUrl: config.callbackUrl,
wantAuthnResponseSigned: false,
};
this.saml = new node_saml_1.SAML(samlConfig);
}
async generateAuthUrl(relayState) {
return this.saml.getAuthorizeUrlAsync(relayState ?? '', undefined, {});
}
async validateResponse(body) {
const { profile } = await this.saml.validatePostResponseAsync(body);
if (!profile) {
throw new Error('SAML validation failed: no profile');
}
return {
nameID: typeof profile.nameID === 'string' ? profile.nameID : '',
email: typeof profile['email'] === 'string' ? profile['email'] : undefined,
displayName: typeof profile.displayName === 'string' ? profile.displayName : undefined,
};
}
}
exports.SAMLProvider = SAMLProvider;

View File

@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TOTPService = void 0;
/**
* TOTP (Time-based One-Time Password) service.
* Uses otpauth library for RFC 6238 compliant TOTP.
*/
const otpauth_1 = require("otpauth");
class TOTPService {
constructor(issuer = 'ABE') {
this.issuer = issuer;
}
generateSecret(userId, label) {
const totp = new otpauth_1.TOTP({
issuer: this.issuer,
label,
algorithm: 'SHA1',
digits: 6,
period: 30,
secret: new otpauth_1.Secret({ size: 20 }),
});
return {
secret: totp.secret.base32,
otpauthUrl: totp.toString(),
};
}
verify(secret, token) {
const totp = new otpauth_1.TOTP({
issuer: this.issuer,
algorithm: 'SHA1',
digits: 6,
period: 30,
secret: otpauth_1.Secret.fromBase32(secret),
});
const delta = totp.validate({ token, window: 1 });
return delta !== null;
}
}
exports.TOTPService = TOTPService;

View File

@@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KyselySSOConfigRepository = void 0;
const SSOConfig_1 = require("../../domain/entities/SSOConfig");
const UniqueId_1 = require("../../../../shared/domain/UniqueId");
class KyselySSOConfigRepository {
constructor(db) {
this.db = db;
}
async save(config) {
await this.db
.insertInto('sso_configs')
.values({
id: config.id.toString(),
organization_id: config.organizationId,
provider: config.provider,
enabled: config.enabled ? 1 : 0,
config_json: JSON.stringify(config.config),
created_at: config.createdAt.getTime(),
})
.onConflict((oc) => oc.column('id').doUpdateSet({
enabled: config.enabled ? 1 : 0,
config_json: JSON.stringify(config.config),
}))
.execute();
}
async findByOrganizationId(organizationId) {
const row = await this.db
.selectFrom('sso_configs')
.selectAll()
.where('organization_id', '=', organizationId)
.executeTakeFirst();
return row ? this.toDomain(row) : null;
}
async findById(id) {
const row = await this.db
.selectFrom('sso_configs')
.selectAll()
.where('id', '=', id)
.executeTakeFirst();
return row ? this.toDomain(row) : null;
}
toDomain(row) {
return SSOConfig_1.SSOConfig.reconstitute({
organizationId: row.organization_id,
provider: row.provider,
enabled: row.enabled === 1,
config: JSON.parse(row.config_json),
createdAt: new Date(row.created_at),
}, UniqueId_1.UniqueId.from(row.id));
}
}
exports.KyselySSOConfigRepository = KyselySSOConfigRepository;

View File

@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KyselyTOTPRepository = void 0;
const TOTPSecret_1 = require("../../domain/entities/TOTPSecret");
const UniqueId_1 = require("../../../../shared/domain/UniqueId");
class KyselyTOTPRepository {
constructor(db) {
this.db = db;
}
async save(secret) {
await this.db
.insertInto('totp_secrets')
.values({
id: secret.id.toString(),
user_id: secret.userId,
secret: secret.secret,
verified: secret.verified ? 1 : 0,
created_at: secret.createdAt.getTime(),
})
.onConflict((oc) => oc.column('user_id').doUpdateSet({
secret: secret.secret,
verified: secret.verified ? 1 : 0,
}))
.execute();
}
async findByUserId(userId) {
const row = await this.db
.selectFrom('totp_secrets')
.selectAll()
.where('user_id', '=', userId)
.executeTakeFirst();
if (!row)
return null;
return TOTPSecret_1.TOTPSecret.reconstitute({
userId: row.user_id,
secret: row.secret,
verified: row.verified === 1,
createdAt: new Date(row.created_at),
}, UniqueId_1.UniqueId.from(row.id));
}
async delete(userId) {
await this.db.deleteFrom('totp_secrets').where('user_id', '=', userId).execute();
}
}
exports.KyselyTOTPRepository = KyselyTOTPRepository;