@open-mercato/enterprise 0.10.1-develop.8274.1.c8f0850146 → 0.10.1-develop.8278.1.f7f8e5ab1a
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -53,51 +53,55 @@ class MfaService {
|
|
|
53
53
|
return result;
|
|
54
54
|
}
|
|
55
55
|
async confirmMethod(userId, setupId, payload, providerType, context) {
|
|
56
|
-
const method = await this.em.
|
|
57
|
-
userId
|
|
58
|
-
|
|
59
|
-
deletedAt: null,
|
|
60
|
-
secret: setupId
|
|
61
|
-
});
|
|
62
|
-
if (!method) {
|
|
63
|
-
throw new MfaServiceError("MFA setup session not found", 404);
|
|
64
|
-
}
|
|
65
|
-
if (providerType && method.type !== providerType) {
|
|
66
|
-
throw new MfaServiceError("MFA setup session does not match the requested provider", 400);
|
|
67
|
-
}
|
|
68
|
-
const provider = this.mfaProviderRegistry.get(method.type);
|
|
69
|
-
if (!provider) {
|
|
70
|
-
throw new MfaServiceError(`MFA provider '${method.type}' is not registered`, 400);
|
|
71
|
-
}
|
|
72
|
-
await this.ensureProviderCanBeConfigured(userId, method.type, provider.allowMultiple);
|
|
73
|
-
let confirmation;
|
|
74
|
-
try {
|
|
75
|
-
confirmation = await provider.confirmSetup(userId, setupId, payload, context);
|
|
76
|
-
} catch (error) {
|
|
77
|
-
if (error instanceof ZodError) {
|
|
78
|
-
throw new MfaServiceError("Invalid payload", 400);
|
|
79
|
-
}
|
|
80
|
-
throw error;
|
|
81
|
-
}
|
|
82
|
-
const resolvedLabel = this.getLabelFromMetadata(confirmation.metadata) ?? method.label ?? null;
|
|
83
|
-
if (resolvedLabel && provider.allowMultiple) {
|
|
84
|
-
const duplicate = await this.em.findOne(UserMfaMethod, {
|
|
56
|
+
const method = await this.em.transactional(async (em) => {
|
|
57
|
+
await em.execute("select pg_advisory_xact_lock(hashtextextended(?::text, 0))", [`security:mfa:enrollment:${userId}`]);
|
|
58
|
+
const method2 = await findOneWithDecryption(em, UserMfaMethod, {
|
|
85
59
|
userId,
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
throw new MfaServiceError(`An MFA method with this name already exists`, 409);
|
|
60
|
+
isActive: false,
|
|
61
|
+
deletedAt: null,
|
|
62
|
+
secret: setupId
|
|
63
|
+
}, { refresh: true }, {});
|
|
64
|
+
if (!method2) {
|
|
65
|
+
throw new MfaServiceError("MFA setup session not found", 404);
|
|
93
66
|
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
67
|
+
if (providerType && method2.type !== providerType) {
|
|
68
|
+
throw new MfaServiceError("MFA setup session does not match the requested provider", 400);
|
|
69
|
+
}
|
|
70
|
+
const provider = this.mfaProviderRegistry.get(method2.type);
|
|
71
|
+
if (!provider) {
|
|
72
|
+
throw new MfaServiceError(`MFA provider '${method2.type}' is not registered`, 400);
|
|
73
|
+
}
|
|
74
|
+
await this.ensureProviderCanBeConfigured(userId, method2.type, provider.allowMultiple, em);
|
|
75
|
+
let confirmation;
|
|
76
|
+
try {
|
|
77
|
+
confirmation = await provider.confirmSetup(userId, setupId, payload, context);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (error instanceof ZodError) {
|
|
80
|
+
throw new MfaServiceError("Invalid payload", 400);
|
|
81
|
+
}
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
const resolvedLabel = this.getLabelFromMetadata(confirmation.metadata) ?? method2.label ?? null;
|
|
85
|
+
if (resolvedLabel && provider.allowMultiple) {
|
|
86
|
+
const duplicate = await findOneWithDecryption(em, UserMfaMethod, {
|
|
87
|
+
userId,
|
|
88
|
+
type: method2.type,
|
|
89
|
+
label: resolvedLabel,
|
|
90
|
+
isActive: true,
|
|
91
|
+
deletedAt: null
|
|
92
|
+
}, { refresh: true }, { tenantId: method2.tenantId, organizationId: method2.organizationId });
|
|
93
|
+
if (duplicate) {
|
|
94
|
+
throw new MfaServiceError(`An MFA method with this name already exists`, 409);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
method2.providerMetadata = confirmation.metadata;
|
|
98
|
+
method2.secret = confirmation.secret ?? null;
|
|
99
|
+
method2.label = resolvedLabel;
|
|
100
|
+
method2.isActive = true;
|
|
101
|
+
method2.updatedAt = /* @__PURE__ */ new Date();
|
|
102
|
+
await em.flush();
|
|
103
|
+
return method2;
|
|
104
|
+
});
|
|
101
105
|
await emitSecurityEvent("security.mfa.enrolled", {
|
|
102
106
|
userId,
|
|
103
107
|
tenantId: method.tenantId,
|
|
@@ -211,9 +215,11 @@ class MfaService {
|
|
|
211
215
|
}
|
|
212
216
|
}
|
|
213
217
|
if (!valid) continue;
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
218
|
+
const claimed = await this.em.execute(
|
|
219
|
+
"UPDATE mfa_recovery_codes SET is_used = true, used_at = ? WHERE id = ? AND user_id = ? AND tenant_id = ? AND is_used = false RETURNING id",
|
|
220
|
+
[/* @__PURE__ */ new Date(), recoveryCode.id, userId, recoveryCode.tenantId]
|
|
221
|
+
);
|
|
222
|
+
if (claimed.length === 0) return false;
|
|
217
223
|
const remaining = await this.em.count(MfaRecoveryCode, { userId, isUsed: false });
|
|
218
224
|
await emitSecurityEvent("security.recovery.used", { userId, remaining });
|
|
219
225
|
return true;
|
|
@@ -234,14 +240,14 @@ class MfaService {
|
|
|
234
240
|
const value = metadata.label;
|
|
235
241
|
return typeof value === "string" && value.length > 0 ? value : null;
|
|
236
242
|
}
|
|
237
|
-
async ensureProviderCanBeConfigured(userId, providerType, allowMultiple) {
|
|
243
|
+
async ensureProviderCanBeConfigured(userId, providerType, allowMultiple, em = this.em) {
|
|
238
244
|
if (allowMultiple) return;
|
|
239
|
-
const existingMethod = await
|
|
245
|
+
const existingMethod = await findOneWithDecryption(em, UserMfaMethod, {
|
|
240
246
|
userId,
|
|
241
247
|
type: providerType,
|
|
242
248
|
isActive: true,
|
|
243
249
|
deletedAt: null
|
|
244
|
-
});
|
|
250
|
+
}, { refresh: true }, {});
|
|
245
251
|
if (existingMethod) {
|
|
246
252
|
throw new MfaServiceError(`MFA provider '${providerType}' is already configured`, 409);
|
|
247
253
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/security/services/MfaService.ts"],
|
|
4
|
-
"sourcesContent": ["import { randomBytes } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { compare, hash } from 'bcryptjs'\nimport { ZodError } from 'zod'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { EnforcementScope, MfaEnforcementPolicy, MfaRecoveryCode, UserMfaMethod } from '../data/entities'\nimport { emitSecurityEvent } from '../events'\nimport type { MfaProviderRegistry } from '../lib/mfa-provider-registry'\nimport type { MfaProviderConfirmResult, MfaProviderRuntimeContext } from '../lib/mfa-provider-interface'\nimport type { SecurityModuleConfig } from '../lib/security-config'\nimport { readSecurityModuleConfig } from '../lib/security-config'\n\ntype SetupResult = {\n setupId: string\n clientData: Record<string, unknown>\n}\n\ntype ProviderDisplay = {\n type: string\n label: string\n icon: string\n allowMultiple: boolean\n components?: {\n setup?: string\n list?: string\n details?: string\n challenge?: string\n }\n}\n\nexport class MfaServiceError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n ) {\n super(message)\n this.name = 'MfaServiceError'\n }\n}\n\nexport class MfaService {\n constructor(\n private readonly em: EntityManager,\n private readonly mfaProviderRegistry: MfaProviderRegistry,\n private readonly securityConfig: SecurityModuleConfig = readSecurityModuleConfig(),\n ) {}\n\n async setupMethod(\n userId: string,\n providerType: string,\n payload: unknown,\n context?: MfaProviderRuntimeContext,\n ): Promise<SetupResult> {\n const provider = this.mfaProviderRegistry.get(providerType)\n if (!provider) {\n throw new MfaServiceError(`MFA provider '${providerType}' is not registered`, 400)\n }\n\n const user = await this.findUserById(userId)\n if (!user?.tenantId) {\n throw new MfaServiceError('User not found', 404)\n }\n\n await this.ensureProviderCanBeConfigured(userId, providerType, provider.allowMultiple)\n\n const resolvedPayload = provider.resolveSetupPayload\n ? await provider.resolveSetupPayload({\n id: user.id,\n email: user.email ?? null,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n }, payload)\n : payload\n\n const result = context\n ? await provider.setup(userId, resolvedPayload, context)\n : await provider.setup(userId, resolvedPayload)\n const now = new Date()\n const method = this.em.create(UserMfaMethod, {\n userId,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n type: providerType,\n isActive: false,\n secret: result.setupId,\n providerMetadata: null,\n createdAt: now,\n updatedAt: now,\n })\n this.em.persist(method)\n await this.em.flush()\n\n return result\n }\n\n async confirmMethod(\n userId: string,\n setupId: string,\n payload: unknown,\n providerType?: string,\n context?: MfaProviderRuntimeContext,\n ): Promise<{ recoveryCodes?: string[] }> {\n const method = await this.em.findOne(UserMfaMethod, {\n userId,\n isActive: false,\n deletedAt: null,\n secret: setupId,\n })\n if (!method) {\n throw new MfaServiceError('MFA setup session not found', 404)\n }\n if (providerType && method.type !== providerType) {\n throw new MfaServiceError('MFA setup session does not match the requested provider', 400)\n }\n\n const provider = this.mfaProviderRegistry.get(method.type)\n if (!provider) {\n throw new MfaServiceError(`MFA provider '${method.type}' is not registered`, 400)\n }\n\n await this.ensureProviderCanBeConfigured(userId, method.type, provider.allowMultiple)\n\n let confirmation: MfaProviderConfirmResult\n try {\n confirmation = await provider.confirmSetup(userId, setupId, payload, context)\n } catch (error) {\n if (error instanceof ZodError) {\n throw new MfaServiceError('Invalid payload', 400)\n }\n throw error\n }\n const resolvedLabel = this.getLabelFromMetadata(confirmation.metadata) ?? method.label ?? null\n\n if (resolvedLabel && provider.allowMultiple) {\n const duplicate = await this.em.findOne(UserMfaMethod, {\n userId,\n type: method.type,\n label: resolvedLabel,\n isActive: true,\n deletedAt: null,\n })\n if (duplicate) {\n throw new MfaServiceError(`An MFA method with this name already exists`, 409)\n }\n }\n\n method.providerMetadata = confirmation.metadata\n method.secret = confirmation.secret ?? null\n method.label = resolvedLabel\n method.isActive = true\n method.updatedAt = new Date()\n await this.em.flush()\n\n await emitSecurityEvent('security.mfa.enrolled', {\n userId,\n tenantId: method.tenantId,\n organizationId: method.organizationId ?? null,\n methodType: method.type,\n methodId: method.id,\n enrolledAt: new Date().toISOString(),\n })\n\n return {}\n }\n\n async getUserMethods(userId: string): Promise<UserMfaMethod[]> {\n return this.em.find(\n UserMfaMethod,\n {\n userId,\n isActive: true,\n deletedAt: null,\n },\n {\n orderBy: { createdAt: 'asc' },\n },\n )\n }\n\n async getAvailableProviders(tenantId: string, orgId?: string): Promise<ProviderDisplay[]> {\n const activePolicy = await this.resolveActiveEnforcementPolicy(tenantId, orgId)\n const providers = this.mfaProviderRegistry.listAvailable(activePolicy?.allowedMethods ?? null)\n return providers.map((provider) => ({\n type: provider.type,\n label: provider.label,\n icon: provider.icon,\n allowMultiple: provider.allowMultiple,\n ...(provider.components ? { components: provider.components } : {}),\n }))\n }\n\n async removeMethod(userId: string, methodId: string): Promise<void> {\n const method = await this.em.findOne(UserMfaMethod, {\n id: methodId,\n userId,\n isActive: true,\n deletedAt: null,\n })\n if (!method) {\n throw new MfaServiceError('MFA method not found', 404)\n }\n\n method.isActive = false\n method.deletedAt = new Date()\n method.updatedAt = new Date()\n await this.em.flush()\n\n await emitSecurityEvent('security.mfa.removed', {\n userId,\n methodId: method.id,\n methodType: method.type,\n })\n }\n\n async generateRecoveryCodes(userId: string): Promise<string[]> {\n const user = await this.findUserById(userId)\n if (!user?.tenantId) {\n throw new MfaServiceError('User not found', 404)\n }\n\n const existingCodes = await this.em.find(MfaRecoveryCode, {\n userId,\n isUsed: false,\n })\n const now = new Date()\n for (const code of existingCodes) {\n code.isUsed = true\n code.usedAt = now\n }\n\n const plaintextCodes: string[] = []\n for (let index = 0; index < this.securityConfig.recoveryCodes.count; index += 1) {\n const code = this.createRecoveryCode()\n const codeHash = await hash(code, this.securityConfig.recoveryCodes.bcryptCost)\n const recoveryCode = this.em.create(MfaRecoveryCode, {\n userId,\n tenantId: user.tenantId,\n codeHash,\n isUsed: false,\n createdAt: new Date(),\n })\n this.em.persist(recoveryCode)\n plaintextCodes.push(code)\n }\n\n await this.em.flush()\n await emitSecurityEvent('security.recovery.regenerated', {\n userId,\n total: plaintextCodes.length,\n })\n return plaintextCodes\n }\n\n async verifyRecoveryCode(userId: string, code: string): Promise<boolean> {\n const candidates = this.buildRecoveryCodeCandidates(code)\n if (candidates.length === 0) {\n return false\n }\n\n const recoveryCodes = await this.em.find(\n MfaRecoveryCode,\n {\n userId,\n isUsed: false,\n },\n {\n orderBy: { createdAt: 'asc' },\n },\n )\n\n for (const recoveryCode of recoveryCodes) {\n let valid = false\n for (const candidate of candidates) {\n if (await compare(candidate, recoveryCode.codeHash)) {\n valid = true\n break\n }\n }\n if (!valid) continue\n recoveryCode.isUsed = true\n recoveryCode.usedAt = new Date()\n await this.em.flush()\n const remaining = await this.em.count(MfaRecoveryCode, { userId, isUsed: false })\n await emitSecurityEvent('security.recovery.used', { userId, remaining })\n return true\n }\n\n return false\n }\n\n private createRecoveryCode(): string {\n return randomBytes(5).toString('hex').toUpperCase()\n }\n\n private buildRecoveryCodeCandidates(input: string): string[] {\n const trimmed = input.trim()\n const compact = trimmed.replace(/[\\s-]/g, '')\n const normalized = compact.toUpperCase()\n const candidates = [trimmed, trimmed.toUpperCase(), compact, normalized]\n .filter((value) => value.length > 0)\n return [...new Set(candidates)]\n }\n\n private getLabelFromMetadata(metadata: Record<string, unknown>): string | null {\n const value = metadata.label\n return typeof value === 'string' && value.length > 0 ? value : null\n }\n\n private async ensureProviderCanBeConfigured(\n userId: string,\n providerType: string,\n allowMultiple: boolean,\n ): Promise<void> {\n if (allowMultiple) return\n\n const existingMethod = await this.em.findOne(UserMfaMethod, {\n userId,\n type: providerType,\n isActive: true,\n deletedAt: null,\n })\n if (existingMethod) {\n throw new MfaServiceError(`MFA provider '${providerType}' is already configured`, 409)\n }\n }\n\n private async findUserById(userId: string): Promise<User | null> {\n return findOneWithDecryption(this.em, User, { id: userId, deletedAt: null }, undefined, {})\n }\n\n private async resolveActiveEnforcementPolicy(\n tenantId: string,\n orgId?: string,\n ): Promise<MfaEnforcementPolicy | null> {\n if (orgId) {\n const organizationPolicy = await this.em.findOne(MfaEnforcementPolicy, {\n scope: EnforcementScope.ORGANISATION,\n tenantId,\n organizationId: orgId,\n isEnforced: true,\n deletedAt: null,\n })\n if (organizationPolicy) return organizationPolicy\n }\n\n const tenantPolicy = await this.em.findOne(MfaEnforcementPolicy, {\n scope: EnforcementScope.TENANT,\n tenantId,\n isEnforced: true,\n deletedAt: null,\n })\n if (tenantPolicy) return tenantPolicy\n\n return this.em.findOne(MfaEnforcementPolicy, {\n scope: EnforcementScope.PLATFORM,\n isEnforced: true,\n deletedAt: null,\n })\n }\n}\n\nexport default MfaService\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,mBAAmB;AAE5B,SAAS,SAAS,YAAY;AAC9B,SAAS,gBAAgB;AACzB,SAAS,YAAY;AACrB,SAAS,6BAA6B;AACtC,SAAS,kBAAkB,sBAAsB,iBAAiB,qBAAqB;AACvF,SAAS,yBAAyB;AAIlC,SAAS,gCAAgC;AAoBlC,MAAM,wBAAwB,MAAM;AAAA,EACzC,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,WAAW;AAAA,EACtB,YACmB,IACA,qBACA,iBAAuC,yBAAyB,GACjF;AAHiB;AACA;AACA;AAAA,EAChB;AAAA,EAEH,MAAM,YACJ,QACA,cACA,SACA,SACsB;AACtB,UAAM,WAAW,KAAK,oBAAoB,IAAI,YAAY;AAC1D,QAAI,CAAC,UAAU;AACb,YAAM,IAAI,gBAAgB,iBAAiB,YAAY,uBAAuB,GAAG;AAAA,IACnF;AAEA,UAAM,OAAO,MAAM,KAAK,aAAa,MAAM;AAC3C,QAAI,CAAC,MAAM,UAAU;AACnB,YAAM,IAAI,gBAAgB,kBAAkB,GAAG;AAAA,IACjD;AAEA,UAAM,KAAK,8BAA8B,QAAQ,cAAc,SAAS,aAAa;AAErF,UAAM,kBAAkB,SAAS,sBAC7B,MAAM,SAAS,oBAAoB;AAAA,MACnC,IAAI,KAAK;AAAA,MACT,OAAO,KAAK,SAAS;AAAA,MACrB,UAAU,KAAK;AAAA,MACf,gBAAgB,KAAK,kBAAkB;AAAA,IACzC,GAAG,OAAO,IACR;AAEJ,UAAM,SAAS,UACX,MAAM,SAAS,MAAM,QAAQ,iBAAiB,OAAO,IACrD,MAAM,SAAS,MAAM,QAAQ,eAAe;AAChD,UAAM,MAAM,oBAAI,KAAK;AACrB,UAAM,SAAS,KAAK,GAAG,OAAO,eAAe;AAAA,MAC3C;AAAA,MACA,UAAU,KAAK;AAAA,MACf,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,MAAM;AAAA,MACN,UAAU;AAAA,MACV,QAAQ,OAAO;AAAA,MACf,kBAAkB;AAAA,MAClB,WAAW;AAAA,MACX,WAAW;AAAA,IACb,CAAC;AACD,SAAK,GAAG,QAAQ,MAAM;AACtB,UAAM,KAAK,GAAG,MAAM;AAEpB,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,cACJ,QACA,SACA,SACA,cACA,SACuC;AACvC,UAAM,SAAS,MAAM,KAAK,GAAG,QAAQ,eAAe;AAAA,
|
|
6
|
-
"names": []
|
|
4
|
+
"sourcesContent": ["import { randomBytes } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { compare, hash } from 'bcryptjs'\nimport { ZodError } from 'zod'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { EnforcementScope, MfaEnforcementPolicy, MfaRecoveryCode, UserMfaMethod } from '../data/entities'\nimport { emitSecurityEvent } from '../events'\nimport type { MfaProviderRegistry } from '../lib/mfa-provider-registry'\nimport type { MfaProviderConfirmResult, MfaProviderRuntimeContext } from '../lib/mfa-provider-interface'\nimport type { SecurityModuleConfig } from '../lib/security-config'\nimport { readSecurityModuleConfig } from '../lib/security-config'\n\ntype SetupResult = {\n setupId: string\n clientData: Record<string, unknown>\n}\n\ntype ProviderDisplay = {\n type: string\n label: string\n icon: string\n allowMultiple: boolean\n components?: {\n setup?: string\n list?: string\n details?: string\n challenge?: string\n }\n}\n\nexport class MfaServiceError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n ) {\n super(message)\n this.name = 'MfaServiceError'\n }\n}\n\nexport class MfaService {\n constructor(\n private readonly em: EntityManager,\n private readonly mfaProviderRegistry: MfaProviderRegistry,\n private readonly securityConfig: SecurityModuleConfig = readSecurityModuleConfig(),\n ) {}\n\n async setupMethod(\n userId: string,\n providerType: string,\n payload: unknown,\n context?: MfaProviderRuntimeContext,\n ): Promise<SetupResult> {\n const provider = this.mfaProviderRegistry.get(providerType)\n if (!provider) {\n throw new MfaServiceError(`MFA provider '${providerType}' is not registered`, 400)\n }\n\n const user = await this.findUserById(userId)\n if (!user?.tenantId) {\n throw new MfaServiceError('User not found', 404)\n }\n\n await this.ensureProviderCanBeConfigured(userId, providerType, provider.allowMultiple)\n\n const resolvedPayload = provider.resolveSetupPayload\n ? await provider.resolveSetupPayload({\n id: user.id,\n email: user.email ?? null,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n }, payload)\n : payload\n\n const result = context\n ? await provider.setup(userId, resolvedPayload, context)\n : await provider.setup(userId, resolvedPayload)\n const now = new Date()\n const method = this.em.create(UserMfaMethod, {\n userId,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n type: providerType,\n isActive: false,\n secret: result.setupId,\n providerMetadata: null,\n createdAt: now,\n updatedAt: now,\n })\n this.em.persist(method)\n await this.em.flush()\n\n return result\n }\n\n async confirmMethod(\n userId: string,\n setupId: string,\n payload: unknown,\n providerType?: string,\n context?: MfaProviderRuntimeContext,\n ): Promise<{ recoveryCodes?: string[] }> {\n const method = await this.em.transactional(async (em) => {\n await em.execute('select pg_advisory_xact_lock(hashtextextended(?::text, 0))', [`security:mfa:enrollment:${userId}`])\n const method = await findOneWithDecryption(em, UserMfaMethod, {\n userId,\n isActive: false,\n deletedAt: null,\n secret: setupId,\n }, { refresh: true }, {})\n if (!method) {\n throw new MfaServiceError('MFA setup session not found', 404)\n }\n if (providerType && method.type !== providerType) {\n throw new MfaServiceError('MFA setup session does not match the requested provider', 400)\n }\n\n const provider = this.mfaProviderRegistry.get(method.type)\n if (!provider) {\n throw new MfaServiceError(`MFA provider '${method.type}' is not registered`, 400)\n }\n\n await this.ensureProviderCanBeConfigured(userId, method.type, provider.allowMultiple, em)\n\n let confirmation: MfaProviderConfirmResult\n try {\n confirmation = await provider.confirmSetup(userId, setupId, payload, context)\n } catch (error) {\n if (error instanceof ZodError) {\n throw new MfaServiceError('Invalid payload', 400)\n }\n throw error\n }\n const resolvedLabel = this.getLabelFromMetadata(confirmation.metadata) ?? method.label ?? null\n\n if (resolvedLabel && provider.allowMultiple) {\n const duplicate = await findOneWithDecryption(em, UserMfaMethod, {\n userId,\n type: method.type,\n label: resolvedLabel,\n isActive: true,\n deletedAt: null,\n }, { refresh: true }, { tenantId: method.tenantId, organizationId: method.organizationId })\n if (duplicate) {\n throw new MfaServiceError(`An MFA method with this name already exists`, 409)\n }\n }\n\n method.providerMetadata = confirmation.metadata\n method.secret = confirmation.secret ?? null\n method.label = resolvedLabel\n method.isActive = true\n method.updatedAt = new Date()\n await em.flush()\n\n return method\n })\n\n await emitSecurityEvent('security.mfa.enrolled', {\n userId,\n tenantId: method.tenantId,\n organizationId: method.organizationId ?? null,\n methodType: method.type,\n methodId: method.id,\n enrolledAt: new Date().toISOString(),\n })\n\n return {}\n }\n\n async getUserMethods(userId: string): Promise<UserMfaMethod[]> {\n return this.em.find(\n UserMfaMethod,\n {\n userId,\n isActive: true,\n deletedAt: null,\n },\n {\n orderBy: { createdAt: 'asc' },\n },\n )\n }\n\n async getAvailableProviders(tenantId: string, orgId?: string): Promise<ProviderDisplay[]> {\n const activePolicy = await this.resolveActiveEnforcementPolicy(tenantId, orgId)\n const providers = this.mfaProviderRegistry.listAvailable(activePolicy?.allowedMethods ?? null)\n return providers.map((provider) => ({\n type: provider.type,\n label: provider.label,\n icon: provider.icon,\n allowMultiple: provider.allowMultiple,\n ...(provider.components ? { components: provider.components } : {}),\n }))\n }\n\n async removeMethod(userId: string, methodId: string): Promise<void> {\n const method = await this.em.findOne(UserMfaMethod, {\n id: methodId,\n userId,\n isActive: true,\n deletedAt: null,\n })\n if (!method) {\n throw new MfaServiceError('MFA method not found', 404)\n }\n\n method.isActive = false\n method.deletedAt = new Date()\n method.updatedAt = new Date()\n await this.em.flush()\n\n await emitSecurityEvent('security.mfa.removed', {\n userId,\n methodId: method.id,\n methodType: method.type,\n })\n }\n\n async generateRecoveryCodes(userId: string): Promise<string[]> {\n const user = await this.findUserById(userId)\n if (!user?.tenantId) {\n throw new MfaServiceError('User not found', 404)\n }\n\n const existingCodes = await this.em.find(MfaRecoveryCode, {\n userId,\n isUsed: false,\n })\n const now = new Date()\n for (const code of existingCodes) {\n code.isUsed = true\n code.usedAt = now\n }\n\n const plaintextCodes: string[] = []\n for (let index = 0; index < this.securityConfig.recoveryCodes.count; index += 1) {\n const code = this.createRecoveryCode()\n const codeHash = await hash(code, this.securityConfig.recoveryCodes.bcryptCost)\n const recoveryCode = this.em.create(MfaRecoveryCode, {\n userId,\n tenantId: user.tenantId,\n codeHash,\n isUsed: false,\n createdAt: new Date(),\n })\n this.em.persist(recoveryCode)\n plaintextCodes.push(code)\n }\n\n await this.em.flush()\n await emitSecurityEvent('security.recovery.regenerated', {\n userId,\n total: plaintextCodes.length,\n })\n return plaintextCodes\n }\n\n async verifyRecoveryCode(userId: string, code: string): Promise<boolean> {\n const candidates = this.buildRecoveryCodeCandidates(code)\n if (candidates.length === 0) {\n return false\n }\n\n const recoveryCodes = await this.em.find(\n MfaRecoveryCode,\n {\n userId,\n isUsed: false,\n },\n {\n orderBy: { createdAt: 'asc' },\n },\n )\n\n for (const recoveryCode of recoveryCodes) {\n let valid = false\n for (const candidate of candidates) {\n if (await compare(candidate, recoveryCode.codeHash)) {\n valid = true\n break\n }\n }\n if (!valid) continue\n const claimed = await this.em.execute<Array<{ id: string }>>(\n 'UPDATE mfa_recovery_codes SET is_used = true, used_at = ? WHERE id = ? AND user_id = ? AND tenant_id = ? AND is_used = false RETURNING id',\n [new Date(), recoveryCode.id, userId, recoveryCode.tenantId],\n )\n if (claimed.length === 0) return false\n const remaining = await this.em.count(MfaRecoveryCode, { userId, isUsed: false })\n await emitSecurityEvent('security.recovery.used', { userId, remaining })\n return true\n }\n\n return false\n }\n\n private createRecoveryCode(): string {\n return randomBytes(5).toString('hex').toUpperCase()\n }\n\n private buildRecoveryCodeCandidates(input: string): string[] {\n const trimmed = input.trim()\n const compact = trimmed.replace(/[\\s-]/g, '')\n const normalized = compact.toUpperCase()\n const candidates = [trimmed, trimmed.toUpperCase(), compact, normalized]\n .filter((value) => value.length > 0)\n return [...new Set(candidates)]\n }\n\n private getLabelFromMetadata(metadata: Record<string, unknown>): string | null {\n const value = metadata.label\n return typeof value === 'string' && value.length > 0 ? value : null\n }\n\n private async ensureProviderCanBeConfigured(\n userId: string,\n providerType: string,\n allowMultiple: boolean,\n em: EntityManager = this.em,\n ): Promise<void> {\n if (allowMultiple) return\n\n const existingMethod = await findOneWithDecryption(em, UserMfaMethod, {\n userId,\n type: providerType,\n isActive: true,\n deletedAt: null,\n }, { refresh: true }, {})\n if (existingMethod) {\n throw new MfaServiceError(`MFA provider '${providerType}' is already configured`, 409)\n }\n }\n\n private async findUserById(userId: string): Promise<User | null> {\n return findOneWithDecryption(this.em, User, { id: userId, deletedAt: null }, undefined, {})\n }\n\n private async resolveActiveEnforcementPolicy(\n tenantId: string,\n orgId?: string,\n ): Promise<MfaEnforcementPolicy | null> {\n if (orgId) {\n const organizationPolicy = await this.em.findOne(MfaEnforcementPolicy, {\n scope: EnforcementScope.ORGANISATION,\n tenantId,\n organizationId: orgId,\n isEnforced: true,\n deletedAt: null,\n })\n if (organizationPolicy) return organizationPolicy\n }\n\n const tenantPolicy = await this.em.findOne(MfaEnforcementPolicy, {\n scope: EnforcementScope.TENANT,\n tenantId,\n isEnforced: true,\n deletedAt: null,\n })\n if (tenantPolicy) return tenantPolicy\n\n return this.em.findOne(MfaEnforcementPolicy, {\n scope: EnforcementScope.PLATFORM,\n isEnforced: true,\n deletedAt: null,\n })\n }\n}\n\nexport default MfaService\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,mBAAmB;AAE5B,SAAS,SAAS,YAAY;AAC9B,SAAS,gBAAgB;AACzB,SAAS,YAAY;AACrB,SAAS,6BAA6B;AACtC,SAAS,kBAAkB,sBAAsB,iBAAiB,qBAAqB;AACvF,SAAS,yBAAyB;AAIlC,SAAS,gCAAgC;AAoBlC,MAAM,wBAAwB,MAAM;AAAA,EACzC,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,WAAW;AAAA,EACtB,YACmB,IACA,qBACA,iBAAuC,yBAAyB,GACjF;AAHiB;AACA;AACA;AAAA,EAChB;AAAA,EAEH,MAAM,YACJ,QACA,cACA,SACA,SACsB;AACtB,UAAM,WAAW,KAAK,oBAAoB,IAAI,YAAY;AAC1D,QAAI,CAAC,UAAU;AACb,YAAM,IAAI,gBAAgB,iBAAiB,YAAY,uBAAuB,GAAG;AAAA,IACnF;AAEA,UAAM,OAAO,MAAM,KAAK,aAAa,MAAM;AAC3C,QAAI,CAAC,MAAM,UAAU;AACnB,YAAM,IAAI,gBAAgB,kBAAkB,GAAG;AAAA,IACjD;AAEA,UAAM,KAAK,8BAA8B,QAAQ,cAAc,SAAS,aAAa;AAErF,UAAM,kBAAkB,S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,EAAE,IAAI,QAAQ,WAAW,KAAK,GAAG,QAAW,CAAC,CAAC;AAAA,EAC5F;AAAA,EAEA,MAAc,+BACZ,UACA,OACsC;AACtC,QAAI,OAAO;AACT,YAAM,qBAAqB,MAAM,KAAK,GAAG,QAAQ,sBAAsB;AAAA,QACrE,OAAO,iBAAiB;AAAA,QACxB;AAAA,QACA,gBAAgB;AAAA,QAChB,YAAY;AAAA,QACZ,WAAW;AAAA,MACb,CAAC;AACD,UAAI,mBAAoB,QAAO;AAAA,IACjC;AAEA,UAAM,eAAe,MAAM,KAAK,GAAG,QAAQ,sBAAsB;AAAA,MAC/D,OAAO,iBAAiB;AAAA,MACxB;AAAA,MACA,YAAY;AAAA,MACZ,WAAW;AAAA,IACb,CAAC;AACD,QAAI,aAAc,QAAO;AAEzB,WAAO,KAAK,GAAG,QAAQ,sBAAsB;AAAA,MAC3C,OAAO,iBAAiB;AAAA,MACxB,YAAY;AAAA,MACZ,WAAW;AAAA,IACb,CAAC;AAAA,EACH;AACF;AAEA,IAAO,qBAAQ;",
|
|
6
|
+
"names": ["method"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/enterprise",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.8278.1.f7f8e5ab1a",
|
|
4
4
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -70,12 +70,12 @@
|
|
|
70
70
|
"@dnd-kit/core": "^6.3.1",
|
|
71
71
|
"@dnd-kit/sortable": "^10.0.0",
|
|
72
72
|
"@dnd-kit/utilities": "^3.2.2",
|
|
73
|
-
"@open-mercato/ai-assistant": "0.10.1-develop.
|
|
74
|
-
"@open-mercato/core": "0.10.1-develop.
|
|
75
|
-
"@open-mercato/queue": "0.10.1-develop.
|
|
76
|
-
"@open-mercato/scheduler": "0.10.1-develop.
|
|
77
|
-
"@open-mercato/ui": "0.10.1-develop.
|
|
78
|
-
"@open-mercato/web-research": "0.10.1-develop.
|
|
73
|
+
"@open-mercato/ai-assistant": "0.10.1-develop.8278.1.f7f8e5ab1a",
|
|
74
|
+
"@open-mercato/core": "0.10.1-develop.8278.1.f7f8e5ab1a",
|
|
75
|
+
"@open-mercato/queue": "0.10.1-develop.8278.1.f7f8e5ab1a",
|
|
76
|
+
"@open-mercato/scheduler": "0.10.1-develop.8278.1.f7f8e5ab1a",
|
|
77
|
+
"@open-mercato/ui": "0.10.1-develop.8278.1.f7f8e5ab1a",
|
|
78
|
+
"@open-mercato/web-research": "0.10.1-develop.8278.1.f7f8e5ab1a",
|
|
79
79
|
"@simplewebauthn/browser": "^13.3.0",
|
|
80
80
|
"@simplewebauthn/server": "^13.3.2",
|
|
81
81
|
"@simplewebauthn/types": "^12.0.0",
|
|
@@ -87,14 +87,14 @@
|
|
|
87
87
|
},
|
|
88
88
|
"peerDependencies": {
|
|
89
89
|
"@mikro-orm/core": "^7.0.14",
|
|
90
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
90
|
+
"@open-mercato/shared": "0.10.1-develop.8278.1.f7f8e5ab1a",
|
|
91
91
|
"react": "^19.0.0",
|
|
92
92
|
"react-dom": "^19.0.0",
|
|
93
93
|
"react-is": ">=18.0.0",
|
|
94
94
|
"zod": ">=3.23.0"
|
|
95
95
|
},
|
|
96
96
|
"devDependencies": {
|
|
97
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
97
|
+
"@open-mercato/shared": "0.10.1-develop.8278.1.f7f8e5ab1a",
|
|
98
98
|
"@types/jest": "^30.0.0",
|
|
99
99
|
"@types/react": "^19.2.18",
|
|
100
100
|
"@types/react-dom": "^19.2.5",
|
|
@@ -101,56 +101,61 @@ export class MfaService {
|
|
|
101
101
|
providerType?: string,
|
|
102
102
|
context?: MfaProviderRuntimeContext,
|
|
103
103
|
): Promise<{ recoveryCodes?: string[] }> {
|
|
104
|
-
const method = await this.em.
|
|
105
|
-
userId
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
104
|
+
const method = await this.em.transactional(async (em) => {
|
|
105
|
+
await em.execute('select pg_advisory_xact_lock(hashtextextended(?::text, 0))', [`security:mfa:enrollment:${userId}`])
|
|
106
|
+
const method = await findOneWithDecryption(em, UserMfaMethod, {
|
|
107
|
+
userId,
|
|
108
|
+
isActive: false,
|
|
109
|
+
deletedAt: null,
|
|
110
|
+
secret: setupId,
|
|
111
|
+
}, { refresh: true }, {})
|
|
112
|
+
if (!method) {
|
|
113
|
+
throw new MfaServiceError('MFA setup session not found', 404)
|
|
114
|
+
}
|
|
115
|
+
if (providerType && method.type !== providerType) {
|
|
116
|
+
throw new MfaServiceError('MFA setup session does not match the requested provider', 400)
|
|
117
|
+
}
|
|
116
118
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
119
|
+
const provider = this.mfaProviderRegistry.get(method.type)
|
|
120
|
+
if (!provider) {
|
|
121
|
+
throw new MfaServiceError(`MFA provider '${method.type}' is not registered`, 400)
|
|
122
|
+
}
|
|
121
123
|
|
|
122
|
-
|
|
124
|
+
await this.ensureProviderCanBeConfigured(userId, method.type, provider.allowMultiple, em)
|
|
123
125
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
126
|
+
let confirmation: MfaProviderConfirmResult
|
|
127
|
+
try {
|
|
128
|
+
confirmation = await provider.confirmSetup(userId, setupId, payload, context)
|
|
129
|
+
} catch (error) {
|
|
130
|
+
if (error instanceof ZodError) {
|
|
131
|
+
throw new MfaServiceError('Invalid payload', 400)
|
|
132
|
+
}
|
|
133
|
+
throw error
|
|
130
134
|
}
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
throw new MfaServiceError(`An MFA method with this name already exists`, 409)
|
|
135
|
+
const resolvedLabel = this.getLabelFromMetadata(confirmation.metadata) ?? method.label ?? null
|
|
136
|
+
|
|
137
|
+
if (resolvedLabel && provider.allowMultiple) {
|
|
138
|
+
const duplicate = await findOneWithDecryption(em, UserMfaMethod, {
|
|
139
|
+
userId,
|
|
140
|
+
type: method.type,
|
|
141
|
+
label: resolvedLabel,
|
|
142
|
+
isActive: true,
|
|
143
|
+
deletedAt: null,
|
|
144
|
+
}, { refresh: true }, { tenantId: method.tenantId, organizationId: method.organizationId })
|
|
145
|
+
if (duplicate) {
|
|
146
|
+
throw new MfaServiceError(`An MFA method with this name already exists`, 409)
|
|
147
|
+
}
|
|
145
148
|
}
|
|
146
|
-
}
|
|
147
149
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
150
|
+
method.providerMetadata = confirmation.metadata
|
|
151
|
+
method.secret = confirmation.secret ?? null
|
|
152
|
+
method.label = resolvedLabel
|
|
153
|
+
method.isActive = true
|
|
154
|
+
method.updatedAt = new Date()
|
|
155
|
+
await em.flush()
|
|
156
|
+
|
|
157
|
+
return method
|
|
158
|
+
})
|
|
154
159
|
|
|
155
160
|
await emitSecurityEvent('security.mfa.enrolled', {
|
|
156
161
|
userId,
|
|
@@ -278,9 +283,11 @@ export class MfaService {
|
|
|
278
283
|
}
|
|
279
284
|
}
|
|
280
285
|
if (!valid) continue
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
286
|
+
const claimed = await this.em.execute<Array<{ id: string }>>(
|
|
287
|
+
'UPDATE mfa_recovery_codes SET is_used = true, used_at = ? WHERE id = ? AND user_id = ? AND tenant_id = ? AND is_used = false RETURNING id',
|
|
288
|
+
[new Date(), recoveryCode.id, userId, recoveryCode.tenantId],
|
|
289
|
+
)
|
|
290
|
+
if (claimed.length === 0) return false
|
|
284
291
|
const remaining = await this.em.count(MfaRecoveryCode, { userId, isUsed: false })
|
|
285
292
|
await emitSecurityEvent('security.recovery.used', { userId, remaining })
|
|
286
293
|
return true
|
|
@@ -311,15 +318,16 @@ export class MfaService {
|
|
|
311
318
|
userId: string,
|
|
312
319
|
providerType: string,
|
|
313
320
|
allowMultiple: boolean,
|
|
321
|
+
em: EntityManager = this.em,
|
|
314
322
|
): Promise<void> {
|
|
315
323
|
if (allowMultiple) return
|
|
316
324
|
|
|
317
|
-
const existingMethod = await
|
|
325
|
+
const existingMethod = await findOneWithDecryption(em, UserMfaMethod, {
|
|
318
326
|
userId,
|
|
319
327
|
type: providerType,
|
|
320
328
|
isActive: true,
|
|
321
329
|
deletedAt: null,
|
|
322
|
-
})
|
|
330
|
+
}, { refresh: true }, {})
|
|
323
331
|
if (existingMethod) {
|
|
324
332
|
throw new MfaServiceError(`MFA provider '${providerType}' is already configured`, 409)
|
|
325
333
|
}
|