@open-mercato/enterprise 0.8.1-develop.7297.1.67605e74f9 → 0.9.0

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 (39) hide show
  1. package/dist/modules/agent_orchestrator/api/processes/[id]/executions/route.js +2 -1
  2. package/dist/modules/agent_orchestrator/api/processes/[id]/executions/route.js.map +2 -2
  3. package/dist/modules/agent_orchestrator/i18n/de.json +2 -1
  4. package/dist/modules/agent_orchestrator/i18n/en.json +2 -1
  5. package/dist/modules/agent_orchestrator/i18n/es.json +2 -1
  6. package/dist/modules/agent_orchestrator/i18n/ko.json +2 -1
  7. package/dist/modules/agent_orchestrator/i18n/pl.json +2 -1
  8. package/dist/modules/agent_orchestrator/lib/identity/agentPrincipalService.js +33 -28
  9. package/dist/modules/agent_orchestrator/lib/identity/agentPrincipalService.js.map +2 -2
  10. package/dist/modules/record_locks/i18n/de.json +1 -0
  11. package/dist/modules/record_locks/i18n/en.json +1 -0
  12. package/dist/modules/record_locks/i18n/es.json +1 -0
  13. package/dist/modules/record_locks/i18n/ko.json +1 -0
  14. package/dist/modules/record_locks/i18n/pl.json +1 -0
  15. package/dist/modules/security/notifications.js +4 -0
  16. package/dist/modules/security/notifications.js.map +2 -2
  17. package/dist/modules/sso/lib/errors.js +15 -1
  18. package/dist/modules/sso/lib/errors.js.map +2 -2
  19. package/dist/modules/sso/services/accountLinkingService.js +77 -26
  20. package/dist/modules/sso/services/accountLinkingService.js.map +2 -2
  21. package/dist/modules/sso/services/ssoService.js +9 -1
  22. package/dist/modules/sso/services/ssoService.js.map +2 -2
  23. package/package.json +10 -11
  24. package/src/modules/agent_orchestrator/api/processes/[id]/executions/route.ts +2 -1
  25. package/src/modules/agent_orchestrator/i18n/de.json +2 -1
  26. package/src/modules/agent_orchestrator/i18n/en.json +2 -1
  27. package/src/modules/agent_orchestrator/i18n/es.json +2 -1
  28. package/src/modules/agent_orchestrator/i18n/ko.json +2 -1
  29. package/src/modules/agent_orchestrator/i18n/pl.json +2 -1
  30. package/src/modules/agent_orchestrator/lib/identity/agentPrincipalService.ts +37 -31
  31. package/src/modules/record_locks/i18n/de.json +1 -0
  32. package/src/modules/record_locks/i18n/en.json +1 -0
  33. package/src/modules/record_locks/i18n/es.json +1 -0
  34. package/src/modules/record_locks/i18n/ko.json +1 -0
  35. package/src/modules/record_locks/i18n/pl.json +1 -0
  36. package/src/modules/security/notifications.ts +4 -0
  37. package/src/modules/sso/lib/errors.ts +20 -0
  38. package/src/modules/sso/services/accountLinkingService.ts +90 -29
  39. package/src/modules/sso/services/ssoService.ts +8 -1
@@ -3,6 +3,7 @@ import { z } from "zod";
3
3
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
4
4
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
5
  import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
6
+ import { resolveSingleOrganizationIdOrDeny } from "@open-mercato/core/modules/directory/utils/organizationScopeFilter";
6
7
  import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
7
8
  import { validateCrudMutationGuard, runCrudMutationGuardAfterSuccess } from "@open-mercato/shared/lib/crud/mutation-guard";
8
9
  import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
@@ -34,7 +35,7 @@ async function POST(req, ctx) {
34
35
  }
35
36
  const container = await createRequestContainer();
36
37
  const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
