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:
@@ -14,6 +14,8 @@ import { LicenseService } from '../modules/licensing/application/LicenseService'
|
||||
import { requireFeature } from '../modules/licensing/infrastructure/middleware/FeatureGateMiddleware';
|
||||
import { createAuthController } from '../modules/auth/infrastructure/http/AuthController';
|
||||
import { createAuthMiddleware } from '../modules/auth/application/middleware/AuthMiddleware';
|
||||
import { createSSORouter } from '../modules/sso/infrastructure/http/SSOController';
|
||||
import { createAuditRouter } from '../modules/audit/infrastructure/http/AuditController';
|
||||
import { ServerDependencies } from './server';
|
||||
import { RegisterCommand } from '../modules/auth/application/commands/RegisterCommand';
|
||||
import { LoginCommand } from '../modules/auth/application/commands/LoginCommand';
|
||||
@@ -80,5 +82,19 @@ export function createRouter(deps: ServerDependencies): Router {
|
||||
const licensingController = new LicensingController(licenseService);
|
||||
router.use('/license', licensingController.router);
|
||||
|
||||
// Enterprise: SSO + MFA (feature-gated)
|
||||
router.use(
|
||||
'/sso',
|
||||
requireFeature(licenseService, 'auth:sso'),
|
||||
createSSORouter(deps.ssoDeps)
|
||||
);
|
||||
|
||||
// Enterprise: Audit logs (feature-gated)
|
||||
router.use(
|
||||
'/audit',
|
||||
requireFeature(licenseService, 'audit:logs'),
|
||||
createAuditRouter(deps.auditRepository)
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
@@ -25,6 +25,16 @@ import { AuthControllerDeps } from './router';
|
||||
import { LicenseService } from '../modules/licensing/application/LicenseService';
|
||||
import { SchedulingControllerDeps } from '../modules/scheduling/infrastructure/http/SchedulingController';
|
||||
import { VisualRegressionControllerDeps } from '../modules/visual-regression/infrastructure/http/VisualRegressionController';
|
||||
import { KyselySSOConfigRepository } from '../modules/sso/infrastructure/repositories/KyselySSOConfigRepository';
|
||||
import { KyselyTOTPRepository } from '../modules/sso/infrastructure/repositories/KyselyTOTPRepository';
|
||||
import { TOTPService } from '../modules/sso/infrastructure/providers/TOTPService';
|
||||
import { KyselyAuditRepository } from '../modules/audit/infrastructure/repositories/KyselyAuditRepository';
|
||||
|
||||
export interface SSODeps {
|
||||
ssoConfigRepository: KyselySSOConfigRepository;
|
||||
totpRepository: KyselyTOTPRepository;
|
||||
totpService: TOTPService;
|
||||
}
|
||||
|
||||
export interface ServerDependencies {
|
||||
config: AppConfig;
|
||||
@@ -39,6 +49,8 @@ export interface ServerDependencies {
|
||||
visualRegressionDeps: VisualRegressionControllerDeps;
|
||||
authDeps: AuthControllerDeps;
|
||||
licenseService: LicenseService;
|
||||
ssoDeps: SSODeps;
|
||||
auditRepository: KyselyAuditRepository;
|
||||
}
|
||||
|
||||
export function createServer(deps: ServerDependencies): Express {
|
||||
|
||||
51
src/db/migrations/007_enterprise_tables.ts
Normal file
51
src/db/migrations/007_enterprise_tables.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { Kysely, sql } from 'kysely';
|
||||
|
||||
export async function up(db: Kysely<unknown>): Promise<void> {
|
||||
// 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 sql`CREATE INDEX IF NOT EXISTS idx_audit_logs_user ON audit_logs (user_id)`.execute(db);
|
||||
await sql`CREATE INDEX IF NOT EXISTS idx_audit_logs_occurred ON audit_logs (occurred_at)`.execute(db);
|
||||
}
|
||||
|
||||
export async function down(db: Kysely<unknown>): Promise<void> {
|
||||
await db.schema.dropTable('audit_logs').ifExists().execute();
|
||||
await db.schema.dropTable('totp_secrets').ifExists().execute();
|
||||
await db.schema.dropTable('sso_configs').ifExists().execute();
|
||||
}
|
||||
14
src/main.ts
14
src/main.ts
@@ -75,6 +75,12 @@ import { ListComparisonsQuery } from './modules/visual-regression/application/qu
|
||||
import { LocalStorageProvider } from './shared/infrastructure/StorageProvider';
|
||||
import path from 'path';
|
||||
|
||||
// SSO + Audit modules (enterprise)
|
||||
import { KyselySSOConfigRepository } from './modules/sso/infrastructure/repositories/KyselySSOConfigRepository';
|
||||
import { KyselyTOTPRepository } from './modules/sso/infrastructure/repositories/KyselyTOTPRepository';
|
||||
import { TOTPService } from './modules/sso/infrastructure/providers/TOTPService';
|
||||
import { KyselyAuditRepository } from './modules/audit/infrastructure/repositories/KyselyAuditRepository';
|
||||
|
||||
// Scheduling module
|
||||
import { KyselyScheduleRepository } from './modules/scheduling/infrastructure/repositories/KyselyScheduleRepository';
|
||||
import { CreateScheduleCommand } from './modules/scheduling/application/commands/CreateScheduleCommand';
|
||||
@@ -210,6 +216,12 @@ async function bootstrap(): Promise<void> {
|
||||
const schedulingService = new SchedulingService(scheduleRepo, jobQueue, eventBus, logger);
|
||||
await schedulingService.start();
|
||||
|
||||
// 12c. SSO + Audit modules (enterprise)
|
||||
const ssoConfigRepo = new KyselySSOConfigRepository(db);
|
||||
const totpRepo = new KyselyTOTPRepository(db);
|
||||
const totpService = new TOTPService();
|
||||
const auditRepo = new KyselyAuditRepository(db);
|
||||
|
||||
// 13. HTTP server
|
||||
const app = createServer({
|
||||
config,
|
||||
@@ -235,6 +247,8 @@ async function bootstrap(): Promise<void> {
|
||||
apiKeyRepository: apiKeyRepo,
|
||||
userRepository: userRepo,
|
||||
},
|
||||
ssoDeps: { ssoConfigRepository: ssoConfigRepo, totpRepository: totpRepo, totpService },
|
||||
auditRepository: auditRepo,
|
||||
});
|
||||
|
||||
const httpServer = http.createServer(app);
|
||||
|
||||
34
src/modules/audit/domain/entities/AuditLog.ts
Normal file
34
src/modules/audit/domain/entities/AuditLog.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { Entity } from '../../../../shared/domain/Entity';
|
||||
import { UniqueId } from '../../../../shared/domain/UniqueId';
|
||||
|
||||
export interface AuditLogProps {
|
||||
userId: string | null;
|
||||
organizationId: string | null;
|
||||
action: string;
|
||||
resource: string;
|
||||
resourceId: string | null;
|
||||
ipAddress: string | null;
|
||||
userAgent: string | null;
|
||||
details: Record<string, unknown>;
|
||||
occurredAt: Date;
|
||||
}
|
||||
|
||||
export class AuditLog extends Entity<AuditLogProps> {
|
||||
static create(props: AuditLogProps, id?: UniqueId): AuditLog {
|
||||
return new AuditLog(props, id ?? UniqueId.create());
|
||||
}
|
||||
|
||||
static reconstitute(props: AuditLogProps, id: UniqueId): AuditLog {
|
||||
return new AuditLog(props, id);
|
||||
}
|
||||
|
||||
get userId(): string | null { return this.props.userId; }
|
||||
get organizationId(): string | null { return this.props.organizationId; }
|
||||
get action(): string { return this.props.action; }
|
||||
get resource(): string { return this.props.resource; }
|
||||
get resourceId(): string | null { return this.props.resourceId; }
|
||||
get ipAddress(): string | null { return this.props.ipAddress; }
|
||||
get userAgent(): string | null { return this.props.userAgent; }
|
||||
get details(): Record<string, unknown> { return this.props.details; }
|
||||
get occurredAt(): Date { return this.props.occurredAt; }
|
||||
}
|
||||
5
src/modules/audit/index.ts
Normal file
5
src/modules/audit/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export { AuditLog } from './domain/entities/AuditLog';
|
||||
export type { AuditLogProps } from './domain/entities/AuditLog';
|
||||
export { KyselyAuditRepository } from './infrastructure/repositories/KyselyAuditRepository';
|
||||
export type { AuditFilters } from './infrastructure/repositories/KyselyAuditRepository';
|
||||
export { createAuditRouter } from './infrastructure/http/AuditController';
|
||||
39
src/modules/audit/infrastructure/http/AuditController.ts
Normal file
39
src/modules/audit/infrastructure/http/AuditController.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { KyselyAuditRepository, AuditFilters } from '../repositories/KyselyAuditRepository';
|
||||
|
||||
export function createAuditRouter(repo: KyselyAuditRepository): Router {
|
||||
const router = Router();
|
||||
|
||||
// GET /api/audit — list audit logs (enterprise only)
|
||||
router.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const filters: AuditFilters = {
|
||||
userId: req.query['userId'] as string | undefined,
|
||||
organizationId: req.query['organizationId'] as string | undefined,
|
||||
action: req.query['action'] as string | undefined,
|
||||
resource: req.query['resource'] as string | undefined,
|
||||
limit: req.query['limit'] ? Number(req.query['limit']) : 100,
|
||||
};
|
||||
|
||||
if (req.query['from']) filters.from = new Date(req.query['from'] as string);
|
||||
if (req.query['to']) filters.to = new Date(req.query['to'] as string);
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Kysely } from 'kysely';
|
||||
import { Database } from '../../../../shared/infrastructure/DatabaseConnection';
|
||||
import { UniqueId } from '../../../../shared/domain/UniqueId';
|
||||
import { AuditLog } from '../../domain/entities/AuditLog';
|
||||
|
||||
export interface AuditFilters {
|
||||
userId?: string;
|
||||
organizationId?: string;
|
||||
action?: string;
|
||||
resource?: string;
|
||||
from?: Date;
|
||||
to?: Date;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export class KyselyAuditRepository {
|
||||
constructor(private readonly db: Kysely<Database>) {}
|
||||
|
||||
async save(log: AuditLog): Promise<void> {
|
||||
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: AuditFilters = {}): Promise<AuditLog[]> {
|
||||
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.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) as Record<string, unknown>,
|
||||
occurredAt: new Date(row.occurred_at),
|
||||
},
|
||||
UniqueId.from(row.id)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ export interface AuthSession {
|
||||
export interface ISessionRepository {
|
||||
save(session: AuthSession): Promise<void>;
|
||||
findByToken(token: string): Promise<AuthSession | undefined>;
|
||||
findByUserId(userId: string): Promise<AuthSession[]>;
|
||||
deleteByToken(token: string): Promise<void>;
|
||||
deleteById(id: string): Promise<void>;
|
||||
deleteExpired(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -206,5 +206,31 @@ export function createAuthController(
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// GET /api/auth/sessions — list active sessions (session management dashboard)
|
||||
router.get('/sessions', authMiddleware, async (req: Request, res: Response) => {
|
||||
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: Request, res: Response) => {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -34,10 +34,31 @@ export class KyselySessionRepository implements ISessionRepository {
|
||||
};
|
||||
}
|
||||
|
||||
async findByUserId(userId: string): Promise<AuthSession[]> {
|
||||
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: string): Promise<void> {
|
||||
await this.db.deleteFrom('auth_sessions').where('token', '=', token).execute();
|
||||
}
|
||||
|
||||
async deleteById(id: string): Promise<void> {
|
||||
await this.db.deleteFrom('auth_sessions').where('id', '=', id).execute();
|
||||
}
|
||||
|
||||
async deleteExpired(): Promise<void> {
|
||||
await this.db
|
||||
.deleteFrom('auth_sessions')
|
||||
|
||||
31
src/modules/sso/domain/entities/SSOConfig.ts
Normal file
31
src/modules/sso/domain/entities/SSOConfig.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { Entity } from '../../../../shared/domain/Entity';
|
||||
import { UniqueId } from '../../../../shared/domain/UniqueId';
|
||||
|
||||
export type SSOProvider = 'saml' | 'oidc' | 'ldap';
|
||||
|
||||
export interface SSOConfigProps {
|
||||
organizationId: string;
|
||||
provider: SSOProvider;
|
||||
enabled: boolean;
|
||||
config: Record<string, string>;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export class SSOConfig extends Entity<SSOConfigProps> {
|
||||
static create(props: SSOConfigProps, id?: UniqueId): SSOConfig {
|
||||
return new SSOConfig(props, id ?? UniqueId.create());
|
||||
}
|
||||
|
||||
static reconstitute(props: SSOConfigProps, id: UniqueId): SSOConfig {
|
||||
return new SSOConfig(props, id);
|
||||
}
|
||||
|
||||
get organizationId(): string { return this.props.organizationId; }
|
||||
get provider(): SSOProvider { return this.props.provider; }
|
||||
get enabled(): boolean { return this.props.enabled; }
|
||||
get config(): Record<string, string> { return this.props.config; }
|
||||
get createdAt(): Date { return this.props.createdAt; }
|
||||
|
||||
enable(): void { this.props.enabled = true; }
|
||||
disable(): void { this.props.enabled = false; }
|
||||
}
|
||||
26
src/modules/sso/domain/entities/TOTPSecret.ts
Normal file
26
src/modules/sso/domain/entities/TOTPSecret.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { Entity } from '../../../../shared/domain/Entity';
|
||||
import { UniqueId } from '../../../../shared/domain/UniqueId';
|
||||
|
||||
export interface TOTPSecretProps {
|
||||
userId: string;
|
||||
secret: string;
|
||||
verified: boolean;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export class TOTPSecret extends Entity<TOTPSecretProps> {
|
||||
static create(props: TOTPSecretProps, id?: UniqueId): TOTPSecret {
|
||||
return new TOTPSecret(props, id ?? UniqueId.create());
|
||||
}
|
||||
|
||||
static reconstitute(props: TOTPSecretProps, id: UniqueId): TOTPSecret {
|
||||
return new TOTPSecret(props, id);
|
||||
}
|
||||
|
||||
get userId(): string { return this.props.userId; }
|
||||
get secret(): string { return this.props.secret; }
|
||||
get verified(): boolean { return this.props.verified; }
|
||||
get createdAt(): Date { return this.props.createdAt; }
|
||||
|
||||
verify(): void { this.props.verified = true; }
|
||||
}
|
||||
7
src/modules/sso/domain/ports/ISSOConfigRepository.ts
Normal file
7
src/modules/sso/domain/ports/ISSOConfigRepository.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { SSOConfig } from '../entities/SSOConfig';
|
||||
|
||||
export interface ISSOConfigRepository {
|
||||
save(config: SSOConfig): Promise<void>;
|
||||
findByOrganizationId(organizationId: string): Promise<SSOConfig | null>;
|
||||
findById(id: string): Promise<SSOConfig | null>;
|
||||
}
|
||||
7
src/modules/sso/domain/ports/ITOTPRepository.ts
Normal file
7
src/modules/sso/domain/ports/ITOTPRepository.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { TOTPSecret } from '../entities/TOTPSecret';
|
||||
|
||||
export interface ITOTPRepository {
|
||||
save(secret: TOTPSecret): Promise<void>;
|
||||
findByUserId(userId: string): Promise<TOTPSecret | null>;
|
||||
delete(userId: string): Promise<void>;
|
||||
}
|
||||
12
src/modules/sso/index.ts
Normal file
12
src/modules/sso/index.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
export { SSOConfig } from './domain/entities/SSOConfig';
|
||||
export type { SSOProvider } from './domain/entities/SSOConfig';
|
||||
export { TOTPSecret } from './domain/entities/TOTPSecret';
|
||||
export type { ISSOConfigRepository } from './domain/ports/ISSOConfigRepository';
|
||||
export type { ITOTPRepository } from './domain/ports/ITOTPRepository';
|
||||
export { KyselySSOConfigRepository } from './infrastructure/repositories/KyselySSOConfigRepository';
|
||||
export { KyselyTOTPRepository } from './infrastructure/repositories/KyselyTOTPRepository';
|
||||
export { TOTPService } from './infrastructure/providers/TOTPService';
|
||||
export { SAMLProvider } from './infrastructure/providers/SAMLProvider';
|
||||
export { OIDCProvider } from './infrastructure/providers/OIDCProvider';
|
||||
export { LDAPProvider } from './infrastructure/providers/LDAPProvider';
|
||||
export { createSSORouter } from './infrastructure/http/SSOController';
|
||||
169
src/modules/sso/infrastructure/http/SSOController.ts
Normal file
169
src/modules/sso/infrastructure/http/SSOController.ts
Normal file
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* SSO Controller — manages SSO provider configurations and TOTP/MFA.
|
||||
* Feature-gated: enterprise license required.
|
||||
*/
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { KyselySSOConfigRepository } from '../repositories/KyselySSOConfigRepository';
|
||||
import { KyselyTOTPRepository } from '../repositories/KyselyTOTPRepository';
|
||||
import { TOTPService } from '../providers/TOTPService';
|
||||
import { SSOConfig } from '../../domain/entities/SSOConfig';
|
||||
import { TOTPSecret } from '../../domain/entities/TOTPSecret';
|
||||
import { AuthenticatedUser } from '../../../auth/application/middleware/AuthMiddleware';
|
||||
|
||||
interface SSODeps {
|
||||
ssoConfigRepository: KyselySSOConfigRepository;
|
||||
totpRepository: KyselyTOTPRepository;
|
||||
totpService: TOTPService;
|
||||
}
|
||||
|
||||
export function createSSORouter(deps: SSODeps): Router {
|
||||
const router = Router();
|
||||
const { ssoConfigRepository, totpRepository, totpService } = deps;
|
||||
|
||||
// GET /api/sso/config — get SSO config for the current org
|
||||
router.get('/config', async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const user = req.user as AuthenticatedUser;
|
||||
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: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const user = req.user as AuthenticatedUser;
|
||||
if (!user?.orgId) return res.status(400).json({ error: 'No organization' });
|
||||
|
||||
const { provider, enabled, config } = req.body as {
|
||||
provider: 'saml' | 'oidc' | 'ldap';
|
||||
enabled: boolean;
|
||||
config: Record<string, string>;
|
||||
};
|
||||
|
||||
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.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: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const user = req.user as AuthenticatedUser;
|
||||
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: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const user = req.user as AuthenticatedUser;
|
||||
const { otpauthUrl, secret } = totpService.generateSecret(user.id, user.email);
|
||||
|
||||
// Save unverified secret
|
||||
const totpSecret = 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: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const user = req.user as AuthenticatedUser;
|
||||
const { token } = req.body as { token: string };
|
||||
|
||||
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: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const user = req.user as AuthenticatedUser;
|
||||
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: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const user = req.user as AuthenticatedUser;
|
||||
const stored = await totpRepository.findByUserId(user.id);
|
||||
res.json({ enabled: !!stored, verified: stored?.verified ?? false });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
107
src/modules/sso/infrastructure/providers/LDAPProvider.ts
Normal file
107
src/modules/sso/infrastructure/providers/LDAPProvider.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* LDAP/Active Directory authentication provider.
|
||||
*/
|
||||
import ldap from 'ldapjs';
|
||||
|
||||
export interface LDAPProviderConfig {
|
||||
url: string;
|
||||
baseDN: string;
|
||||
bindDN?: string;
|
||||
bindPassword?: string;
|
||||
userSearchFilter?: string;
|
||||
tlsOptions?: { rejectUnauthorized: boolean };
|
||||
}
|
||||
|
||||
export interface LDAPUser {
|
||||
dn: string;
|
||||
email?: string;
|
||||
displayName?: string;
|
||||
groups?: string[];
|
||||
}
|
||||
|
||||
export class LDAPProvider {
|
||||
constructor(private readonly config: LDAPProviderConfig) {}
|
||||
|
||||
async authenticate(username: string, password: string): Promise<LDAPUser | null> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const client = ldap.createClient({
|
||||
url: this.config.url,
|
||||
tlsOptions: this.config.tlsOptions,
|
||||
});
|
||||
|
||||
client.on('error', (err: Error) => {
|
||||
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: ldap.SearchEntry | null = 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 as ldap.SearchEntry;
|
||||
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: string): string | undefined => {
|
||||
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 ?? [],
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
68
src/modules/sso/infrastructure/providers/OIDCProvider.ts
Normal file
68
src/modules/sso/infrastructure/providers/OIDCProvider.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* OIDC (OpenID Connect) SSO provider.
|
||||
* Supports Okta, Azure AD, Google Workspace.
|
||||
*/
|
||||
import { discovery, authorizationCodeGrant, randomState, buildAuthorizationUrl } from 'openid-client';
|
||||
|
||||
export interface OIDCProviderConfig {
|
||||
issuer: string;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
redirectUri: string;
|
||||
scopes?: string[];
|
||||
}
|
||||
|
||||
export interface OIDCProfile {
|
||||
sub: string;
|
||||
email?: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export class OIDCProvider {
|
||||
private readonly config: OIDCProviderConfig;
|
||||
|
||||
constructor(config: OIDCProviderConfig) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
async generateAuthUrl(): Promise<{ url: string; state: string; codeVerifier: string }> {
|
||||
const issuerUrl = new URL(this.config.issuer);
|
||||
const oidcConfig = await discovery(issuerUrl, this.config.clientId, this.config.clientSecret);
|
||||
const state = 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 = buildAuthorizationUrl(oidcConfig, params);
|
||||
return { url: url.href, state, codeVerifier: '' };
|
||||
}
|
||||
|
||||
async handleCallback(
|
||||
params: URLSearchParams,
|
||||
expectedState: string,
|
||||
_codeVerifier: string
|
||||
): Promise<OIDCProfile> {
|
||||
const issuerUrl = new URL(this.config.issuer);
|
||||
const oidcConfig = await discovery(issuerUrl, this.config.clientId, this.config.clientSecret);
|
||||
|
||||
const currentUrl = new URL(`${this.config.redirectUri}?${params.toString()}`);
|
||||
const tokens = await 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
49
src/modules/sso/infrastructure/providers/SAMLProvider.ts
Normal file
49
src/modules/sso/infrastructure/providers/SAMLProvider.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* SAML 2.0 SSO provider.
|
||||
* Uses @node-saml/node-saml for SP-initiated SSO.
|
||||
*/
|
||||
import { SAML, SamlConfig } from '@node-saml/node-saml';
|
||||
|
||||
export interface SAMLProviderConfig {
|
||||
entryPoint: string;
|
||||
issuer: string;
|
||||
cert: string;
|
||||
callbackUrl: string;
|
||||
}
|
||||
|
||||
export interface SAMLProfile {
|
||||
nameID: string;
|
||||
email?: string;
|
||||
displayName?: string;
|
||||
}
|
||||
|
||||
export class SAMLProvider {
|
||||
private readonly saml: SAML;
|
||||
|
||||
constructor(config: SAMLProviderConfig) {
|
||||
const samlConfig: SamlConfig = {
|
||||
entryPoint: config.entryPoint,
|
||||
issuer: config.issuer,
|
||||
idpCert: config.cert,
|
||||
callbackUrl: config.callbackUrl,
|
||||
wantAuthnResponseSigned: false,
|
||||
};
|
||||
this.saml = new SAML(samlConfig);
|
||||
}
|
||||
|
||||
async generateAuthUrl(relayState?: string): Promise<string> {
|
||||
return this.saml.getAuthorizeUrlAsync(relayState ?? '', undefined, {});
|
||||
}
|
||||
|
||||
async validateResponse(body: Record<string, string>): Promise<SAMLProfile> {
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
47
src/modules/sso/infrastructure/providers/TOTPService.ts
Normal file
47
src/modules/sso/infrastructure/providers/TOTPService.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* TOTP (Time-based One-Time Password) service.
|
||||
* Uses otpauth library for RFC 6238 compliant TOTP.
|
||||
*/
|
||||
import { TOTP, Secret } from 'otpauth';
|
||||
|
||||
export interface TOTPSetup {
|
||||
secret: string;
|
||||
otpauthUrl: string;
|
||||
}
|
||||
|
||||
export class TOTPService {
|
||||
private readonly issuer: string;
|
||||
|
||||
constructor(issuer = 'ABE') {
|
||||
this.issuer = issuer;
|
||||
}
|
||||
|
||||
generateSecret(userId: string, label: string): TOTPSetup {
|
||||
const totp = new TOTP({
|
||||
issuer: this.issuer,
|
||||
label,
|
||||
algorithm: 'SHA1',
|
||||
digits: 6,
|
||||
period: 30,
|
||||
secret: new Secret({ size: 20 }),
|
||||
});
|
||||
|
||||
return {
|
||||
secret: totp.secret.base32,
|
||||
otpauthUrl: totp.toString(),
|
||||
};
|
||||
}
|
||||
|
||||
verify(secret: string, token: string): boolean {
|
||||
const totp = new TOTP({
|
||||
issuer: this.issuer,
|
||||
algorithm: 'SHA1',
|
||||
digits: 6,
|
||||
period: 30,
|
||||
secret: Secret.fromBase32(secret),
|
||||
});
|
||||
|
||||
const delta = totp.validate({ token, window: 1 });
|
||||
return delta !== null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Kysely } from 'kysely';
|
||||
import { Database } from '../../../../shared/infrastructure/DatabaseConnection';
|
||||
import { ISSOConfigRepository } from '../../domain/ports/ISSOConfigRepository';
|
||||
import { SSOConfig, SSOProvider } from '../../domain/entities/SSOConfig';
|
||||
import { UniqueId } from '../../../../shared/domain/UniqueId';
|
||||
|
||||
export class KyselySSOConfigRepository implements ISSOConfigRepository {
|
||||
constructor(private readonly db: Kysely<Database>) {}
|
||||
|
||||
async save(config: SSOConfig): Promise<void> {
|
||||
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: string): Promise<SSOConfig | null> {
|
||||
const row = await this.db
|
||||
.selectFrom('sso_configs')
|
||||
.selectAll()
|
||||
.where('organization_id', '=', organizationId)
|
||||
.executeTakeFirst();
|
||||
return row ? this.toDomain(row) : null;
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<SSOConfig | null> {
|
||||
const row = await this.db
|
||||
.selectFrom('sso_configs')
|
||||
.selectAll()
|
||||
.where('id', '=', id)
|
||||
.executeTakeFirst();
|
||||
return row ? this.toDomain(row) : null;
|
||||
}
|
||||
|
||||
private toDomain(row: {
|
||||
id: string;
|
||||
organization_id: string;
|
||||
provider: string;
|
||||
enabled: number;
|
||||
config_json: string;
|
||||
created_at: number;
|
||||
}): SSOConfig {
|
||||
return SSOConfig.reconstitute(
|
||||
{
|
||||
organizationId: row.organization_id,
|
||||
provider: row.provider as SSOProvider,
|
||||
enabled: row.enabled === 1,
|
||||
config: JSON.parse(row.config_json) as Record<string, string>,
|
||||
createdAt: new Date(row.created_at),
|
||||
},
|
||||
UniqueId.from(row.id)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Kysely } from 'kysely';
|
||||
import { Database } from '../../../../shared/infrastructure/DatabaseConnection';
|
||||
import { ITOTPRepository } from '../../domain/ports/ITOTPRepository';
|
||||
import { TOTPSecret } from '../../domain/entities/TOTPSecret';
|
||||
import { UniqueId } from '../../../../shared/domain/UniqueId';
|
||||
|
||||
export class KyselyTOTPRepository implements ITOTPRepository {
|
||||
constructor(private readonly db: Kysely<Database>) {}
|
||||
|
||||
async save(secret: TOTPSecret): Promise<void> {
|
||||
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: string): Promise<TOTPSecret | null> {
|
||||
const row = await this.db
|
||||
.selectFrom('totp_secrets')
|
||||
.selectAll()
|
||||
.where('user_id', '=', userId)
|
||||
.executeTakeFirst();
|
||||
if (!row) return null;
|
||||
return TOTPSecret.reconstitute(
|
||||
{
|
||||
userId: row.user_id,
|
||||
secret: row.secret,
|
||||
verified: row.verified === 1,
|
||||
createdAt: new Date(row.created_at),
|
||||
},
|
||||
UniqueId.from(row.id)
|
||||
);
|
||||
}
|
||||
|
||||
async delete(userId: string): Promise<void> {
|
||||
await this.db.deleteFrom('totp_secrets').where('user_id', '=', userId).execute();
|
||||
}
|
||||
}
|
||||
@@ -242,6 +242,36 @@ export interface WebhookDeliveryTable {
|
||||
attempted_at: number;
|
||||
}
|
||||
|
||||
export interface SSOConfigTable {
|
||||
id: string;
|
||||
organization_id: string;
|
||||
provider: string;
|
||||
enabled: number;
|
||||
config_json: string;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
export interface TOTPSecretTable {
|
||||
id: string;
|
||||
user_id: string;
|
||||
secret: string;
|
||||
verified: number;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
export interface AuditLogTable {
|
||||
id: string;
|
||||
user_id: string | null;
|
||||
organization_id: string | null;
|
||||
action: string;
|
||||
resource: string;
|
||||
resource_id: string | null;
|
||||
ip_address: string | null;
|
||||
user_agent: string | null;
|
||||
details_json: string;
|
||||
occurred_at: number;
|
||||
}
|
||||
|
||||
export interface Database {
|
||||
sessions: SessionTable;
|
||||
states: StateTable;
|
||||
@@ -263,6 +293,9 @@ export interface Database {
|
||||
integrations: IntegrationTable;
|
||||
webhook_endpoints: WebhookEndpointTable;
|
||||
webhook_deliveries: WebhookDeliveryTable;
|
||||
sso_configs: SSOConfigTable;
|
||||
totp_secrets: TOTPSecretTable;
|
||||
audit_logs: AuditLogTable;
|
||||
}
|
||||
|
||||
export function createDatabase(config: { driver: string; path: string; url?: string }): Kysely<Database> {
|
||||
|
||||
Reference in New Issue
Block a user