@open-mercato/core 0.11.1-develop.8557.1.e615240a3e → 0.11.1-develop.8567.1.a167594505

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 (134) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/api_keys/di.js +6 -2
  3. package/dist/modules/api_keys/di.js.map +2 -2
  4. package/dist/modules/api_keys/services/oneTimeIssuerService.js +47 -0
  5. package/dist/modules/api_keys/services/oneTimeIssuerService.js.map +7 -0
  6. package/dist/modules/audit_logs/di.js +2 -1
  7. package/dist/modules/audit_logs/di.js.map +2 -2
  8. package/dist/modules/audit_logs/services/actionLogService.js +65 -1
  9. package/dist/modules/audit_logs/services/actionLogService.js.map +2 -2
  10. package/dist/modules/auth/cli.js +1 -0
  11. package/dist/modules/auth/cli.js.map +2 -2
  12. package/dist/modules/auth/commands/users.js +10 -2
  13. package/dist/modules/auth/commands/users.js.map +2 -2
  14. package/dist/modules/auth/lib/setup-app.js +19 -5
  15. package/dist/modules/auth/lib/setup-app.js.map +2 -2
  16. package/dist/modules/configs/cli.js +26 -29
  17. package/dist/modules/configs/cli.js.map +2 -2
  18. package/dist/modules/configs/di.js +3 -1
  19. package/dist/modules/configs/di.js.map +2 -2
  20. package/dist/modules/configs/lib/instance-config-initializer.js +44 -0
  21. package/dist/modules/configs/lib/instance-config-initializer.js.map +7 -0
  22. package/dist/modules/configs/lib/instance-defaults.js +204 -0
  23. package/dist/modules/configs/lib/instance-defaults.js.map +7 -0
  24. package/dist/modules/configs/lib/module-config-service.js +115 -1
  25. package/dist/modules/configs/lib/module-config-service.js.map +2 -2
  26. package/dist/modules/entities/api/definitions.batch.js +55 -25
  27. package/dist/modules/entities/api/definitions.batch.js.map +2 -2
  28. package/dist/modules/entities/api/definitions.js +35 -8
  29. package/dist/modules/entities/api/definitions.js.map +2 -2
  30. package/dist/modules/entities/backend/entities/user/[entityId]/page.js +14 -8
  31. package/dist/modules/entities/backend/entities/user/[entityId]/page.js.map +2 -2
  32. package/dist/modules/notifications/lib/deliveryConfig.js +19 -12
  33. package/dist/modules/notifications/lib/deliveryConfig.js.map +2 -2
  34. package/dist/modules/notifications/setup.js +10 -0
  35. package/dist/modules/notifications/setup.js.map +2 -2
  36. package/dist/modules/translations/components/TranslationManager.js +47 -10
  37. package/dist/modules/translations/components/TranslationManager.js.map +2 -2
  38. package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js +8 -1
  39. package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js.map +2 -2
  40. package/dist/modules/workflows/ai-tools/authoring-pack.js +1 -1
  41. package/dist/modules/workflows/ai-tools/authoring-pack.js.map +2 -2
  42. package/dist/modules/workflows/api/instances/[id]/advance/route.js +1 -0
  43. package/dist/modules/workflows/api/instances/[id]/advance/route.js.map +2 -2
  44. package/dist/modules/workflows/api/instances/route.js +1 -1
  45. package/dist/modules/workflows/api/instances/route.js.map +2 -2
  46. package/dist/modules/workflows/api/instances/validate-start/route.js +3 -1
  47. package/dist/modules/workflows/api/instances/validate-start/route.js.map +2 -2
  48. package/dist/modules/workflows/di.js +3 -1
  49. package/dist/modules/workflows/di.js.map +2 -2
  50. package/dist/modules/workflows/lib/activity-executor.js +35 -7
  51. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  52. package/dist/modules/workflows/lib/condition-handler.js +1 -1
  53. package/dist/modules/workflows/lib/condition-handler.js.map +2 -2
  54. package/dist/modules/workflows/lib/error-handler.js +1 -1
  55. package/dist/modules/workflows/lib/error-handler.js.map +2 -2
  56. package/dist/modules/workflows/lib/event-trigger-service.js +1 -1
  57. package/dist/modules/workflows/lib/event-trigger-service.js.map +2 -2
  58. package/dist/modules/workflows/lib/example-definition-authoring.js +90 -0
  59. package/dist/modules/workflows/lib/example-definition-authoring.js.map +7 -0
  60. package/dist/modules/workflows/lib/named-rules.js +42 -0
  61. package/dist/modules/workflows/lib/named-rules.js.map +7 -0
  62. package/dist/modules/workflows/lib/owned-definition.js +2 -0
  63. package/dist/modules/workflows/lib/owned-definition.js.map +2 -2
  64. package/dist/modules/workflows/lib/parallel-handler.js +1 -1
  65. package/dist/modules/workflows/lib/parallel-handler.js.map +2 -2
  66. package/dist/modules/workflows/lib/signal-handler.js +1 -0
  67. package/dist/modules/workflows/lib/signal-handler.js.map +2 -2
  68. package/dist/modules/workflows/lib/start-validator.js +87 -85
  69. package/dist/modules/workflows/lib/start-validator.js.map +2 -2
  70. package/dist/modules/workflows/lib/step-handler.js +1 -1
  71. package/dist/modules/workflows/lib/step-handler.js.map +2 -2
  72. package/dist/modules/workflows/lib/task-handler.js +1 -0
  73. package/dist/modules/workflows/lib/task-handler.js.map +2 -2
  74. package/dist/modules/workflows/lib/timer-handler.js +1 -0
  75. package/dist/modules/workflows/lib/timer-handler.js.map +2 -2
  76. package/dist/modules/workflows/lib/transition-handler.js +48 -166
  77. package/dist/modules/workflows/lib/transition-handler.js.map +3 -3
  78. package/dist/modules/workflows/lib/workflow-executor.js +3 -2
  79. package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
  80. package/package.json +8 -8
  81. package/src/modules/api_keys/di.ts +7 -2
  82. package/src/modules/api_keys/services/oneTimeIssuerService.ts +61 -0
  83. package/src/modules/audit_logs/di.ts +1 -0
  84. package/src/modules/audit_logs/services/actionLogService.ts +132 -1
  85. package/src/modules/auth/cli.ts +1 -0
  86. package/src/modules/auth/commands/users.ts +10 -2
  87. package/src/modules/auth/i18n/de.json +2 -0
  88. package/src/modules/auth/i18n/en.json +2 -0
  89. package/src/modules/auth/i18n/es.json +2 -0
  90. package/src/modules/auth/i18n/ko.json +2 -0
  91. package/src/modules/auth/i18n/pl.json +2 -0
  92. package/src/modules/auth/lib/setup-app.ts +30 -7
  93. package/src/modules/configs/cli.ts +39 -37
  94. package/src/modules/configs/di.ts +2 -0
  95. package/src/modules/configs/lib/instance-config-initializer.ts +56 -0
  96. package/src/modules/configs/lib/instance-defaults.ts +262 -0
  97. package/src/modules/configs/lib/module-config-service.ts +156 -0
  98. package/src/modules/entities/api/definitions.batch.ts +65 -27
  99. package/src/modules/entities/api/definitions.ts +40 -11
  100. package/src/modules/entities/backend/entities/user/[entityId]/page.tsx +14 -7
  101. package/src/modules/notifications/lib/deliveryConfig.ts +20 -11
  102. package/src/modules/notifications/setup.ts +11 -0
  103. package/src/modules/translations/components/TranslationManager.tsx +49 -10
  104. package/src/modules/translations/i18n/de.json +1 -0
  105. package/src/modules/translations/i18n/en.json +1 -0
  106. package/src/modules/translations/i18n/es.json +1 -0
  107. package/src/modules/translations/i18n/ko.json +1 -0
  108. package/src/modules/translations/i18n/pl.json +1 -0
  109. package/src/modules/wms/components/backend/CompletePutawayTaskDialog.tsx +8 -1
  110. package/src/modules/wms/i18n/de.json +1 -0
  111. package/src/modules/wms/i18n/en.json +1 -0
  112. package/src/modules/wms/i18n/es.json +1 -0
  113. package/src/modules/wms/i18n/ko.json +1 -0
  114. package/src/modules/wms/i18n/pl.json +1 -0
  115. package/src/modules/workflows/ai-tools/authoring-pack.ts +3 -1
  116. package/src/modules/workflows/api/instances/[id]/advance/route.ts +1 -0
  117. package/src/modules/workflows/api/instances/route.ts +1 -1
  118. package/src/modules/workflows/api/instances/validate-start/route.ts +3 -1
  119. package/src/modules/workflows/di.ts +2 -0
  120. package/src/modules/workflows/lib/activity-executor.ts +48 -30
  121. package/src/modules/workflows/lib/condition-handler.ts +1 -1
  122. package/src/modules/workflows/lib/error-handler.ts +1 -1
  123. package/src/modules/workflows/lib/event-trigger-service.ts +1 -1
  124. package/src/modules/workflows/lib/example-definition-authoring.ts +114 -0
  125. package/src/modules/workflows/lib/named-rules.ts +54 -0
  126. package/src/modules/workflows/lib/owned-definition.ts +4 -1
  127. package/src/modules/workflows/lib/parallel-handler.ts +1 -1
  128. package/src/modules/workflows/lib/signal-handler.ts +1 -0
  129. package/src/modules/workflows/lib/start-validator.ts +96 -94
  130. package/src/modules/workflows/lib/step-handler.ts +1 -1
  131. package/src/modules/workflows/lib/task-handler.ts +1 -0
  132. package/src/modules/workflows/lib/timer-handler.ts +1 -0
  133. package/src/modules/workflows/lib/transition-handler.ts +74 -238
  134. package/src/modules/workflows/lib/workflow-executor.ts +7 -4
