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:
6
dist/api/router.js
vendored
6
dist/api/router.js
vendored
@@ -16,6 +16,8 @@ const LicensingController_1 = require("../modules/licensing/infrastructure/http/
|
||||
const FeatureGateMiddleware_1 = require("../modules/licensing/infrastructure/middleware/FeatureGateMiddleware");
|
||||
const AuthController_1 = require("../modules/auth/infrastructure/http/AuthController");
|
||||
const AuthMiddleware_1 = require("../modules/auth/application/middleware/AuthMiddleware");
|
||||
const SSOController_1 = require("../modules/sso/infrastructure/http/SSOController");
|
||||
const AuditController_1 = require("../modules/audit/infrastructure/http/AuditController");
|
||||
function createRouter(deps) {
|
||||
const router = (0, express_1.Router)();
|
||||
const { authDeps, licenseService } = deps;
|
||||
@@ -34,5 +36,9 @@ function createRouter(deps) {
|
||||
// Licensing routes (public-ish — only status and activate, no sensitive data)
|
||||
const licensingController = new LicensingController_1.LicensingController(licenseService);
|
||||
router.use('/license', licensingController.router);
|
||||
// Enterprise: SSO + MFA (feature-gated)
|
||||
router.use('/sso', (0, FeatureGateMiddleware_1.requireFeature)(licenseService, 'auth:sso'), (0, SSOController_1.createSSORouter)(deps.ssoDeps));
|
||||
// Enterprise: Audit logs (feature-gated)
|
||||
router.use('/audit', (0, FeatureGateMiddleware_1.requireFeature)(licenseService, 'audit:logs'), (0, AuditController_1.createAuditRouter)(deps.auditRepository));
|
||||
return router;
|
||||
}
|
||||
|
||||
50
dist/db/migrations/007_enterprise_tables.js
vendored
Normal file
50
dist/db/migrations/007_enterprise_tables.js
vendored
Normal file
@@ -0,0 +1,50 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.up = up;
|
||||
exports.down = down;
|
||||
const kysely_1 = require("kysely");
|
||||
async function up(db) {
|
||||
// SSO configurations per organization
|
||||
await db.schema
|
||||
.createTable('sso_configs')
|
||||
.ifNotExists()
|
||||
.addColumn('id', 'text', (c) => c.primaryKey())
|
||||
.addColumn('organization_id', 'text', (c) => c.notNull())
|
||||
.addColumn('provider', 'text', (c) => c.notNull())
|
||||
.addColumn('enabled', 'integer', (c) => c.notNull().defaultTo(1))
|
||||
.addColumn('config_json', 'text', (c) => c.notNull().defaultTo('{}'))
|
||||
.addColumn('created_at', 'integer', (c) => c.notNull())
|
||||
.execute();
|
||||
// TOTP secrets for MFA
|
||||
await db.schema
|
||||
.createTable('totp_secrets')
|
||||
.ifNotExists()
|
||||
.addColumn('id', 'text', (c) => c.primaryKey())
|
||||
.addColumn('user_id', 'text', (c) => c.notNull().unique())
|
||||
.addColumn('secret', 'text', (c) => c.notNull())
|
||||
.addColumn('verified', 'integer', (c) => c.notNull().defaultTo(0))
|
||||
.addColumn('created_at', 'integer', (c) => c.notNull())
|
||||
.execute();
|
||||
// Audit logs
|
||||
await db.schema
|
||||
.createTable('audit_logs')
|
||||
.ifNotExists()
|
||||
.addColumn('id', 'text', (c) => c.primaryKey())
|
||||
.addColumn('user_id', 'text')
|
||||
.addColumn('organization_id', 'text')
|
||||
.addColumn('action', 'text', (c) => c.notNull())
|
||||
.addColumn('resource', 'text', (c) => c.notNull())
|
||||
.addColumn('resource_id', 'text')
|
||||
.addColumn('ip_address', 'text')
|
||||
.addColumn('user_agent', 'text')
|
||||
.addColumn('details_json', 'text', (c) => c.notNull().defaultTo('{}'))
|
||||
.addColumn('occurred_at', 'integer', (c) => c.notNull())
|
||||
.execute();
|
||||
await (0, kysely_1.sql) `CREATE INDEX IF NOT EXISTS idx_audit_logs_user ON audit_logs (user_id)`.execute(db);
|
||||
await (0, kysely_1.sql) `CREATE INDEX IF NOT EXISTS idx_audit_logs_occurred ON audit_logs (occurred_at)`.execute(db);
|
||||
}
|
||||
async function down(db) {
|
||||
await db.schema.dropTable('audit_logs').ifExists().execute();
|
||||
await db.schema.dropTable('totp_secrets').ifExists().execute();
|
||||
await db.schema.dropTable('sso_configs').ifExists().execute();
|
||||
}
|
||||
12
dist/main.js
vendored
12
dist/main.js
vendored
@@ -69,6 +69,11 @@ const ApproveAllNewStatesCommand_1 = require("./modules/visual-regression/applic
|
||||
const ListComparisonsQuery_1 = require("./modules/visual-regression/application/queries/ListComparisonsQuery");
|
||||
const StorageProvider_1 = require("./shared/infrastructure/StorageProvider");
|
||||
const path_1 = __importDefault(require("path"));
|
||||
// SSO + Audit modules (enterprise)
|
||||
const KyselySSOConfigRepository_1 = require("./modules/sso/infrastructure/repositories/KyselySSOConfigRepository");
|
||||
const KyselyTOTPRepository_1 = require("./modules/sso/infrastructure/repositories/KyselyTOTPRepository");
|
||||
const TOTPService_1 = require("./modules/sso/infrastructure/providers/TOTPService");
|
||||
const KyselyAuditRepository_1 = require("./modules/audit/infrastructure/repositories/KyselyAuditRepository");
|
||||
// Scheduling module
|
||||
const KyselyScheduleRepository_1 = require("./modules/scheduling/infrastructure/repositories/KyselyScheduleRepository");
|
||||
const CreateScheduleCommand_1 = require("./modules/scheduling/application/commands/CreateScheduleCommand");
|
||||
@@ -173,6 +178,11 @@ async function bootstrap() {
|
||||
const listSchedules = new ListSchedulesQuery_1.ListSchedulesQuery(scheduleRepo);
|
||||
const schedulingService = new SchedulingService_1.SchedulingService(scheduleRepo, jobQueue, eventBus, logger);
|
||||
await schedulingService.start();
|
||||
// 12c. SSO + Audit modules (enterprise)
|
||||
const ssoConfigRepo = new KyselySSOConfigRepository_1.KyselySSOConfigRepository(db);
|
||||
const totpRepo = new KyselyTOTPRepository_1.KyselyTOTPRepository(db);
|
||||
const totpService = new TOTPService_1.TOTPService();
|
||||
const auditRepo = new KyselyAuditRepository_1.KyselyAuditRepository(db);
|
||||
// 13. HTTP server
|
||||
const app = (0, server_1.createServer)({
|
||||
config,
|
||||
@@ -198,6 +208,8 @@ async function bootstrap() {
|
||||
apiKeyRepository: apiKeyRepo,
|
||||
userRepository: userRepo,
|
||||
},
|
||||
ssoDeps: { ssoConfigRepository: ssoConfigRepo, totpRepository: totpRepo, totpService },
|
||||
auditRepository: auditRepo,
|
||||
});
|
||||
const httpServer = http_1.default.createServer(app);
|
||||
// 12. Socket.io + gateway
|
||||
|
||||
23
dist/modules/audit/domain/entities/AuditLog.js
vendored
Normal file
23
dist/modules/audit/domain/entities/AuditLog.js
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AuditLog = void 0;
|
||||
const Entity_1 = require("../../../../shared/domain/Entity");
|
||||
const UniqueId_1 = require("../../../../shared/domain/UniqueId");
|
||||
class AuditLog extends Entity_1.Entity {
|
||||
static create(props, id) {
|
||||
return new AuditLog(props, id ?? UniqueId_1.UniqueId.create());
|
||||
}
|
||||
static reconstitute(props, id) {
|
||||
return new AuditLog(props, id);
|
||||
}
|
||||
get userId() { return this.props.userId; }
|
||||
get organizationId() { return this.props.organizationId; }
|
||||
get action() { return this.props.action; }
|
||||
get resource() { return this.props.resource; }
|
||||
get resourceId() { return this.props.resourceId; }
|
||||
get ipAddress() { return this.props.ipAddress; }
|
||||
get userAgent() { return this.props.userAgent; }
|
||||
get details() { return this.props.details; }
|
||||
get occurredAt() { return this.props.occurredAt; }
|
||||
}
|
||||
exports.AuditLog = AuditLog;
|
||||
9
dist/modules/audit/index.js
vendored
Normal file
9
dist/modules/audit/index.js
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createAuditRouter = exports.KyselyAuditRepository = exports.AuditLog = void 0;
|
||||
var AuditLog_1 = require("./domain/entities/AuditLog");
|
||||
Object.defineProperty(exports, "AuditLog", { enumerable: true, get: function () { return AuditLog_1.AuditLog; } });
|
||||
var KyselyAuditRepository_1 = require("./infrastructure/repositories/KyselyAuditRepository");
|
||||
Object.defineProperty(exports, "KyselyAuditRepository", { enumerable: true, get: function () { return KyselyAuditRepository_1.KyselyAuditRepository; } });
|
||||
var AuditController_1 = require("./infrastructure/http/AuditController");
|
||||
Object.defineProperty(exports, "createAuditRouter", { enumerable: true, get: function () { return AuditController_1.createAuditRouter; } });
|
||||
39
dist/modules/audit/infrastructure/http/AuditController.js
vendored
Normal file
39
dist/modules/audit/infrastructure/http/AuditController.js
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createAuditRouter = createAuditRouter;
|
||||
const express_1 = require("express");
|
||||
function createAuditRouter(repo) {
|
||||
const router = (0, express_1.Router)();
|
||||
// GET /api/audit — list audit logs (enterprise only)
|
||||
router.get('/', async (req, res, next) => {
|
||||
try {
|
||||
const filters = {
|
||||
userId: req.query['userId'],
|
||||
organizationId: req.query['organizationId'],
|
||||
action: req.query['action'],
|
||||
resource: req.query['resource'],
|
||||
limit: req.query['limit'] ? Number(req.query['limit']) : 100,
|
||||
};
|
||||
if (req.query['from'])
|
||||
filters.from = new Date(req.query['from']);
|
||||
if (req.query['to'])
|
||||
filters.to = new Date(req.query['to']);
|
||||
const logs = await repo.findAll(filters);
|
||||
res.json(logs.map((l) => ({
|
||||
id: l.id.toString(),
|
||||
userId: l.userId,
|
||||
organizationId: l.organizationId,
|
||||
action: l.action,
|
||||
resource: l.resource,
|
||||
resourceId: l.resourceId,
|
||||
ipAddress: l.ipAddress,
|
||||
details: l.details,
|
||||
occurredAt: l.occurredAt.toISOString(),
|
||||
})));
|
||||
}
|
||||
catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
return router;
|
||||
}
|
||||
55
dist/modules/audit/infrastructure/repositories/KyselyAuditRepository.js
vendored
Normal file
55
dist/modules/audit/infrastructure/repositories/KyselyAuditRepository.js
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.KyselyAuditRepository = void 0;
|
||||
const UniqueId_1 = require("../../../../shared/domain/UniqueId");
|
||||
const AuditLog_1 = require("../../domain/entities/AuditLog");
|
||||
class KyselyAuditRepository {
|
||||
constructor(db) {
|
||||
this.db = db;
|
||||
}
|
||||
async save(log) {
|
||||
await this.db.insertInto('audit_logs').values({
|
||||
id: log.id.toString(),
|
||||
user_id: log.userId,
|
||||
organization_id: log.organizationId,
|
||||
action: log.action,
|
||||
resource: log.resource,
|
||||
resource_id: log.resourceId,
|
||||
ip_address: log.ipAddress,
|
||||
user_agent: log.userAgent,
|
||||
details_json: JSON.stringify(log.details),
|
||||
occurred_at: log.occurredAt.getTime(),
|
||||
}).execute();
|
||||
}
|
||||
async findAll(filters = {}) {
|
||||
let query = this.db.selectFrom('audit_logs').selectAll();
|
||||
if (filters.userId)
|
||||
query = query.where('user_id', '=', filters.userId);
|
||||
if (filters.organizationId)
|
||||
query = query.where('organization_id', '=', filters.organizationId);
|
||||
if (filters.action)
|
||||
query = query.where('action', '=', filters.action);
|
||||
if (filters.resource)
|
||||
query = query.where('resource', '=', filters.resource);
|
||||
if (filters.from)
|
||||
query = query.where('occurred_at', '>=', filters.from.getTime());
|
||||
if (filters.to)
|
||||
query = query.where('occurred_at', '<=', filters.to.getTime());
|
||||
const rows = await query
|
||||
.orderBy('occurred_at', 'desc')
|
||||
.limit(filters.limit ?? 100)
|
||||
.execute();
|
||||
return rows.map((row) => AuditLog_1.AuditLog.reconstitute({
|
||||
userId: row.user_id,
|
||||
organizationId: row.organization_id,
|
||||
action: row.action,
|
||||
resource: row.resource,
|
||||
resourceId: row.resource_id,
|
||||
ipAddress: row.ip_address,
|
||||
userAgent: row.user_agent,
|
||||
details: JSON.parse(row.details_json),
|
||||
occurredAt: new Date(row.occurred_at),
|
||||
}, UniqueId_1.UniqueId.from(row.id)));
|
||||
}
|
||||
}
|
||||
exports.KyselyAuditRepository = KyselyAuditRepository;
|
||||
@@ -166,5 +166,27 @@ function createAuthController(registerCommand, loginCommand, createOrgCommand, i
|
||||
await apiKeyRepository.delete(keyId);
|
||||
res.json({ success: true });
|
||||
});
|
||||
// GET /api/auth/sessions — list active sessions (session management dashboard)
|
||||
router.get('/sessions', authMiddleware, async (req, res) => {
|
||||
const sessions = await sessionRepository.findByUserId(req.user.id);
|
||||
res.json(sessions.map((s) => ({
|
||||
id: s.id,
|
||||
createdAt: new Date(s.createdAt).toISOString(),
|
||||
expiresAt: new Date(s.expiresAt).toISOString(),
|
||||
})));
|
||||
});
|
||||
// DELETE /api/auth/sessions/:id — revoke a specific session
|
||||
router.delete('/sessions/:id', authMiddleware, async (req, res) => {
|
||||
const sessionId = String(req.params['id']);
|
||||
// Only allow revoking own sessions
|
||||
const userSessions = await sessionRepository.findByUserId(req.user.id);
|
||||
const owns = userSessions.some((s) => s.id === sessionId);
|
||||
if (!owns) {
|
||||
res.status(404).json({ error: 'Session not found' });
|
||||
return;
|
||||
}
|
||||
await sessionRepository.deleteById(sessionId);
|
||||
res.json({ success: true });
|
||||
});
|
||||
return router;
|
||||
}
|
||||
|
||||
@@ -33,9 +33,28 @@ class KyselySessionRepository {
|
||||
createdAt: new Date(row.created_at),
|
||||
};
|
||||
}
|
||||
async findByUserId(userId) {
|
||||
const rows = await this.db
|
||||
.selectFrom('auth_sessions')
|
||||
.selectAll()
|
||||
.where('user_id', '=', userId)
|
||||
.where('expires_at', '>', Date.now())
|
||||
.orderBy('created_at', 'desc')
|
||||
.execute();
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
userId: row.user_id,
|
||||
token: row.token,
|
||||
expiresAt: new Date(row.expires_at),
|
||||
createdAt: new Date(row.created_at),
|
||||
}));
|
||||
}
|
||||
async deleteByToken(token) {
|
||||
await this.db.deleteFrom('auth_sessions').where('token', '=', token).execute();
|
||||
}
|
||||
async deleteById(id) {
|
||||
await this.db.deleteFrom('auth_sessions').where('id', '=', id).execute();
|
||||
}
|
||||
async deleteExpired() {
|
||||
await this.db
|
||||
.deleteFrom('auth_sessions')
|
||||
|
||||
21
dist/modules/sso/domain/entities/SSOConfig.js
vendored
Normal file
21
dist/modules/sso/domain/entities/SSOConfig.js
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SSOConfig = void 0;
|
||||
const Entity_1 = require("../../../../shared/domain/Entity");
|
||||
const UniqueId_1 = require("../../../../shared/domain/UniqueId");
|
||||
class SSOConfig extends Entity_1.Entity {
|
||||
static create(props, id) {
|
||||
return new SSOConfig(props, id ?? UniqueId_1.UniqueId.create());
|
||||
}
|
||||
static reconstitute(props, id) {
|
||||
return new SSOConfig(props, id);
|
||||
}
|
||||
get organizationId() { return this.props.organizationId; }
|
||||
get provider() { return this.props.provider; }
|
||||
get enabled() { return this.props.enabled; }
|
||||
get config() { return this.props.config; }
|
||||
get createdAt() { return this.props.createdAt; }
|
||||
enable() { this.props.enabled = true; }
|
||||
disable() { this.props.enabled = false; }
|
||||
}
|
||||
exports.SSOConfig = SSOConfig;
|
||||
19
dist/modules/sso/domain/entities/TOTPSecret.js
vendored
Normal file
19
dist/modules/sso/domain/entities/TOTPSecret.js
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.TOTPSecret = void 0;
|
||||
const Entity_1 = require("../../../../shared/domain/Entity");
|
||||
const UniqueId_1 = require("../../../../shared/domain/UniqueId");
|
||||
class TOTPSecret extends Entity_1.Entity {
|
||||
static create(props, id) {
|
||||
return new TOTPSecret(props, id ?? UniqueId_1.UniqueId.create());
|
||||
}
|
||||
static reconstitute(props, id) {
|
||||
return new TOTPSecret(props, id);
|
||||
}
|
||||
get userId() { return this.props.userId; }
|
||||
get secret() { return this.props.secret; }
|
||||
get verified() { return this.props.verified; }
|
||||
get createdAt() { return this.props.createdAt; }
|
||||
verify() { this.props.verified = true; }
|
||||
}
|
||||
exports.TOTPSecret = TOTPSecret;
|
||||
2
dist/modules/sso/domain/ports/ISSOConfigRepository.js
vendored
Normal file
2
dist/modules/sso/domain/ports/ISSOConfigRepository.js
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
2
dist/modules/sso/domain/ports/ITOTPRepository.js
vendored
Normal file
2
dist/modules/sso/domain/ports/ITOTPRepository.js
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
21
dist/modules/sso/index.js
vendored
Normal file
21
dist/modules/sso/index.js
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createSSORouter = exports.LDAPProvider = exports.OIDCProvider = exports.SAMLProvider = exports.TOTPService = exports.KyselyTOTPRepository = exports.KyselySSOConfigRepository = exports.TOTPSecret = exports.SSOConfig = void 0;
|
||||
var SSOConfig_1 = require("./domain/entities/SSOConfig");
|
||||
Object.defineProperty(exports, "SSOConfig", { enumerable: true, get: function () { return SSOConfig_1.SSOConfig; } });
|
||||
var TOTPSecret_1 = require("./domain/entities/TOTPSecret");
|
||||
Object.defineProperty(exports, "TOTPSecret", { enumerable: true, get: function () { return TOTPSecret_1.TOTPSecret; } });
|
||||
var KyselySSOConfigRepository_1 = require("./infrastructure/repositories/KyselySSOConfigRepository");
|
||||
Object.defineProperty(exports, "KyselySSOConfigRepository", { enumerable: true, get: function () { return KyselySSOConfigRepository_1.KyselySSOConfigRepository; } });
|
||||
var KyselyTOTPRepository_1 = require("./infrastructure/repositories/KyselyTOTPRepository");
|
||||
Object.defineProperty(exports, "KyselyTOTPRepository", { enumerable: true, get: function () { return KyselyTOTPRepository_1.KyselyTOTPRepository; } });
|
||||
var TOTPService_1 = require("./infrastructure/providers/TOTPService");
|
||||
Object.defineProperty(exports, "TOTPService", { enumerable: true, get: function () { return TOTPService_1.TOTPService; } });
|
||||
var SAMLProvider_1 = require("./infrastructure/providers/SAMLProvider");
|
||||
Object.defineProperty(exports, "SAMLProvider", { enumerable: true, get: function () { return SAMLProvider_1.SAMLProvider; } });
|
||||
var OIDCProvider_1 = require("./infrastructure/providers/OIDCProvider");
|
||||
Object.defineProperty(exports, "OIDCProvider", { enumerable: true, get: function () { return OIDCProvider_1.OIDCProvider; } });
|
||||
var LDAPProvider_1 = require("./infrastructure/providers/LDAPProvider");
|
||||
Object.defineProperty(exports, "LDAPProvider", { enumerable: true, get: function () { return LDAPProvider_1.LDAPProvider; } });
|
||||
var SSOController_1 = require("./infrastructure/http/SSOController");
|
||||
Object.defineProperty(exports, "createSSORouter", { enumerable: true, get: function () { return SSOController_1.createSSORouter; } });
|
||||
147
dist/modules/sso/infrastructure/http/SSOController.js
vendored
Normal file
147
dist/modules/sso/infrastructure/http/SSOController.js
vendored
Normal 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;
|
||||
}
|
||||
81
dist/modules/sso/infrastructure/providers/LDAPProvider.js
vendored
Normal file
81
dist/modules/sso/infrastructure/providers/LDAPProvider.js
vendored
Normal 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;
|
||||
45
dist/modules/sso/infrastructure/providers/OIDCProvider.js
vendored
Normal file
45
dist/modules/sso/infrastructure/providers/OIDCProvider.js
vendored
Normal 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;
|
||||
35
dist/modules/sso/infrastructure/providers/SAMLProvider.js
vendored
Normal file
35
dist/modules/sso/infrastructure/providers/SAMLProvider.js
vendored
Normal 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;
|
||||
39
dist/modules/sso/infrastructure/providers/TOTPService.js
vendored
Normal file
39
dist/modules/sso/infrastructure/providers/TOTPService.js
vendored
Normal 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;
|
||||
53
dist/modules/sso/infrastructure/repositories/KyselySSOConfigRepository.js
vendored
Normal file
53
dist/modules/sso/infrastructure/repositories/KyselySSOConfigRepository.js
vendored
Normal 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;
|
||||
45
dist/modules/sso/infrastructure/repositories/KyselyTOTPRepository.js
vendored
Normal file
45
dist/modules/sso/infrastructure/repositories/KyselyTOTPRepository.js
vendored
Normal 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;
|
||||
Reference in New Issue
Block a user