@open-mercato/enterprise 0.6.6-develop.5612.1.d382eb2f33 → 0.6.6-develop.5619.1.29f01e2c42

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.
Files changed (48) hide show
  1. package/dist/modules/security/api/i18n.js +3 -0
  2. package/dist/modules/security/api/i18n.js.map +2 -2
  3. package/dist/modules/security/api/mfa/prepare/route.js +6 -1
  4. package/dist/modules/security/api/mfa/prepare/route.js.map +2 -2
  5. package/dist/modules/security/api/mfa/verify/route.js +7 -1
  6. package/dist/modules/security/api/mfa/verify/route.js.map +2 -2
  7. package/dist/modules/security/api/sudo/prepare/route.js +6 -1
  8. package/dist/modules/security/api/sudo/prepare/route.js.map +2 -2
  9. package/dist/modules/security/api/users/mfa/compliance/route.js +4 -2
  10. package/dist/modules/security/api/users/mfa/compliance/route.js.map +2 -2
  11. package/dist/modules/security/commands/createEnforcementPolicy.js +6 -4
  12. package/dist/modules/security/commands/createEnforcementPolicy.js.map +2 -2
  13. package/dist/modules/security/commands/deleteEnforcementPolicy.js +6 -4
  14. package/dist/modules/security/commands/deleteEnforcementPolicy.js.map +2 -2
  15. package/dist/modules/security/commands/resetUserMfa.js +11 -4
  16. package/dist/modules/security/commands/resetUserMfa.js.map +2 -2
  17. package/dist/modules/security/commands/updateEnforcementPolicy.js +6 -4
  18. package/dist/modules/security/commands/updateEnforcementPolicy.js.map +2 -2
  19. package/dist/modules/security/i18n/de.json +3 -0
  20. package/dist/modules/security/i18n/en.json +3 -0
  21. package/dist/modules/security/i18n/es.json +3 -0
  22. package/dist/modules/security/i18n/pl.json +3 -0
  23. package/dist/modules/security/services/MfaAdminService.js +42 -8
  24. package/dist/modules/security/services/MfaAdminService.js.map +2 -2
  25. package/dist/modules/security/services/MfaEnforcementService.js +57 -7
  26. package/dist/modules/security/services/MfaEnforcementService.js.map +2 -2
  27. package/dist/modules/security/services/MfaVerificationService.js +15 -6
  28. package/dist/modules/security/services/MfaVerificationService.js.map +2 -2
  29. package/dist/modules/security/services/SudoChallengeService.js +26 -4
  30. package/dist/modules/security/services/SudoChallengeService.js.map +2 -2
  31. package/package.json +5 -5
  32. package/src/modules/security/api/i18n.ts +3 -0
  33. package/src/modules/security/api/mfa/prepare/route.ts +6 -1
  34. package/src/modules/security/api/mfa/verify/route.ts +7 -1
  35. package/src/modules/security/api/sudo/prepare/route.ts +6 -1
  36. package/src/modules/security/api/users/mfa/compliance/route.ts +6 -3
  37. package/src/modules/security/commands/createEnforcementPolicy.ts +7 -5
  38. package/src/modules/security/commands/deleteEnforcementPolicy.ts +10 -5
  39. package/src/modules/security/commands/resetUserMfa.ts +12 -5
  40. package/src/modules/security/commands/updateEnforcementPolicy.ts +10 -5
  41. package/src/modules/security/i18n/de.json +3 -0
  42. package/src/modules/security/i18n/en.json +3 -0
  43. package/src/modules/security/i18n/es.json +3 -0
  44. package/src/modules/security/i18n/pl.json +3 -0
  45. package/src/modules/security/services/MfaAdminService.ts +101 -8
  46. package/src/modules/security/services/MfaEnforcementService.ts +174 -7
  47. package/src/modules/security/services/MfaVerificationService.ts +58 -4
  48. package/src/modules/security/services/SudoChallengeService.ts +31 -6
@@ -5,6 +5,12 @@ import { MfaRecoveryCode, UserMfaMethod } from '../data/entities'
5
5
  import { emitSecurityEvent } from '../events'
6
6
  import type { MfaEnforcementService } from './MfaEnforcementService'
7
7
 