@@ -0,0 +1,61 @@
1
+ import type { EntityManager } from '@mikro-orm/postgresql'
2
+ import type {
3
+ ApiKeyOneTimeIssuer,
4
+ IssueOneTimeApiKeyInput,
5
+ } from '@open-mercato/shared/lib/auth/principal-service'
6
+ import { withOnetimeApiKey } from './apiKeyService'
7
+
8
+ export type { ApiKeyOneTimeIssuer, IssueOneTimeApiKeyInput }
9
+
10
+ export class DefaultApiKeyOneTimeIssuer implements ApiKeyOneTimeIssuer {
11
+ constructor(private readonly em: EntityManager) {}
12
+
13
+ async withOneTimeApiKey<T>(
14
+ input: IssueOneTimeApiKeyInput,
15
+ callback: (secret: string) => Promise<T>,
16
+ ): Promise<T> {
17
+ const tenantId = typeof input.tenantId === 'string' ? input.tenantId.trim() : ''
18
+ if (!tenantId) {
19
+ throw new Error('One-time API key issuance requires a non-empty tenantId.')
20
+ }
21
+ const roleIds = Array.from(
22
+ new Set(
23
+ (input.roles ?? [])
24
+ .map((roleId) => (typeof roleId === 'string' ? roleId.trim() : ''))
25
+ .filter(Boolean),
26
+ ),
27
+ )
28
+ if (roleIds.length === 0) {
29
+ throw new Error('One-time API key issuance requires at least one authorized role ID.')
30
+ }
31
+
32
+ const organizationId =
33
+ typeof input.organizationId === 'string' ? (input.organizationId.trim() || null) : null
34
+ const name = typeof input.name === 'string' ? input.name.trim() : ''
35
+
36
+ // Fork a context-detached EntityManager so key creation and soft-delete cleanup
37
+ // commit on their own pooled connection outside any surrounding caller transaction.
38
+ const isolatedEm = this.em.fork({
39
+ clear: true,
40
+ freshEventManager: true,
41
+ useContext: false,
42
+ }) as EntityManager
43
+
44
+ return withOnetimeApiKey(
45
+ isolatedEm,
46
+ {
47
+ name,
48
+ description: input.description ?? null,
49
+ tenantId,
50
+ organizationId,
51
+ roles: roleIds,
52
+ expiresAt: input.expiresAt ?? null,
53
+ },
54
+ callback,
55
+ )
56
+ }
57
+ }
58
+
59
+ export function createApiKeyOneTimeIssuer(em: EntityManager): ApiKeyOneTimeIssuer {
60
+ return new DefaultApiKeyOneTimeIssuer(em)
61
+ }
@@ -7,6 +7,7 @@ import { AccessLogService } from '@open-mercato/core/modules/audit_logs/services
7
7
  export function register(container: AppContainer) {
8
8
  container.register({
9
9
  actionLogService: asClass(ActionLogService).scoped(),
10
+ actionLogHistoryService: asClass(ActionLogService).scoped(),
10
11
  })
11
12
 
12
13
  container.register({
@@ -23,6 +23,7 @@ import {
23
23
  } from '@open-mercato/shared/lib/encryption/tenantDataEncryptionService'
24
24
  import { toOptionalString } from '@open-mercato/shared/lib/string/coerce'
25
25
  import { createLogger } from '@open-mercato/shared/lib/logger'
26
+ import { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'
26
27
  import {
27
28
  ACTION_LOG_ACTOR_SUBJECT_CONTEXT_KEY,
28
29
  actionLogBelongsToSubject,
@@ -178,13 +179,61 @@ function stringArraysEqual(left: string[] | null, right: string[]): boolean {
178
179
  return left.every((value, index) => value === right[index])
179
180
  }
180
181
 
182
+ export type AuditHistoryOrganizationScope =
183
+ | { mode: 'exact'; organizationId: string | null }
184
+ | { mode: 'tenant-level-fallback'; organizationIds: readonly string[] | 'all-authorized' }
185
+
186
+ export type AuditHistoryResource = {
187
+ tenantId: string
188
+ resourceKind: string
189
+ resourceId: string
190
+ }
191
+
192
+ type AuditHistoryQuery = AuditHistoryResource & { organization: AuditHistoryOrganizationScope }
193
+
194
+ type AuditHistoryRow = {
195
+ id: string
196
+ tenant_id: string | null
197
+ organization_id: string | null
198
+ resource_kind: string | null
199
+ resource_id: string | null
200
+ actor_user_id: string | null
201
+ deleted_at: Date | null
202
+ created_at: Date
203
+ changes_json: unknown
204
+ snapshot_before: unknown
205
+ snapshot_after: unknown
206
+ }
207
+
208
+ export type AuditHistoryEntry = {
209
+ id: string
210
+ actorUserId: string | null
211
+ createdAt: Date
212
+ changesJson: Record<string, unknown> | null
213
+ snapshotBefore: Record<string, unknown> | null
214
+ snapshotAfter: Record<string, unknown> | null
215
+ }
216
+
217
+ export type ActionLogHistoryService = Pick<
218
+ ActionLogService,
219
+ 'findLatestResourceHistory' | 'findLatestActorHistory' | 'findResourceHistoryById'
220
+ >
221
+
222
+ function readAuditHistoryRecord(value: unknown): Record<string, unknown> | null {
223
+ const parsed = typeof value === 'string' ? parseDecryptedFieldValue(value) : value
224
+ return isRecord(parsed) ? parsed : null
225
+ }
226
+
181
227
  export class ActionLogService {
182
228
  constructor(
183
229
  private readonly em: EntityManager,
184
230
  private readonly tenantEncryptionService?: TenantDataEncryptionService,
185
231
  ) {}
186
232
 
187
- private async decryptEntryPayload<T extends Record<string, unknown>>(entry: T): Promise<T> {
233
+ private async decryptEntryPayload<T extends Record<string, unknown>>(
234
+ entry: T,
235
+ options?: { throwOnFailure?: boolean },
236
+ ): Promise<T> {
188
237
  if (!this.tenantEncryptionService?.isEnabled()) return entry
189
238
 
190
239
  try {
@@ -243,6 +292,7 @@ export class ActionLogService {
243
292
 
244
293
  return merged as T
245
294
  } catch (err) {
295
+ if (options?.throwOnFailure) throw err
246
296
  if (!decryptionWarningLogged) {
247
297
  decryptionWarningLogged = true
248
298
  logger.warn('Failed to decrypt action log entry', { err })
@@ -799,6 +849,87 @@ export class ActionLogService {
799
849
  return entry
800
850
  }
801
851
 
852
+ async findLatestResourceHistory(query: AuditHistoryQuery): Promise<AuditHistoryEntry | null> {
853
+ return this.readResourceHistory(query, {})
854
+ }
855
+
856
+ async findLatestActorHistory(query: AuditHistoryQuery, actorUserId: string): Promise<AuditHistoryEntry | null> {
857
+ if (!isSchemaUuid(actorUserId)) return null
858
+ return this.readResourceHistory(query, { actorUserId })
859
+ }
860
+
861
+ async findResourceHistoryById(
862
+ query: AuditHistoryResource & { organization: Extract<AuditHistoryOrganizationScope, { mode: 'exact' }> },
863
+ id: string,
864
+ ): Promise<AuditHistoryEntry | null> {
865
+ if (query.organization?.mode !== 'exact' || !isSchemaUuid(id)) return null
866
+ return this.readResourceHistory(query, { id })
867
+ }
868
+
869
+ private async readResourceHistory(
870
+ query: AuditHistoryQuery,
871
+ filters: { actorUserId?: string; id?: string },
872
+ ): Promise<AuditHistoryEntry | null> {
873
+ const { tenantId, resourceKind, resourceId, organization } = query
874
+ if (!tenantId || !resourceKind || !resourceId || !organization) return null
875
+
876
+ let lookup = this.em.getKysely<{ action_logs: AuditHistoryRow }>()
877
+ .selectFrom('action_logs')
878
+ .select(['id', 'tenant_id', 'organization_id', 'actor_user_id', 'created_at', 'changes_json', 'snapshot_before', 'snapshot_after'])
879
+ .where('tenant_id', '=', tenantId)
880
+ .where('resource_kind', '=', resourceKind)
881
+ .where('resource_id', '=', resourceId)
882
+ .where('deleted_at', 'is', null)
883
+
884
+ switch (organization.mode) {
885
+ case 'exact':
886
+ if (organization.organizationId === undefined) return null
887
+ lookup = organization.organizationId === null
888
+ ? lookup.where('organization_id', 'is', null)
889
+ : lookup.where('organization_id', '=', organization.organizationId)
890
+ break
891
+ case 'tenant-level-fallback':
892
+ if (organization.organizationIds === 'all-authorized') {
893
+ lookup = lookup.where('organization_id', 'is not', null)
894
+ } else {
895
+ if (!organization.organizationIds?.length) return null
896
+ lookup = lookup.where('organization_id', 'in', organization.organizationIds)
897
+ }
898
+ break
899
+ default:
900
+ return null
901
+ }
902
+
903
+ if (filters.actorUserId) lookup = lookup.where('actor_user_id', '=', filters.actorUserId)
904
+ lookup = filters.id ? lookup.where('id', '=', filters.id) : lookup.orderBy('created_at', 'desc')
905
+
906
+ const row = await lookup.limit(1).executeTakeFirst()
907
+ if (!row) return null
908
+
909
+ const entry = { id: row.id, actorUserId: row.actor_user_id, createdAt: row.created_at }
910
+ try {
911
+ const decrypted = await this.decryptEntryPayload({
912
+ tenantId: row.tenant_id,
913
+ organizationId: row.organization_id,
914
+ changesJson: row.changes_json,
915
+ snapshotBefore: row.snapshot_before,
916
+ snapshotAfter: row.snapshot_after,
917
+ }, { throwOnFailure: true })
918
+ return {
919
+ ...entry,
920
+ changesJson: readAuditHistoryRecord(decrypted.changesJson),
921
+ snapshotBefore: readAuditHistoryRecord(decrypted.snapshotBefore),
922
+ snapshotAfter: readAuditHistoryRecord(decrypted.snapshotAfter),
923
+ }
924
+ } catch {
925
+ getTelemetryRuntime()?.reportError(new Error('[internal] Audit history payload could not be decrypted'), {
926
+ module: 'audit_logs',
927
+ code: 'audit_logs.history_decryption_failed',
928
+ })
929
+ return { ...entry, changesJson: null, snapshotBefore: null, snapshotAfter: null }
930
+ }
931
+ }
932
+
802
933
  async latestUndoableForResource(params: {
803
934
  actorUserId: string
804
935
  tenantId?: string | null
@@ -520,6 +520,7 @@ const setupApp: ModuleCli = {
520
520
  try {
521
521
  const modules = getCliModules()
522
522
  const result = await setupInitialTenant(em, {
523
+ container,
523
524
  orgName,
524
525
  orgSlug,
525
526
  roleNames,
@@ -253,7 +253,11 @@ async function notifyRoleChanges(
253
253
  if (assignedRoles.length) {
254
254
  const assignedType = notificationTypes.find((type) => type.type === 'auth.role.assigned')
255
255
  if (assignedType) {
256
- const notificationInput = buildNotificationFromType(assignedType, {
256
+ const notificationInput = buildNotificationFromType({
257
+ ...assignedType,
258
+ bodyKey: 'auth.notifications.role.assigned.bodyWithRoles',
259
+ }, {
260
+ bodyVariables: { roles: assignedRoles.join(', ') },
257
261
  recipientUserId: String(user.id),
258
262
  sourceEntityType: 'auth:user',
259
263
  sourceEntityId: String(user.id),
@@ -265,7 +269,11 @@ async function notifyRoleChanges(
265
269
  if (revokedRoles.length) {
266
270
  const revokedType = notificationTypes.find((type) => type.type === 'auth.role.revoked')
267
271
  if (revokedType) {
268
- const notificationInput = buildNotificationFromType(revokedType, {
272
+ const notificationInput = buildNotificationFromType({
273
+ ...revokedType,
274
+ bodyKey: 'auth.notifications.role.revoked.bodyWithRoles',
275
+ }, {
276
+ bodyVariables: { roles: revokedRoles.join(', ') },
269
277
  recipientUserId: String(user.id),
270
278
  sourceEntityType: 'auth:user',
271
279
  sourceEntityId: String(user.id),
@@ -579,8 +579,10 @@
579
579
  "auth.notifications.passwordReset.requested.body": "Ein Link zum Zurücksetzen des Passworts wurde an Ihre E-Mail gesendet",
580
580
  "auth.notifications.passwordReset.requested.title": "Passwort-Zurücksetzung angefordert",
581
581
  "auth.notifications.role.assigned.body": "Ihnen wurde eine neue Rolle mit zusätzlichen Berechtigungen zugewiesen",
582
+ "auth.notifications.role.assigned.bodyWithRoles": "Ihrem Konto zugewiesene Rollen: {roles}",
582
583
  "auth.notifications.role.assigned.title": "Neue Rolle zugewiesen",
583
584
  "auth.notifications.role.revoked.body": "Eine Rolle wurde von Ihrem Konto entfernt",
585
+ "auth.notifications.role.revoked.bodyWithRoles": "Aus Ihrem Konto entfernte Rollen: {roles}",
584
586
  "auth.notifications.role.revoked.title": "Rolle entfernt",
585
587
  "auth.password": "Passwort",
586
588
  "auth.password.requirements.digit": "Eine Zahl",
@@ -579,8 +579,10 @@
579
579
  "auth.notifications.passwordReset.requested.body": "A password reset link has been sent to your email",
580
580
  "auth.notifications.passwordReset.requested.title": "Password reset requested",
581
581
  "auth.notifications.role.assigned.body": "You have been assigned a new role with additional permissions",
582
+ "auth.notifications.role.assigned.bodyWithRoles": "Roles assigned to your account: {roles}",
582
583
  "auth.notifications.role.assigned.title": "New role assigned",
583
584
  "auth.notifications.role.revoked.body": "A role has been removed from your account",
585
+ "auth.notifications.role.revoked.bodyWithRoles": "Roles removed from your account: {roles}",
584
586
  "auth.notifications.role.revoked.title": "Role removed",
585
587
  "auth.password": "Password",
586
588
  "auth.password.requirements.digit": "One number",
@@ -579,8 +579,10 @@
579
579
  "auth.notifications.passwordReset.requested.body": "Se ha enviado un enlace de restablecimiento de contraseña a tu correo electrónico",
580
580
  "auth.notifications.passwordReset.requested.title": "Solicitud de restablecimiento de contraseña",
581
581
  "auth.notifications.role.assigned.body": "Se te ha asignado un nuevo rol con permisos adicionales",
582
+ "auth.notifications.role.assigned.bodyWithRoles": "Roles asignados a tu cuenta: {roles}",
582
583
  "auth.notifications.role.assigned.title": "Nuevo rol asignado",
583
584
  "auth.notifications.role.revoked.body": "Se ha eliminado un rol de tu cuenta",
585
+ "auth.notifications.role.revoked.bodyWithRoles": "Roles eliminados de tu cuenta: {roles}",
584
586
  "auth.notifications.role.revoked.title": "Rol eliminado",
585
587
  "auth.password": "Contraseña",
586
588
  "auth.password.requirements.digit": "Un número",
@@ -579,8 +579,10 @@
579
579
  "auth.notifications.passwordReset.requested.body": "이메일로 비밀번호 재설정 링크가 전송되었습니다",
580
580
  "auth.notifications.passwordReset.requested.title": "비밀번호 재설정 요청됨",
581
581
  "auth.notifications.role.assigned.body": "추가 권한이 있는 새 역할이 부여되었습니다",
582
+ "auth.notifications.role.assigned.bodyWithRoles": "계정에 부여된 역할: {roles}",
582
583
  "auth.notifications.role.assigned.title": "새 역할 부여됨",
583
584
  "auth.notifications.role.revoked.body": "계정에서 역할이 제거되었습니다",
585
+ "auth.notifications.role.revoked.bodyWithRoles": "계정에서 제거된 역할: {roles}",
584
586
  "auth.notifications.role.revoked.title": "역할 제거됨",
585
587
  "auth.password": "비밀번호",
586
588
  "auth.password.requirements.digit": "숫자 1개",
@@ -579,8 +579,10 @@
579
579
  "auth.notifications.passwordReset.requested.body": "Link do resetu hasła został wysłany na Twój adres e-mail",
580
580
  "auth.notifications.passwordReset.requested.title": "Żądanie resetu hasła",
581
581
  "auth.notifications.role.assigned.body": "Przypisano Ci nową rolę z dodatkowymi uprawnieniami",
582
+ "auth.notifications.role.assigned.bodyWithRoles": "Role przypisane do Twojego konta: {roles}",
582
583
  "auth.notifications.role.assigned.title": "Przypisano nową rolę",
583
584
  "auth.notifications.role.revoked.body": "Z Twojego konta usunięto rolę",
585
+ "auth.notifications.role.revoked.bodyWithRoles": "Role usunięte z Twojego konta: {roles}",
584
586
  "auth.notifications.role.revoked.title": "Rola usunięta",
585
587
  "auth.password": "Hasło",
586
588
  "auth.password.requirements.digit": "Jedna cyfra",
@@ -20,6 +20,9 @@ import {
20
20
  import { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'
21
21
  import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'
22
22
  import { createLogger } from '@open-mercato/shared/lib/logger'
23
+ import { createRequestContainer, type AppContainer } from '@open-mercato/shared/lib/di/container'
24
+ import { runInOwnedRequestScope } from '@open-mercato/shared/lib/di/request-scope'
25
+ import type { TenantSetupScope } from '@open-mercato/shared/modules/setup'
23
26
 
24
27
  const logger = createLogger('auth').child({ component: 'setup' })
25
28
 
@@ -121,7 +124,8 @@ export type SetupInitialTenantOptions = {
121
124
  failIfUserExists?: boolean
122
125
  primaryUserRoles?: string[]
123
126
  includeSuperadminRole?: boolean
124
- /** Optional list of enabled modules. When provided, module setup hooks are called. */
127
+ container?: AppContainer
128
+ /** Optional override for the list of enabled modules used by setup hooks. */
125
129
  modules?: Module[]
126
130
  /**
127
131
  * Optional global slug to persist on the new Organization. When set, a
@@ -507,12 +511,7 @@ export async function setupInitialTenant(
507
511
  await ensureDefaultRoleAcls(em, tenantId, resolvedModules, { includeSuperadminRole })
508
512
  await deactivateDemoUsersIfSelfOnboardingEnabled(em)
509
513
 
510
- // Call module onTenantCreated hooks
511
- for (const mod of resolvedModules) {
512
- if (mod.setup?.onTenantCreated) {
513
- await mod.setup.onTenantCreated({ em, tenantId, organizationId })
514
- }
515
- }
514
+ await runTenantCreatedHooks(em, { tenantId, organizationId }, resolvedModules, options.container)
516
515
 
517
516
  // Custom roles are often created inside onTenantCreated hooks, so they did not
518
517
  // exist yet when ensureDefaultRoleAcls ran above and were skipped there. Sync
@@ -528,6 +527,30 @@ export async function setupInitialTenant(
528
527
  }
529
528
  }
530
529
 
530
+ async function runTenantCreatedHooks(
531
+ em: EntityManager,
532
+ scope: TenantSetupScope,
533
+ modules: Module[],
534
+ container?: AppContainer,
535
+ ): Promise<void> {
536
+ const enabledModuleIds = new Set(modules.map((mod) => mod.id))
537
+ const runHooks = async (setupContainer?: AppContainer) => {
538
+ for (const mod of modules) {
539
+ await mod.setup?.onTenantCreated?.({ em, ...scope, container: setupContainer, enabledModuleIds })
540
+ }
541
+ }
542
+
543
+ if (container || !enabledModuleIds.has('configs') || !modules.some((mod) => mod.setup?.onTenantCreated)) {
544
+ await runHooks(container)
545
+ return
546
+ }
547
+
548
+ await runInOwnedRequestScope(async () => {
549
+ const setupContainer = await createRequestContainer()
550
+ await runHooks(setupContainer)
551
+ })
552
+ }
553
+
531
554
  function resolvePrimaryName(input: PrimaryUserInput): string | null {
532
555
  if (input.displayName && input.displayName.trim()) return input.displayName.trim()
533
556
  const parts = [input.firstName, input.lastName].map((value) => value?.trim()).filter(Boolean)
@@ -4,8 +4,14 @@ import type { EntityManager } from '@mikro-orm/postgresql'
4
4
  import { runWithCacheTenant, type CacheStrategy } from '@open-mercato/cache'
5
5
  import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
6
6
  import type { ModuleConfigService } from './lib/module-config-service'
7
+ import { restoreInstanceDefaultsStrict } from './lib/module-config-service'
8
+ import { collectInstanceConfigDefaults } from './lib/instance-defaults'
7
9
  import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'
8
- import { STORED_DEFAULT_NOTIFICATION_DELIVERY_CONFIG, NOTIFICATIONS_DELIVERY_CONFIG_KEY } from '../notifications/lib/deliveryConfig'
10
+ import {
11
+ envDisablesAutoIndexing,
12
+ SEARCH_AUTO_INDEX_CONFIG_KEY,
13
+ SEARCH_AUTO_INDEX_CONFIG_MODULE,
14
+ } from '@open-mercato/shared/lib/search/auto-indexing'
9
15
  import { Tenant } from '../directory/data/entities'
10
16
  import {
11
17
  collectCacheStats,
@@ -282,56 +288,52 @@ async function runStructuralCachePurge(args: ParsedArgs) {
282
288
  }
283
289
  }
284
290
 
285
- function envDisablesAutoIndexing(): boolean {
286
- const raw =
287
- process.env.OM_DISABLE_VECTOR_SEARCH_AUTOINDEXING ??
288
- process.env.DISABLE_VECTOR_SEARCH_AUTOINDEXING
289
- if (!raw) return false
290
- return parseBooleanToken(raw) === true
291
- }
292
-
293
291
  const restoreDefaults: ModuleCli = {
294
292
  command: 'restore-defaults',
295
293
  async run() {
294
+ const entries = collectInstanceConfigDefaults()
295
+ if (entries.length === 0) {
296
+ console.log('[configs] No enabled modules declared instance configuration defaults.')
297
+ return
298
+ }
299
+
296
300
  const container = await createRequestContainer()
297
301
  try {
298
302
  let service: ModuleConfigService
299
303
  try {
300
- service = (container.resolve('moduleConfigService') as ModuleConfigService)
304
+ service = container.resolve('moduleConfigService') as ModuleConfigService
301
305
  } catch {
302
- console.error('[configs] moduleConfigService is not registered in the container.')
303
- return
306
+ throw new Error('[configs] moduleConfigService is not registered in the container.')
304
307
  }
305
308
 
306
- const disabledByEnv = envDisablesAutoIndexing()
307
- const defaultEnabled = !disabledByEnv
308
- await service.restoreDefaults(
309
- [
310
- {
311
- moduleId: 'vector',
312
- name: 'auto_index_enabled',
313
- value: defaultEnabled,
314
- },
315
- {
316
- moduleId: 'notifications',
317
- name: NOTIFICATIONS_DELIVERY_CONFIG_KEY,
318
- value: STORED_DEFAULT_NOTIFICATION_DELIVERY_CONFIG,
319
- },
320
- ],
321
- { force: true },
309
+ const restored =
310
+ typeof service.restoreDefaultsStrict === 'function'
311
+ ? await service.restoreDefaultsStrict(entries, { force: true })
312
+ : await restoreInstanceDefaultsStrict(container, entries, { force: true })
313
+
314
+ const vectorEntry = entries.find(
315
+ (entry) =>
316
+ entry.moduleId === SEARCH_AUTO_INDEX_CONFIG_MODULE &&
317
+ entry.name === SEARCH_AUTO_INDEX_CONFIG_KEY,
322
318
  )
319
+ if (vectorEntry) {
320
+ const defaultEnabled = vectorEntry.value === true
321
+ const disabledByEnv = !defaultEnabled && envDisablesAutoIndexing()
322
+ console.log(
323
+ `[configs] Vector auto-indexing default set to ${defaultEnabled ? 'enabled' : 'disabled'}${
324
+ disabledByEnv
325
+ ? ' (forced by OM_DISABLE_VECTOR_SEARCH_AUTOINDEXING or legacy DISABLE_VECTOR_SEARCH_AUTOINDEXING)'
326
+ : ''
327
+ }.`,
328
+ )
329
+ }
330
+
331
+ const restoredKeys = entries.map((entry) => `${entry.ownerModuleId}:${entry.moduleId}.${entry.name}`).join(', ')
323
332
  console.log(
324
- `[configs] Vector auto-indexing default set to ${defaultEnabled ? 'enabled' : 'disabled'}${
325
- disabledByEnv
326
- ? ' (forced by OM_DISABLE_VECTOR_SEARCH_AUTOINDEXING or legacy DISABLE_VECTOR_SEARCH_AUTOINDEXING)'
327
- : ''
328
- }.`,
333
+ `[configs] Restored ${restored.length} instance configuration default(s) (${restoredKeys}).`,
329
334
  )
330
335
  } finally {
331
- const disposable = container as unknown as { dispose?: () => Promise<void> }
332
- if (typeof disposable.dispose === 'function') {
333
- await disposable.dispose()
334
- }
336
+ await disposeContainer(container)
335
337
  }
336
338
  },
337
339
  }
@@ -1,10 +1,12 @@
1
1
  import { defineProcessDiRegistrar, asScopedService } from '@open-mercato/shared/lib/di/process-registrar'
2
2
  import type { AppContainer } from '@open-mercato/shared/lib/di/container'
3
3
  import { createModuleConfigService } from './lib/module-config-service'
4
+ import { createInstanceConfigInitializer } from './lib/instance-config-initializer'
4
5
 
5
6
  export function register(container: AppContainer) {
6
7
  container.register({
7
8
  moduleConfigService: asScopedService(createModuleConfigService),
9
+ instanceConfigInitializer: asScopedService(createInstanceConfigInitializer),
8
10
  })
9
11
  }
10
12
 
@@ -0,0 +1,56 @@
1
+ import { LockMode } from '@mikro-orm/core'
2
+ import type { EntityManager } from '@mikro-orm/postgresql'
3
+ import type { AppContainer } from '@open-mercato/shared/lib/di/container'
4
+ import { deferAfterTransactionCommit } from '@open-mercato/shared/lib/db/afterCommit'
5
+ import { ModuleConfig } from '../data/entities'
6
+ import { moduleConfigKeySchema, type ModuleConfigKey } from '../data/validators'
7
+ import type { ModuleConfigService } from './module-config-service'
8
+
9
+ type InstanceConfigInitialization = ModuleConfigKey & {
10
+ initialValue: unknown
11
+ merge(current: unknown): { value: unknown } | undefined
12
+ }
13
+
14
+ export type InstanceConfigInitializer = {
15
+ initialize(em: EntityManager, input: InstanceConfigInitialization): Promise<void>
16
+ }
17
+
18
+ export function createInstanceConfigInitializer(container: AppContainer): InstanceConfigInitializer {
19
+ const configService = container.resolve<ModuleConfigService>('moduleConfigService')
20
+ return {
21
+ async initialize(setupEm, input) {
22
+ const { moduleId, name } = moduleConfigKeySchema.parse(input)
23
+ const where = { moduleId, name, tenantId: null, organizationId: null }
24
+ const em = setupEm.getContext(false)
25
+
26
+ const initialize = async (txEm: EntityManager): Promise<boolean> => {
27
+ const lockRow = () => txEm.findOne(ModuleConfig, where, { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true })
28
+ let row = await lockRow()
29
+ if (!row) {
30
+ const inserted = await txEm.execute<Array<{ id: string }>>(
31
+ `insert into "module_configs"
32
+ ("module_id", "name", "value_json", "tenant_id", "organization_id", "created_at", "updated_at")
33
+ values (?, ?, ?::jsonb, null, null, now(), now())
34
+ on conflict ("module_id", "name") where "tenant_id" is null do nothing
35
+ returning "id"`,
36
+ [moduleId, name, JSON.stringify(input.initialValue ?? null)],
37
+ )
38
+ if (inserted.length > 0) return true
39
+ row = await lockRow()
40
+ if (!row) throw new Error('[internal] Instance config key conflicts with a row outside the instance scope')
41
+ }
42
+
43
+ const merged = input.merge(row.valueJson)
44
+ if (!merged) return false
45
+ row.valueJson = merged.value ?? null
46
+ await txEm.flush()
47
+ return true
48
+ }
49
+
50
+ const changed = em.isInTransaction() ? await initialize(em) : await em.transactional(initialize)
51
+ if (changed) {
52
+ await deferAfterTransactionCommit(em, () => configService.invalidate(moduleId, name))
53
+ }
54
+ },
55
+ }
56
+ }