37
- const organizationId = scope?.selectedId ?? auth.orgId ?? null;
38
+ const organizationId = resolveSingleOrganizationIdOrDeny(scope, auth) ?? null;
38
39
  if (!organizationId) {
39
40
  return NextResponse.json(
40
41
  { error: "Select a single organization before starting a process." },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/agent_orchestrator/api/processes/%5Bid%5D/executions/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { validateCrudMutationGuard, runCrudMutationGuardAfterSuccess } from '@open-mercato/shared/lib/crud/mutation-guard'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { processExecutionStartSchema } from '../../../../data/validators'\nimport { ProcessDefinition } from '../../../../data/entities'\nimport { manualTrigger, parseProcessTriggers } from '../../../../lib/tasks/triggers'\nimport type {\n StartProcessExecutionInput,\n StartProcessExecutionResult,\n} from '../../../../commands/processes'\n\n/**\n * Start one business execution \u2014 always async (`202 { executionId }`).\n *\n * This is the external contract: a caller asks a PROCESS to run and gets back an\n * execution id to poll or subscribe to. It never exposes an agent, a runtime or a\n * workflow step, so the process can be re-implemented underneath without breaking\n * the integration.\n *\n * Callable by a human session or an ApiKey bearer whose role grants\n * `agent_orchestrator.processes.run`, and only when the definition DECLARES a\n * `{ kind: 'manual' }` trigger (403 otherwise): hand-starting is a declared\n * capability rather than an ambient one.\n *\n * `{ kind: 'manual', ref: <userId> }` records the INVOKER. It is provenance and\n * never an ACL identity \u2014 the run executes under the bound workflow definition's\n * own least-privilege principal, whoever started it.\n */\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['agent_orchestrator.processes.run'] },\n}\n\nconst errorSchema = z.object({ error: z.string() })\nconst acceptedSchema = z.object({ executionId: z.string().uuid() })\n\ntype RouteContext = { params: Promise<{ id: string }> }\n\nexport async function POST(req: Request, ctx: RouteContext) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n if (!auth.tenantId || !auth.sub) {\n return NextResponse.json({ error: 'Tenant context required' }, { status: 400 })\n }\n\n const { id } = await ctx.params\n if (!z.string().uuid().safeParse(id).success) {\n return NextResponse.json({ error: 'Process definition not found' }, { status: 404 })\n }\n\n const body = await readJsonSafe(req, {})\n const parsed = processExecutionStartSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json(\n { error: 'Validation failed', fieldErrors: parsed.error.flatten().fieldErrors },\n { status: 400 },\n )\n }\n\n const container = await createRequestContainer()\n\n // Fail-closed single-org attribution (same rule as the playground run route):\n // an execution must land in exactly one organization's ledger/caseload.\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n return NextResponse.json(\n { error: 'Select a single organization before starting a process.' },\n { status: 400 },\n )\n }\n\n // The declared manual trigger is resolved BEFORE the mutation guard so an\n // undeclared hand-start never reaches the command or an approval queue. The\n // command re-checks it \u2014 this is the surface that also enforces the trigger's\n // own `requireFeatures`, which only a request-scoped RBAC lookup can answer.\n const em = (container.resolve('em') as EntityManager).fork()\n const definition = await em.findOne(ProcessDefinition, {\n id,\n tenantId: auth.tenantId,\n organizationId,\n deletedAt: null,\n })\n if (!definition) return NextResponse.json({ error: 'Process definition not found' }, { status: 404 })\n const manual = manualTrigger(parseProcessTriggers(definition.triggers))\n if (!manual) {\n return NextResponse.json(\n { error: 'This process declares no manual trigger \u2014 add one to start it by hand.' },\n { status: 403 },\n )\n }\n if (manual.requireFeatures.length > 0) {\n const rbac = container.resolve('rbacService') as {\n userHasAllFeatures: (\n userId: string,\n features: string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<boolean>\n }\n const allowed = await rbac.userHasAllFeatures(auth.sub, manual.requireFeatures, {\n tenantId: auth.tenantId,\n organizationId,\n })\n if (!allowed) {\n return NextResponse.json(\n { error: 'Missing the features this process requires to be started by hand.' },\n { status: 403 },\n )\n }\n }\n\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId,\n userId: auth.sub,\n resourceKind: 'agent_orchestrator.process_execution',\n resourceId: id,\n operation: 'custom',\n requestMethod: 'POST',\n requestHeaders: req.headers,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const commandBus = container.resolve('commandBus') as CommandBus\n const commandCtx: CommandRuntimeContext = {\n container,\n auth: { sub: auth.sub, tenantId: auth.tenantId, orgId: organizationId } as CommandRuntimeContext['auth'],\n organizationScope: null,\n selectedOrganizationId: organizationId,\n organizationIds: [organizationId],\n request: req,\n }\n\n // Both a human session and an ApiKey bearer are MANUAL entry \u2014 the difference\n // is which principal id the provenance ref carries.\n const triggeredBy = { kind: 'manual' as const, ref: auth.sub }\n\n let result: StartProcessExecutionResult\n try {\n const executed = await commandBus.execute<StartProcessExecutionInput, StartProcessExecutionResult>(\n 'agent_orchestrator.processes.startExecution',\n {\n input: {\n tenantId: auth.tenantId,\n organizationId,\n processDefinitionId: id,\n input: parsed.data.input,\n idempotencyKey: parsed.data.idempotencyKey ?? null,\n sourceEntityType: parsed.data.sourceEntityType ?? null,\n sourceEntityId: parsed.data.sourceEntityId ?? null,\n triggeredBy,\n },\n ctx: commandCtx,\n },\n )\n result = executed.result\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n if (guardResult?.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId,\n userId: auth.sub,\n resourceKind: 'agent_orchestrator.process_execution',\n resourceId: id,\n operation: 'custom',\n requestMethod: 'POST',\n requestHeaders: req.headers,\n metadata: guardResult.metadata,\n })\n }\n\n return NextResponse.json({ executionId: result.executionId }, { status: 202 })\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Agent Orchestrator',\n summary: 'Start a business execution',\n methods: {\n POST: {\n summary: 'Start one execution of this process (always async)',\n description:\n 'Requires the definition to declare a { kind: \"manual\" } trigger (403 otherwise) plus any features that trigger names. Validates input against the definition inputSchema when set, dedupes on idempotencyKey so one key can never produce two executions, and starts the bound workflow. Returns 202 with the executionId immediately; observe completion via the agent_orchestrator.process.execution.* events or GET /executions/:id. Gated by agent_orchestrator.processes.run (session or API key).',\n responses: [{ status: 202, description: 'Execution accepted', schema: acceptedSchema }],\n errors: [\n { status: 400, description: 'Validation failed (body or inputSchema)', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n {\n status: 403,\n description:\n 'Missing agent_orchestrator.processes.run, no declared manual trigger, or missing the trigger\\'s requireFeatures',\n schema: errorSchema,\n },\n { status: 404, description: 'Unknown process definition id (or cross-tenant)', schema: errorSchema },\n { status: 409, description: 'Process definition disabled', schema: errorSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,0CAA0C;AACnD,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B,wCAAwC;AAE5E,SAAS,uBAAuB;AAEhC,SAAS,mCAAmC;AAC5C,SAAS,yBAAyB;AAClC,SAAS,eAAe,4BAA4B;AAuB7C,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,kCAAkC,EAAE;AACnF;AAEA,MAAM,cAAc,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAClD,MAAM,iBAAiB,EAAE,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAIlE,eAAsB,KAAK,KAAc,KAAmB;AAC1D,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,KAAM,QAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAC9E,MAAI,CAAC,KAAK,YAAY,CAAC,KAAK,KAAK;AAC/B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next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveSingleOrganizationIdOrDeny } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { validateCrudMutationGuard, runCrudMutationGuardAfterSuccess } from '@open-mercato/shared/lib/crud/mutation-guard'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { processExecutionStartSchema } from '../../../../data/validators'\nimport { ProcessDefinition } from '../../../../data/entities'\nimport { manualTrigger, parseProcessTriggers } from '../../../../lib/tasks/triggers'\nimport type {\n StartProcessExecutionInput,\n StartProcessExecutionResult,\n} from '../../../../commands/processes'\n\n/**\n * Start one business execution \u2014 always async (`202 { executionId }`).\n *\n * This is the external contract: a caller asks a PROCESS to run and gets back an\n * execution id to poll or subscribe to. It never exposes an agent, a runtime or a\n * workflow step, so the process can be re-implemented underneath without breaking\n * the integration.\n *\n * Callable by a human session or an ApiKey bearer whose role grants\n * `agent_orchestrator.processes.run`, and only when the definition DECLARES a\n * `{ kind: 'manual' }` trigger (403 otherwise): hand-starting is a declared\n * capability rather than an ambient one.\n *\n * `{ kind: 'manual', ref: <userId> }` records the INVOKER. It is provenance and\n * never an ACL identity \u2014 the run executes under the bound workflow definition's\n * own least-privilege principal, whoever started it.\n */\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['agent_orchestrator.processes.run'] },\n}\n\nconst errorSchema = z.object({ error: z.string() })\nconst acceptedSchema = z.object({ executionId: z.string().uuid() })\n\ntype RouteContext = { params: Promise<{ id: string }> }\n\nexport async function POST(req: Request, ctx: RouteContext) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n if (!auth.tenantId || !auth.sub) {\n return NextResponse.json({ error: 'Tenant context required' }, { status: 400 })\n }\n\n const { id } = await ctx.params\n if (!z.string().uuid().safeParse(id).success) {\n return NextResponse.json({ error: 'Process definition not found' }, { status: 404 })\n }\n\n const body = await readJsonSafe(req, {})\n const parsed = processExecutionStartSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json(\n { error: 'Validation failed', fieldErrors: parsed.error.flatten().fieldErrors },\n { status: 400 },\n )\n }\n\n const container = await createRequestContainer()\n\n // Fail-closed single-org attribution (same rule as the playground run route):\n // an execution must land in exactly one organization's ledger/caseload.\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = resolveSingleOrganizationIdOrDeny(scope, auth) ?? null\n if (!organizationId) {\n return NextResponse.json(\n { error: 'Select a single organization before starting a process.' },\n { status: 400 },\n )\n }\n\n // The declared manual trigger is resolved BEFORE the mutation guard so an\n // undeclared hand-start never reaches the command or an approval queue. The\n // command re-checks it \u2014 this is the surface that also enforces the trigger's\n // own `requireFeatures`, which only a request-scoped RBAC lookup can answer.\n const em = (container.resolve('em') as EntityManager).fork()\n const definition = await em.findOne(ProcessDefinition, {\n id,\n tenantId: auth.tenantId,\n organizationId,\n deletedAt: null,\n })\n if (!definition) return NextResponse.json({ error: 'Process definition not found' }, { status: 404 })\n const manual = manualTrigger(parseProcessTriggers(definition.triggers))\n if (!manual) {\n return NextResponse.json(\n { error: 'This process declares no manual trigger \u2014 add one to start it by hand.' },\n { status: 403 },\n )\n }\n if (manual.requireFeatures.length > 0) {\n const rbac = container.resolve('rbacService') as {\n userHasAllFeatures: (\n userId: string,\n features: string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<boolean>\n }\n const allowed = await rbac.userHasAllFeatures(auth.sub, manual.requireFeatures, {\n tenantId: auth.tenantId,\n organizationId,\n })\n if (!allowed) {\n return NextResponse.json(\n { error: 'Missing the features this process requires to be started by hand.' },\n { status: 403 },\n )\n }\n }\n\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId,\n userId: auth.sub,\n resourceKind: 'agent_orchestrator.process_execution',\n resourceId: id,\n operation: 'custom',\n requestMethod: 'POST',\n requestHeaders: req.headers,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const commandBus = container.resolve('commandBus') as CommandBus\n const commandCtx: CommandRuntimeContext = {\n container,\n auth: { sub: auth.sub, tenantId: auth.tenantId, orgId: organizationId } as CommandRuntimeContext['auth'],\n organizationScope: null,\n selectedOrganizationId: organizationId,\n organizationIds: [organizationId],\n request: req,\n }\n\n // Both a human session and an ApiKey bearer are MANUAL entry \u2014 the difference\n // is which principal id the provenance ref carries.\n const triggeredBy = { kind: 'manual' as const, ref: auth.sub }\n\n let result: StartProcessExecutionResult\n try {\n const executed = await commandBus.execute<StartProcessExecutionInput, StartProcessExecutionResult>(\n 'agent_orchestrator.processes.startExecution',\n {\n input: {\n tenantId: auth.tenantId,\n organizationId,\n processDefinitionId: id,\n input: parsed.data.input,\n idempotencyKey: parsed.data.idempotencyKey ?? null,\n sourceEntityType: parsed.data.sourceEntityType ?? null,\n sourceEntityId: parsed.data.sourceEntityId ?? null,\n triggeredBy,\n },\n ctx: commandCtx,\n },\n )\n result = executed.result\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n if (guardResult?.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId,\n userId: auth.sub,\n resourceKind: 'agent_orchestrator.process_execution',\n resourceId: id,\n operation: 'custom',\n requestMethod: 'POST',\n requestHeaders: req.headers,\n metadata: guardResult.metadata,\n })\n }\n\n return NextResponse.json({ executionId: result.executionId }, { status: 202 })\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Agent Orchestrator',\n summary: 'Start a business execution',\n methods: {\n POST: {\n summary: 'Start one execution of this process (always async)',\n description:\n 'Requires the definition to declare a { kind: \"manual\" } trigger (403 otherwise) plus any features that trigger names. Validates input against the definition inputSchema when set, dedupes on idempotencyKey so one key can never produce two executions, and starts the bound workflow. Returns 202 with the executionId immediately; observe completion via the agent_orchestrator.process.execution.* events or GET /executions/:id. Gated by agent_orchestrator.processes.run (session or API key).',\n responses: [{ status: 202, description: 'Execution accepted', schema: acceptedSchema }],\n errors: [\n { status: 400, description: 'Validation failed (body or inputSchema)', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n {\n status: 403,\n description:\n 'Missing agent_orchestrator.processes.run, no declared manual trigger, or missing the trigger\\'s requireFeatures',\n schema: errorSchema,\n },\n { status: 404, description: 'Unknown process definition id (or cross-tenant)', schema: errorSchema },\n { status: 409, description: 'Process definition disabled', schema: errorSchema },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,0CAA0C;AACnD,SAAS,yCAAyC;AAClD,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B,wCAAwC;AAE5E,SAAS,uBAAuB;AAEhC,SAAS,mCAAmC;AAC5C,SAAS,yBAAyB;AAClC,SAAS,eAAe,4BAA4B;AAuB7C,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,kCAAkC,EAAE;AACnF;AAEA,MAAM,cAAc,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAClD,MAAM,iBAAiB,EAAE,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAIlE,eAAsB,KAAK,KAAc,KAAmB;AAC1D,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,KA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AA,QACnG,EAAE,QAAQ,KAAK,aAAa,+BAA+B,QAAQ,YAAY;AAAA,MACjF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1491,5 +1491,6 @@