8
+ export type MfaAdminAuthScope = {
9
+ tenantId: string | null
10
+ organizationId?: string | null
11
+ isSuperAdmin?: boolean
12
+ }
13
+
8
14
  type MfaMethodStatus = {
9
15
  type: string
10
16
  label?: string
@@ -48,7 +54,25 @@ export class MfaAdminService {
48
54
  private readonly mfaEnforcementService: MfaEnforcementService,
49
55
  ) {}
50
56
 
51
- async resetUserMfa(adminId: string, userId: string, reason: string, actor?: ActorContext): Promise<void> {
57
+ /**
58
+ * @deprecated Since 0.6 — pass an {@link MfaAdminAuthScope} so the target user is
59
+ * loaded with tenant/organization scoping. The no-scope overload now treats the
60
+ * caller as a non-superadmin with unknown tenant and rejects every load with 404;
61
+ * it will be removed in a future release.
62
+ */
63
+ async resetUserMfa(adminId: string, userId: string, reason: string): Promise<void>
64
+ async resetUserMfa(
65
+ adminId: string,
66
+ userId: string,
67
+ reason: string,
68
+ scope: MfaAdminAuthScope,
69
+ ): Promise<void>
70
+ async resetUserMfa(
71
+ adminId: string,
72
+ userId: string,
73
+ reason: string,
74
+ scope?: MfaAdminAuthScope,
75
+ ): Promise<void> {
52
76
  if (!adminId.trim()) {
53
77
  throw new MfaAdminServiceError('Admin ID is required', 400)
54
78
  }
@@ -61,11 +85,12 @@ export class MfaAdminService {
61
85
  throw new MfaAdminServiceError('Reset reason is required', 400)
62
86
  }
63
87
 
64
- const user = await this.findUserById(userId)
88
+ const effectiveScope: MfaAdminAuthScope = scope ?? { tenantId: null, isSuperAdmin: false }
89
+ const user = await this.loadUserForScope(userId, effectiveScope)
65
90
  if (!user) {
91
+ // Unified 404 for both "missing" and "out of scope" — prevents existence enumeration.
66
92
  throw new MfaAdminServiceError('User not found', 404)
67
93
  }
68
- this.assertActorOwnsUser(user, actor)
69
94
 
70
95
  const activeMethods = await this.em.find(UserMfaMethod, {
71
96
  userId,
@@ -143,25 +168,45 @@ export class MfaAdminService {
143
168
  }
144
169
  }
145
170
 
146
- async bulkComplianceCheck(tenantId: string, actor?: ActorContext): Promise<BulkComplianceStatus[]> {
171
+ /**
172
+ * @deprecated Since 0.6 — pass an {@link MfaAdminAuthScope} so the tenant list is
173
+ * enforced against the caller's actual scope rather than the caller-supplied
174
+ * tenantId. The no-scope overload now treats the caller as a non-superadmin
175
+ * with unknown tenant and rejects every request with 404; it will be removed
176
+ * in a future release.
177
+ */
178
+ async bulkComplianceCheck(tenantId: string): Promise<BulkComplianceStatus[]>
179
+ async bulkComplianceCheck(
180
+ tenantId: string,
181
+ scope: MfaAdminAuthScope,
182
+ ): Promise<BulkComplianceStatus[]>
183
+ async bulkComplianceCheck(
184
+ tenantId: string,
185
+ scope?: MfaAdminAuthScope,
186
+ ): Promise<BulkComplianceStatus[]> {
147
187
  if (!tenantId.trim()) {
148
188
  throw new MfaAdminServiceError('Tenant ID is required', 400)
149
189
  }
150
- if (actor && !actor.isSuperAdmin && tenantId !== actor.tenantId) {
151
- throw new MfaAdminServiceError('Not authorized for the requested tenant scope.', 403)
190
+
191
+ const effectiveScope: MfaAdminAuthScope = scope ?? { tenantId: null, isSuperAdmin: false }
192
+ const effectiveTenantId = this.resolveTenantForScope(tenantId, effectiveScope)
193
+ if (!effectiveTenantId) {
194
+ // Unified 404 for missing-scope, cross-tenant mismatch, and unknown tenant —
195
+ // prevents existence enumeration and matches the resetUserMfa contract.
196
+ throw new MfaAdminServiceError('Tenant not found', 404)
152
197
  }
153
198
 
154
199
  const users = await findWithDecryption(
155
200
  this.em,
156
201
  User,
157
202
  {
158
- tenantId,
203
+ tenantId: effectiveTenantId,
159
204
  deletedAt: null,
160
205
  },
161
206
  {
162
207
  orderBy: { createdAt: 'asc' },
163
208
  },
164
- { tenantId, organizationId: null },
209
+ { tenantId: effectiveTenantId, organizationId: null },
165
210
  )
166
211
 
167
212
  const userIds = users.map((user) => user.id)
@@ -212,6 +257,54 @@ export class MfaAdminService {
212
257
  { tenantId: null, organizationId: null },
213
258
  )
214
259
  }
260
+
261
+ private resolveTenantForScope(
262
+ requestedTenantId: string,
263
+ scope: MfaAdminAuthScope,
264
+ ): string | null {
265
+ if (scope.isSuperAdmin) {
266
+ return requestedTenantId
267
+ }
268
+ if (!scope.tenantId) return null
269
+ if (scope.tenantId !== requestedTenantId) return null
270
+ return scope.tenantId
271
+ }
272
+
273
+ private async loadUserForScope(
274
+ userId: string,
275
+ scope: MfaAdminAuthScope,
276
+ ): Promise<User | null> {
277
+ if (scope.isSuperAdmin) {
278
+ return findOneWithDecryption(
279
+ this.em,
280
+ User,
281
+ { id: userId, deletedAt: null },
282
+ undefined,
283
+ { tenantId: null, organizationId: null },
284
+ )
285
+ }
286
+
287
+ if (!scope.tenantId) return null
288
+
289
+ const user = await findOneWithDecryption(
290
+ this.em,
291
+ User,
292
+ { id: userId, tenantId: scope.tenantId, deletedAt: null },
293
+ undefined,
294
+ { tenantId: scope.tenantId, organizationId: scope.organizationId ?? null },
295
+ )
296
+ if (!user) return null
297
+
298
+ if (
299
+ scope.organizationId !== undefined
300
+ && scope.organizationId !== null
301
+ && user.organizationId !== null
302
+ && user.organizationId !== scope.organizationId
303
+ ) {
304
+ return null
305
+ }
306
+ return user
307
+ }
215
308
  }
216
309
 
217
310
  export default MfaAdminService
@@ -49,6 +49,12 @@ export function isEnforcementDeadlineOverdue(
49
49
  return deadlineTime <= now
50
50
  }
51
51
 
52
+ export type MfaEnforcementAuthScope = {
53
+ tenantId: string | null
54
+ organizationId?: string | null
55
+ isSuperAdmin?: boolean
56
+ }
57
+
52
58
  export class MfaEnforcementServiceError extends Error {
53
59
  constructor(
54
60
  message: string,
@@ -136,13 +142,32 @@ export class MfaEnforcementService {
136
142
  }
137
143
  }
138
144
 
145
+ /**
146
+ * @deprecated Since 0.6 — pass an {@link MfaEnforcementAuthScope} so the policy
147
+ * write is enforced against the caller's actual tenant/organization scope
148
+ * rather than caller-supplied body fields. The no-scope overload now treats
149
+ * the caller as a non-superadmin with unknown tenant and rejects every write
150
+ * with 403; it will be removed in a future release.
151
+ */
139
152
  async createPolicy(
140
153
  data: EnforcementPolicyInput,
141
154
  adminId: string,
142
- actor?: EnforcementActorContext,
155
+ ): Promise<MfaEnforcementPolicy>
156
+ async createPolicy(
157
+ data: EnforcementPolicyInput,
158
+ adminId: string,
159
+ scope: MfaEnforcementAuthScope,
160
+ ): Promise<MfaEnforcementPolicy>
161
+ async createPolicy(
162
+ data: EnforcementPolicyInput,
163
+ adminId: string,
164
+ scope?: MfaEnforcementAuthScope,
143
165
  ): Promise<MfaEnforcementPolicy> {
144
166
  const normalized = this.normalizePolicyInput(data)
145
- this.assertActorOwnsScopeFilters(actor, normalized.scope, normalized.tenantId)
167
+ const effectiveScope: MfaEnforcementAuthScope = scope ?? { tenantId: null, isSuperAdmin: false }
168
+ this.assertCreatePolicyScope(normalized, effectiveScope)
169
+
170
+
146
171
  const existing = await this.findPolicyByScope(
147
172
  normalized.scope,
148
173
  normalized.tenantId ?? undefined,
@@ -190,12 +215,32 @@ export class MfaEnforcementService {
190
215
  return policy
191
216
  }
192
217
 
218
+ /**
219
+ * @deprecated Since 0.6 — pass an {@link MfaEnforcementAuthScope} so the policy
220
+ * update is enforced against the caller's actual tenant/organization scope
221
+ * rather than caller-supplied body fields. The no-scope overload now treats
222
+ * the caller as a non-superadmin with unknown tenant and rejects every write
223
+ * with 403; it will be removed in a future release.
224
+ */
193
225
  async updatePolicy(
194
226
  id: string,
195
227
  data: UpdateEnforcementPolicyInput,
196
228
  adminId: string,
197
- actor?: EnforcementActorContext,
229
+ ): Promise<MfaEnforcementPolicy>
230
+ async updatePolicy(
231
+ id: string,
232
+ data: UpdateEnforcementPolicyInput,
233
+ adminId: string,
234
+ scope: MfaEnforcementAuthScope,
235
+ ): Promise<MfaEnforcementPolicy>
236
+ async updatePolicy(
237
+ id: string,
238
+ data: UpdateEnforcementPolicyInput,
239
+ adminId: string,
240
+ scope?: MfaEnforcementAuthScope,
198
241
  ): Promise<MfaEnforcementPolicy> {
242
+ const effectiveScope: MfaEnforcementAuthScope = scope ?? { tenantId: null, isSuperAdmin: false }
243
+
199
244
  const policy = await this.em.findOne(MfaEnforcementPolicy, {
200
245
  id,
201
246
  deletedAt: null,
@@ -203,7 +248,6 @@ export class MfaEnforcementService {
203
248
  if (!policy) {
204
249
  throw new MfaEnforcementServiceError('Enforcement policy not found', 404)
205
250
  }
206
- this.assertActorOwnsScopeFilters(actor, policy.scope, policy.tenantId ?? null)
207
251
 
208
252
  const mergedInput = this.normalizePolicyInput({
209
253
  scope: data.scope ?? policy.scope,
@@ -217,7 +261,7 @@ export class MfaEnforcementService {
217
261
  : data.enforcementDeadline,
218
262
  })
219
263
 
220
- this.assertActorOwnsScopeFilters(actor, mergedInput.scope, mergedInput.tenantId)
264
+ this.assertUpdatePolicyScope(policy, mergedInput, effectiveScope)
221
265
 
222
266
  if (
223
267
  mergedInput.scope !== policy.scope ||
@@ -253,7 +297,18 @@ export class MfaEnforcementService {
253
297
  return policy
254
298
  }
255
299
 
256
- async deletePolicy(id: string, actor?: EnforcementActorContext): Promise<void> {
300
+ /**
301
+ * @deprecated Since 0.6 — pass an {@link MfaEnforcementAuthScope} so the policy
302
+ * delete is enforced against the caller's actual tenant/organization scope
303
+ * rather than the caller-supplied id alone. The no-scope overload now treats
304
+ * the caller as a non-superadmin with unknown tenant and rejects every delete
305
+ * with 403; it will be removed in a future release.
306
+ */
307
+ async deletePolicy(id: string): Promise<void>
308
+ async deletePolicy(id: string, scope: MfaEnforcementAuthScope): Promise<void>
309
+ async deletePolicy(id: string, scope?: MfaEnforcementAuthScope): Promise<void> {
310
+ const effectiveScope: MfaEnforcementAuthScope = scope ?? { tenantId: null, isSuperAdmin: false }
311
+
257
312
  const policy = await this.em.findOne(MfaEnforcementPolicy, {
258
313
  id,
259
314
  deletedAt: null,
@@ -261,7 +316,8 @@ export class MfaEnforcementService {
261
316
  if (!policy) {
262
317
  throw new MfaEnforcementServiceError('Enforcement policy not found', 404)
263
318
  }
264
- this.assertActorOwnsScopeFilters(actor, policy.scope, policy.tenantId ?? null)
319
+
320
+ this.assertDeletePolicyScope(policy, effectiveScope)
265
321
 
266
322
  const now = new Date()
267
323
  policy.deletedAt = now
@@ -318,6 +374,117 @@ export class MfaEnforcementService {
318
374
  return this.findPolicyByScope(EnforcementScope.PLATFORM, undefined, undefined)
319
375
  }
320
376
 
377
+ private assertCreatePolicyScope(
378
+ normalized: {
379
+ scope: EnforcementScope
380
+ tenantId: string | null
381
+ organizationId: string | null
382
+ },
383
+ scope: MfaEnforcementAuthScope,
384
+ ): void {
385
+ if (scope.isSuperAdmin) return
386
+
387
+ // Fail closed when the caller has no concrete tenant context. Mirrors the
388
+ // MfaAdminService.loadUserForScope precedent — a missing scope.tenantId for
389
+ // a non-superadmin means we cannot prove ownership of anything.
390
+ if (!scope.tenantId) {
391
+ throw new MfaEnforcementServiceError('Insufficient scope for enforcement policy', 403)
392
+ }
393
+
394
+ if (normalized.scope === EnforcementScope.PLATFORM) {
395
+ throw new MfaEnforcementServiceError('Insufficient scope for enforcement policy', 403)
396
+ }
397
+
398
+ if (normalized.tenantId !== scope.tenantId) {
399
+ throw new MfaEnforcementServiceError('Insufficient scope for enforcement policy', 403)
400
+ }
401
+
402
+ if (
403
+ normalized.scope === EnforcementScope.ORGANISATION
404
+ && scope.organizationId !== undefined
405
+ && scope.organizationId !== null
406
+ && normalized.organizationId !== scope.organizationId
407
+ ) {
408
+ throw new MfaEnforcementServiceError('Insufficient scope for enforcement policy', 403)
409
+ }
410
+ }
411
+
412
+ private assertUpdatePolicyScope(
413
+ existing: MfaEnforcementPolicy,
414
+ proposed: {
415
+ scope: EnforcementScope
416
+ tenantId: string | null
417
+ organizationId: string | null
418
+ },
419
+ scope: MfaEnforcementAuthScope,
420
+ ): void {
421
+ if (scope.isSuperAdmin) return
422
+
423
+ if (!scope.tenantId) {
424
+ throw new MfaEnforcementServiceError('Insufficient scope for enforcement policy', 403)
425
+ }
426
+
427
+ if (
428
+ existing.scope === EnforcementScope.PLATFORM
429
+ || existing.tenantId !== scope.tenantId
430
+ ) {
431
+ throw new MfaEnforcementServiceError('Insufficient scope for enforcement policy', 403)
432
+ }
433
+
434
+ if (proposed.scope === EnforcementScope.PLATFORM) {
435
+ throw new MfaEnforcementServiceError('Insufficient scope for enforcement policy', 403)
436
+ }
437
+
438
+ if (proposed.tenantId !== scope.tenantId) {
439
+ throw new MfaEnforcementServiceError('Insufficient scope for enforcement policy', 403)
440
+ }
441
+
442
+ if (
443
+ proposed.scope === EnforcementScope.ORGANISATION
444
+ && scope.organizationId !== undefined
445
+ && scope.organizationId !== null
446
+ && proposed.organizationId !== scope.organizationId
447
+ ) {
448
+ throw new MfaEnforcementServiceError('Insufficient scope for enforcement policy', 403)
449
+ }
450
+
451
+ if (
452
+ existing.scope === EnforcementScope.ORGANISATION
453
+ && scope.organizationId !== undefined
454
+ && scope.organizationId !== null
455
+ && existing.organizationId !== scope.organizationId
456
+ ) {
457
+ throw new MfaEnforcementServiceError('Insufficient scope for enforcement policy', 403)
458
+ }
459
+ }
460
+
461
+ private assertDeletePolicyScope(
462
+ existing: MfaEnforcementPolicy,
463
+ scope: MfaEnforcementAuthScope,
464
+ ): void {
465
+ if (scope.isSuperAdmin) return
466
+
467
+ if (!scope.tenantId) {
468
+ throw new MfaEnforcementServiceError('Insufficient scope for enforcement policy', 403)
469
+ }
470
+
471
+ if (
472
+ existing.scope === EnforcementScope.PLATFORM
473
+ || existing.tenantId !== scope.tenantId
474
+ ) {
475
+ throw new MfaEnforcementServiceError('Insufficient scope for enforcement policy', 403)
476
+ }
477
+
478
+ if (
479
+ existing.scope === EnforcementScope.ORGANISATION
480
+ && scope.organizationId !== undefined
481
+ && scope.organizationId !== null
482
+ && existing.organizationId !== scope.organizationId
483
+ ) {
484
+ throw new MfaEnforcementServiceError('Insufficient scope for enforcement policy', 403)
485
+ }
486
+ }
487
+
321
488
  private async findPolicyByScope(
322
489
  scope: EnforcementScope,
323
490
  tenantId?: string,
@@ -24,6 +24,10 @@ type ChallengeCreationResult = {
24
24
  availableMethods: AvailableMethod[]
25
25
  }
26
26
 
27
+ export type MfaVerificationAuthScope = {
28
+ userId: string
29
+ }
30
+
27
31
  export class MfaVerificationServiceError extends Error {
28
32
  constructor(
29
33
  message: string,
@@ -81,12 +85,33 @@ export class MfaVerificationService {
81
85
  }
82
86
  }
83
87
 
88
+ /**
89
+ * @deprecated Since 0.6 — pass an {@link MfaVerificationAuthScope} bound to the
90
+ * authenticated user (`auth.sub`). The no-scope overload now treats the caller as
91
+ * unknown and rejects every challenge lookup with 404; it will be removed in a
92
+ * future release.
93
+ */
94
+ async prepareChallenge(
95
+ challengeId: string,
96
+ methodType: string,
97
+ context?: MfaProviderRuntimeContext,
98
+ ): Promise<{ clientData?: Record<string, unknown> }>
99
+ async prepareChallenge(
100
+ challengeId: string,
101
+ methodType: string,
102
+ context: MfaProviderRuntimeContext | undefined,
103
+ scope: MfaVerificationAuthScope,
104
+ ): Promise<{ clientData?: Record<string, unknown> }>
84
105
  async prepareChallenge(
85
106
  challengeId: string,
86
107
  methodType: string,
87
108
  context?: MfaProviderRuntimeContext,
109
+ scope?: MfaVerificationAuthScope,
88
110
  ): Promise<{ clientData?: Record<string, unknown> }> {
89
- const challenge = await this.getValidChallenge(challengeId)
111
+ if (!scope) {
112
+ throw new MfaVerificationServiceError('MFA challenge not found', 404)
113
+ }
114
+ const challenge = await this.getValidChallenge(challengeId, scope)
90
115
  await this.assertMethodAllowedByPolicy(challenge.userId, methodType)
91
116
  const provider = this.mfaProviderRegistry.get(methodType)
92
117
  if (!provider) {
@@ -109,13 +134,36 @@ export class MfaVerificationService {
109
134
  return result
110
135
  }
111
136
 
137
+ /**
138
+ * @deprecated Since 0.6 — pass an {@link MfaVerificationAuthScope} bound to the
139
+ * authenticated user (`auth.sub`). The no-scope overload now treats the caller as
140
+ * unknown and rejects every challenge lookup with 404; it will be removed in a
141
+ * future release.
142
+ */
143
+ async verifyChallenge(
144
+ challengeId: string,
145
+ methodType: string,
146
+ payload: unknown,
147
+ runtimeContext?: MfaProviderRuntimeContext,
148
+ ): Promise<boolean>
149
+ async verifyChallenge(
150
+ challengeId: string,
151
+ methodType: string,
152
+ payload: unknown,
153
+ runtimeContext: MfaProviderRuntimeContext | undefined,
154
+ scope: MfaVerificationAuthScope,
155
+ ): Promise<boolean>
112
156
  async verifyChallenge(
113
157
  challengeId: string,
114
158
  methodType: string,
115
159
  payload: unknown,
116
160
  runtimeContext?: MfaProviderRuntimeContext,
161
+ scope?: MfaVerificationAuthScope,
117
162
  ): Promise<boolean> {
118
- const challenge = await this.getValidChallenge(challengeId)
163
+ if (!scope) {
164
+ throw new MfaVerificationServiceError('MFA challenge not found', 404)
165
+ }
166
+ const challenge = await this.getValidChallenge(challengeId, scope)
119
167
  if (challenge.attempts >= this.securityConfig.mfa.maxAttempts) {
120
168
  return false
121
169
  }
@@ -167,8 +215,14 @@ export class MfaVerificationService {
167
215
  return this.mfaService.verifyRecoveryCode(userId, code)
168
216
  }
169
217
 
170
- private async getValidChallenge(challengeId: string): Promise<MfaChallenge> {
171
- const challenge = await this.em.findOne(MfaChallenge, { id: challengeId })
218
+ private async getValidChallenge(
219
+ challengeId: string,
220
+ scope: MfaVerificationAuthScope,
221
+ ): Promise<MfaChallenge> {
222
+ const challenge = await this.em.findOne(MfaChallenge, {
223
+ id: challengeId,
224
+ userId: scope.userId,
225
+ })
172
226
  if (!challenge) {
173
227
  throw new MfaVerificationServiceError('MFA challenge not found', 404)
174
228
  }
@@ -69,6 +69,11 @@ type DeveloperDefaultPayload = {
69
69
  challengeMethod?: ChallengeMethod
70
70
  }
71
71
 
72
+ function readTrimmedEnv(value: string | undefined): string | undefined {
73
+ const trimmed = value?.trim()
74
+ return trimmed ? trimmed : undefined
75
+ }
76
+
72
77
  export class SudoChallengeServiceError extends Error {
73
78
  constructor(
74
79
  message: string,
@@ -212,13 +217,22 @@ export class SudoChallengeService {
212
217
  async prepare(
213
218
  sessionId: string,
214
219
  methodType: string,
220
+ options: { expectedUserId?: string } = {},
215
221
  request?: Request,
216
222
  ): Promise<{ clientData?: Record<string, unknown> }> {
217
223
  const session = await this.getPendingSession(sessionId)
224
+ if (options.expectedUserId && session.userId !== options.expectedUserId) {
225
+ throw new SudoChallengeServiceError('Sudo challenge user mismatch', 403)
226
+ }
218
227
  if (session.challengeMethod !== 'mfa') {
219
228
  throw new SudoChallengeServiceError('This sudo session does not require MFA', 400)
220
229
  }
221
- return this.mfaVerificationService.prepareChallenge(session.sessionToken, methodType, { request })
230
+ return this.mfaVerificationService.prepareChallenge(
231
+ session.sessionToken,
232
+ methodType,
233
+ { request },
234
+ { userId: session.userId },
235
+ )
222
236
  }
223
237
 
224
238
  async verify(
@@ -260,7 +274,13 @@ export class SudoChallengeService {
260
274
  verified = await this.passwordService.verifyPassword(session.userId, password)
261
275
  methodUsed = SudoChallengeMethodUsed.PASSWORD
262
276
  } else {
263
- verified = await this.mfaVerificationService.verifyChallenge(session.sessionToken, methodType, payload, { request })
277
+ verified = await this.mfaVerificationService.verifyChallenge(
278
+ session.sessionToken,
279
+ methodType,
280
+ payload,
281
+ { request },
282
+ { userId: session.userId },
283
+ )
264
284
  }
265
285
 
266
286
  if (!verified) {
@@ -679,10 +699,15 @@ export class SudoChallengeService {
679
699
  }
680
700
 
681
701
  private getSudoSecret(): string {
682
- return process.env.OM_SECURITY_SUDO_SECRET
683
- ?? process.env.AUTH_JWT_SECRET
684
- ?? process.env.JWT_SECRET
685
- ?? 'open-mercato-sudo-secret'
702
+ const secret =
703
+ readTrimmedEnv(process.env.OM_SECURITY_SUDO_SECRET)
704
+ ?? readTrimmedEnv(process.env.AUTH_JWT_SECRET)
705
+ ?? readTrimmedEnv(process.env.AUTH_SECRET)
706
+ ?? readTrimmedEnv(process.env.JWT_SECRET)
707
+ if (secret) return secret
708
+ throw new Error(
709
+ 'Sudo step-up tokens require OM_SECURITY_SUDO_SECRET, AUTH_JWT_SECRET, AUTH_SECRET, or JWT_SECRET to be set.',
710
+ )
686
711
  }
687
712
 
688
713
  private toChallengeMethod(