1491
1491
  "agent_orchestrator.webSearch.activity.stage.merging": "Ergebnisse werden zusammengeführt",
1492
1492
  "agent_orchestrator.webSearch.activity.stage.reading": "Seiten werden gelesen",
1493
1493
  "agent_orchestrator.webSearch.activity.title": "Websuche",
1494
- "agent_orchestrator.workInbox.disposition.title": "Zu prüfender Agentenvorschlag: {agent}"
1494
+ "agent_orchestrator.workInbox.disposition.title": "Zu prüfender Agentenvorschlag: {agent}",
1495
+ "notifications.categories.agent_orchestrator": "KI-Agenten"
1495
1496
  }
@@ -1491,5 +1491,6 @@
1491
1491
  "agent_orchestrator.webSearch.activity.stage.merging": "Merging results",
1492
1492
  "agent_orchestrator.webSearch.activity.stage.reading": "Reading pages",
1493
1493
  "agent_orchestrator.webSearch.activity.title": "Web search",
1494
- "agent_orchestrator.workInbox.disposition.title": "Agent proposal to review: {agent}"
1494
+ "agent_orchestrator.workInbox.disposition.title": "Agent proposal to review: {agent}",
1495
+ "notifications.categories.agent_orchestrator": "AI agents"
1495
1496
  }
@@ -1491,5 +1491,6 @@
1491
1491
  "agent_orchestrator.webSearch.activity.stage.merging": "Combinando resultados",
1492
1492
  "agent_orchestrator.webSearch.activity.stage.reading": "Leyendo páginas",
1493
1493
  "agent_orchestrator.webSearch.activity.title": "Búsqueda web",
1494
- "agent_orchestrator.workInbox.disposition.title": "Propuesta del agente para revisar: {agent}"
1494
+ "agent_orchestrator.workInbox.disposition.title": "Propuesta del agente para revisar: {agent}",
1495
+ "notifications.categories.agent_orchestrator": "Agentes de IA"
1495
1496
  }
@@ -1491,5 +1491,6 @@
1491
1491
  "agent_orchestrator.webSearch.activity.stage.merging": "결과 병합 중",
1492
1492
  "agent_orchestrator.webSearch.activity.stage.reading": "페이지 읽는 중",
1493
1493
  "agent_orchestrator.webSearch.activity.title": "웹 검색",
1494
- "agent_orchestrator.workInbox.disposition.title": "검토할 에이전트 제안: {agent}"
1494
+ "agent_orchestrator.workInbox.disposition.title": "검토할 에이전트 제안: {agent}",
1495
+ "notifications.categories.agent_orchestrator": "AI 에이전트"
1495
1496
  }
@@ -1491,5 +1491,6 @@
1491
1491
  "agent_orchestrator.webSearch.activity.stage.merging": "Scalanie wyników",
1492
1492
  "agent_orchestrator.webSearch.activity.stage.reading": "Czytanie stron",
1493
1493
  "agent_orchestrator.webSearch.activity.title": "Wyszukiwanie w sieci",
1494
- "agent_orchestrator.workInbox.disposition.title": "Propozycja agenta do przejrzenia: {agent}"
1494
+ "agent_orchestrator.workInbox.disposition.title": "Propozycja agenta do przejrzenia: {agent}",
1495
+ "notifications.categories.agent_orchestrator": "Agenci AI"
1495
1496
  }
@@ -1,5 +1,6 @@
1
1
  import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
2
2
  import { computeEmailHash } from "@open-mercato/core/modules/auth/lib/emailHash";
3
+ import { lockAuthorizationState } from "@open-mercato/core/modules/auth/lib/authorizationStateLocks";
3
4
  import {
4
5
  provisionAgentPrincipalSchema
5
6
  } from "../../data/validators.js";
@@ -38,34 +39,6 @@ async function provisionAgentPrincipal(container, scope, input) {
38
39
  tem.persist(role);
39
40
  await tem.flush();
40
41
  }
41
- const existingAcl = await findOneWithDecryption(
42
- tem,
43
- auth.RoleAcl,
44
- { role, tenantId },
45
- {},
46
- { tenantId, organizationId: null }
47
- );
48
- if (!existingAcl) {
49
- tem.persist(
50
- tem.create(auth.RoleAcl, {
51
- role,
52
- tenantId,
53
- featuresJson: parsed.roleFeatures,
54
- isSuperAdmin: false,
55
- organizationsJson: [organizationId],
56
- createdAt: /* @__PURE__ */ new Date()
57
- })
58
- );
59
- await tem.flush();
60
- } else {
61
- const current = Array.isArray(existingAcl.featuresJson) ? existingAcl.featuresJson : [];
62
- const merged = Array.from(/* @__PURE__ */ new Set([...current, ...parsed.roleFeatures]));
63
- if (merged.length !== current.length) {
64
- existingAcl.featuresJson = merged;
65
- tem.persist(existingAcl);
66
- await tem.flush();
67
- }
68
- }
69
42
  const agentEmail = buildAgentUserEmail(parsed.agentDefinitionId, organizationId);
70
43
  let user = existingPrincipal ? await findOneWithDecryption(
71
44
  tem,
@@ -99,6 +72,38 @@ async function provisionAgentPrincipal(container, scope, input) {
99
72
  } else if (user.kind !== "agent") {
100
73
  throw new Error("[internal] resolved a non-agent User for an agent principal");
101
74
  }
75
+ await lockAuthorizationState(tem, {
76
+ userIds: [String(user.id)],
77
+ roleIds: [String(role.id)]
78
+ });
79
+ const existingAcl = await findOneWithDecryption(
80
+ tem,
81
+ auth.RoleAcl,
82
+ { role, tenantId },
83
+ {},
84
+ { tenantId, organizationId: null }
85
+ );
86
+ if (!existingAcl) {
87
+ tem.persist(
88
+ tem.create(auth.RoleAcl, {
89
+ role,
90
+ tenantId,
91
+ featuresJson: parsed.roleFeatures,
92
+ isSuperAdmin: false,
93
+ organizationsJson: [organizationId],
94
+ createdAt: /* @__PURE__ */ new Date()
95
+ })
96
+ );
97
+ await tem.flush();
98
+ } else {
99
+ const current = Array.isArray(existingAcl.featuresJson) ? existingAcl.featuresJson : [];
100
+ const merged = Array.from(/* @__PURE__ */ new Set([...current, ...parsed.roleFeatures]));
101
+ if (merged.length !== current.length) {
102
+ existingAcl.featuresJson = merged;
103
+ tem.persist(existingAcl);
104
+ await tem.flush();
105
+ }
106
+ }
102
107
  const existingLink = await findOneWithDecryption(
103
108
  tem,
104
109
  auth.UserRole,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/agent_orchestrator/lib/identity/agentPrincipalService.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { computeEmailHash } from '@open-mercato/core/modules/auth/lib/emailHash'\nimport {\n provisionAgentPrincipalSchema,\n type ProvisionAgentPrincipalInput,\n} from '../../data/validators'\nimport { AgentPrincipal } from '../../data/entities'\n\nexport type AgentPrincipalScope = { tenantId: string; organizationId: string }\n\n/**\n * The resolved identity of a provisioned agent \u2014 the concrete `auth.User` id used\n * as the actor on every write the agent makes, plus the scoped role and the\n * principal row. Phase 2 (`runAs` / on-behalf-of) reads `userId` as the\n * `actorUserId` it stamps on each `ActionLog`.\n */\nexport type ResolvedAgentPrincipal = {\n principal: AgentPrincipal\n userId: string\n roleId: string\n /** True iff the agent `User` holds NO interactive credential (passwordHash null + not confirmed). */\n interactiveLoginDisabled: boolean\n}\n\n/**\n * Deterministic, internal-only email for an agent `User`. Not a deliverable\n * mailbox \u2014 agents never receive mail and never log in interactively. Keyed by\n * the agent definition id + organization so it is stable across re-provisioning\n * (idempotency) and unique per org. The `.agent.internal` TLD is reserved/non-\n * routable so it can never collide with a real human's address.\n */\nfunction buildAgentUserEmail(agentDefinitionId: string, organizationId: string): string {\n const slug = agentDefinitionId.toLowerCase().replace(/[^a-z0-9._-]+/g, '-')\n return `agent+${slug}+${organizationId}@agent.internal`\n}\n\n/** Deterministic, tenant-scoped role name for an agent's least-privilege role. */\nfunction buildAgentRoleName(agentDefinitionId: string): string {\n return `agent:${agentDefinitionId}`\n}\n\nfunction resolveEm(container: AwilixContainer): EntityManager {\n return (container.resolve('em') as EntityManager).fork()\n}\n\n/**\n * Provisions \u2014 idempotently \u2014 an `AgentPrincipal`: a non-interactive `auth.User`\n * (`kind='agent'`) and a scoped, least-privilege `auth.Role`, so the agent is a\n * first-class principal attributed identically to a human on every write (agent\n * identity & on-behalf-of spec, Wave 4 Phase 1).\n *\n * Internal-agent attribution: the returned `userId` is the concrete actor id the\n * Phase-2 `runAs` wrapper stamps on each `ActionLog`.\n *\n * Non-interactive enforcement: the agent `User` is created with\n * `passwordHash = null` and `isConfirmed = false`, so the interactive\n * password/SSO login flow has no credential to verify against \u2014 it is a property\n * of the principal, not a special-case block. External token flows are Phase 3\n * (`credentialMode='oauth_client'`) and are NOT provisioned here.\n *\n * Idempotency: keyed on `(organizationId, agentDefinitionId)` over live rows\n * (partial unique index). A second call resolves and returns the same principal,\n * creating no duplicate `User`/`Role`/`AgentPrincipal` rows. Tenant-scoped: every\n * lookup and write pins both `tenantId` and `organizationId`.\n */\nexport async function provisionAgentPrincipal(\n container: AwilixContainer,\n scope: AgentPrincipalScope,\n input: ProvisionAgentPrincipalInput,\n): Promise<ResolvedAgentPrincipal> {\n const parsed = provisionAgentPrincipalSchema.parse(input)\n const em = resolveEm(container)\n const { tenantId, organizationId } = scope\n\n const auth = (await import(\n '@open-mercato/core/modules/auth/data/entities'\n )) as typeof import('@open-mercato/core/modules/auth/data/entities')\n\n return em.transactional(async (tem) => {\n const existingPrincipal = await tem.findOne(AgentPrincipal, {\n organizationId,\n agentDefinitionId: parsed.agentDefinitionId,\n deletedAt: null,\n })\n\n // \u2500\u2500 Scoped, least-privilege role (find-or-create, idempotent) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const roleName = buildAgentRoleName(parsed.agentDefinitionId)\n let role = await findOneWithDecryption(\n tem,\n auth.Role,\n { name: roleName, tenantId },\n {},\n { tenantId, organizationId: null },\n )\n if (!role) {\n role = tem.create(auth.Role, { name: roleName, tenantId, minActiveHolders: 0, createdAt: new Date() })\n tem.persist(role)\n await tem.flush()\n }\n\n // The scoped role's ACL grants the agent's least-privilege features (merged\n // idempotently on re-provision), never super-admin.\n const existingAcl = await findOneWithDecryption(\n tem,\n auth.RoleAcl,\n { role, tenantId },\n {},\n { tenantId, organizationId: null },\n )\n if (!existingAcl) {\n tem.persist(\n tem.create(auth.RoleAcl, {\n role,\n tenantId,\n featuresJson: parsed.roleFeatures,\n isSuperAdmin: false,\n organizationsJson: [organizationId],\n createdAt: new Date(),\n }),\n )\n await tem.flush()\n } else {\n const current = Array.isArray(existingAcl.featuresJson) ? existingAcl.featuresJson : []\n const merged = Array.from(new Set([...current, ...parsed.roleFeatures]))\n if (merged.length !== current.length) {\n existingAcl.featuresJson = merged\n tem.persist(existingAcl)\n await tem.flush()\n }\n }\n\n // \u2500\u2500 Non-interactive agent User (find-or-create, idempotent) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const agentEmail = buildAgentUserEmail(parsed.agentDefinitionId, organizationId)\n let user = existingPrincipal\n ? await findOneWithDecryption(\n tem,\n auth.User,\n { id: existingPrincipal.userId },\n {},\n { tenantId, organizationId },\n )\n : await findOneWithDecryption(\n tem,\n auth.User,\n { emailHash: computeEmailHash(agentEmail), tenantId, deletedAt: null },\n {},\n { tenantId, organizationId },\n )\n\n if (!user) {\n user = tem.create(auth.User, {\n email: agentEmail,\n emailHash: computeEmailHash(agentEmail),\n // No interactive credential: a null passwordHash + unconfirmed account\n // means the password/SSO login flow has nothing to authenticate against.\n passwordHash: null,\n isConfirmed: false,\n kind: 'agent',\n name: parsed.displayName ?? parsed.agentDefinitionId,\n tenantId,\n organizationId,\n createdAt: new Date(),\n })\n tem.persist(user)\n await tem.flush()\n } else if (user.kind !== 'agent') {\n // Defensive: an existing row resolved by the deterministic agent email must\n // be an agent principal. Never silently repurpose a human/service row.\n throw new Error('[internal] resolved a non-agent User for an agent principal')\n }\n\n // Link the agent User to its scoped role (idempotent).\n const existingLink = await findOneWithDecryption(\n tem,\n auth.UserRole,\n { user, role },\n {},\n { tenantId, organizationId: null },\n )\n if (!existingLink) {\n tem.persist(tem.create(auth.UserRole, { user, role, createdAt: new Date() }))\n await tem.flush()\n }\n\n // \u2500\u2500 AgentPrincipal row (find-or-create, idempotent) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n let principal = existingPrincipal\n if (!principal) {\n principal = tem.create(AgentPrincipal, {\n tenantId,\n organizationId,\n userId: user.id,\n agentDefinitionId: parsed.agentDefinitionId,\n roleId: role.id,\n credentialMode: parsed.credentialMode,\n enabled: true,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n tem.persist(principal)\n await tem.flush()\n }\n\n return {\n principal,\n userId: principal.userId,\n roleId: principal.roleId,\n interactiveLoginDisabled: !user.passwordHash && user.isConfirmed === false,\n }\n })\n}\n\n/**\n * Resolves the agent principal for `(organizationId, agentDefinitionId)` without\n * provisioning. Returns null when the agent has not been provisioned yet (or was\n * soft-deleted). Org-scoped \u2014 never returns another tenant's row.\n */\nexport async function resolveAgentPrincipal(\n container: AwilixContainer,\n scope: AgentPrincipalScope,\n agentDefinitionId: string,\n): Promise<AgentPrincipal | null> {\n const em = resolveEm(container)\n return em.findOne(AgentPrincipal, {\n organizationId: scope.organizationId,\n agentDefinitionId,\n deletedAt: null,\n })\n}\n"],
5
- "mappings": "AAEA,SAAS,6BAA6B;AACtC,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,OAEK;AACP,SAAS,sBAAsB;AAyB/B,SAAS,oBAAoB,mBAA2B,gBAAgC;AACtF,QAAM,OAAO,kBAAkB,YAAY,EAAE,QAAQ,kBAAkB,GAAG;AAC1E,SAAO,SAAS,IAAI,IAAI,cAAc;AACxC;AAGA,SAAS,mBAAmB,mBAAmC;AAC7D,SAAO,SAAS,iBAAiB;AACnC;AAEA,SAAS,UAAU,WAA2C;AAC5D,SAAQ,UAAU,QAAQ,IAAI,EAAoB,KAAK;AACzD;AAsBA,eAAsB,wBACpB,WACA,OACA,OACiC;AACjC,QAAM,SAAS,8BAA8B,MAAM,KAAK;AACxD,QAAM,KAAK,UAAU,SAAS;AAC9B,QAAM,EAAE,UAAU,eAAe,IAAI;AAErC,QAAM,OAAQ,MAAM,OAClB,+CACF;AAEA,SAAO,GAAG,cAAc,OAAO,QAAQ;AACrC,UAAM,oBAAoB,MAAM,IAAI,QAAQ,gBAAgB;AAAA,MAC1D;AAAA,MACA,mBAAmB,OAAO;AAAA,MAC1B,WAAW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I,KAAK;AAAA,MACtB,CAAC;AACD,UAAI,QAAQ,SAAS;AACrB,YAAM,IAAI,MAAM;AAAA,IAClB;AAEA,WAAO;AAAA,MACL;AAAA,MACA,QAAQ,UAAU;AAAA,MAClB,QAAQ,UAAU;AAAA,MAClB,0BAA0B,CAAC,KAAK,gBAAgB,KAAK,gBAAgB;AAAA,IACvE;AAAA,EACF,CAAC;AACH;AAOA,eAAsB,sBACpB,WACA,OACA,mBACgC;AAChC,QAAM,KAAK,UAAU,SAAS;AAC9B,SAAO,GAAG,QAAQ,gBAAgB;AAAA,IAChC,gBAAgB,MAAM;AAAA,IACtB;AAAA,IACA,WAAW;AAAA,EACb,CAAC;AACH;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { computeEmailHash } from '@open-mercato/core/modules/auth/lib/emailHash'\nimport { lockAuthorizationState } from '@open-mercato/core/modules/auth/lib/authorizationStateLocks'\nimport {\n provisionAgentPrincipalSchema,\n type ProvisionAgentPrincipalInput,\n} from '../../data/validators'\nimport { AgentPrincipal } from '../../data/entities'\n\nexport type AgentPrincipalScope = { tenantId: string; organizationId: string }\n\n/**\n * The resolved identity of a provisioned agent \u2014 the concrete `auth.User` id used\n * as the actor on every write the agent makes, plus the scoped role and the\n * principal row. Phase 2 (`runAs` / on-behalf-of) reads `userId` as the\n * `actorUserId` it stamps on each `ActionLog`.\n */\nexport type ResolvedAgentPrincipal = {\n principal: AgentPrincipal\n userId: string\n roleId: string\n /** True iff the agent `User` holds NO interactive credential (passwordHash null + not confirmed). */\n interactiveLoginDisabled: boolean\n}\n\n/**\n * Deterministic, internal-only email for an agent `User`. Not a deliverable\n * mailbox \u2014 agents never receive mail and never log in interactively. Keyed by\n * the agent definition id + organization so it is stable across re-provisioning\n * (idempotency) and unique per org. The `.agent.internal` TLD is reserved/non-\n * routable so it can never collide with a real human's address.\n */\nfunction buildAgentUserEmail(agentDefinitionId: string, organizationId: string): string {\n const slug = agentDefinitionId.toLowerCase().replace(/[^a-z0-9._-]+/g, '-')\n return `agent+${slug}+${organizationId}@agent.internal`\n}\n\n/** Deterministic, tenant-scoped role name for an agent's least-privilege role. */\nfunction buildAgentRoleName(agentDefinitionId: string): string {\n return `agent:${agentDefinitionId}`\n}\n\nfunction resolveEm(container: AwilixContainer): EntityManager {\n return (container.resolve('em') as EntityManager).fork()\n}\n\n/**\n * Provisions \u2014 idempotently \u2014 an `AgentPrincipal`: a non-interactive `auth.User`\n * (`kind='agent'`) and a scoped, least-privilege `auth.Role`, so the agent is a\n * first-class principal attributed identically to a human on every write (agent\n * identity & on-behalf-of spec, Wave 4 Phase 1).\n *\n * Internal-agent attribution: the returned `userId` is the concrete actor id the\n * Phase-2 `runAs` wrapper stamps on each `ActionLog`.\n *\n * Non-interactive enforcement: the agent `User` is created with\n * `passwordHash = null` and `isConfirmed = false`, so the interactive\n * password/SSO login flow has no credential to verify against \u2014 it is a property\n * of the principal, not a special-case block. External token flows are Phase 3\n * (`credentialMode='oauth_client'`) and are NOT provisioned here.\n *\n * Idempotency: keyed on `(organizationId, agentDefinitionId)` over live rows\n * (partial unique index). A second call resolves and returns the same principal,\n * creating no duplicate `User`/`Role`/`AgentPrincipal` rows. Tenant-scoped: every\n * lookup and write pins both `tenantId` and `organizationId`.\n */\nexport async function provisionAgentPrincipal(\n container: AwilixContainer,\n scope: AgentPrincipalScope,\n input: ProvisionAgentPrincipalInput,\n): Promise<ResolvedAgentPrincipal> {\n const parsed = provisionAgentPrincipalSchema.parse(input)\n const em = resolveEm(container)\n const { tenantId, organizationId } = scope\n\n const auth = (await import(\n '@open-mercato/core/modules/auth/data/entities'\n )) as typeof import('@open-mercato/core/modules/auth/data/entities')\n\n return em.transactional(async (tem) => {\n const existingPrincipal = await tem.findOne(AgentPrincipal, {\n organizationId,\n agentDefinitionId: parsed.agentDefinitionId,\n deletedAt: null,\n })\n\n // \u2500\u2500 Scoped, least-privilege role (find-or-create, idempotent) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const roleName = buildAgentRoleName(parsed.agentDefinitionId)\n let role = await findOneWithDecryption(\n tem,\n auth.Role,\n { name: roleName, tenantId },\n {},\n { tenantId, organizationId: null },\n )\n if (!role) {\n role = tem.create(auth.Role, { name: roleName, tenantId, minActiveHolders: 0, createdAt: new Date() })\n tem.persist(role)\n await tem.flush()\n }\n\n // \u2500\u2500 Non-interactive agent User (find-or-create, idempotent) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const agentEmail = buildAgentUserEmail(parsed.agentDefinitionId, organizationId)\n let user = existingPrincipal\n ? await findOneWithDecryption(\n tem,\n auth.User,\n { id: existingPrincipal.userId },\n {},\n { tenantId, organizationId },\n )\n : await findOneWithDecryption(\n tem,\n auth.User,\n { emailHash: computeEmailHash(agentEmail), tenantId, deletedAt: null },\n {},\n { tenantId, organizationId },\n )\n\n if (!user) {\n user = tem.create(auth.User, {\n email: agentEmail,\n emailHash: computeEmailHash(agentEmail),\n // No interactive credential: a null passwordHash + unconfirmed account\n // means the password/SSO login flow has nothing to authenticate against.\n passwordHash: null,\n isConfirmed: false,\n kind: 'agent',\n name: parsed.displayName ?? parsed.agentDefinitionId,\n tenantId,\n organizationId,\n createdAt: new Date(),\n })\n tem.persist(user)\n await tem.flush()\n } else if (user.kind !== 'agent') {\n // Defensive: an existing row resolved by the deterministic agent email must\n // be an agent principal. Never silently repurpose a human/service row.\n throw new Error('[internal] resolved a non-agent User for an agent principal')\n }\n\n await lockAuthorizationState(tem, {\n userIds: [String(user.id)],\n roleIds: [String(role.id)],\n })\n\n // The scoped role's ACL grants the agent's least-privilege features (merged\n // idempotently on re-provision), never super-admin.\n const existingAcl = await findOneWithDecryption(\n tem,\n auth.RoleAcl,\n { role, tenantId },\n {},\n { tenantId, organizationId: null },\n )\n if (!existingAcl) {\n tem.persist(\n tem.create(auth.RoleAcl, {\n role,\n tenantId,\n featuresJson: parsed.roleFeatures,\n isSuperAdmin: false,\n organizationsJson: [organizationId],\n createdAt: new Date(),\n }),\n )\n await tem.flush()\n } else {\n const current = Array.isArray(existingAcl.featuresJson) ? existingAcl.featuresJson : []\n const merged = Array.from(new Set([...current, ...parsed.roleFeatures]))\n if (merged.length !== current.length) {\n existingAcl.featuresJson = merged\n tem.persist(existingAcl)\n await tem.flush()\n }\n }\n\n // Link the agent User to its scoped role (idempotent).\n const existingLink = await findOneWithDecryption(\n tem,\n auth.UserRole,\n { user, role },\n {},\n { tenantId, organizationId: null },\n )\n if (!existingLink) {\n tem.persist(tem.create(auth.UserRole, { user, role, createdAt: new Date() }))\n await tem.flush()\n }\n\n // \u2500\u2500 AgentPrincipal row (find-or-create, idempotent) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n let principal = existingPrincipal\n if (!principal) {\n principal = tem.create(AgentPrincipal, {\n tenantId,\n organizationId,\n userId: user.id,\n agentDefinitionId: parsed.agentDefinitionId,\n roleId: role.id,\n credentialMode: parsed.credentialMode,\n enabled: true,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n tem.persist(principal)\n await tem.flush()\n }\n\n return {\n principal,\n userId: principal.userId,\n roleId: principal.roleId,\n interactiveLoginDisabled: !user.passwordHash && user.isConfirmed === false,\n }\n })\n}\n\n/**\n * Resolves the agent principal for `(organizationId, agentDefinitionId)` without\n * provisioning. Returns null when the agent has not been provisioned yet (or was\n * soft-deleted). Org-scoped \u2014 never returns another tenant's row.\n */\nexport async function resolveAgentPrincipal(\n container: AwilixContainer,\n scope: AgentPrincipalScope,\n agentDefinitionId: string,\n): Promise<AgentPrincipal | null> {\n const em = resolveEm(container)\n return em.findOne(AgentPrincipal, {\n organizationId: scope.organizationId,\n agentDefinitionId,\n deletedAt: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B;AAAA,IAChC,gBAAgB,MAAM;AAAA,IACtB;AAAA,IACA,WAAW;AAAA,EACb,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -1,4 +1,5 @@
1
1
  {
2
+ "notifications.categories.record_locks": "Datensatzsperren",
2
3
  "record_locks.banner.active_users_label": "Active users",
3
4
  "record_locks.banner.contention_notice": "Ein anderer Benutzer hat diesen Datensatz geöffnet, während Sie ihn bearbeiten. Beim Speichern können Konflikte auftreten.",
4
5
  "record_locks.banner.local_machine": "lokaler Rechner",
@@ -1,4 +1,5 @@
1
1
  {
2
+ "notifications.categories.record_locks": "Record locking",
2
3
  "record_locks.banner.active_users_label": "Active users",
3
4
  "record_locks.banner.contention_notice": "Another user opened this record while you are editing it. Conflicts may occur on save.",
4
5
  "record_locks.banner.local_machine": "local machine",
@@ -1,4 +1,5 @@
1
1
  {
2
+ "notifications.categories.record_locks": "Bloqueo de registros",
2
3
  "record_locks.banner.active_users_label": "Active users",
3
4
  "record_locks.banner.contention_notice": "Otro usuario abrió este registro mientras lo estás editando. Puede haber conflictos al guardar.",
4
5
  "record_locks.banner.local_machine": "equipo local",
@@ -1,4 +1,5 @@
1
1
  {
2
+ "notifications.categories.record_locks": "레코드 잠금",
2
3
  "record_locks.banner.active_users_label": "활성 사용자",
3
4
  "record_locks.banner.contention_notice": "다른 사용자가 이 레코드를 편집 중에 열었습니다. 저장 시 충돌이 발생할 수 있습니다.",
4
5
  "record_locks.banner.local_machine": "로컬 기기",
@@ -1,4 +1,5 @@
1
1
  {
2
+ "notifications.categories.record_locks": "Blokowanie rekordów",
2
3
  "record_locks.banner.active_users_label": "Aktywni użytkownicy",
3
4
  "record_locks.banner.contention_notice": "Inny użytkownik otworzył ten rekord, gdy go edytujesz. Przy zapisie może wystąpić konflikt.",
4
5
  "record_locks.banner.local_machine": "lokalna maszyna",
@@ -2,6 +2,7 @@ const notificationTypes = [
2
2
  {
3
3
  type: "security.password.changed",
4
4
  module: "security",
5
+ category: "auth",
5
6
  channels: ["in_app", "email"],
6
7
  titleKey: "security.notifications.passwordChanged.title",
7
8
  bodyKey: "security.notifications.passwordChanged.body",
@@ -22,6 +23,7 @@ const notificationTypes = [
22
23
  {
23
24
  type: "security.mfa.enrolled",
24
25
  module: "security",
26
+ category: "auth",
25
27
  channels: ["in_app", "email"],
26
28
  titleKey: "security.notifications.mfaEnrolled.title",
27
29
  bodyKey: "security.notifications.mfaEnrolled.body",
@@ -42,6 +44,7 @@ const notificationTypes = [
42
44
  {
43
45
  type: "security.mfa.reset",
44
46
  module: "security",
47
+ category: "auth",
45
48
  channels: ["in_app", "email"],
46
49
  titleKey: "security.notifications.mfaReset.title",
47
50
  bodyKey: "security.notifications.mfaReset.body",
@@ -62,6 +65,7 @@ const notificationTypes = [
62
65
  {
63
66
  type: "security.mfa.enforcement_deadline",
64
67
  module: "security",
68
+ category: "auth",
65
69
  channels: ["in_app", "email"],
66
70
  titleKey: "security.notifications.enforcementDeadline.title",
67
71
  bodyKey: "security.notifications.enforcementDeadline.bodyImmediate",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/security/notifications.ts"],
4
- "sourcesContent": ["import type { NotificationTypeDefinition } from '@open-mercato/shared/modules/notifications/types'\n\nexport const notificationTypes: NotificationTypeDefinition[] = [\n {\n type: 'security.password.changed',\n module: 'security',\n channels: ['in_app', 'email'],\n titleKey: 'security.notifications.passwordChanged.title',\n bodyKey: 'security.notifications.passwordChanged.body',\n icon: 'key-round',\n severity: 'success',\n actions: [\n {\n id: 'open_security_settings',\n labelKey: 'common.view',\n variant: 'outline',\n href: '/backend/profile/security',\n icon: 'external-link',\n },\n ],\n linkHref: '/backend/profile/security',\n expiresAfterHours: 168,\n },\n {\n type: 'security.mfa.enrolled',\n module: 'security',\n channels: ['in_app', 'email'],\n titleKey: 'security.notifications.mfaEnrolled.title',\n bodyKey: 'security.notifications.mfaEnrolled.body',\n icon: 'shield-check',\n severity: 'success',\n actions: [\n {\n id: 'open_mfa_settings',\n labelKey: 'common.view',\n variant: 'outline',\n href: '/backend/profile/security/mfa',\n icon: 'external-link',\n },\n ],\n linkHref: '/backend/profile/security/mfa',\n expiresAfterHours: 168,\n },\n {\n type: 'security.mfa.reset',\n module: 'security',\n channels: ['in_app', 'email'],\n titleKey: 'security.notifications.mfaReset.title',\n bodyKey: 'security.notifications.mfaReset.body',\n icon: 'shield-alert',\n severity: 'warning',\n actions: [\n {\n id: 'open_mfa_settings',\n labelKey: 'common.view',\n variant: 'outline',\n href: '/backend/profile/security/mfa',\n icon: 'external-link',\n },\n ],\n linkHref: '/backend/profile/security/mfa',\n expiresAfterHours: 168,\n },\n {\n type: 'security.mfa.enforcement_deadline',\n module: 'security',\n channels: ['in_app', 'email'],\n titleKey: 'security.notifications.enforcementDeadline.title',\n bodyKey: 'security.notifications.enforcementDeadline.bodyImmediate',\n icon: 'clock-3',\n severity: 'warning',\n actions: [\n {\n id: 'open_mfa_settings',\n labelKey: 'common.view',\n variant: 'outline',\n href: '/backend/profile/security/mfa',\n icon: 'external-link',\n },\n ],\n linkHref: '/backend/profile/security/mfa',\n expiresAfterHours: 168,\n },\n]\n\nexport default notificationTypes\n"],
5
- "mappings": "AAEO,MAAM,oBAAkD;AAAA,EAC7D;AAAA,IACE,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,UAAU,CAAC,UAAU,OAAO;AAAA,IAC5B,UAAU;AAAA,IACV,SAAS;AAAA,IACT,MAAM;AAAA,IACN,UAAU;AAAA,IACV,SAAS;AAAA,MACP;AAAA,QACE,IAAI;AAAA,QACJ,UAAU;AAAA,QACV,SAAS;AAAA,QACT,MAAM;AAAA,QACN,MAAM;AAAA,MACR;AAAA,IACF;AAAA,IACA,UAAU;AAAA,IACV,mBAAmB;AAAA,EACrB;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,UAAU,CAAC,UAAU,OAAO;AAAA,IAC5B,UAAU;AAAA,IACV,SAAS;AAAA,IACT,MAAM;AAAA,IACN,UAAU;AAAA,IACV,SAAS;AAAA,MACP;AAAA,QACE,IAAI;AAAA,QACJ,UAAU;AAAA,QACV,SAAS;AAAA,QACT,MAAM;AAAA,QACN,MAAM;AAAA,MACR;AAAA,IACF;AAAA,IACA,UAAU;AAAA,IACV,mBAAmB;AAAA,EACrB;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,UAAU,CAAC,UAAU,OAAO;AAAA,IAC5B,UAAU;AAAA,IACV,SAAS;AAAA,IACT,MAAM;AAAA,IACN,UAAU;AAAA,IACV,SAAS;AAAA,MACP;AAAA,QACE,IAAI;AAAA,QACJ,UAAU;AAAA,QACV,SAAS;AAAA,QACT,MAAM;AAAA,QACN,MAAM;AAAA,MACR;AAAA,IACF;AAAA,IACA,UAAU;AAAA,IACV,mBAAmB;AAAA,EACrB;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,UAAU,CAAC,UAAU,OAAO;AAAA,IAC5B,UAAU;AAAA,IACV,SAAS;AAAA,IACT,MAAM;AAAA,IACN,UAAU;AAAA,IACV,SAAS;AAAA,MACP;AAAA,QACE,IAAI;AAAA,QACJ,UAAU;AAAA,QACV,SAAS;AAAA,QACT,MAAM;AAAA,QACN,MAAM;AAAA,MACR;AAAA,IACF;AAAA,IACA,UAAU;AAAA,IACV,mBAAmB;AAAA,EACrB;AACF;AAEA,IAAO,wBAAQ;",
4
+ "sourcesContent": ["import type { NotificationTypeDefinition } from '@open-mercato/shared/modules/notifications/types'\n\nexport const notificationTypes: NotificationTypeDefinition[] = [\n {\n type: 'security.password.changed',\n module: 'security',\n category: 'auth',\n channels: ['in_app', 'email'],\n titleKey: 'security.notifications.passwordChanged.title',\n bodyKey: 'security.notifications.passwordChanged.body',\n icon: 'key-round',\n severity: 'success',\n actions: [\n {\n id: 'open_security_settings',\n labelKey: 'common.view',\n variant: 'outline',\n href: '/backend/profile/security',\n icon: 'external-link',\n },\n ],\n linkHref: '/backend/profile/security',\n expiresAfterHours: 168,\n },\n {\n type: 'security.mfa.enrolled',\n module: 'security',\n category: 'auth',\n channels: ['in_app', 'email'],\n titleKey: 'security.notifications.mfaEnrolled.title',\n bodyKey: 'security.notifications.mfaEnrolled.body',\n icon: 'shield-check',\n severity: 'success',\n actions: [\n {\n id: 'open_mfa_settings',\n labelKey: 'common.view',\n variant: 'outline',\n href: '/backend/profile/security/mfa',\n icon: 'external-link',\n },\n ],\n linkHref: '/backend/profile/security/mfa',\n expiresAfterHours: 168,\n },\n {\n type: 'security.mfa.reset',\n module: 'security',\n category: 'auth',\n channels: ['in_app', 'email'],\n titleKey: 'security.notifications.mfaReset.title',\n bodyKey: 'security.notifications.mfaReset.body',\n icon: 'shield-alert',\n severity: 'warning',\n actions: [\n {\n id: 'open_mfa_settings',\n labelKey: 'common.view',\n variant: 'outline',\n href: '/backend/profile/security/mfa',\n icon: 'external-link',\n },\n ],\n linkHref: '/backend/profile/security/mfa',\n expiresAfterHours: 168,\n },\n {\n type: 'security.mfa.enforcement_deadline',\n module: 'security',\n category: 'auth',\n channels: ['in_app', 'email'],\n titleKey: 'security.notifications.enforcementDeadline.title',\n bodyKey: 'security.notifications.enforcementDeadline.bodyImmediate',\n icon: 'clock-3',\n severity: 'warning',\n actions: [\n {\n id: 'open_mfa_settings',\n labelKey: 'common.view',\n variant: 'outline',\n href: '/backend/profile/security/mfa',\n icon: 'external-link',\n },\n ],\n linkHref: '/backend/profile/security/mfa',\n expiresAfterHours: 168,\n },\n]\n\nexport default notificationTypes\n"],
5
+ "mappings": "AAEO,MAAM,oBAAkD;AAAA,EAC7D;AAAA,IACE,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,UAAU,CAAC,UAAU,OAAO;AAAA,IAC5B,UAAU;AAAA,IACV,SAAS;AAAA,IACT,MAAM;AAAA,IACN,UAAU;AAAA,IACV,SAAS;AAAA,MACP;AAAA,QACE,IAAI;AAAA,QACJ,UAAU;AAA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@
1
- var _a, _b;
1
+ var _a, _b, _c, _d;
2
2
  const EMAIL_NOT_VERIFIED_ERROR_MARKER = /* @__PURE__ */ Symbol.for("@open-mercato/sso/EmailNotVerifiedError");
3
3
  class EmailNotVerifiedError extends (_b = Error, _a = EMAIL_NOT_VERIFIED_ERROR_MARKER, _b) {
4
4
  constructor(message, options) {
@@ -10,12 +10,26 @@ class EmailNotVerifiedError extends (_b = Error, _a = EMAIL_NOT_VERIFIED_ERROR_M
10
10
  function isEmailNotVerifiedError(err) {
11
11
  return !!err && typeof err === "object" && err[EMAIL_NOT_VERIFIED_ERROR_MARKER] === true;
12
12
  }
13
+ const SSO_ROLES_REVOKED_ERROR_MARKER = /* @__PURE__ */ Symbol.for("@open-mercato/sso/SsoRolesRevokedError");
14
+ class SsoRolesRevokedError extends (_d = Error, _c = SSO_ROLES_REVOKED_ERROR_MARKER, _d) {
15
+ constructor(userId, message) {
16
+ super(message);
17
+ this.userId = userId;
18
+ this[_c] = true;
19
+ this.name = "SsoRolesRevokedError";
20
+ }
21
+ }
22
+ function isSsoRolesRevokedError(err) {
23
+ return !!err && typeof err === "object" && err[SSO_ROLES_REVOKED_ERROR_MARKER] === true;
24
+ }
13
25
  function resolveSsoCallbackErrorCode(err) {
14
26
  return isEmailNotVerifiedError(err) ? "sso_email_not_verified" : "sso_failed";
15
27
  }
16
28
  export {
17
29
  EmailNotVerifiedError,
30
+ SsoRolesRevokedError,
18
31
  isEmailNotVerifiedError,
32
+ isSsoRolesRevokedError,
19
33
  resolveSsoCallbackErrorCode
20
34
  };
21
35
  //# sourceMappingURL=errors.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/sso/lib/errors.ts"],
4
- "sourcesContent": ["// Use Symbol.for so the marker survives module duplication across bundle\n// boundaries: the OIDC callback route and the account-linking service can be\n// bundled into separate chunks where `instanceof` silently returns false\n// (same rationale as isCrudHttpError in @open-mercato/shared).\nconst EMAIL_NOT_VERIFIED_ERROR_MARKER = Symbol.for('@open-mercato/sso/EmailNotVerifiedError')\n\nexport class EmailNotVerifiedError extends Error {\n readonly [EMAIL_NOT_VERIFIED_ERROR_MARKER] = true\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options)\n this.name = 'EmailNotVerifiedError'\n }\n}\n\n/**\n * Type-safe check that works across module/bundle boundaries. Prefer this over\n * `instanceof EmailNotVerifiedError` because the SSO callback route may be\n * bundled separately from the service that throws the error.\n */\nexport function isEmailNotVerifiedError(err: unknown): err is EmailNotVerifiedError {\n return !!err && typeof err === 'object' && (err as Record<symbol, unknown>)[EMAIL_NOT_VERIFIED_ERROR_MARKER] === true\n}\n\nexport type SsoCallbackErrorCode = 'sso_email_not_verified' | 'sso_failed'\n\n/**\n * Maps an error thrown during the OIDC callback to the login-page UX error code.\n * Keyed off the error type rather than a substring of the human-readable message,\n * which previously drifted out of sync and left `sso_email_not_verified`\n * unreachable (#2741).\n */\nexport function resolveSsoCallbackErrorCode(err: unknown): SsoCallbackErrorCode {\n return isEmailNotVerifiedError(err) ? 'sso_email_not_verified' : 'sso_failed'\n}\n"],
5
- "mappings": "AAAA;AAIA,MAAM,kCAAkC,uBAAO,IAAI,yCAAyC;AAErF,MAAM,+BAA8B,YAC/B,sCAD+B,IAAM;AAAA,EAG/C,YAAY,SAAiB,SAA+B;AAC1D,UAAM,SAAS,OAAO;AAHxB,SAAU,MAAmC;AAI3C,SAAK,OAAO;AAAA,EACd;AACF;AAOO,SAAS,wBAAwB,KAA4C;AAClF,SAAO,CAAC,CAAC,OAAO,OAAO,QAAQ,YAAa,IAAgC,+BAA+B,MAAM;AACnH;AAUO,SAAS,4BAA4B,KAAoC;AAC9E,SAAO,wBAAwB,GAAG,IAAI,2BAA2B;AACnE;",
4
+ "sourcesContent": ["// Use Symbol.for so the marker survives module duplication across bundle\n// boundaries: the OIDC callback route and the account-linking service can be\n// bundled into separate chunks where `instanceof` silently returns false\n// (same rationale as isCrudHttpError in @open-mercato/shared).\nconst EMAIL_NOT_VERIFIED_ERROR_MARKER = Symbol.for('@open-mercato/sso/EmailNotVerifiedError')\n\nexport class EmailNotVerifiedError extends Error {\n readonly [EMAIL_NOT_VERIFIED_ERROR_MARKER] = true\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options)\n this.name = 'EmailNotVerifiedError'\n }\n}\n\n/**\n * Type-safe check that works across module/bundle boundaries. Prefer this over\n * `instanceof EmailNotVerifiedError` because the SSO callback route may be\n * bundled separately from the service that throws the error.\n */\nexport function isEmailNotVerifiedError(err: unknown): err is EmailNotVerifiedError {\n return !!err && typeof err === 'object' && (err as Record<symbol, unknown>)[EMAIL_NOT_VERIFIED_ERROR_MARKER] === true\n}\n\nconst SSO_ROLES_REVOKED_ERROR_MARKER = Symbol.for('@open-mercato/sso/SsoRolesRevokedError')\n\n/**\n * Login denial raised after the IdP resolved no mapped roles. The revoked SSO\n * grants are already committed; `userId` lets the caller drop cached RBAC for\n * sessions that still hold the revoked roles.\n */\nexport class SsoRolesRevokedError extends Error {\n readonly [SSO_ROLES_REVOKED_ERROR_MARKER] = true\n\n constructor(readonly userId: string, message: string) {\n super(message)\n this.name = 'SsoRolesRevokedError'\n }\n}\n\nexport function isSsoRolesRevokedError(err: unknown): err is SsoRolesRevokedError {\n return !!err && typeof err === 'object' && (err as Record<symbol, unknown>)[SSO_ROLES_REVOKED_ERROR_MARKER] === true\n}\n\nexport type SsoCallbackErrorCode = 'sso_email_not_verified' | 'sso_failed'\n\n/**\n * Maps an error thrown during the OIDC callback to the login-page UX error code.\n * Keyed off the error type rather than a substring of the human-readable message,\n * which previously drifted out of sync and left `sso_email_not_verified`\n * unreachable (#2741).\n */\nexport function resolveSsoCallbackErrorCode(err: unknown): SsoCallbackErrorCode {\n return isEmailNotVerifiedError(err) ? 'sso_email_not_verified' : 'sso_failed'\n}\n"],
5
+ "mappings": "AAAA;AAIA,MAAM,kCAAkC,uBAAO,IAAI,yCAAyC;AAErF,MAAM,+BAA8B,YAC/B,sCAD+B,IAAM;AAAA,EAG/C,YAAY,SAAiB,SAA+B;AAC1D,UAAM,SAAS,OAAO;AAHxB,SAAU,MAAmC;AAI3C,SAAK,OAAO;AAAA,EACd;AACF;AAOO,SAAS,wBAAwB,KAA4C;AAClF,SAAO,CAAC,CAAC,OAAO,OAAO,QAAQ,YAAa,IAAgC,+BAA+B,MAAM;AACnH;AAEA,MAAM,iCAAiC,uBAAO,IAAI,wCAAwC;AAOnF,MAAM,8BAA6B,YAC9B,qCAD8B,IAAM;AAAA,EAG9C,YAAqB,QAAgB,SAAiB;AACpD,UAAM,OAAO;AADM;AAFrB,SAAU,MAAkC;AAI1C,SAAK,OAAO;AAAA,EACd;AACF;AAEO,SAAS,uBAAuB,KAA2C;AAChF,SAAO,CAAC,CAAC,OAAO,OAAO,QAAQ,YAAa,IAAgC,8BAA8B,MAAM;AAClH;AAUO,SAAS,4BAA4B,KAAoC;AAC9E,SAAO,wBAAwB,GAAG,IAAI,2BAA2B;AACnE;",
6
6
  "names": []
7
7
  }
@@ -3,8 +3,10 @@ import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find"
3
3
  import { computeEmailHash } from "@open-mercato/core/modules/auth/lib/emailHash";
4
4
  import { SsoIdentity, SsoRoleGrant, ScimToken } from "../data/entities.js";
5
5
  import { emitSsoEvent } from "../events.js";
6
- import { EmailNotVerifiedError } from "../lib/errors.js";
6
+ import { EmailNotVerifiedError, SsoRolesRevokedError } from "../lib/errors.js";
7
7
  import { createLogger } from "@open-mercato/shared/lib/logger";
8
+ import { conflict } from "@open-mercato/shared/lib/crud/errors";
9
+ import { lockUserRoleWriterAuthorizationState } from "@open-mercato/core/modules/auth/lib/authorizationStateLocks";
8
10
  const logger = createLogger("sso").child({ component: "account-linking" });
9
11
  class AccountLinkingService {
10
12
  constructor(em) {
@@ -145,13 +147,21 @@ class AccountLinkingService {
145
147
  async assignRolesFromSso(em, user, config, tenantId, idpGroups) {
146
148
  const hasMappings = config.appRoleMappings && Object.keys(config.appRoleMappings).length > 0;
147
149
  if (!hasMappings) return;
148
- await this.syncMappedRoles(em, user, config, tenantId, idpGroups);
149
- const hasAnySsoRole = await em.findOne(SsoRoleGrant, {
150
- userId: user.id,
151
- ssoConfigId: config.id
152
- });
150
+ const synchronize = async (transactionalEm) => {
151
+ const managedUser = typeof transactionalEm.getReference === "function" ? transactionalEm.getReference(User, String(user.id)) : user;
152
+ await this.syncMappedRoles(transactionalEm, managedUser, config, tenantId, idpGroups);
153
+ const remainingGrant = await transactionalEm.findOne(SsoRoleGrant, {
154
+ userId: user.id,
155
+ ssoConfigId: config.id
156
+ });
157
+ return remainingGrant !== null;
158
+ };
159
+ const hasAnySsoRole = typeof em.isInTransaction === "function" && em.isInTransaction() ? await synchronize(em) : await em.transactional(synchronize);
153
160
  if (!hasAnySsoRole) {
154
- throw new Error("No roles could be resolved from IdP groups \u2014 login denied. Configure role mappings or ensure the IdP sends matching group claims.");
161
+ throw new SsoRolesRevokedError(
162
+ String(user.id),
163
+ "No roles could be resolved from IdP groups \u2014 login denied. Configure role mappings or ensure the IdP sends matching group claims."
164
+ );
155
165
  }
156
166
  }
157
167
  /**
@@ -161,25 +171,49 @@ class AccountLinkingService {
161
171
  async syncMappedRoles(em, user, config, tenantId, idpGroups) {
162
172
  const resolvedTenantId = tenantId || user.tenantId || "";
163
173
  if (!resolvedTenantId) return;
164
- const allRoles = await em.find(Role, { tenantId: resolvedTenantId, deletedAt: null });
165
- const roleByNormalizedName = /* @__PURE__ */ new Map();
166
- for (const role of allRoles) {
167
- const normalized = normalizeToken(role.name);
168
- if (normalized) roleByNormalizedName.set(normalized, role);
169
- }
170
174
  const desiredRoleNames = resolveRoleNamesFromIdpGroups(idpGroups, config.appRoleMappings);
171
- const desiredRoleIds = /* @__PURE__ */ new Set();
172
- for (const roleName of desiredRoleNames) {
173
- const role = roleByNormalizedName.get(roleName);
174
- if (role) desiredRoleIds.add(role.id);
175
- }
176
- const existingGrants = await em.find(SsoRoleGrant, {
175
+ let allRoles = await em.find(Role, {
176
+ tenantId: resolvedTenantId,
177
+ deletedAt: null
178
+ });
179
+ let desiredRoleIds = resolveActiveRoleIds(allRoles, desiredRoleNames);
180
+ let existingGrants = await em.find(SsoRoleGrant, {
177
181
  userId: user.id,
178
182
  ssoConfigId: config.id
179
183
  });
184
+ let allUserRoles = await em.find(UserRole, { user: user.id });
185
+ const lockedRoleIds = /* @__PURE__ */ new Set([
186
+ ...desiredRoleIds,
187
+ ...existingGrants.map((grant) => grant.roleId),
188
+ ...allUserRoles.filter((userRole) => userRole.deletedAt).map((userRole) => String(userRole.role?.id ?? userRole.role))
189
+ ]);
190
+ await lockUserRoleWriterAuthorizationState(em, {
191
+ userIds: [String(user.id)],
192
+ roleIds: Array.from(lockedRoleIds)
193
+ });
194
+ allRoles = await em.find(Role, {
195
+ tenantId: resolvedTenantId,
196
+ deletedAt: null
197
+ }, { refresh: true });
198
+ existingGrants = await em.find(SsoRoleGrant, {
199
+ userId: user.id,
200
+ ssoConfigId: config.id
201
+ }, { refresh: true });
202
+ allUserRoles = await em.find(
203
+ UserRole,
204
+ { user: user.id },
205
+ { refresh: true }
206
+ );
207
+ desiredRoleIds = resolveActiveRoleIds(allRoles, desiredRoleNames);
180
208
  const existingGrantedRoleIds = new Set(existingGrants.map((g) => g.roleId));
181
209
  const toAdd = [...desiredRoleIds].filter((id) => !existingGrantedRoleIds.has(id));
182
210
  const toRemove = existingGrants.filter((g) => !desiredRoleIds.has(g.roleId));
211
+ const softDeletedUserRoles = allUserRoles.filter((userRole) => userRole.deletedAt);
212
+ assertRoleMutationFootprintWasLocked([
213
+ ...desiredRoleIds,
214
+ ...toRemove.map((grant) => grant.roleId),
215
+ ...softDeletedUserRoles.map((userRole) => String(userRole.role?.id ?? userRole.role))
216
+ ], lockedRoleIds);
183
217
  for (const roleId of toAdd) {
184
218
  const role = allRoles.find((r) => r.id === roleId);
185
219
  if (!role) continue;
@@ -204,13 +238,10 @@ class AccountLinkingService {
204
238
  }
205
239
  em.remove(grant);
206
240
  }
207
- const allUserRoles = await em.find(UserRole, { user: user.id });
208
- for (const ur of allUserRoles) {
209
- if (ur.deletedAt) {
210
- em.remove(ur);
211
- }
241
+ for (const userRole of softDeletedUserRoles) {
242
+ em.remove(userRole);
212
243
  }
213
- if (toAdd.length > 0 || toRemove.length > 0 || allUserRoles.some((ur) => ur.deletedAt)) {
244
+ if (toAdd.length > 0 || toRemove.length > 0 || softDeletedUserRoles.length > 0) {
214
245
  await em.flush();
215
246
  }
216
247
  }
@@ -222,8 +253,28 @@ class AccountLinkingService {
222
253
  });
223
254
  if (existingLink) return;
224
255
  const userRole = em.create(UserRole, { user, role, createdAt: /* @__PURE__ */ new Date() });
225
- await em.persist(userRole).flush();
256
+ em.persist(userRole);
257
+ }
258
+ }
259
+ function assertRoleMutationFootprintWasLocked(roleIds, lockedRoleIds) {
260
+ for (const roleId of roleIds) {
261
+ if (!lockedRoleIds.has(roleId)) {
262
+ throw conflict("[internal] Authorization state changed while acquiring its lock footprint");
263
+ }
264
+ }
265
+ }
266
+ function resolveActiveRoleIds(roles, desiredRoleNames) {
267
+ const roleByNormalizedName = /* @__PURE__ */ new Map();
268
+ for (const role of roles) {
269
+ const normalized = normalizeToken(role.name);
270
+ if (normalized) roleByNormalizedName.set(normalized, role);
271
+ }
272
+ const desiredRoleIds = /* @__PURE__ */ new Set();
273
+ for (const roleName of desiredRoleNames) {
274
+ const role = roleByNormalizedName.get(roleName);
275
+ if (role) desiredRoleIds.add(role.id);
226
276
  }
277
+ return desiredRoleIds;
227
278
  }
228
279
  function resolveRoleNamesFromIdpGroups(idpGroups, configMappings) {
229
280
  if (!Array.isArray(idpGroups) || idpGroups.length === 0) return [];