@open-mercato/core 0.10.1-develop.7767.2.440f7c2b4c → 0.10.1-develop.7769.1.0e6458bb99
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.
- package/dist/modules/api_keys/data/entities.js.map +1 -1
- package/dist/modules/api_keys/services/apiKeyService.js +1 -0
- package/dist/modules/api_keys/services/apiKeyService.js.map +2 -2
- package/dist/modules/auth/lib/authorizationStateLocks.js +13 -5
- package/dist/modules/auth/lib/authorizationStateLocks.js.map +2 -2
- package/dist/modules/auth/services/rbacService.js +68 -11
- package/dist/modules/auth/services/rbacService.js.map +2 -2
- package/dist/modules/directory/utils/organizationScope.js +6 -3
- package/dist/modules/directory/utils/organizationScope.js.map +2 -2
- package/dist/modules/notifications/lib/notificationService.js +19 -1
- package/dist/modules/notifications/lib/notificationService.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/api_keys/data/entities.ts +1 -1
- package/src/modules/api_keys/services/apiKeyService.ts +2 -0
- package/src/modules/auth/lib/authorizationStateLocks.ts +13 -7
- package/src/modules/auth/services/rbacService.ts +86 -9
- package/src/modules/directory/utils/organizationScope.ts +6 -3
- package/src/modules/notifications/lib/notificationService.ts +24 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/directory/utils/organizationScope.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { FilterQuery } from '@mikro-orm/core'\nimport type { AwilixContainer } from 'awilix'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { ApiKey } from '@open-mercato/core/modules/api_keys/data/entities'\nimport { isSessionBoundApiKey } from '@open-mercato/core/modules/api_keys/services/sessionKeyRoles'\nimport { isAllOrganizationsSelection } from '@open-mercato/core/modules/directory/constants'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport type { OrganizationScope } from '@open-mercato/shared/lib/auth/principal-service'\nimport { getCurrentCacheTenant, runWithCacheTenant, type CacheStrategy } from '@open-mercato/cache'\nimport { parseSelectedOrganizationCookie, parseSelectedTenantCookie } from './scopeCookies'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('directory').child({ component: 'org-scope-cache' })\n\nexport { parseSelectedOrganizationCookie, parseSelectedTenantCookie }\n\nexport type { OrganizationScope }\n\n// Phase 4 \u2014 short-TTL cache for resolveOrganizationScopeForRequest.\n// OrganizationScope is a pure function of (userId, tenantId, selectedOrgId,\n// requestedTenant) between membership changes; caching it bypasses 1\n// SELECT on `organizations` per CRUD request. TTL is short (60s default)\n// to keep staleness bounded as a backstop. Tag-based invalidation also fires\n// eagerly: per-user entries are dropped by RbacService.invalidateUserCache\n// (every ACL/role grant change goes through it \u2014 see buildOrgScopeUserCacheTag)\n// and per-tenant entries by the directory.organization.* subscriber plus\n// RbacService.invalidateTenantCache (role-ACL changes).\nconst ORG_SCOPE_CACHE_KEY_PREFIX = 'org-scope:v2'\n// Phase 4 default-off until the same readiness probe (`GET /api/customers/people`)\n// stays green with the cache layer engaged. Set `OM_ORG_SCOPE_CACHE_TTL_MS=60000`\n// (or any positive integer) to opt in once cross-request safety is re-verified.\nconst ORG_SCOPE_DEFAULT_TTL_MS = 0\n\nfunction resolveOrgScopeTtlMs(): number {\n const raw = process.env.OM_ORG_SCOPE_CACHE_TTL_MS\n if (raw === undefined) return ORG_SCOPE_DEFAULT_TTL_MS\n const parsed = Number(raw)\n if (!Number.isFinite(parsed) || parsed < 0) return ORG_SCOPE_DEFAULT_TTL_MS\n return parsed\n}\n\nfunction buildOrgScopeCacheKey(parts: {\n userId: string\n effectiveTenantId: string\n selectedOrgId: string | null\n requestedTenantId: string | null\n}): string {\n const selected = parts.selectedOrgId ?? 'none'\n const requested = parts.requestedTenantId ?? 'none'\n return `${ORG_SCOPE_CACHE_KEY_PREFIX}:${parts.userId}:${parts.effectiveTenantId}:${selected}:${requested}`\n}\n\n// Tag builders are exported so the modules that own the \"this user's scope\n// changed\" / \"this tenant's org tree changed\" signals (auth RBAC invalidation,\n// the directory.organization.* subscriber) can drop the matching cross-request\n// cache entries without re-deriving the tag format. Keeping the format in one\n// place is what lets the TTL be enabled safely (issue #2259).\nexport function buildOrgScopeUserCacheTag(userId: string): string {\n return `${ORG_SCOPE_CACHE_KEY_PREFIX}:user:${userId}`\n}\n\nexport function buildOrgScopeTenantCacheTag(tenantId: string): string {\n return `${ORG_SCOPE_CACHE_KEY_PREFIX}:tenant:${tenantId}`\n}\n\nfunction buildOrgScopeCacheTags(parts: { userId: string; effectiveTenantId: string }): string[] {\n return [\n buildOrgScopeUserCacheTag(parts.userId),\n buildOrgScopeTenantCacheTag(parts.effectiveTenantId),\n ]\n}\n\nfunction isValidCachedScope(value: unknown): value is OrganizationScope {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<OrganizationScope>\n const idOk = (v: unknown) => v === null || typeof v === 'string'\n const arrOk = (v: unknown) => v === null || (Array.isArray(v) && v.every((entry) => typeof entry === 'string'))\n const flagOk = record.selectionRejected === undefined || typeof record.selectionRejected === 'boolean'\n return idOk(record.selectedId) && idOk(record.tenantId) && arrOk(record.filterIds) && arrOk(record.allowedIds) && flagOk\n}\n\nfunction resolveCacheFromContainer(container: AwilixContainer | null | undefined): CacheStrategy | null {\n if (!container) return null\n try {\n const c = container.resolve('cache') as CacheStrategy | undefined\n if (c && typeof c.get === 'function' && typeof c.set === 'function') return c\n } catch {\n return null\n }\n return null\n}\n\nexport async function invalidateOrganizationScopeCacheForUser(\n container: AwilixContainer,\n userId: string,\n tenantId?: string | null,\n): Promise<void> {\n const cache = resolveCacheFromContainer(container)\n if (!cache?.deleteByTags) return\n try {\n const cacheTenantId = tenantId === undefined ? getCurrentCacheTenant() : tenantId\n await runWithCacheTenant(cacheTenantId, () =>\n cache.deleteByTags([buildOrgScopeUserCacheTag(userId)]),\n )\n } catch (err) {\n logger.warn('Cache invalidate user failed', { err })\n }\n}\n\nexport async function invalidateOrganizationScopeCacheForTenant(\n container: AwilixContainer,\n tenantId: string,\n): Promise<void> {\n const cache = resolveCacheFromContainer(container)\n if (!cache?.deleteByTags) return\n try {\n await runWithCacheTenant(tenantId, () =>\n cache.deleteByTags([buildOrgScopeTenantCacheTag(tenantId)]),\n )\n } catch (err) {\n logger.warn('Cache invalidate tenant failed', { err })\n }\n}\n\n// Issue #2259 \u2014 per-request memoization. resolveOrganizationScopeForRequest\n// runs at least twice per CRUD request: once for the route-level feature check\n// (resolveFeatureCheckContext) and once inside the shared factory's withCtx.\n// Those two call sites use different request-scoped DI containers but are handed\n// the SAME Request instance, so memoizing the resolved scope on a WeakMap keyed\n// by that request collapses the duplicate work \u2014 and the duplicate\n// `organizations` SELECT \u2014 into a single resolution. The inner map is keyed by\n// the same identity tuple as the cross-request cache key, so distinct explicit\n// selectedId/tenant overrides on one request stay independent. There is no\n// staleness risk: the memo lives only for the lifetime of one request and is\n// dropped with the request object by the GC.\nconst orgScopeRequestMemo = new WeakMap<object, Map<string, Promise<OrganizationScope>>>()\n\ntype BoundFeatureScope = {\n userId: string\n scope: OrganizationScope\n organizationId: string | null\n}\n\nconst featureScopeRequestMemo = new WeakMap<object, BoundFeatureScope>()\n\nfunction getRequestScopeMemo(request: unknown): Map<string, Promise<OrganizationScope>> | null {\n if (!request || (typeof request !== 'object' && typeof request !== 'function')) return null\n const key = request as object\n let memo = orgScopeRequestMemo.get(key)\n if (!memo) {\n memo = new Map<string, Promise<OrganizationScope>>()\n orgScopeRequestMemo.set(key, memo)\n }\n return memo\n}\n\nfunction bindFeatureScopeToRequest(request: unknown, binding: BoundFeatureScope): void {\n if (!request || (typeof request !== 'object' && typeof request !== 'function')) return\n featureScopeRequestMemo.set(request as object, binding)\n}\n\nfunction getFeatureScopeForRequest(\n request: unknown,\n userId: string,\n tenantOverride: string | null | undefined,\n): BoundFeatureScope | null {\n if (!request || (typeof request !== 'object' && typeof request !== 'function')) return null\n const entry = featureScopeRequestMemo.get(request as object)\n if (!entry || entry.userId !== userId) return null\n if (tenantOverride === undefined) return entry\n const requestedTenantId = typeof tenantOverride === 'string' ? tenantOverride.trim() : ''\n return requestedTenantId.length > 0 && requestedTenantId === entry.scope.tenantId ? entry : null\n}\n\nfunction normalizeOrganizationId(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : null\n}\n\nexport function getSelectedOrganizationFromRequest(req: Request | { cookies?: { get: (name: string) => { value: string } | undefined }; headers?: { get(name: string): string | null } }): string | null {\n const cookieContainer = (req as { cookies?: { get: (name: string) => { value: string } | undefined } }).cookies\n if (cookieContainer && typeof cookieContainer.get === 'function') {\n const val = cookieContainer.get('om_selected_org')?.value\n return val ?? null\n }\n const headerContainer = (req as { headers?: { get(name: string): string | null } }).headers\n const header = typeof headerContainer?.get === 'function' ? headerContainer.get('cookie') : null\n return parseSelectedOrganizationCookie(header)\n}\n\nexport function getSelectedTenantFromRequest(\n req: Request | { cookies?: { get: (name: string) => { value: string } | undefined }; headers?: { get(name: string): string | null } },\n): string | null {\n const cookieContainer = (req as { cookies?: { get: (name: string) => { value: string } | undefined } }).cookies\n if (cookieContainer && typeof cookieContainer.get === 'function') {\n const val = cookieContainer.get('om_selected_tenant')?.value\n return val ?? null\n }\n const headerContainer = (req as { headers?: { get(name: string): string | null } }).headers\n const header = typeof headerContainer?.get === 'function' ? headerContainer.get('cookie') : null\n return parseSelectedTenantCookie(header)\n}\n\nfunction normalizeOrganizationIds(ids: string[]): string[] {\n return Array.from(new Set(\n ids.map((value) => normalizeOrganizationId(value)).filter((value): value is string => {\n if (!value) return false\n if (isAllOrganizationsSelection(value)) return false\n return true\n })\n ))\n}\n\n// Map each organization id to itself plus its persisted descendant ids. Only\n// orgs that exist for the tenant and are not soft-deleted are included, so an\n// unknown/inaccessible id simply has no entry (matching the per-id query that\n// returned an empty set for it).\ntype OrgDescendantMap = Map<string, string[]>\n\n// Issue #2228 \u2014 single round-trip for org-scope resolution. Instead of issuing\n// one `organizations` SELECT per `collectWithDescendants` call (up to 3-4\n// sequential queries per request: accessible set, fallback set, selected set),\n// gather every candidate id up front and fetch their descendant expansions in\n// one `em.find(Organization, { id: $in })`. Expansion then happens in-memory.\nasync function loadOrgDescendantMap(em: EntityManager, tenantId: string, ids: string[]): Promise<OrgDescendantMap> {\n const unique = normalizeOrganizationIds(ids)\n if (!unique.length) return new Map()\n const filter: FilterQuery<Organization> = {\n tenant: tenantId,\n id: { $in: unique },\n deletedAt: null,\n }\n const orgs = await em.find(Organization, filter)\n const map: OrgDescendantMap = new Map()\n for (const org of orgs) {\n const id = String(org.id)\n const expansion = [id]\n if (Array.isArray(org.descendantIds)) {\n for (const desc of org.descendantIds) expansion.push(String(desc))\n }\n map.set(id, expansion)\n }\n return map\n}\n\nfunction expandWithDescendants(map: OrgDescendantMap, ids: string[]): Set<string> {\n const set = new Set<string>()\n for (const value of ids) {\n const id = normalizeOrganizationId(value)\n if (!id || isAllOrganizationsSelection(id)) continue\n const expansion = map.get(id)\n if (!expansion) continue\n for (const entry of expansion) set.add(entry)\n }\n return set\n}\n\nexport async function resolveOrganizationScope({\n em,\n rbac,\n auth,\n selectedId,\n tenantId: tenantIdOverride,\n}: {\n em: EntityManager\n rbac: Pick<RbacService, 'loadAcl'>\n auth: AuthContext | null | undefined\n selectedId?: string | null\n tenantId?: string | null\n}): Promise<OrganizationScope> {\n if (!auth || !auth.sub) {\n return { selectedId: null, filterIds: null, allowedIds: null, tenantId: null }\n }\n const actorTenantId = typeof auth.tenantId === 'string' && auth.tenantId.trim().length > 0 ? auth.tenantId.trim() : null\n const candidateTenantId = typeof tenantIdOverride === 'string' && tenantIdOverride.trim().length > 0\n ? tenantIdOverride.trim()\n : tenantIdOverride === null\n ? null\n : actorTenantId\n if (!candidateTenantId) {\n return { selectedId: null, filterIds: null, allowedIds: null, tenantId: null }\n }\n const usingOverride = candidateTenantId !== actorTenantId\n const isSuperAdminActor = auth.isSuperAdmin === true\n const tenantId = usingOverride && actorTenantId && !isSuperAdminActor ? actorTenantId : candidateTenantId\n if (!tenantId) {\n return { selectedId: null, filterIds: null, allowedIds: null, tenantId: null }\n }\n const normalizedRequestedSelection = normalizeOrganizationId(selectedId)\n const explicitAllOrgsChoice =\n normalizedRequestedSelection !== null && isAllOrganizationsSelection(normalizedRequestedSelection)\n const normalizedSelectedId = explicitAllOrgsChoice\n ? null\n : normalizedRequestedSelection\n const contextOrgId = actorTenantId && actorTenantId === tenantId ? normalizeOrganizationId(auth.orgId) : null\n const acl = await rbac.loadAcl(auth.sub, { tenantId, organizationId: contextOrgId })\n const aclIsSuperAdmin = acl?.isSuperAdmin === true\n const effectiveSuperAdmin = aclIsSuperAdmin || isSuperAdminActor\n const normalizedAccessible = effectiveSuperAdmin\n ? null\n : Array.isArray(acl?.organizations)\n ? acl.organizations\n .map((value) => normalizeOrganizationId(value))\n .filter((value): value is string => value !== null)\n : null\n const accessibleList = effectiveSuperAdmin\n ? null\n : normalizedAccessible && normalizedAccessible.some((value) => isAllOrganizationsSelection(value))\n ? null\n : normalizedAccessible?.filter((value) => !isAllOrganizationsSelection(value)) ?? null\n\n const accountOrgId = actorTenantId && actorTenantId === tenantId ? normalizeOrganizationId(auth.orgId) : null\n const fallbackOrgId = accountOrgId ?? null\n\n // Every id that could be expanded below \u2014 accessible set, fallback (account)\n // org, and the requested selection \u2014 is known up front, so fetch them all in\n // a single `organizations` query and expand from the in-memory map.\n const candidateIds = [\n ...(accessibleList ?? []),\n ...(fallbackOrgId ? [fallbackOrgId] : []),\n ...(normalizedSelectedId ? [normalizedSelectedId] : []),\n ]\n const orgDescendants = await loadOrgDescendantMap(em, tenantId, candidateIds)\n const loadFallbackSet = (): Set<string> | null =>\n fallbackOrgId ? expandWithDescendants(orgDescendants, [fallbackOrgId]) : null\n\n let allowedSet: Set<string> | null = null\n if (accessibleList === null) {\n allowedSet = null\n } else if (accessibleList.length === 0) {\n allowedSet = new Set()\n } else {\n allowedSet = expandWithDescendants(orgDescendants, accessibleList)\n }\n\n const hasUnrestrictedAccess = effectiveSuperAdmin || (accessibleList === null)\n const noOrgSelection = normalizedSelectedId === null && !explicitAllOrgsChoice\n const widenToAllOrgs =\n (explicitAllOrgsChoice && hasUnrestrictedAccess)\n || (effectiveSuperAdmin && noOrgSelection)\n const initialSelected =\n normalizedSelectedId\n ?? (widenToAllOrgs ? null : accountOrgId ?? null)\n // A selection is only honored when it resolves to a real, non-deleted org for\n // this tenant. `orgDescendants` holds exactly the existing orgs among the\n // candidate ids, so a stale/dead id (e.g. a selected-org cookie or JWT org\n // that no longer resolves after a DB reset) has no entry and is dropped here.\n // Without the existence guard an unrestricted (all-orgs) principal \u2014 whose\n // `allowedSet` is null \u2014 would accept the dead id as `effectiveSelected`, and\n // writes derived from `selectedId` would land under an org the read scope\n // (`filterIds`) never filters to, silently orphaning the record.\n const selectionResolvesToOrg = (id: string): boolean => orgDescendants.has(id)\n let effectiveSelected: string | null = null\n if (initialSelected) {\n if ((allowedSet === null || allowedSet.has(initialSelected)) && selectionResolvesToOrg(initialSelected)) {\n effectiveSelected = initialSelected\n }\n }\n\n let filterSet: Set<string> | null = null\n if (effectiveSelected) {\n filterSet = expandWithDescendants(orgDescendants, [effectiveSelected])\n } else if (allowedSet !== null) {\n filterSet = allowedSet\n } else if (widenToAllOrgs) {\n filterSet = null\n } else if (auth.orgId) {\n filterSet = loadFallbackSet()\n // Keep the write target (`selectedId`) aligned with the read scope\n // (`filterIds`): when an unrestricted principal's requested selection was\n // dropped above, fall the selection back to the account org too so a record\n // created here is always readable back by the same caller.\n if (!effectiveSelected && fallbackOrgId && filterSet && filterSet.size > 0) {\n effectiveSelected = fallbackOrgId\n }\n }\n\n if (allowedSet === null && (!filterSet || filterSet.size === 0) && fallbackOrgId && !widenToAllOrgs) {\n const computed = loadFallbackSet()\n if (computed && computed.size > 0) {\n filterSet = computed\n if (!effectiveSelected) {\n effectiveSelected = fallbackOrgId\n }\n }\n }\n\n // A concrete organization was explicitly requested (`normalizedSelectedId` is\n // null for both \"no selection\" and the \"all organizations\" token) but the\n // resolver could not honor it \u2014 it was dropped as non-existent/inaccessible\n // and the effective selection fell back to something else. Surface this so the\n // write layer can reject the request instead of silently creating the record\n // under the fallback org. Only set the field when true to keep the scope shape\n // unchanged for the common (honored) case.\n const selectionRejected = normalizedSelectedId !== null && effectiveSelected !== normalizedSelectedId\n\n return {\n selectedId: effectiveSelected,\n filterIds: filterSet ? Array.from(filterSet) : null,\n allowedIds: allowedSet ? Array.from(allowedSet) : null,\n tenantId,\n ...(selectionRejected ? { selectionRejected: true } : {}),\n }\n}\n\nexport async function resolveOrganizationScopeForRequest({\n container,\n auth,\n request,\n selectedId,\n tenantId: tenantOverride,\n}: {\n container: AwilixContainer\n auth: AuthContext | null | undefined\n request?: Request | { cookies?: { get: (name: string) => { value: string } | undefined }; headers?: { get(name: string): string | null } }\n selectedId?: string | null\n tenantId?: string | null\n}): Promise<OrganizationScope> {\n if (!auth || !auth.sub) {\n return { selectedId: null, filterIds: null, allowedIds: null, tenantId: null }\n }\n\n if (selectedId === undefined) {\n const boundFeatureScope = getFeatureScopeForRequest(request, auth.sub, tenantOverride)\n if (boundFeatureScope) return boundFeatureScope.scope\n }\n\n let em: EntityManager | null = null\n let rbac: RbacService | null = null\n try { em = container.resolve<EntityManager>('em') } catch { em = null }\n try { rbac = container.resolve<RbacService>('rbacService') } catch { rbac = null }\n const normalizeString = (value: unknown): string | null => {\n if (typeof value === 'string' && value.trim().length > 0) return value.trim()\n return null\n }\n if (!em || !rbac) {\n const fallbackSelected = normalizeOrganizationId(selectedId ?? auth.orgId ?? null)\n return {\n selectedId: fallbackSelected,\n filterIds: fallbackSelected ? [fallbackSelected] : null,\n allowedIds: fallbackSelected ? [fallbackSelected] : null,\n tenantId: normalizeString(auth.tenantId),\n }\n }\n\n const actorTenantField = (auth as { actorTenantId?: string | null }).actorTenantId\n const actorTenant = actorTenantField === undefined\n ? normalizeString(auth.tenantId)\n : actorTenantField === null\n ? null\n : normalizeString(actorTenantField)\n const actorOrgField = (auth as { actorOrgId?: string | null }).actorOrgId\n const actorOrgId = actorOrgField === undefined\n ? normalizeString(auth.orgId)\n : actorOrgField === null\n ? null\n : normalizeString(actorOrgField)\n\n const cookieTenant = request ? getSelectedTenantFromRequest(request) : null\n const requestedTenant =\n tenantOverride !== undefined\n ? tenantOverride\n : cookieTenant !== undefined\n ? cookieTenant\n : undefined\n const requestedTenantId = typeof requestedTenant === 'string' && requestedTenant.trim().length > 0 ? requestedTenant.trim() : null\n const isSuperAdminActor = auth.isSuperAdmin === true\n let effectiveTenantId = requestedTenantId ?? actorTenant ?? null\n if (actorTenant && effectiveTenantId && effectiveTenantId !== actorTenant && !isSuperAdminActor) {\n effectiveTenantId = actorTenant\n }\n if (!effectiveTenantId) {\n return { selectedId: null, filterIds: null, allowedIds: null, tenantId: null }\n }\n\n const scopedAuth = {\n ...auth,\n tenantId: effectiveTenantId,\n orgId: actorTenant && actorTenant === effectiveTenantId ? actorOrgId ?? null : null,\n }\n\n const rawSelected = selectedId !== undefined ? selectedId : (request ? getSelectedOrganizationFromRequest(request) : null)\n const normalizedSelectedId = typeof rawSelected === 'string' && rawSelected.trim().length > 0\n ? rawSelected.trim()\n : null\n\n const userId = typeof auth.sub === 'string' && auth.sub.length > 0 ? auth.sub : null\n const ttlMs = resolveOrgScopeTtlMs()\n const cache = ttlMs > 0 ? resolveCacheFromContainer(container) : null\n const cacheKey = userId\n ? buildOrgScopeCacheKey({\n userId,\n effectiveTenantId,\n selectedOrgId: normalizedSelectedId,\n requestedTenantId: requestedTenantId ?? null,\n })\n : null\n\n const requestMemo = getRequestScopeMemo(request)\n if (requestMemo && cacheKey) {\n const memoized = requestMemo.get(cacheKey)\n if (memoized) return memoized\n }\n\n const resolveScope = async (): Promise<OrganizationScope> => {\n let crossRequestCache = cache\n if (crossRequestCache && userId?.startsWith('api_key:')) {\n const key = await em.findOne(ApiKey, { id: userId.slice('api_key:'.length), deletedAt: null })\n if (!key || isSessionBoundApiKey(key)) crossRequestCache = null\n }\n if (crossRequestCache && cacheKey && typeof crossRequestCache.get === 'function') {\n try {\n const cached = await crossRequestCache.get(cacheKey)\n if (isValidCachedScope(cached)) return cached\n } catch (err) {\n logger.warn('Cache read failed', { err })\n }\n }\n\n const baseScope = await resolveOrganizationScope({\n em,\n rbac,\n auth: scopedAuth,\n selectedId: rawSelected,\n tenantId: effectiveTenantId,\n })\n\n if (crossRequestCache && cacheKey && userId && typeof crossRequestCache.set === 'function') {\n try {\n await crossRequestCache.set(cacheKey, baseScope, {\n ttl: ttlMs,\n tags: buildOrgScopeCacheTags({ userId, effectiveTenantId }),\n })\n } catch (err) {\n logger.warn('Cache write failed', { err })\n }\n }\n\n return baseScope\n }\n\n if (requestMemo && cacheKey) {\n const pending = resolveScope()\n requestMemo.set(cacheKey, pending)\n return pending\n }\n\n return resolveScope()\n}\n\nexport type FeatureCheckContext = {\n organizationId: string | null\n scope: OrganizationScope\n allowedOrganizationIds: string[] | null\n}\n\nexport async function resolveFeatureCheckContext({\n container,\n auth,\n request,\n selectedId,\n tenantId,\n requiredFeatures,\n}: {\n container: AwilixContainer\n auth: AuthContext | null | undefined\n request?: Request | {\n cookies?: { get: (name: string) => { value: string } | undefined }\n headers?: { get(name: string): string | null }\n }\n selectedId?: string | null\n tenantId?: string | null\n requiredFeatures?: readonly string[]\n}): Promise<FeatureCheckContext> {\n const boundFeatureScope = auth?.sub && selectedId === undefined\n ? getFeatureScopeForRequest(request, auth.sub, tenantId)\n : null\n let scope = boundFeatureScope\n ? boundFeatureScope.scope\n : await resolveOrganizationScopeForRequest({ container, auth, request, selectedId, tenantId })\n const organizationId = boundFeatureScope\n ? boundFeatureScope.organizationId\n : resolveFeatureCheckOrganizationId(scope, auth)\n if (\n auth?.sub\n && request\n && scope.selectedId === null\n && scope.tenantId\n && Array.isArray(requiredFeatures)\n && requiredFeatures.length > 0\n ) {\n const em = container.resolve<EntityManager>('em')\n const rbac = container.resolve<RbacService>('rbacService')\n const featureAccess = await rbac.resolveFeatureOrganizationAccess(\n auth.sub,\n requiredFeatures,\n { tenantId: scope.tenantId },\n )\n if (!featureAccess.unrestricted) {\n const organizationFilter: FilterQuery<Organization> = {\n tenant: scope.tenantId,\n deletedAt: null,\n ...(Array.isArray(scope.filterIds) ? { id: { $in: scope.filterIds } } : {}),\n }\n const organizations = await em.find(Organization, organizationFilter, {\n fields: ['id', 'ancestorIds'],\n })\n const candidateOrganizationIds = new Set(\n organizations.map((organization) => String(organization.id)),\n )\n const featureOrganizationIds = featureAccess.filterOrganizationIds(\n organizations.map((organization) => ({\n id: String(organization.id),\n ancestorIds: Array.isArray(organization.ancestorIds) ? organization.ancestorIds : [],\n })),\n )\n const approvedOrganizationIds = Array.from(new Set(\n featureOrganizationIds.filter((featureOrganizationId) => candidateOrganizationIds.has(featureOrganizationId)),\n ))\n scope = {\n selectedId: null,\n filterIds: approvedOrganizationIds,\n allowedIds: approvedOrganizationIds,\n tenantId: scope.tenantId,\n }\n }\n bindFeatureScopeToRequest(request, { userId: auth.sub, scope, organizationId })\n }\n\n return { organizationId, scope, allowedOrganizationIds: scope.allowedIds ?? null }\n}\n\nfunction resolveFeatureCheckOrganizationId(\n scope: OrganizationScope,\n auth: AuthContext | null | undefined,\n): string | null {\n const allowedOrganizationIds = scope.allowedIds ?? null\n const authOrgId = auth?.orgId ?? null\n return scope.selectedId\n ?? (authOrgId && (!Array.isArray(allowedOrganizationIds) || allowedOrganizationIds.includes(authOrgId)) ? authOrgId : null)\n ?? (Array.isArray(allowedOrganizationIds) && allowedOrganizationIds.length ? allowedOrganizationIds[0] : null)\n}\n"],
|
|
5
|
-
"mappings": "AAGA,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,mCAAmC;AAI5C,SAAS,uBAAuB,0BAA8C;AAC9E,SAAS,iCAAiC,iCAAiC;AAC3E,SAAS,oBAAoB;AA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AQ,CAAC,MAAM,aAAa;AAAA,MAC9B,CAAC;AACD,YAAM,2BAA2B,IAAI;AAAA,QACnC,cAAc,IAAI,CAAC,iBAAiB,OAAO,aAAa,EAAE,CAAC;AAAA,MAC7D;AACA,YAAM,yBAAyB,cAAc;AAAA,QAC3C,cAAc,IAAI,CAAC,kBAAkB;AAAA,UACnC,IAAI,OAAO,aAAa,EAAE;AAAA,UAC1B,aAAa,MAAM,QAAQ,aAAa,WAAW,IAAI,aAAa,cAAc,CAAC;AAAA,QACrF,EAAE;AAAA,MACJ;AACA,YAAM,0BAA0B,MAAM,KAAK,IAAI;AAAA,QAC7C,uBAAuB,OAAO,CAAC,0BAA0B,yBAAyB,IAAI,qBAAqB,CAAC;AAAA,MAC9G,CAAC;AACD,cAAQ;AAAA,QACN,YAAY;AAAA,QACZ,WAAW;AAAA,QACX,YAAY;AAAA,QACZ,UAAU,MAAM;AAAA,MAClB;AAAA,IACF;AACA,8BAA0B,SAAS,EAAE,QAAQ,KAAK,KAAK,OAAO,eAAe,CAAC;AAAA,EAChF;AAEA,SAAO,EAAE,gBAAgB,OAAO,wBAAwB,MAAM,cAAc,KAAK;AACnF;AAEA,SAAS,kCACP,OACA,MACe;AACf,QAAM,yBAAyB,MAAM,cAAc;AACnD,QAAM,YAAY,MAAM,SAAS;AACjC,SAAO,MAAM,eACP,cAAc,CAAC,MAAM,QAAQ,sBAAsB,KAAK,uBAAuB,SAAS,SAAS,KAAK,YAAY,UAClH,MAAM,QAAQ,sBAAsB,KAAK,uBAAuB,SAAS,uBAAuB,CAAC,IAAI;AAC7G;",
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { FilterQuery } from '@mikro-orm/core'\nimport type { AwilixContainer } from 'awilix'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { ApiKey } from '@open-mercato/core/modules/api_keys/data/entities'\nimport { isSessionBoundApiKey } from '@open-mercato/core/modules/api_keys/services/sessionKeyRoles'\nimport { isAllOrganizationsSelection } from '@open-mercato/core/modules/directory/constants'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport type { OrganizationScope } from '@open-mercato/shared/lib/auth/principal-service'\nimport { getCurrentCacheTenant, runWithCacheTenant, type CacheStrategy } from '@open-mercato/cache'\nimport { parseSelectedOrganizationCookie, parseSelectedTenantCookie } from './scopeCookies'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('directory').child({ component: 'org-scope-cache' })\n\nexport { parseSelectedOrganizationCookie, parseSelectedTenantCookie }\n\nexport type { OrganizationScope }\n\n// Phase 4 \u2014 short-TTL cache for resolveOrganizationScopeForRequest.\n// OrganizationScope is a pure function of (userId, tenantId, selectedOrgId,\n// requestedTenant) between membership changes; caching it bypasses 1\n// SELECT on `organizations` per CRUD request. TTL is short (60s default)\n// to keep staleness bounded as a backstop. Tag-based invalidation also fires\n// eagerly: per-user entries are dropped by RbacService.invalidateUserCache\n// (every ACL/role grant change goes through it \u2014 see buildOrgScopeUserCacheTag)\n// and per-tenant entries by the directory.organization.* subscriber plus\n// RbacService.invalidateTenantCache (role-ACL changes).\nconst ORG_SCOPE_CACHE_KEY_PREFIX = 'org-scope:v2'\n// Phase 4 default-off until the same readiness probe (`GET /api/customers/people`)\n// stays green with the cache layer engaged. Set `OM_ORG_SCOPE_CACHE_TTL_MS=60000`\n// (or any positive integer) to opt in once cross-request safety is re-verified.\nconst ORG_SCOPE_DEFAULT_TTL_MS = 0\n\nfunction resolveOrgScopeTtlMs(): number {\n const raw = process.env.OM_ORG_SCOPE_CACHE_TTL_MS\n if (raw === undefined) return ORG_SCOPE_DEFAULT_TTL_MS\n const parsed = Number(raw)\n if (!Number.isFinite(parsed) || parsed < 0) return ORG_SCOPE_DEFAULT_TTL_MS\n return parsed\n}\n\nfunction buildOrgScopeCacheKey(parts: {\n userId: string\n effectiveTenantId: string\n selectedOrgId: string | null\n requestedTenantId: string | null\n}): string {\n const selected = parts.selectedOrgId ?? 'none'\n const requested = parts.requestedTenantId ?? 'none'\n const namespace = parts.userId.startsWith('api_key:') ? `${ORG_SCOPE_CACHE_KEY_PREFIX}:delegated-v1` : ORG_SCOPE_CACHE_KEY_PREFIX\n return `${namespace}:${parts.userId}:${parts.effectiveTenantId}:${selected}:${requested}`\n}\n\n// Tag builders are exported so the modules that own the \"this user's scope\n// changed\" / \"this tenant's org tree changed\" signals (auth RBAC invalidation,\n// the directory.organization.* subscriber) can drop the matching cross-request\n// cache entries without re-deriving the tag format. Keeping the format in one\n// place is what lets the TTL be enabled safely (issue #2259).\nexport function buildOrgScopeUserCacheTag(userId: string): string {\n return `${ORG_SCOPE_CACHE_KEY_PREFIX}:user:${userId}`\n}\n\nexport function buildOrgScopeTenantCacheTag(tenantId: string): string {\n return `${ORG_SCOPE_CACHE_KEY_PREFIX}:tenant:${tenantId}`\n}\n\nfunction buildOrgScopeCacheTags(parts: { userId: string; effectiveTenantId: string; ownerUserId: string | null }): string[] {\n return [\n buildOrgScopeUserCacheTag(parts.userId),\n buildOrgScopeTenantCacheTag(parts.effectiveTenantId),\n ...(parts.ownerUserId ? [buildOrgScopeUserCacheTag(parts.ownerUserId)] : []),\n ]\n}\n\nfunction isValidCachedScope(value: unknown): value is OrganizationScope {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<OrganizationScope>\n const idOk = (v: unknown) => v === null || typeof v === 'string'\n const arrOk = (v: unknown) => v === null || (Array.isArray(v) && v.every((entry) => typeof entry === 'string'))\n const flagOk = record.selectionRejected === undefined || typeof record.selectionRejected === 'boolean'\n return idOk(record.selectedId) && idOk(record.tenantId) && arrOk(record.filterIds) && arrOk(record.allowedIds) && flagOk\n}\n\nfunction resolveCacheFromContainer(container: AwilixContainer | null | undefined): CacheStrategy | null {\n if (!container) return null\n try {\n const c = container.resolve('cache') as CacheStrategy | undefined\n if (c && typeof c.get === 'function' && typeof c.set === 'function') return c\n } catch {\n return null\n }\n return null\n}\n\nexport async function invalidateOrganizationScopeCacheForUser(\n container: AwilixContainer,\n userId: string,\n tenantId?: string | null,\n): Promise<void> {\n const cache = resolveCacheFromContainer(container)\n if (!cache?.deleteByTags) return\n try {\n const cacheTenantId = tenantId === undefined ? getCurrentCacheTenant() : tenantId\n await runWithCacheTenant(cacheTenantId, () =>\n cache.deleteByTags([buildOrgScopeUserCacheTag(userId)]),\n )\n } catch (err) {\n logger.warn('Cache invalidate user failed', { err })\n }\n}\n\nexport async function invalidateOrganizationScopeCacheForTenant(\n container: AwilixContainer,\n tenantId: string,\n): Promise<void> {\n const cache = resolveCacheFromContainer(container)\n if (!cache?.deleteByTags) return\n try {\n await runWithCacheTenant(tenantId, () =>\n cache.deleteByTags([buildOrgScopeTenantCacheTag(tenantId)]),\n )\n } catch (err) {\n logger.warn('Cache invalidate tenant failed', { err })\n }\n}\n\n// Issue #2259 \u2014 per-request memoization. resolveOrganizationScopeForRequest\n// runs at least twice per CRUD request: once for the route-level feature check\n// (resolveFeatureCheckContext) and once inside the shared factory's withCtx.\n// Those two call sites use different request-scoped DI containers but are handed\n// the SAME Request instance, so memoizing the resolved scope on a WeakMap keyed\n// by that request collapses the duplicate work \u2014 and the duplicate\n// `organizations` SELECT \u2014 into a single resolution. The inner map is keyed by\n// the same identity tuple as the cross-request cache key, so distinct explicit\n// selectedId/tenant overrides on one request stay independent. There is no\n// staleness risk: the memo lives only for the lifetime of one request and is\n// dropped with the request object by the GC.\nconst orgScopeRequestMemo = new WeakMap<object, Map<string, Promise<OrganizationScope>>>()\n\ntype BoundFeatureScope = {\n userId: string\n scope: OrganizationScope\n organizationId: string | null\n}\n\nconst featureScopeRequestMemo = new WeakMap<object, BoundFeatureScope>()\n\nfunction getRequestScopeMemo(request: unknown): Map<string, Promise<OrganizationScope>> | null {\n if (!request || (typeof request !== 'object' && typeof request !== 'function')) return null\n const key = request as object\n let memo = orgScopeRequestMemo.get(key)\n if (!memo) {\n memo = new Map<string, Promise<OrganizationScope>>()\n orgScopeRequestMemo.set(key, memo)\n }\n return memo\n}\n\nfunction bindFeatureScopeToRequest(request: unknown, binding: BoundFeatureScope): void {\n if (!request || (typeof request !== 'object' && typeof request !== 'function')) return\n featureScopeRequestMemo.set(request as object, binding)\n}\n\nfunction getFeatureScopeForRequest(\n request: unknown,\n userId: string,\n tenantOverride: string | null | undefined,\n): BoundFeatureScope | null {\n if (!request || (typeof request !== 'object' && typeof request !== 'function')) return null\n const entry = featureScopeRequestMemo.get(request as object)\n if (!entry || entry.userId !== userId) return null\n if (tenantOverride === undefined) return entry\n const requestedTenantId = typeof tenantOverride === 'string' ? tenantOverride.trim() : ''\n return requestedTenantId.length > 0 && requestedTenantId === entry.scope.tenantId ? entry : null\n}\n\nfunction normalizeOrganizationId(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : null\n}\n\nexport function getSelectedOrganizationFromRequest(req: Request | { cookies?: { get: (name: string) => { value: string } | undefined }; headers?: { get(name: string): string | null } }): string | null {\n const cookieContainer = (req as { cookies?: { get: (name: string) => { value: string } | undefined } }).cookies\n if (cookieContainer && typeof cookieContainer.get === 'function') {\n const val = cookieContainer.get('om_selected_org')?.value\n return val ?? null\n }\n const headerContainer = (req as { headers?: { get(name: string): string | null } }).headers\n const header = typeof headerContainer?.get === 'function' ? headerContainer.get('cookie') : null\n return parseSelectedOrganizationCookie(header)\n}\n\nexport function getSelectedTenantFromRequest(\n req: Request | { cookies?: { get: (name: string) => { value: string } | undefined }; headers?: { get(name: string): string | null } },\n): string | null {\n const cookieContainer = (req as { cookies?: { get: (name: string) => { value: string } | undefined } }).cookies\n if (cookieContainer && typeof cookieContainer.get === 'function') {\n const val = cookieContainer.get('om_selected_tenant')?.value\n return val ?? null\n }\n const headerContainer = (req as { headers?: { get(name: string): string | null } }).headers\n const header = typeof headerContainer?.get === 'function' ? headerContainer.get('cookie') : null\n return parseSelectedTenantCookie(header)\n}\n\nfunction normalizeOrganizationIds(ids: string[]): string[] {\n return Array.from(new Set(\n ids.map((value) => normalizeOrganizationId(value)).filter((value): value is string => {\n if (!value) return false\n if (isAllOrganizationsSelection(value)) return false\n return true\n })\n ))\n}\n\n// Map each organization id to itself plus its persisted descendant ids. Only\n// orgs that exist for the tenant and are not soft-deleted are included, so an\n// unknown/inaccessible id simply has no entry (matching the per-id query that\n// returned an empty set for it).\ntype OrgDescendantMap = Map<string, string[]>\n\n// Issue #2228 \u2014 single round-trip for org-scope resolution. Instead of issuing\n// one `organizations` SELECT per `collectWithDescendants` call (up to 3-4\n// sequential queries per request: accessible set, fallback set, selected set),\n// gather every candidate id up front and fetch their descendant expansions in\n// one `em.find(Organization, { id: $in })`. Expansion then happens in-memory.\nasync function loadOrgDescendantMap(em: EntityManager, tenantId: string, ids: string[]): Promise<OrgDescendantMap> {\n const unique = normalizeOrganizationIds(ids)\n if (!unique.length) return new Map()\n const filter: FilterQuery<Organization> = {\n tenant: tenantId,\n id: { $in: unique },\n deletedAt: null,\n }\n const orgs = await em.find(Organization, filter)\n const map: OrgDescendantMap = new Map()\n for (const org of orgs) {\n const id = String(org.id)\n const expansion = [id]\n if (Array.isArray(org.descendantIds)) {\n for (const desc of org.descendantIds) expansion.push(String(desc))\n }\n map.set(id, expansion)\n }\n return map\n}\n\nfunction expandWithDescendants(map: OrgDescendantMap, ids: string[]): Set<string> {\n const set = new Set<string>()\n for (const value of ids) {\n const id = normalizeOrganizationId(value)\n if (!id || isAllOrganizationsSelection(id)) continue\n const expansion = map.get(id)\n if (!expansion) continue\n for (const entry of expansion) set.add(entry)\n }\n return set\n}\n\nexport async function resolveOrganizationScope({\n em,\n rbac,\n auth,\n selectedId,\n tenantId: tenantIdOverride,\n}: {\n em: EntityManager\n rbac: Pick<RbacService, 'loadAcl'>\n auth: AuthContext | null | undefined\n selectedId?: string | null\n tenantId?: string | null\n}): Promise<OrganizationScope> {\n if (!auth || !auth.sub) {\n return { selectedId: null, filterIds: null, allowedIds: null, tenantId: null }\n }\n const actorTenantId = typeof auth.tenantId === 'string' && auth.tenantId.trim().length > 0 ? auth.tenantId.trim() : null\n const candidateTenantId = typeof tenantIdOverride === 'string' && tenantIdOverride.trim().length > 0\n ? tenantIdOverride.trim()\n : tenantIdOverride === null\n ? null\n : actorTenantId\n if (!candidateTenantId) {\n return { selectedId: null, filterIds: null, allowedIds: null, tenantId: null }\n }\n const usingOverride = candidateTenantId !== actorTenantId\n const isSuperAdminActor = auth.isSuperAdmin === true\n const tenantId = usingOverride && actorTenantId && !isSuperAdminActor ? actorTenantId : candidateTenantId\n if (!tenantId) {\n return { selectedId: null, filterIds: null, allowedIds: null, tenantId: null }\n }\n const normalizedRequestedSelection = normalizeOrganizationId(selectedId)\n const explicitAllOrgsChoice =\n normalizedRequestedSelection !== null && isAllOrganizationsSelection(normalizedRequestedSelection)\n const normalizedSelectedId = explicitAllOrgsChoice\n ? null\n : normalizedRequestedSelection\n const contextOrgId = actorTenantId && actorTenantId === tenantId ? normalizeOrganizationId(auth.orgId) : null\n const acl = await rbac.loadAcl(auth.sub, { tenantId, organizationId: contextOrgId })\n const aclIsSuperAdmin = acl?.isSuperAdmin === true\n const effectiveSuperAdmin = aclIsSuperAdmin || isSuperAdminActor\n const normalizedAccessible = effectiveSuperAdmin\n ? null\n : Array.isArray(acl?.organizations)\n ? acl.organizations\n .map((value) => normalizeOrganizationId(value))\n .filter((value): value is string => value !== null)\n : null\n const accessibleList = effectiveSuperAdmin\n ? null\n : normalizedAccessible && normalizedAccessible.some((value) => isAllOrganizationsSelection(value))\n ? null\n : normalizedAccessible?.filter((value) => !isAllOrganizationsSelection(value)) ?? null\n\n const accountOrgId = actorTenantId && actorTenantId === tenantId ? normalizeOrganizationId(auth.orgId) : null\n const fallbackOrgId = accountOrgId ?? null\n\n // Every id that could be expanded below \u2014 accessible set, fallback (account)\n // org, and the requested selection \u2014 is known up front, so fetch them all in\n // a single `organizations` query and expand from the in-memory map.\n const candidateIds = [\n ...(accessibleList ?? []),\n ...(fallbackOrgId ? [fallbackOrgId] : []),\n ...(normalizedSelectedId ? [normalizedSelectedId] : []),\n ]\n const orgDescendants = await loadOrgDescendantMap(em, tenantId, candidateIds)\n const loadFallbackSet = (): Set<string> | null =>\n fallbackOrgId ? expandWithDescendants(orgDescendants, [fallbackOrgId]) : null\n\n let allowedSet: Set<string> | null = null\n if (accessibleList === null) {\n allowedSet = null\n } else if (accessibleList.length === 0) {\n allowedSet = new Set()\n } else {\n allowedSet = expandWithDescendants(orgDescendants, accessibleList)\n }\n\n const hasUnrestrictedAccess = effectiveSuperAdmin || (accessibleList === null)\n const noOrgSelection = normalizedSelectedId === null && !explicitAllOrgsChoice\n const widenToAllOrgs =\n (explicitAllOrgsChoice && hasUnrestrictedAccess)\n || (effectiveSuperAdmin && noOrgSelection)\n const initialSelected =\n normalizedSelectedId\n ?? (widenToAllOrgs ? null : accountOrgId ?? null)\n // A selection is only honored when it resolves to a real, non-deleted org for\n // this tenant. `orgDescendants` holds exactly the existing orgs among the\n // candidate ids, so a stale/dead id (e.g. a selected-org cookie or JWT org\n // that no longer resolves after a DB reset) has no entry and is dropped here.\n // Without the existence guard an unrestricted (all-orgs) principal \u2014 whose\n // `allowedSet` is null \u2014 would accept the dead id as `effectiveSelected`, and\n // writes derived from `selectedId` would land under an org the read scope\n // (`filterIds`) never filters to, silently orphaning the record.\n const selectionResolvesToOrg = (id: string): boolean => orgDescendants.has(id)\n let effectiveSelected: string | null = null\n if (initialSelected) {\n if ((allowedSet === null || allowedSet.has(initialSelected)) && selectionResolvesToOrg(initialSelected)) {\n effectiveSelected = initialSelected\n }\n }\n\n let filterSet: Set<string> | null = null\n if (effectiveSelected) {\n filterSet = expandWithDescendants(orgDescendants, [effectiveSelected])\n } else if (allowedSet !== null) {\n filterSet = allowedSet\n } else if (widenToAllOrgs) {\n filterSet = null\n } else if (auth.orgId) {\n filterSet = loadFallbackSet()\n // Keep the write target (`selectedId`) aligned with the read scope\n // (`filterIds`): when an unrestricted principal's requested selection was\n // dropped above, fall the selection back to the account org too so a record\n // created here is always readable back by the same caller.\n if (!effectiveSelected && fallbackOrgId && filterSet && filterSet.size > 0) {\n effectiveSelected = fallbackOrgId\n }\n }\n\n if (allowedSet === null && (!filterSet || filterSet.size === 0) && fallbackOrgId && !widenToAllOrgs) {\n const computed = loadFallbackSet()\n if (computed && computed.size > 0) {\n filterSet = computed\n if (!effectiveSelected) {\n effectiveSelected = fallbackOrgId\n }\n }\n }\n\n // A concrete organization was explicitly requested (`normalizedSelectedId` is\n // null for both \"no selection\" and the \"all organizations\" token) but the\n // resolver could not honor it \u2014 it was dropped as non-existent/inaccessible\n // and the effective selection fell back to something else. Surface this so the\n // write layer can reject the request instead of silently creating the record\n // under the fallback org. Only set the field when true to keep the scope shape\n // unchanged for the common (honored) case.\n const selectionRejected = normalizedSelectedId !== null && effectiveSelected !== normalizedSelectedId\n\n return {\n selectedId: effectiveSelected,\n filterIds: filterSet ? Array.from(filterSet) : null,\n allowedIds: allowedSet ? Array.from(allowedSet) : null,\n tenantId,\n ...(selectionRejected ? { selectionRejected: true } : {}),\n }\n}\n\nexport async function resolveOrganizationScopeForRequest({\n container,\n auth,\n request,\n selectedId,\n tenantId: tenantOverride,\n}: {\n container: AwilixContainer\n auth: AuthContext | null | undefined\n request?: Request | { cookies?: { get: (name: string) => { value: string } | undefined }; headers?: { get(name: string): string | null } }\n selectedId?: string | null\n tenantId?: string | null\n}): Promise<OrganizationScope> {\n if (!auth || !auth.sub) {\n return { selectedId: null, filterIds: null, allowedIds: null, tenantId: null }\n }\n\n if (selectedId === undefined) {\n const boundFeatureScope = getFeatureScopeForRequest(request, auth.sub, tenantOverride)\n if (boundFeatureScope) return boundFeatureScope.scope\n }\n\n let em: EntityManager | null = null\n let rbac: RbacService | null = null\n try { em = container.resolve<EntityManager>('em') } catch { em = null }\n try { rbac = container.resolve<RbacService>('rbacService') } catch { rbac = null }\n const normalizeString = (value: unknown): string | null => {\n if (typeof value === 'string' && value.trim().length > 0) return value.trim()\n return null\n }\n if (!em || !rbac) {\n const fallbackSelected = normalizeOrganizationId(selectedId ?? auth.orgId ?? null)\n return {\n selectedId: fallbackSelected,\n filterIds: fallbackSelected ? [fallbackSelected] : null,\n allowedIds: fallbackSelected ? [fallbackSelected] : null,\n tenantId: normalizeString(auth.tenantId),\n }\n }\n\n const actorTenantField = (auth as { actorTenantId?: string | null }).actorTenantId\n const actorTenant = actorTenantField === undefined\n ? normalizeString(auth.tenantId)\n : actorTenantField === null\n ? null\n : normalizeString(actorTenantField)\n const actorOrgField = (auth as { actorOrgId?: string | null }).actorOrgId\n const actorOrgId = actorOrgField === undefined\n ? normalizeString(auth.orgId)\n : actorOrgField === null\n ? null\n : normalizeString(actorOrgField)\n\n const cookieTenant = request ? getSelectedTenantFromRequest(request) : null\n const requestedTenant =\n tenantOverride !== undefined\n ? tenantOverride\n : cookieTenant !== undefined\n ? cookieTenant\n : undefined\n const requestedTenantId = typeof requestedTenant === 'string' && requestedTenant.trim().length > 0 ? requestedTenant.trim() : null\n const isSuperAdminActor = auth.isSuperAdmin === true\n let effectiveTenantId = requestedTenantId ?? actorTenant ?? null\n if (actorTenant && effectiveTenantId && effectiveTenantId !== actorTenant && !isSuperAdminActor) {\n effectiveTenantId = actorTenant\n }\n if (!effectiveTenantId) {\n return { selectedId: null, filterIds: null, allowedIds: null, tenantId: null }\n }\n\n const scopedAuth = {\n ...auth,\n tenantId: effectiveTenantId,\n orgId: actorTenant && actorTenant === effectiveTenantId ? actorOrgId ?? null : null,\n }\n\n const rawSelected = selectedId !== undefined ? selectedId : (request ? getSelectedOrganizationFromRequest(request) : null)\n const normalizedSelectedId = typeof rawSelected === 'string' && rawSelected.trim().length > 0\n ? rawSelected.trim()\n : null\n\n const userId = typeof auth.sub === 'string' && auth.sub.length > 0 ? auth.sub : null\n const ownerUserId = auth.isApiKey && typeof auth.userId === 'string' && auth.userId.length > 0 ? auth.userId : null\n const ttlMs = resolveOrgScopeTtlMs()\n const cache = ttlMs > 0 ? resolveCacheFromContainer(container) : null\n const cacheKey = userId\n ? buildOrgScopeCacheKey({\n userId,\n effectiveTenantId,\n selectedOrgId: normalizedSelectedId,\n requestedTenantId: requestedTenantId ?? null,\n })\n : null\n\n const requestMemo = getRequestScopeMemo(request)\n if (requestMemo && cacheKey) {\n const memoized = requestMemo.get(cacheKey)\n if (memoized) return memoized\n }\n\n const resolveScope = async (): Promise<OrganizationScope> => {\n let crossRequestCache = cache\n if (crossRequestCache && userId?.startsWith('api_key:')) {\n const key = await em.findOne(ApiKey, { id: userId.slice('api_key:'.length), deletedAt: null })\n if (!key || isSessionBoundApiKey(key)) crossRequestCache = null\n }\n if (crossRequestCache && cacheKey && typeof crossRequestCache.get === 'function') {\n try {\n const cached = await crossRequestCache.get(cacheKey)\n if (isValidCachedScope(cached)) return cached\n } catch (err) {\n logger.warn('Cache read failed', { err })\n }\n }\n\n const baseScope = await resolveOrganizationScope({\n em,\n rbac,\n auth: scopedAuth,\n selectedId: rawSelected,\n tenantId: effectiveTenantId,\n })\n\n if (crossRequestCache && cacheKey && userId && typeof crossRequestCache.set === 'function') {\n try {\n await crossRequestCache.set(cacheKey, baseScope, {\n ttl: ttlMs,\n tags: buildOrgScopeCacheTags({ userId, effectiveTenantId, ownerUserId }),\n })\n } catch (err) {\n logger.warn('Cache write failed', { err })\n }\n }\n\n return baseScope\n }\n\n if (requestMemo && cacheKey) {\n const pending = resolveScope()\n requestMemo.set(cacheKey, pending)\n return pending\n }\n\n return resolveScope()\n}\n\nexport type FeatureCheckContext = {\n organizationId: string | null\n scope: OrganizationScope\n allowedOrganizationIds: string[] | null\n}\n\nexport async function resolveFeatureCheckContext({\n container,\n auth,\n request,\n selectedId,\n tenantId,\n requiredFeatures,\n}: {\n container: AwilixContainer\n auth: AuthContext | null | undefined\n request?: Request | {\n cookies?: { get: (name: string) => { value: string } | undefined }\n headers?: { get(name: string): string | null }\n }\n selectedId?: string | null\n tenantId?: string | null\n requiredFeatures?: readonly string[]\n}): Promise<FeatureCheckContext> {\n const boundFeatureScope = auth?.sub && selectedId === undefined\n ? getFeatureScopeForRequest(request, auth.sub, tenantId)\n : null\n let scope = boundFeatureScope\n ? boundFeatureScope.scope\n : await resolveOrganizationScopeForRequest({ container, auth, request, selectedId, tenantId })\n const organizationId = boundFeatureScope\n ? boundFeatureScope.organizationId\n : resolveFeatureCheckOrganizationId(scope, auth)\n if (\n auth?.sub\n && request\n && scope.selectedId === null\n && scope.tenantId\n && Array.isArray(requiredFeatures)\n && requiredFeatures.length > 0\n ) {\n const em = container.resolve<EntityManager>('em')\n const rbac = container.resolve<RbacService>('rbacService')\n const featureAccess = await rbac.resolveFeatureOrganizationAccess(\n auth.sub,\n requiredFeatures,\n { tenantId: scope.tenantId },\n )\n if (!featureAccess.unrestricted) {\n const organizationFilter: FilterQuery<Organization> = {\n tenant: scope.tenantId,\n deletedAt: null,\n ...(Array.isArray(scope.filterIds) ? { id: { $in: scope.filterIds } } : {}),\n }\n const organizations = await em.find(Organization, organizationFilter, {\n fields: ['id', 'ancestorIds'],\n })\n const candidateOrganizationIds = new Set(\n organizations.map((organization) => String(organization.id)),\n )\n const featureOrganizationIds = featureAccess.filterOrganizationIds(\n organizations.map((organization) => ({\n id: String(organization.id),\n ancestorIds: Array.isArray(organization.ancestorIds) ? organization.ancestorIds : [],\n })),\n )\n const approvedOrganizationIds = Array.from(new Set(\n featureOrganizationIds.filter((featureOrganizationId) => candidateOrganizationIds.has(featureOrganizationId)),\n ))\n scope = {\n selectedId: null,\n filterIds: approvedOrganizationIds,\n allowedIds: approvedOrganizationIds,\n tenantId: scope.tenantId,\n }\n }\n bindFeatureScopeToRequest(request, { userId: auth.sub, scope, organizationId })\n }\n\n return { organizationId, scope, allowedOrganizationIds: scope.allowedIds ?? null }\n}\n\nfunction resolveFeatureCheckOrganizationId(\n scope: OrganizationScope,\n auth: AuthContext | null | undefined,\n): string | null {\n const allowedOrganizationIds = scope.allowedIds ?? null\n const authOrgId = auth?.orgId ?? null\n return scope.selectedId\n ?? (authOrgId && (!Array.isArray(allowedOrganizationIds) || allowedOrganizationIds.includes(authOrgId)) ? authOrgId : null)\n ?? (Array.isArray(allowedOrganizationIds) && allowedOrganizationIds.length ? allowedOrganizationIds[0] : null)\n}\n"],
|
|
5
|
+
"mappings": "AAGA,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,mCAAmC;AAI5C,SAAS,uBAAuB,0BAA8C;AAC9E,SAAS,iCAAiC,iCAAiC;AAC3E,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,kBAAkB,CAAC;AAe/E,MAAM,6BAA6B;AAInC,MAAM,2BAA2B;AAEjC,SAAS,uBAA+B;AACtC,QAAM,MAAM,QAAQ,IAAI;AACxB,MAAI,QAAQ,OAAW,QAAO;AAC9B,QAAM,SAAS,OAAO,GAAG;AACzB,MAAI,CAAC,OAAO,SAAS,MAAM,KAAK,SAAS,EAAG,QAAO;AACnD,SAAO;AACT;AAEA,SAAS,sBAAsB,OAKpB;AACT,QAAM,WAAW,MAAM,iBAAiB;AACxC,QAAM,YAAY,MAAM,qBAAqB;AAC7C,QAAM,YAAY,MAAM,OAAO,WAAW,UAAU,IAAI,GAAG,0BAA0B,kBAAkB;AACvG,SAAO,GAAG,SAAS,IAAI,MAAM,MAAM,IAAI,MAAM,iBAAiB,IAAI,QAAQ,IAAI,SAAS;AACzF;AAOO,SAAS,0BAA0B,QAAwB;AAChE,SAAO,GAAG,0BAA0B,SAAS,MAAM;AACrD;AAEO,SAAS,4BAA4B,UAA0B;AACpE,SAAO,GAAG,0BAA0B,WAAW,QAAQ;AACzD;AAEA,SAAS,uBAAuB,OAA4F;AAC1H,SAAO;AAAA,IACL,0BAA0B,MAAM,MAAM;AAAA,IACtC,4BAA4B,MAAM,iBAAiB;AAAA,IACnD,GAAI,MAAM,cAAc,CAAC,0BAA0B,MAAM,WAAW,CAAC,IAAI,CAAC;AAAA,EAC5E;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,SAAO,EAAE,gBAAgB,OAAO,wBAAwB,MAAM,cAAc,KAAK;AACnF;AAEA,SAAS,kCACP,OACA,MACe;AACf,QAAM,yBAAyB,MAAM,cAAc;AACnD,QAAM,YAAY,MAAM,SAAS;AACjC,SAAO,MAAM,eACP,cAAc,CAAC,MAAM,QAAQ,sBAAsB,KAAK,uBAAuB,SAAS,SAAS,KAAK,YAAY,UAClH,MAAM,QAAQ,sBAAsB,KAAK,uBAAuB,SAAS,uBAAuB,CAAC,IAAI;AAC7G;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -260,8 +260,12 @@ function createNotificationService(deps) {
|
|
|
260
260
|
}
|
|
261
261
|
return notification;
|
|
262
262
|
},
|
|
263
|
-
async createBatch(input, ctx) {
|
|
263
|
+
async createBatch(input, ctx, options) {
|
|
264
|
+
if (options?.skipExistingGroup && !input.groupKey?.trim()) {
|
|
265
|
+
throw new Error("[internal] Notification group key is required for deduplicated batch delivery");
|
|
266
|
+
}
|
|
264
267
|
const recipientUserIds = Array.from(new Set(input.recipientUserIds));
|
|
268
|
+
if (options?.skipExistingGroup) recipientUserIds.sort((left, right) => left.localeCompare(right));
|
|
265
269
|
const { recipientUserIds: _recipientUserIds, ...content } = input;
|
|
266
270
|
const notifications = [];
|
|
267
271
|
const resolved = await resolveChannelsForRecipients(content, recipientUserIds, ctx);
|
|
@@ -269,11 +273,25 @@ function createNotificationService(deps) {
|
|
|
269
273
|
await writeEm.transactional(async (tx) => {
|
|
270
274
|
await assertNotificationRecipientsInScope(tx, recipientUserIds, ctx);
|
|
271
275
|
for (const { recipientUserId, channels } of resolved) {
|
|
276
|
+
if (options?.skipExistingGroup) {
|
|
277
|
+
const organizationId = normalizeOrgScope(ctx.organizationId);
|
|
278
|
+
const lockKey = `notifications:${ctx.tenantId}:${organizationId ?? "global"}:${recipientUserId}:${content.type}:${content.groupKey}`;
|
|
279
|
+
await sql`select pg_advisory_xact_lock(hashtext(${lockKey}))`.execute(getDb(tx));
|
|
280
|
+
const existing = await tx.findOne(Notification, {
|
|
281
|
+
recipientUserId,
|
|
282
|
+
tenantId: ctx.tenantId,
|
|
283
|
+
organizationId,
|
|
284
|
+
type: content.type,
|
|
285
|
+
groupKey: content.groupKey
|
|
286
|
+
});
|
|
287
|
+
if (existing) continue;
|
|
288
|
+
}
|
|
272
289
|
const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels);
|
|
273
290
|
notifications.push(notification);
|
|
274
291
|
}
|
|
275
292
|
await tx.flush();
|
|
276
293
|
});
|
|
294
|
+
if (options?.skipExistingGroup && notifications.length === 0) return [];
|
|
277
295
|
await invalidateNotificationCache(container, ctx, "created");
|
|
278
296
|
await emitNotificationCreatedBatch(eventBus, notifications, ctx);
|
|
279
297
|
await emitNotificationSseEvents(eventBus, notifications, ctx);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/notifications/lib/notificationService.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { type Kysely, sql } from 'kysely'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { invalidateCrudCache } from '@open-mercato/shared/lib/crud/cache'\nimport { Notification, type NotificationStatus } from '../data/entities'\nimport type { CreateNotificationInput, CreateBatchNotificationInput, CreateRoleNotificationInput, CreateFeatureNotificationInput, ExecuteActionInput } from '../data/validators'\nimport {\n NOTIFICATION_ACTION_ALREADY_EXECUTED_ERROR_CODE,\n NOTIFICATION_ACTION_FORBIDDEN_ERROR_CODE,\n type NotificationAction,\n type NotificationPollData,\n type NotificationTypeAction,\n} from '@open-mercato/shared/modules/notifications/types'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { NOTIFICATION_EVENTS, NOTIFICATION_SSE_EVENTS } from './events'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n buildNotificationEntity,\n emitNotificationCreated,\n emitNotificationCreatedBatch,\n type NotificationContentInput,\n type NotificationTenantContext,\n} from './notificationFactory'\nimport { toNotificationDto } from './notificationMapper'\nimport { buildNotificationReadScopeWhere } from './notificationScope'\nimport {\n getRecipientUserIdsForFeature,\n getRecipientUserIdsForRole,\n getScopedNotificationRecipientUserIds,\n} from './notificationRecipients'\nimport { assertSafeNotificationHref, sanitizeNotificationActions } from './safeHref'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getNotificationType } from './notification-type-registry'\nimport { getNotificationTypeOverrides, type NotificationTypeOverrides } from './typeOverrides'\nimport { getNotificationDeliveryStrategies } from './deliveryStrategies'\nimport { resolveEffectiveChannels } from './shouldDeliver'\nimport {\n createNotificationPreferenceService,\n type NotificationPreferenceService,\n} from './notificationPreferenceService'\nimport { inAppVisibleFilter, inAppVisibleSql, isInAppVisible } from './notificationVisibility'\n\nconst logger = createLogger('notifications').child({ component: 'service' })\n\nfunction debug(message: string, ...details: unknown[]): void {\n logger.debug(message, details.length ? { details } : undefined)\n}\n\nfunction getDb(em: EntityManager): Kysely<any> {\n return em.getKysely<any>()\n}\n\nconst UNIQUE_NOTIFICATION_ACTIVE_STATUSES: NotificationStatus[] = ['unread', 'read', 'actioned']\nconst NOTIFICATION_RESOURCE_KIND = 'notifications.notification'\n\nfunction normalizeOrgScope(organizationId: string | null | undefined): string | null {\n return organizationId ?? null\n}\n\nasync function invalidateNotificationCache(\n container: NotificationServiceDeps['container'],\n ctx: Pick<NotificationServiceContext, 'tenantId' | 'organizationId'>,\n reason: string,\n notificationId?: string,\n): Promise<void> {\n if (!container) return\n await invalidateCrudCache(\n container as Parameters<typeof invalidateCrudCache>[0],\n NOTIFICATION_RESOURCE_KIND,\n {\n id: notificationId,\n tenantId: ctx.tenantId,\n organizationId: normalizeOrgScope(ctx.organizationId),\n },\n ctx.tenantId,\n reason,\n )\n}\n\nasync function assertNotificationRecipientsInScope(\n em: EntityManager,\n recipientUserIds: string[],\n ctx: NotificationServiceContext,\n): Promise<void> {\n const scopedRecipientUserIds = await getScopedNotificationRecipientUserIds(\n getDb(em),\n ctx.tenantId,\n normalizeOrgScope(ctx.organizationId),\n recipientUserIds,\n )\n\n if (scopedRecipientUserIds.length !== recipientUserIds.length) {\n throw new CrudHttpError(404, { error: 'Notification recipient not found' })\n }\n}\n\nfunction actionAlreadyExecuted(): CrudHttpError {\n return new CrudHttpError(409, {\n error: 'Notification action already executed',\n code: NOTIFICATION_ACTION_ALREADY_EXECUTED_ERROR_CODE,\n })\n}\n\nasync function actionForbidden(): Promise<CrudHttpError> {\n const { translate } = await resolveTranslations()\n return new CrudHttpError(403, {\n error: translate('notifications.error.actionForbidden', 'You are not allowed to run this notification action'),\n code: NOTIFICATION_ACTION_FORBIDDEN_ERROR_CODE,\n })\n}\n\n/**\n * The command action the notification's registered type declares for a stored action: same action\n * id (across `actions` and `optionalActions`) and same `commandId`. Anything else is not dispatched.\n */\nfunction findDeclaredCommandAction(type: string, action: NotificationAction): NotificationTypeAction | null {\n const definition = getNotificationType(type)\n if (!definition) return null\n const declared = [...definition.actions, ...(definition.optionalActions ?? [])]\n .find((candidate) => candidate.id === action.id)\n if (!declared?.commandId || declared.commandId !== action.commandId) return null\n return declared\n}\n\nfunction applyNotificationContent(\n notification: Notification,\n input: NotificationContentInput,\n recipientUserId: string,\n ctx: NotificationTenantContext,\n channels: string[] | null,\n) {\n const actions = sanitizeNotificationActions(input.actions)\n const linkHref = assertSafeNotificationHref(input.linkHref)\n\n notification.recipientUserId = recipientUserId\n notification.type = input.type\n notification.titleKey = input.titleKey\n notification.bodyKey = input.bodyKey\n notification.titleVariables = input.titleVariables\n notification.bodyVariables = input.bodyVariables\n notification.title = input.title || input.titleKey || ''\n notification.body = input.body\n notification.icon = input.icon\n notification.severity = input.severity ?? 'info'\n notification.actionData = actions\n ? {\n actions,\n primaryActionId: input.primaryActionId,\n }\n : null\n notification.sourceModule = input.sourceModule\n notification.sourceEntityType = input.sourceEntityType\n notification.sourceEntityId = input.sourceEntityId\n notification.linkHref = linkHref\n notification.groupKey = input.groupKey\n notification.channels = channels\n notification.expiresAt = input.expiresAt ? new Date(input.expiresAt) : null\n notification.tenantId = ctx.tenantId\n notification.organizationId = normalizeOrgScope(ctx.organizationId)\n notification.status = 'unread'\n notification.readAt = null\n notification.actionedAt = null\n notification.dismissedAt = null\n notification.actionTaken = null\n notification.actionResult = null\n notification.createdAt = new Date()\n}\n\nasync function findScopedNotificationOrThrow(\n em: EntityManager,\n notificationId: string,\n ctx: NotificationServiceContext,\n): Promise<Notification> {\n const notification = await findOneWithDecryption(\n em,\n Notification,\n {\n id: notificationId,\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n },\n undefined,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (!notification) {\n throw new CrudHttpError(404, { error: 'Notification not found' })\n }\n return notification\n}\n\nasync function emitNotificationSseEvents(\n eventBus: { emit: (event: string, payload: unknown) => Promise<void> },\n notifications: Notification[],\n ctx: NotificationServiceContext,\n): Promise<void> {\n // Live bell updates only for notifications actually delivered to the in-app channel; the others\n // exist as records but must not bump anyone's badge/inbox.\n const visible = notifications.filter((notification) => isInAppVisible(notification.channels))\n if (visible.length === 0) return\n\n const visibleRecipientUserIds = Array.from(new Set(visible.map((n) => n.recipientUserId)))\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.BATCH_CREATED, {\n tenantId: ctx.tenantId,\n organizationId: normalizeOrgScope(ctx.organizationId),\n recipientUserIds: visibleRecipientUserIds,\n count: visible.length,\n })\n\n for (const notification of visible) {\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.CREATED, {\n tenantId: notification.tenantId,\n organizationId: notification.organizationId ?? null,\n recipientUserId: notification.recipientUserId,\n notification: toNotificationDto(notification),\n })\n }\n}\n\nasync function createOrRefreshNotification(\n em: EntityManager,\n input: NotificationContentInput,\n recipientUserId: string,\n ctx: NotificationTenantContext,\n channels: string[] | null,\n): Promise<Notification> {\n if (input.groupKey && input.groupKey.trim().length > 0) {\n const orgScope = normalizeOrgScope(ctx.organizationId) ?? 'global'\n const lockKey = `notifications:${ctx.tenantId}:${orgScope}:${recipientUserId}:${input.type}:${input.groupKey}`\n try {\n const db = getDb(em)\n await sql`select pg_advisory_xact_lock(hashtext(${lockKey}))`.execute(db)\n } catch {\n // If advisory locks are unavailable, continue with best-effort dedupe.\n }\n\n const existing = await em.findOne(Notification, {\n recipientUserId,\n tenantId: ctx.tenantId,\n organizationId: normalizeOrgScope(ctx.organizationId),\n type: input.type,\n groupKey: input.groupKey,\n status: { $in: UNIQUE_NOTIFICATION_ACTIVE_STATUSES },\n }, {\n orderBy: { createdAt: 'desc' },\n })\n\n if (existing) {\n applyNotificationContent(existing, input, recipientUserId, ctx, channels)\n return existing\n }\n }\n\n return buildNotificationEntity(em, input, recipientUserId, ctx, channels)\n}\n\nexport interface NotificationServiceContext {\n tenantId: string\n organizationId?: string | null\n organizationIds?: string[] | null\n userId?: string | null\n}\n\nexport type CreateFeatureNotificationServiceInput = CreateFeatureNotificationInput & {\n restrictRecipientsToOrganization?: boolean\n}\n\nexport interface NotificationService {\n create(input: CreateNotificationInput, ctx: NotificationServiceContext): Promise<Notification>\n createBatch(input: CreateBatchNotificationInput, ctx: NotificationServiceContext): Promise<Notification[]>\n createForRole(input: CreateRoleNotificationInput, ctx: NotificationServiceContext): Promise<Notification[]>\n createForFeature(input: CreateFeatureNotificationServiceInput, ctx: NotificationServiceContext): Promise<Notification[]>\n markAsRead(notificationId: string, ctx: NotificationServiceContext): Promise<Notification>\n markAllAsRead(ctx: NotificationServiceContext): Promise<number>\n dismiss(notificationId: string, ctx: NotificationServiceContext): Promise<Notification>\n restoreDismissed(\n notificationId: string,\n status: 'read' | 'unread' | undefined,\n ctx: NotificationServiceContext\n ): Promise<Notification>\n executeAction(\n notificationId: string,\n input: ExecuteActionInput,\n ctx: NotificationServiceContext\n ): Promise<{ notification: Notification; result: unknown }>\n getUnreadCount(ctx: NotificationServiceContext): Promise<number>\n getPollData(ctx: NotificationServiceContext, since?: string): Promise<NotificationPollData>\n cleanupExpired(): Promise<number>\n deleteBySource(\n sourceEntityType: string,\n sourceEntityId: string,\n ctx: NotificationServiceContext\n ): Promise<number>\n}\n\nexport interface NotificationServiceDeps {\n em: EntityManager\n eventBus: { emit: (event: string, payload: unknown) => Promise<void> }\n commandBus?: {\n execute: (\n commandId: string,\n options: { input: unknown; ctx: unknown; metadata?: unknown }\n ) => Promise<{ result: unknown }>\n }\n container?: { resolve: (name: string) => unknown }\n}\n\nexport function createNotificationService(deps: NotificationServiceDeps): NotificationService {\n const { em: rootEm, eventBus, commandBus, container } = deps\n\n /**\n * Whether the clicking user holds every feature a declared notification action requires.\n * Fails closed: no user, no container, or a failing RBAC check denies the action.\n */\n const userHoldsActionFeatures = async (\n requiredFeatures: string[] | undefined,\n scopeCtx: NotificationServiceContext,\n ): Promise<boolean> => {\n if (!requiredFeatures || requiredFeatures.length === 0) return true\n if (!scopeCtx.userId || !container) return false\n try {\n const rbacService = 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 rbacService.userHasAllFeatures(\n scopeCtx.userId,\n requiredFeatures,\n { tenantId: scopeCtx.tenantId, organizationId: scopeCtx.organizationId ?? null },\n )\n return allowed === true\n } catch (err) {\n getTelemetryRuntime()?.reportError(err, {\n module: 'notifications',\n code: 'notifications.action_feature_check_failed',\n })\n return false\n }\n }\n\n /**\n * Resolves the authoritative delivery-channel set for one recipient at create time \u2014 the single\n * gate that folds per-send target, per-type eligibility, registered strategies, and the\n * recipient's per-channel preferences (`nonOptOut` bypasses opt-out). Stored on the row and\n * replayed by the dispatcher; `in_app` membership also drives bell/inbox visibility.\n *\n * Returns `null` (\u21D2 \"all channels\", legacy behavior) when no delivery strategies are registered\n * (e.g. a minimal bootstrap/test), so notifications never become silently undeliverable/invisible\n * in an environment that simply hasn't wired the seam.\n */\n const resolveChannelsFor = async (\n content: NotificationContentInput,\n recipientUserId: string,\n scopeCtx: NotificationServiceContext,\n preferences: NotificationPreferenceService = createNotificationPreferenceService({ em: rootEm.fork() }),\n typeOverrides?: NotificationTypeOverrides | null,\n ): Promise<string[] | null> => {\n const registeredChannels = getNotificationDeliveryStrategies().map((strategy) => strategy.id)\n if (registeredChannels.length === 0) return null\n // Treat an empty target as \"no restriction\" (all channels) rather than \"no deliverable channel\":\n // a programmatic caller that computed an empty array should not silently black-hole the\n // notification. The HTTP layer rejects an empty `channels` outright (see validators.ts).\n const targetChannels = content.channels && content.channels.length > 0 ? content.channels : null\n const overrides = typeOverrides === undefined\n ? (await getNotificationTypeOverrides(rootEm.fork(), scopeCtx.tenantId, [content.type])).get(content.type) ?? null\n : typeOverrides\n return resolveEffectiveChannels({\n typeId: content.type,\n type: getNotificationType(content.type),\n scope: { tenantId: scopeCtx.tenantId, userId: recipientUserId },\n targetChannels,\n registeredChannels,\n preferences,\n channelsOverride: overrides?.channels ?? null,\n nonOptOutOverride: overrides?.nonOptOut ?? null,\n })\n }\n\n /**\n * Broadcast counterpart of {@link resolveChannelsFor}: resolves the channel set for every recipient\n * up front, BEFORE the write transaction opens, reusing a single forked EM / preference service\n * across the whole set. This keeps the preference reads out of the write transaction (matching\n * `create`, which resolves before its transaction) and avoids one EM fork per recipient on large\n * role/feature broadcasts.\n */\n const resolveChannelsForRecipients = async (\n content: NotificationContentInput,\n recipientUserIds: string[],\n scopeCtx: NotificationServiceContext,\n ): Promise<Array<{ recipientUserId: string; channels: string[] | null }>> => {\n const preferences = createNotificationPreferenceService({ em: rootEm.fork() })\n // Stored overrides are per-type (not per-recipient) \u2014 read once for the whole broadcast.\n const typeOverrides =\n (await getNotificationTypeOverrides(rootEm.fork(), scopeCtx.tenantId, [content.type])).get(content.type) ?? null\n const resolved: Array<{ recipientUserId: string; channels: string[] | null }> = []\n for (const recipientUserId of recipientUserIds) {\n resolved.push({\n recipientUserId,\n channels: await resolveChannelsFor(content, recipientUserId, scopeCtx, preferences, typeOverrides),\n })\n }\n return resolved\n }\n\n return {\n async create(input, ctx) {\n const { recipientUserId, ...content } = input\n const channels = await resolveChannelsFor(content, recipientUserId, ctx)\n const writeEm = rootEm.fork()\n const notification = await writeEm.transactional(async (tx) => {\n await assertNotificationRecipientsInScope(tx, [recipientUserId], ctx)\n const entity = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n await tx.flush()\n return entity\n })\n\n await invalidateNotificationCache(container, ctx, 'created')\n // Always emit the domain event (drives the deliver subscriber \u2192 push/email/\u2026). Only bump the\n // live in-app bell when this notification is actually visible in-app.\n await emitNotificationCreated(eventBus, notification, ctx)\n if (isInAppVisible(notification.channels)) {\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.CREATED, {\n tenantId: notification.tenantId,\n organizationId: notification.organizationId ?? null,\n recipientUserId: notification.recipientUserId,\n notification: toNotificationDto(notification),\n })\n }\n\n return notification\n },\n\n async createBatch(input, ctx) {\n const recipientUserIds = Array.from(new Set(input.recipientUserIds))\n const { recipientUserIds: _recipientUserIds, ...content } = input\n const notifications: Notification[] = []\n const resolved = await resolveChannelsForRecipients(content, recipientUserIds, ctx)\n const writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n await assertNotificationRecipientsInScope(tx, recipientUserIds, ctx)\n for (const { recipientUserId, channels } of resolved) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await invalidateNotificationCache(container, ctx, 'created')\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx)\n\n return notifications\n },\n\n async createForRole(input, ctx) {\n const em = rootEm.fork()\n\n const db = getDb(em)\n const recipientUserIds = await getRecipientUserIdsForRole(db, ctx.tenantId, input.roleId)\n if (recipientUserIds.length === 0) {\n return []\n }\n\n const { roleId: _roleId, ...content } = input\n const notifications: Notification[] = []\n const uniqueRecipientUserIds = Array.from(new Set(recipientUserIds))\n const resolved = await resolveChannelsForRecipients(content, uniqueRecipientUserIds, ctx)\n const writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n for (const { recipientUserId, channels } of resolved) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await invalidateNotificationCache(container, ctx, 'created')\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx)\n\n return notifications\n },\n\n async createForFeature(input, ctx) {\n const em = rootEm.fork()\n const db = getDb(em)\n const recipientUserIds = await getRecipientUserIdsForFeature(db, ctx.tenantId, input.requiredFeature)\n\n if (recipientUserIds.length === 0) {\n debug('No users found with feature:', input.requiredFeature, 'in tenant:', ctx.tenantId)\n return []\n }\n\n let authorizedRecipientUserIds = recipientUserIds\n if (input.restrictRecipientsToOrganization) {\n const uniqueCandidateUserIds = Array.from(new Set(recipientUserIds))\n if (!ctx.organizationId) {\n logger.warn('Organization-restricted feature fan-out skipped because organization scope is missing', {\n tenantId: ctx.tenantId,\n requiredFeature: input.requiredFeature,\n })\n return []\n }\n\n if (uniqueCandidateUserIds.length > 200) {\n logger.warn('Organization-restricted feature fan-out skipped because the candidate cap was exceeded', {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n requiredFeature: input.requiredFeature,\n candidateCount: uniqueCandidateUserIds.length,\n candidateCap: 200,\n })\n return []\n }\n\n if (!container) {\n logger.warn('Organization-restricted feature fan-out skipped because the DI container is unavailable', {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n requiredFeature: input.requiredFeature,\n })\n return []\n }\n\n try {\n const rbacService = 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 allowedRecipientUserIds: string[] = []\n for (let offset = 0; offset < uniqueCandidateUserIds.length; offset += 10) {\n const candidates = uniqueCandidateUserIds.slice(offset, offset + 10)\n const results = await Promise.all(candidates.map(async (recipientUserId) => ({\n recipientUserId,\n allowed: await rbacService.userHasAllFeatures(\n recipientUserId,\n [input.requiredFeature],\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId ?? null },\n ),\n })))\n for (const result of results) {\n if (result.allowed) allowedRecipientUserIds.push(result.recipientUserId)\n }\n }\n authorizedRecipientUserIds = allowedRecipientUserIds\n } catch (err) {\n logger.warn('Organization-restricted feature fan-out skipped because RBAC filtering failed', {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n requiredFeature: input.requiredFeature,\n err,\n })\n return []\n }\n\n if (authorizedRecipientUserIds.length === 0) {\n debug('No users found with feature in organization:', input.requiredFeature, ctx.organizationId)\n return []\n }\n }\n\n debug('Creating notifications for', authorizedRecipientUserIds.length, 'user(s) with feature:', input.requiredFeature)\n\n const {\n requiredFeature: _requiredFeature,\n restrictRecipientsToOrganization: _restrictRecipientsToOrganization,\n ...content\n } = input\n const notifications: Notification[] = []\n const uniqueRecipientUserIds = Array.from(new Set(authorizedRecipientUserIds))\n const resolved = await resolveChannelsForRecipients(content, uniqueRecipientUserIds, ctx)\n const writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n for (const { recipientUserId, channels } of resolved) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await invalidateNotificationCache(container, ctx, 'created')\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx)\n\n return notifications\n },\n\n async markAsRead(notificationId, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n if (notification.status === 'unread') {\n notification.status = 'read'\n notification.readAt = new Date()\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.READ, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n }\n\n return notification\n },\n\n async markAllAsRead(ctx) {\n const em = rootEm.fork()\n const db = getDb(em)\n const applyScope = <QB extends { where: (...args: any[]) => QB }>(q: QB): QB => {\n let chain = q\n .where('recipient_user_id' as any, '=', ctx.userId as any)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .where('status' as any, '=', 'unread')\n // Only in-app-visible rows count toward the badge (see getUnreadCount),\n // so \"mark all as read\" must scope to the SAME set \u2014 otherwise it flips\n // push/email-only rows the user never saw and SSE-broadcasts a read for\n // notifications that were never in the bell, inflating the returned\n // count past what the badge showed.\n .where(inAppVisibleSql() as any)\n if (ctx.organizationId) {\n chain = chain.where('organization_id' as any, '=', ctx.organizationId)\n }\n return chain\n }\n\n const targetRows = await applyScope(\n db\n .selectFrom('notifications' as any)\n .select([\n 'id' as any,\n 'organization_id' as any,\n 'recipient_user_id' as any,\n ]),\n ).execute() as Array<{ id: string }>\n\n if (!targetRows.length) {\n return 0\n }\n\n const updateResult = await applyScope(\n db.updateTable('notifications' as any).set({\n status: 'read',\n read_at: sql`now()`,\n } as any) as any,\n ).executeTakeFirst() as { numUpdatedRows?: bigint | number } | undefined\n const result = Number(updateResult?.numUpdatedRows ?? targetRows.length)\n\n await invalidateNotificationCache(container, ctx, 'updated')\n\n const notifications = await findWithDecryption(em, Notification, {\n id: { $in: targetRows.map((row) => row.id) },\n }, undefined, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n })\n\n for (const notification of notifications) {\n await eventBus.emit(NOTIFICATION_EVENTS.READ, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.CREATED, {\n tenantId: notification.tenantId,\n organizationId: notification.organizationId ?? null,\n recipientUserId: notification.recipientUserId,\n notification: toNotificationDto(notification),\n })\n }\n\n return result\n },\n\n async dismiss(notificationId, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n notification.status = 'dismissed'\n notification.dismissedAt = new Date()\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.DISMISSED, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n\n return notification\n },\n\n async restoreDismissed(notificationId, status, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n if (notification.status !== 'dismissed') {\n return notification\n }\n\n // A dismissed notification whose action already ran comes back as `actioned`,\n // whatever the caller asked for: `actioned_at` outlives the dismissal.\n const targetStatus: NotificationStatus = notification.actionedAt != null ? 'actioned' : status ?? 'read'\n notification.status = targetStatus\n notification.dismissedAt = null\n\n if (targetStatus === 'unread') {\n notification.readAt = null\n } else if (!notification.readAt) {\n notification.readAt = new Date()\n }\n\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.RESTORED, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n status: targetStatus,\n })\n\n return notification\n },\n\n async executeAction(notificationId, input, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n const actionData = notification.actionData\n const action = actionData?.actions?.find((a) => a.id === input.actionId)\n\n if (!action) {\n throw new Error('Action not found')\n }\n\n // Reject an already-actioned notification before dispatching the command,\n // so a retry or double-click cannot re-run the side effect. `actioned_at` is\n // the durable marker: `status` is overwritten by a dismissal.\n if (notification.status === 'actioned' || notification.actionedAt != null) {\n throw actionAlreadyExecuted()\n }\n\n if (action.commandId) {\n const declared = findDeclaredCommandAction(notification.type, action)\n if (!declared || !(await userHoldsActionFeatures(declared.requiredFeatures, ctx))) {\n throw await actionForbidden()\n }\n }\n\n const actionedAt = new Date()\n const previousStatus = notification.status\n const previousActionedAt = notification.actionedAt ?? null\n const previousActionTaken = notification.actionTaken ?? null\n\n // Atomically claim the notification so only one concurrent request can run\n // the side-effecting command. The conditional UPDATE matches only while the\n // notification has not been actioned yet; a losing request updates 0 rows.\n const claimResult = (await getDb(em)\n .updateTable('notifications' as any)\n .set({\n status: 'actioned',\n actioned_at: actionedAt,\n action_taken: input.actionId,\n } as any)\n .where('id' as any, '=', notification.id)\n .where('recipient_user_id' as any, '=', ctx.userId as any)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .where('status' as any, '!=', 'actioned')\n .where('actioned_at' as any, 'is', null)\n .executeTakeFirst()) as { numUpdatedRows?: bigint | number } | undefined\n\n if (Number(claimResult?.numUpdatedRows ?? 0) === 0) {\n throw actionAlreadyExecuted()\n }\n\n // The claim is provisional: if the side-effecting command fails, the action\n // never actually completed, so release the claim to its prior state. This\n // lets the user retry the action instead of the notification being locked as\n // `actioned` forever. The claim is owned through its own `actioned_at` and\n // `action_taken`, not through `status`: a dismissal that lands while the\n // command runs overwrites `status`, and the release must still clear the\n // claim then \u2014 while leaving that dismissal in place.\n const releaseClaim = async () => {\n await getDb(em)\n .updateTable('notifications' as any)\n .set({\n status: sql`case when status = 'actioned' then ${previousStatus} else status end`,\n actioned_at: previousActionedAt,\n action_taken: previousActionTaken,\n } as any)\n .where('id' as any, '=', notification.id)\n .where('recipient_user_id' as any, '=', ctx.userId as any)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .where('actioned_at' as any, '=', actionedAt)\n .where('action_taken' as any, '=', input.actionId)\n .executeTakeFirst()\n }\n\n let result: unknown = null\n\n if (action.commandId && commandBus && container) {\n const commandInput = {\n ...input.payload,\n id: notification.sourceEntityId,\n }\n\n // Build a CommandRuntimeContext from the notification service context\n const commandCtx = {\n container,\n auth: {\n sub: ctx.userId,\n tenantId: ctx.tenantId,\n orgId: ctx.organizationId,\n },\n organizationScope: null,\n selectedOrganizationId: ctx.organizationId ?? null,\n organizationIds: ctx.organizationId ? [ctx.organizationId] : null,\n }\n\n let commandResult: { result: unknown }\n try {\n commandResult = await commandBus.execute(action.commandId, {\n input: commandInput,\n ctx: commandCtx,\n metadata: {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n resourceKind: 'notifications',\n },\n })\n } catch (err) {\n // Never let a rollback failure mask the original command error \u2014 the\n // caller needs the real failure to decide whether to retry.\n try {\n await releaseClaim()\n } catch (releaseErr) {\n debug('failed to release notification action claim', releaseErr)\n }\n throw err\n }\n\n result = commandResult.result\n }\n\n notification.status = 'actioned'\n notification.actionedAt = actionedAt\n notification.actionTaken = input.actionId\n notification.actionResult = result as Record<string, unknown>\n\n if (!notification.readAt) {\n notification.readAt = new Date()\n }\n\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.ACTIONED, {\n notificationId: notification.id,\n actionId: input.actionId,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n\n return { notification, result }\n },\n\n async getUnreadCount(ctx) {\n const em = rootEm.fork()\n return em.count(Notification, {\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n status: 'unread',\n $and: [\n buildNotificationReadScopeWhere(ctx),\n inAppVisibleFilter(),\n ],\n })\n },\n\n async getPollData(ctx, since) {\n const em = rootEm.fork()\n const filters: Record<string, unknown> = {\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n $and: [\n buildNotificationReadScopeWhere(ctx),\n inAppVisibleFilter(),\n ],\n }\n\n if (since) {\n filters.createdAt = { $gt: new Date(since) }\n }\n\n const [notifications, unreadCount] = await Promise.all([\n em.find(Notification, filters, {\n orderBy: { createdAt: 'desc' },\n limit: 50,\n }),\n em.count(Notification, {\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n status: 'unread',\n $and: [\n buildNotificationReadScopeWhere(ctx),\n inAppVisibleFilter(),\n ],\n }),\n ])\n\n const recent = notifications.map(toNotificationDto)\n const hasNew = since ? recent.length > 0 : false\n\n return {\n unreadCount,\n recent,\n hasNew,\n lastId: recent[0]?.id,\n }\n },\n\n async cleanupExpired() {\n const em = rootEm.fork()\n const db = getDb(em)\n\n const affectedScopes = await db\n .selectFrom('notifications' as any)\n .select([\n 'tenant_id' as any,\n 'organization_id' as any,\n ])\n .where('expires_at' as any, '<', sql`now()`)\n .where('status' as any, 'not in', ['actioned', 'dismissed'])\n .distinct()\n .execute() as Array<{ tenant_id: string; organization_id: string | null }>\n\n if (!affectedScopes.length) return 0\n\n const updateResult = await db\n .updateTable('notifications' as any)\n .set({\n status: 'dismissed',\n dismissed_at: sql`now()`,\n } as any)\n .where('expires_at' as any, '<', sql`now()`)\n .where('status' as any, 'not in', ['actioned', 'dismissed'])\n .executeTakeFirst() as { numUpdatedRows?: bigint | number } | undefined\n\n for (const scope of affectedScopes) {\n await invalidateNotificationCache(container, {\n tenantId: scope.tenant_id,\n organizationId: scope.organization_id,\n }, 'updated')\n }\n\n return Number(updateResult?.numUpdatedRows ?? 0)\n },\n\n async deleteBySource(sourceEntityType, sourceEntityId, ctx) {\n const em = rootEm.fork()\n const db = getDb(em)\n\n const deleteResult = await db\n .deleteFrom('notifications' as any)\n .where('source_entity_type' as any, '=', sourceEntityType)\n .where('source_entity_id' as any, '=', sourceEntityId)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .executeTakeFirst() as { numDeletedRows?: bigint | number } | undefined\n\n const deletedCount = Number(deleteResult?.numDeletedRows ?? 0)\n if (deletedCount > 0) {\n await invalidateNotificationCache(container, ctx, 'deleted')\n }\n\n return deletedCount\n },\n }\n}\n\n/**\n * Helper to create notification service from a DI container.\n * Use this in API routes and commands to avoid DI resolution issues.\n */\nexport function resolveNotificationService(container: {\n resolve: (name: string) => unknown\n}): NotificationService {\n const em = container.resolve('em') as EntityManager\n const eventBus = container.resolve('eventBus') as { emit: (event: string, payload: unknown) => Promise<void> }\n\n // commandBus may not be registered in all contexts, so resolve it safely\n let commandBus: NotificationServiceDeps['commandBus']\n try {\n commandBus = container.resolve('commandBus') as typeof commandBus\n } catch {\n // commandBus not available - actions with commandId won't work\n commandBus = undefined\n }\n\n return createNotificationService({ em, eventBus, commandBus, container })\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAsB,WAAW;AACjC,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,oBAA6C;AAEtD;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AACP,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AACpC,SAAS,qBAAqB,+BAA+B;AAC7D,SAAS,uBAAuB,0BAA0B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,yBAAyB;AAClC,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,4BAA4B,mCAAmC;AACxE,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,oCAAoE;AAC7E,SAAS,yCAAyC;AAClD,SAAS,gCAAgC;AACzC;AAAA,EACE;AAAA,OAEK;AACP,SAAS,oBAAoB,iBAAiB,sBAAsB;AAEpE,MAAM,SAAS,aAAa,eAAe,EAAE,MAAM,EAAE,WAAW,UAAU,CAAC;AAE3E,SAAS,MAAM,YAAoB,SAA0B;AAC3D,SAAO,MAAM,SAAS,QAAQ,SAAS,EAAE,QAAQ,IAAI,MAAS;AAChE;AAEA,SAAS,MAAM,IAAgC;AAC7C,SAAO,GAAG,UAAe;AAC3B;AAEA,MAAM,sCAA4D,CAAC,UAAU,QAAQ,UAAU;AAC/F,MAAM,6BAA6B;AAEnC,SAAS,kBAAkB,gBAA0D;AACnF,SAAO,kBAAkB;AAC3B;AAEA,eAAe,4BACb,WACA,KACA,QACA,gBACe;AACf,MAAI,CAAC,UAAW;AAChB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,MACE,IAAI;AAAA,MACJ,UAAU,IAAI;AAAA,MACd,gBAAgB,kBAAkB,IAAI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P,MAAM,cAAqB,KAAK,UAAU,EAC1C,MAAM,UAAiB,UAAU,CAAC,YAAY,WAAW,CAAC,EAC1D,iBAAiB;AAEpB,iBAAW,SAAS,gBAAgB;AAClC,cAAM,4BAA4B,WAAW;AAAA,UAC3C,UAAU,MAAM;AAAA,UAChB,gBAAgB,MAAM;AAAA,QACxB,GAAG,SAAS;AAAA,MACd;AAEA,aAAO,OAAO,cAAc,kBAAkB,CAAC;AAAA,IACjD;AAAA,IAEA,MAAM,eAAe,kBAAkB,gBAAgB,KAAK;AAC1D,YAAM,KAAK,OAAO,KAAK;AACvB,YAAM,KAAK,MAAM,EAAE;AAEnB,YAAM,eAAe,MAAM,GACxB,WAAW,eAAsB,EACjC,MAAM,sBAA6B,KAAK,gBAAgB,EACxD,MAAM,oBAA2B,KAAK,cAAc,EACpD,MAAM,aAAoB,KAAK,IAAI,QAAQ,EAC3C,iBAAiB;AAEpB,YAAM,eAAe,OAAO,cAAc,kBAAkB,CAAC;AAC7D,UAAI,eAAe,GAAG;AACpB,cAAM,4BAA4B,WAAW,KAAK,SAAS;AAAA,MAC7D;AAEA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAMO,SAAS,2BAA2B,WAEnB;AACtB,QAAM,KAAK,UAAU,QAAQ,IAAI;AACjC,QAAM,WAAW,UAAU,QAAQ,UAAU;AAG7C,MAAI;AACJ,MAAI;AACF,iBAAa,UAAU,QAAQ,YAAY;AAAA,EAC7C,QAAQ;AAEN,iBAAa;AAAA,EACf;AAEA,SAAO,0BAA0B,EAAE,IAAI,UAAU,YAAY,UAAU,CAAC;AAC1E;",
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { type Kysely, sql } from 'kysely'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { invalidateCrudCache } from '@open-mercato/shared/lib/crud/cache'\nimport { Notification, type NotificationStatus } from '../data/entities'\nimport type { CreateNotificationInput, CreateBatchNotificationInput, CreateRoleNotificationInput, CreateFeatureNotificationInput, ExecuteActionInput } from '../data/validators'\nimport {\n NOTIFICATION_ACTION_ALREADY_EXECUTED_ERROR_CODE,\n NOTIFICATION_ACTION_FORBIDDEN_ERROR_CODE,\n type NotificationAction,\n type NotificationPollData,\n type NotificationTypeAction,\n} from '@open-mercato/shared/modules/notifications/types'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { NOTIFICATION_EVENTS, NOTIFICATION_SSE_EVENTS } from './events'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n buildNotificationEntity,\n emitNotificationCreated,\n emitNotificationCreatedBatch,\n type NotificationContentInput,\n type NotificationTenantContext,\n} from './notificationFactory'\nimport { toNotificationDto } from './notificationMapper'\nimport { buildNotificationReadScopeWhere } from './notificationScope'\nimport {\n getRecipientUserIdsForFeature,\n getRecipientUserIdsForRole,\n getScopedNotificationRecipientUserIds,\n} from './notificationRecipients'\nimport { assertSafeNotificationHref, sanitizeNotificationActions } from './safeHref'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getNotificationType } from './notification-type-registry'\nimport { getNotificationTypeOverrides, type NotificationTypeOverrides } from './typeOverrides'\nimport { getNotificationDeliveryStrategies } from './deliveryStrategies'\nimport { resolveEffectiveChannels } from './shouldDeliver'\nimport {\n createNotificationPreferenceService,\n type NotificationPreferenceService,\n} from './notificationPreferenceService'\nimport { inAppVisibleFilter, inAppVisibleSql, isInAppVisible } from './notificationVisibility'\n\nconst logger = createLogger('notifications').child({ component: 'service' })\n\nfunction debug(message: string, ...details: unknown[]): void {\n logger.debug(message, details.length ? { details } : undefined)\n}\n\nfunction getDb(em: EntityManager): Kysely<any> {\n return em.getKysely<any>()\n}\n\nconst UNIQUE_NOTIFICATION_ACTIVE_STATUSES: NotificationStatus[] = ['unread', 'read', 'actioned']\nconst NOTIFICATION_RESOURCE_KIND = 'notifications.notification'\n\nfunction normalizeOrgScope(organizationId: string | null | undefined): string | null {\n return organizationId ?? null\n}\n\nasync function invalidateNotificationCache(\n container: NotificationServiceDeps['container'],\n ctx: Pick<NotificationServiceContext, 'tenantId' | 'organizationId'>,\n reason: string,\n notificationId?: string,\n): Promise<void> {\n if (!container) return\n await invalidateCrudCache(\n container as Parameters<typeof invalidateCrudCache>[0],\n NOTIFICATION_RESOURCE_KIND,\n {\n id: notificationId,\n tenantId: ctx.tenantId,\n organizationId: normalizeOrgScope(ctx.organizationId),\n },\n ctx.tenantId,\n reason,\n )\n}\n\nasync function assertNotificationRecipientsInScope(\n em: EntityManager,\n recipientUserIds: string[],\n ctx: NotificationServiceContext,\n): Promise<void> {\n const scopedRecipientUserIds = await getScopedNotificationRecipientUserIds(\n getDb(em),\n ctx.tenantId,\n normalizeOrgScope(ctx.organizationId),\n recipientUserIds,\n )\n\n if (scopedRecipientUserIds.length !== recipientUserIds.length) {\n throw new CrudHttpError(404, { error: 'Notification recipient not found' })\n }\n}\n\nfunction actionAlreadyExecuted(): CrudHttpError {\n return new CrudHttpError(409, {\n error: 'Notification action already executed',\n code: NOTIFICATION_ACTION_ALREADY_EXECUTED_ERROR_CODE,\n })\n}\n\nasync function actionForbidden(): Promise<CrudHttpError> {\n const { translate } = await resolveTranslations()\n return new CrudHttpError(403, {\n error: translate('notifications.error.actionForbidden', 'You are not allowed to run this notification action'),\n code: NOTIFICATION_ACTION_FORBIDDEN_ERROR_CODE,\n })\n}\n\n/**\n * The command action the notification's registered type declares for a stored action: same action\n * id (across `actions` and `optionalActions`) and same `commandId`. Anything else is not dispatched.\n */\nfunction findDeclaredCommandAction(type: string, action: NotificationAction): NotificationTypeAction | null {\n const definition = getNotificationType(type)\n if (!definition) return null\n const declared = [...definition.actions, ...(definition.optionalActions ?? [])]\n .find((candidate) => candidate.id === action.id)\n if (!declared?.commandId || declared.commandId !== action.commandId) return null\n return declared\n}\n\nfunction applyNotificationContent(\n notification: Notification,\n input: NotificationContentInput,\n recipientUserId: string,\n ctx: NotificationTenantContext,\n channels: string[] | null,\n) {\n const actions = sanitizeNotificationActions(input.actions)\n const linkHref = assertSafeNotificationHref(input.linkHref)\n\n notification.recipientUserId = recipientUserId\n notification.type = input.type\n notification.titleKey = input.titleKey\n notification.bodyKey = input.bodyKey\n notification.titleVariables = input.titleVariables\n notification.bodyVariables = input.bodyVariables\n notification.title = input.title || input.titleKey || ''\n notification.body = input.body\n notification.icon = input.icon\n notification.severity = input.severity ?? 'info'\n notification.actionData = actions\n ? {\n actions,\n primaryActionId: input.primaryActionId,\n }\n : null\n notification.sourceModule = input.sourceModule\n notification.sourceEntityType = input.sourceEntityType\n notification.sourceEntityId = input.sourceEntityId\n notification.linkHref = linkHref\n notification.groupKey = input.groupKey\n notification.channels = channels\n notification.expiresAt = input.expiresAt ? new Date(input.expiresAt) : null\n notification.tenantId = ctx.tenantId\n notification.organizationId = normalizeOrgScope(ctx.organizationId)\n notification.status = 'unread'\n notification.readAt = null\n notification.actionedAt = null\n notification.dismissedAt = null\n notification.actionTaken = null\n notification.actionResult = null\n notification.createdAt = new Date()\n}\n\nasync function findScopedNotificationOrThrow(\n em: EntityManager,\n notificationId: string,\n ctx: NotificationServiceContext,\n): Promise<Notification> {\n const notification = await findOneWithDecryption(\n em,\n Notification,\n {\n id: notificationId,\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n },\n undefined,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (!notification) {\n throw new CrudHttpError(404, { error: 'Notification not found' })\n }\n return notification\n}\n\nasync function emitNotificationSseEvents(\n eventBus: { emit: (event: string, payload: unknown) => Promise<void> },\n notifications: Notification[],\n ctx: NotificationServiceContext,\n): Promise<void> {\n // Live bell updates only for notifications actually delivered to the in-app channel; the others\n // exist as records but must not bump anyone's badge/inbox.\n const visible = notifications.filter((notification) => isInAppVisible(notification.channels))\n if (visible.length === 0) return\n\n const visibleRecipientUserIds = Array.from(new Set(visible.map((n) => n.recipientUserId)))\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.BATCH_CREATED, {\n tenantId: ctx.tenantId,\n organizationId: normalizeOrgScope(ctx.organizationId),\n recipientUserIds: visibleRecipientUserIds,\n count: visible.length,\n })\n\n for (const notification of visible) {\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.CREATED, {\n tenantId: notification.tenantId,\n organizationId: notification.organizationId ?? null,\n recipientUserId: notification.recipientUserId,\n notification: toNotificationDto(notification),\n })\n }\n}\n\nasync function createOrRefreshNotification(\n em: EntityManager,\n input: NotificationContentInput,\n recipientUserId: string,\n ctx: NotificationTenantContext,\n channels: string[] | null,\n): Promise<Notification> {\n if (input.groupKey && input.groupKey.trim().length > 0) {\n const orgScope = normalizeOrgScope(ctx.organizationId) ?? 'global'\n const lockKey = `notifications:${ctx.tenantId}:${orgScope}:${recipientUserId}:${input.type}:${input.groupKey}`\n try {\n const db = getDb(em)\n await sql`select pg_advisory_xact_lock(hashtext(${lockKey}))`.execute(db)\n } catch {\n // If advisory locks are unavailable, continue with best-effort dedupe.\n }\n\n const existing = await em.findOne(Notification, {\n recipientUserId,\n tenantId: ctx.tenantId,\n organizationId: normalizeOrgScope(ctx.organizationId),\n type: input.type,\n groupKey: input.groupKey,\n status: { $in: UNIQUE_NOTIFICATION_ACTIVE_STATUSES },\n }, {\n orderBy: { createdAt: 'desc' },\n })\n\n if (existing) {\n applyNotificationContent(existing, input, recipientUserId, ctx, channels)\n return existing\n }\n }\n\n return buildNotificationEntity(em, input, recipientUserId, ctx, channels)\n}\n\nexport interface NotificationServiceContext {\n tenantId: string\n organizationId?: string | null\n organizationIds?: string[] | null\n userId?: string | null\n}\n\nexport type CreateFeatureNotificationServiceInput = CreateFeatureNotificationInput & {\n restrictRecipientsToOrganization?: boolean\n}\n\nexport type CreateBatchNotificationOptions = {\n skipExistingGroup?: boolean\n}\n\nexport interface NotificationService {\n create(input: CreateNotificationInput, ctx: NotificationServiceContext): Promise<Notification>\n createBatch(input: CreateBatchNotificationInput, ctx: NotificationServiceContext, options?: CreateBatchNotificationOptions): Promise<Notification[]>\n createForRole(input: CreateRoleNotificationInput, ctx: NotificationServiceContext): Promise<Notification[]>\n createForFeature(input: CreateFeatureNotificationServiceInput, ctx: NotificationServiceContext): Promise<Notification[]>\n markAsRead(notificationId: string, ctx: NotificationServiceContext): Promise<Notification>\n markAllAsRead(ctx: NotificationServiceContext): Promise<number>\n dismiss(notificationId: string, ctx: NotificationServiceContext): Promise<Notification>\n restoreDismissed(\n notificationId: string,\n status: 'read' | 'unread' | undefined,\n ctx: NotificationServiceContext\n ): Promise<Notification>\n executeAction(\n notificationId: string,\n input: ExecuteActionInput,\n ctx: NotificationServiceContext\n ): Promise<{ notification: Notification; result: unknown }>\n getUnreadCount(ctx: NotificationServiceContext): Promise<number>\n getPollData(ctx: NotificationServiceContext, since?: string): Promise<NotificationPollData>\n cleanupExpired(): Promise<number>\n deleteBySource(\n sourceEntityType: string,\n sourceEntityId: string,\n ctx: NotificationServiceContext\n ): Promise<number>\n}\n\nexport interface NotificationServiceDeps {\n em: EntityManager\n eventBus: { emit: (event: string, payload: unknown) => Promise<void> }\n commandBus?: {\n execute: (\n commandId: string,\n options: { input: unknown; ctx: unknown; metadata?: unknown }\n ) => Promise<{ result: unknown }>\n }\n container?: { resolve: (name: string) => unknown }\n}\n\nexport function createNotificationService(deps: NotificationServiceDeps): NotificationService {\n const { em: rootEm, eventBus, commandBus, container } = deps\n\n /**\n * Whether the clicking user holds every feature a declared notification action requires.\n * Fails closed: no user, no container, or a failing RBAC check denies the action.\n */\n const userHoldsActionFeatures = async (\n requiredFeatures: string[] | undefined,\n scopeCtx: NotificationServiceContext,\n ): Promise<boolean> => {\n if (!requiredFeatures || requiredFeatures.length === 0) return true\n if (!scopeCtx.userId || !container) return false\n try {\n const rbacService = 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 rbacService.userHasAllFeatures(\n scopeCtx.userId,\n requiredFeatures,\n { tenantId: scopeCtx.tenantId, organizationId: scopeCtx.organizationId ?? null },\n )\n return allowed === true\n } catch (err) {\n getTelemetryRuntime()?.reportError(err, {\n module: 'notifications',\n code: 'notifications.action_feature_check_failed',\n })\n return false\n }\n }\n\n /**\n * Resolves the authoritative delivery-channel set for one recipient at create time \u2014 the single\n * gate that folds per-send target, per-type eligibility, registered strategies, and the\n * recipient's per-channel preferences (`nonOptOut` bypasses opt-out). Stored on the row and\n * replayed by the dispatcher; `in_app` membership also drives bell/inbox visibility.\n *\n * Returns `null` (\u21D2 \"all channels\", legacy behavior) when no delivery strategies are registered\n * (e.g. a minimal bootstrap/test), so notifications never become silently undeliverable/invisible\n * in an environment that simply hasn't wired the seam.\n */\n const resolveChannelsFor = async (\n content: NotificationContentInput,\n recipientUserId: string,\n scopeCtx: NotificationServiceContext,\n preferences: NotificationPreferenceService = createNotificationPreferenceService({ em: rootEm.fork() }),\n typeOverrides?: NotificationTypeOverrides | null,\n ): Promise<string[] | null> => {\n const registeredChannels = getNotificationDeliveryStrategies().map((strategy) => strategy.id)\n if (registeredChannels.length === 0) return null\n // Treat an empty target as \"no restriction\" (all channels) rather than \"no deliverable channel\":\n // a programmatic caller that computed an empty array should not silently black-hole the\n // notification. The HTTP layer rejects an empty `channels` outright (see validators.ts).\n const targetChannels = content.channels && content.channels.length > 0 ? content.channels : null\n const overrides = typeOverrides === undefined\n ? (await getNotificationTypeOverrides(rootEm.fork(), scopeCtx.tenantId, [content.type])).get(content.type) ?? null\n : typeOverrides\n return resolveEffectiveChannels({\n typeId: content.type,\n type: getNotificationType(content.type),\n scope: { tenantId: scopeCtx.tenantId, userId: recipientUserId },\n targetChannels,\n registeredChannels,\n preferences,\n channelsOverride: overrides?.channels ?? null,\n nonOptOutOverride: overrides?.nonOptOut ?? null,\n })\n }\n\n /**\n * Broadcast counterpart of {@link resolveChannelsFor}: resolves the channel set for every recipient\n * up front, BEFORE the write transaction opens, reusing a single forked EM / preference service\n * across the whole set. This keeps the preference reads out of the write transaction (matching\n * `create`, which resolves before its transaction) and avoids one EM fork per recipient on large\n * role/feature broadcasts.\n */\n const resolveChannelsForRecipients = async (\n content: NotificationContentInput,\n recipientUserIds: string[],\n scopeCtx: NotificationServiceContext,\n ): Promise<Array<{ recipientUserId: string; channels: string[] | null }>> => {\n const preferences = createNotificationPreferenceService({ em: rootEm.fork() })\n // Stored overrides are per-type (not per-recipient) \u2014 read once for the whole broadcast.\n const typeOverrides =\n (await getNotificationTypeOverrides(rootEm.fork(), scopeCtx.tenantId, [content.type])).get(content.type) ?? null\n const resolved: Array<{ recipientUserId: string; channels: string[] | null }> = []\n for (const recipientUserId of recipientUserIds) {\n resolved.push({\n recipientUserId,\n channels: await resolveChannelsFor(content, recipientUserId, scopeCtx, preferences, typeOverrides),\n })\n }\n return resolved\n }\n\n return {\n async create(input, ctx) {\n const { recipientUserId, ...content } = input\n const channels = await resolveChannelsFor(content, recipientUserId, ctx)\n const writeEm = rootEm.fork()\n const notification = await writeEm.transactional(async (tx) => {\n await assertNotificationRecipientsInScope(tx, [recipientUserId], ctx)\n const entity = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n await tx.flush()\n return entity\n })\n\n await invalidateNotificationCache(container, ctx, 'created')\n // Always emit the domain event (drives the deliver subscriber \u2192 push/email/\u2026). Only bump the\n // live in-app bell when this notification is actually visible in-app.\n await emitNotificationCreated(eventBus, notification, ctx)\n if (isInAppVisible(notification.channels)) {\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.CREATED, {\n tenantId: notification.tenantId,\n organizationId: notification.organizationId ?? null,\n recipientUserId: notification.recipientUserId,\n notification: toNotificationDto(notification),\n })\n }\n\n return notification\n },\n\n async createBatch(input, ctx, options) {\n if (options?.skipExistingGroup && !input.groupKey?.trim()) {\n throw new Error('[internal] Notification group key is required for deduplicated batch delivery')\n }\n const recipientUserIds = Array.from(new Set(input.recipientUserIds))\n if (options?.skipExistingGroup) recipientUserIds.sort((left, right) => left.localeCompare(right))\n const { recipientUserIds: _recipientUserIds, ...content } = input\n const notifications: Notification[] = []\n const resolved = await resolveChannelsForRecipients(content, recipientUserIds, ctx)\n const writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n await assertNotificationRecipientsInScope(tx, recipientUserIds, ctx)\n for (const { recipientUserId, channels } of resolved) {\n if (options?.skipExistingGroup) {\n const organizationId = normalizeOrgScope(ctx.organizationId)\n const lockKey = `notifications:${ctx.tenantId}:${organizationId ?? 'global'}:${recipientUserId}:${content.type}:${content.groupKey}`\n await sql`select pg_advisory_xact_lock(hashtext(${lockKey}))`.execute(getDb(tx))\n const existing = await tx.findOne(Notification, {\n recipientUserId,\n tenantId: ctx.tenantId,\n organizationId,\n type: content.type,\n groupKey: content.groupKey,\n })\n if (existing) continue\n }\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n if (options?.skipExistingGroup && notifications.length === 0) return []\n await invalidateNotificationCache(container, ctx, 'created')\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx)\n\n return notifications\n },\n\n async createForRole(input, ctx) {\n const em = rootEm.fork()\n\n const db = getDb(em)\n const recipientUserIds = await getRecipientUserIdsForRole(db, ctx.tenantId, input.roleId)\n if (recipientUserIds.length === 0) {\n return []\n }\n\n const { roleId: _roleId, ...content } = input\n const notifications: Notification[] = []\n const uniqueRecipientUserIds = Array.from(new Set(recipientUserIds))\n const resolved = await resolveChannelsForRecipients(content, uniqueRecipientUserIds, ctx)\n const writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n for (const { recipientUserId, channels } of resolved) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await invalidateNotificationCache(container, ctx, 'created')\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx)\n\n return notifications\n },\n\n async createForFeature(input, ctx) {\n const em = rootEm.fork()\n const db = getDb(em)\n const recipientUserIds = await getRecipientUserIdsForFeature(db, ctx.tenantId, input.requiredFeature)\n\n if (recipientUserIds.length === 0) {\n debug('No users found with feature:', input.requiredFeature, 'in tenant:', ctx.tenantId)\n return []\n }\n\n let authorizedRecipientUserIds = recipientUserIds\n if (input.restrictRecipientsToOrganization) {\n const uniqueCandidateUserIds = Array.from(new Set(recipientUserIds))\n if (!ctx.organizationId) {\n logger.warn('Organization-restricted feature fan-out skipped because organization scope is missing', {\n tenantId: ctx.tenantId,\n requiredFeature: input.requiredFeature,\n })\n return []\n }\n\n if (uniqueCandidateUserIds.length > 200) {\n logger.warn('Organization-restricted feature fan-out skipped because the candidate cap was exceeded', {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n requiredFeature: input.requiredFeature,\n candidateCount: uniqueCandidateUserIds.length,\n candidateCap: 200,\n })\n return []\n }\n\n if (!container) {\n logger.warn('Organization-restricted feature fan-out skipped because the DI container is unavailable', {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n requiredFeature: input.requiredFeature,\n })\n return []\n }\n\n try {\n const rbacService = 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 allowedRecipientUserIds: string[] = []\n for (let offset = 0; offset < uniqueCandidateUserIds.length; offset += 10) {\n const candidates = uniqueCandidateUserIds.slice(offset, offset + 10)\n const results = await Promise.all(candidates.map(async (recipientUserId) => ({\n recipientUserId,\n allowed: await rbacService.userHasAllFeatures(\n recipientUserId,\n [input.requiredFeature],\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId ?? null },\n ),\n })))\n for (const result of results) {\n if (result.allowed) allowedRecipientUserIds.push(result.recipientUserId)\n }\n }\n authorizedRecipientUserIds = allowedRecipientUserIds\n } catch (err) {\n logger.warn('Organization-restricted feature fan-out skipped because RBAC filtering failed', {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n requiredFeature: input.requiredFeature,\n err,\n })\n return []\n }\n\n if (authorizedRecipientUserIds.length === 0) {\n debug('No users found with feature in organization:', input.requiredFeature, ctx.organizationId)\n return []\n }\n }\n\n debug('Creating notifications for', authorizedRecipientUserIds.length, 'user(s) with feature:', input.requiredFeature)\n\n const {\n requiredFeature: _requiredFeature,\n restrictRecipientsToOrganization: _restrictRecipientsToOrganization,\n ...content\n } = input\n const notifications: Notification[] = []\n const uniqueRecipientUserIds = Array.from(new Set(authorizedRecipientUserIds))\n const resolved = await resolveChannelsForRecipients(content, uniqueRecipientUserIds, ctx)\n const writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n for (const { recipientUserId, channels } of resolved) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await invalidateNotificationCache(container, ctx, 'created')\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx)\n\n return notifications\n },\n\n async markAsRead(notificationId, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n if (notification.status === 'unread') {\n notification.status = 'read'\n notification.readAt = new Date()\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.READ, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n }\n\n return notification\n },\n\n async markAllAsRead(ctx) {\n const em = rootEm.fork()\n const db = getDb(em)\n const applyScope = <QB extends { where: (...args: any[]) => QB }>(q: QB): QB => {\n let chain = q\n .where('recipient_user_id' as any, '=', ctx.userId as any)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .where('status' as any, '=', 'unread')\n // Only in-app-visible rows count toward the badge (see getUnreadCount),\n // so \"mark all as read\" must scope to the SAME set \u2014 otherwise it flips\n // push/email-only rows the user never saw and SSE-broadcasts a read for\n // notifications that were never in the bell, inflating the returned\n // count past what the badge showed.\n .where(inAppVisibleSql() as any)\n if (ctx.organizationId) {\n chain = chain.where('organization_id' as any, '=', ctx.organizationId)\n }\n return chain\n }\n\n const targetRows = await applyScope(\n db\n .selectFrom('notifications' as any)\n .select([\n 'id' as any,\n 'organization_id' as any,\n 'recipient_user_id' as any,\n ]),\n ).execute() as Array<{ id: string }>\n\n if (!targetRows.length) {\n return 0\n }\n\n const updateResult = await applyScope(\n db.updateTable('notifications' as any).set({\n status: 'read',\n read_at: sql`now()`,\n } as any) as any,\n ).executeTakeFirst() as { numUpdatedRows?: bigint | number } | undefined\n const result = Number(updateResult?.numUpdatedRows ?? targetRows.length)\n\n await invalidateNotificationCache(container, ctx, 'updated')\n\n const notifications = await findWithDecryption(em, Notification, {\n id: { $in: targetRows.map((row) => row.id) },\n }, undefined, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n })\n\n for (const notification of notifications) {\n await eventBus.emit(NOTIFICATION_EVENTS.READ, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.CREATED, {\n tenantId: notification.tenantId,\n organizationId: notification.organizationId ?? null,\n recipientUserId: notification.recipientUserId,\n notification: toNotificationDto(notification),\n })\n }\n\n return result\n },\n\n async dismiss(notificationId, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n notification.status = 'dismissed'\n notification.dismissedAt = new Date()\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.DISMISSED, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n\n return notification\n },\n\n async restoreDismissed(notificationId, status, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n if (notification.status !== 'dismissed') {\n return notification\n }\n\n // A dismissed notification whose action already ran comes back as `actioned`,\n // whatever the caller asked for: `actioned_at` outlives the dismissal.\n const targetStatus: NotificationStatus = notification.actionedAt != null ? 'actioned' : status ?? 'read'\n notification.status = targetStatus\n notification.dismissedAt = null\n\n if (targetStatus === 'unread') {\n notification.readAt = null\n } else if (!notification.readAt) {\n notification.readAt = new Date()\n }\n\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.RESTORED, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n status: targetStatus,\n })\n\n return notification\n },\n\n async executeAction(notificationId, input, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n const actionData = notification.actionData\n const action = actionData?.actions?.find((a) => a.id === input.actionId)\n\n if (!action) {\n throw new Error('Action not found')\n }\n\n // Reject an already-actioned notification before dispatching the command,\n // so a retry or double-click cannot re-run the side effect. `actioned_at` is\n // the durable marker: `status` is overwritten by a dismissal.\n if (notification.status === 'actioned' || notification.actionedAt != null) {\n throw actionAlreadyExecuted()\n }\n\n if (action.commandId) {\n const declared = findDeclaredCommandAction(notification.type, action)\n if (!declared || !(await userHoldsActionFeatures(declared.requiredFeatures, ctx))) {\n throw await actionForbidden()\n }\n }\n\n const actionedAt = new Date()\n const previousStatus = notification.status\n const previousActionedAt = notification.actionedAt ?? null\n const previousActionTaken = notification.actionTaken ?? null\n\n // Atomically claim the notification so only one concurrent request can run\n // the side-effecting command. The conditional UPDATE matches only while the\n // notification has not been actioned yet; a losing request updates 0 rows.\n const claimResult = (await getDb(em)\n .updateTable('notifications' as any)\n .set({\n status: 'actioned',\n actioned_at: actionedAt,\n action_taken: input.actionId,\n } as any)\n .where('id' as any, '=', notification.id)\n .where('recipient_user_id' as any, '=', ctx.userId as any)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .where('status' as any, '!=', 'actioned')\n .where('actioned_at' as any, 'is', null)\n .executeTakeFirst()) as { numUpdatedRows?: bigint | number } | undefined\n\n if (Number(claimResult?.numUpdatedRows ?? 0) === 0) {\n throw actionAlreadyExecuted()\n }\n\n // The claim is provisional: if the side-effecting command fails, the action\n // never actually completed, so release the claim to its prior state. This\n // lets the user retry the action instead of the notification being locked as\n // `actioned` forever. The claim is owned through its own `actioned_at` and\n // `action_taken`, not through `status`: a dismissal that lands while the\n // command runs overwrites `status`, and the release must still clear the\n // claim then \u2014 while leaving that dismissal in place.\n const releaseClaim = async () => {\n await getDb(em)\n .updateTable('notifications' as any)\n .set({\n status: sql`case when status = 'actioned' then ${previousStatus} else status end`,\n actioned_at: previousActionedAt,\n action_taken: previousActionTaken,\n } as any)\n .where('id' as any, '=', notification.id)\n .where('recipient_user_id' as any, '=', ctx.userId as any)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .where('actioned_at' as any, '=', actionedAt)\n .where('action_taken' as any, '=', input.actionId)\n .executeTakeFirst()\n }\n\n let result: unknown = null\n\n if (action.commandId && commandBus && container) {\n const commandInput = {\n ...input.payload,\n id: notification.sourceEntityId,\n }\n\n // Build a CommandRuntimeContext from the notification service context\n const commandCtx = {\n container,\n auth: {\n sub: ctx.userId,\n tenantId: ctx.tenantId,\n orgId: ctx.organizationId,\n },\n organizationScope: null,\n selectedOrganizationId: ctx.organizationId ?? null,\n organizationIds: ctx.organizationId ? [ctx.organizationId] : null,\n }\n\n let commandResult: { result: unknown }\n try {\n commandResult = await commandBus.execute(action.commandId, {\n input: commandInput,\n ctx: commandCtx,\n metadata: {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n resourceKind: 'notifications',\n },\n })\n } catch (err) {\n // Never let a rollback failure mask the original command error \u2014 the\n // caller needs the real failure to decide whether to retry.\n try {\n await releaseClaim()\n } catch (releaseErr) {\n debug('failed to release notification action claim', releaseErr)\n }\n throw err\n }\n\n result = commandResult.result\n }\n\n notification.status = 'actioned'\n notification.actionedAt = actionedAt\n notification.actionTaken = input.actionId\n notification.actionResult = result as Record<string, unknown>\n\n if (!notification.readAt) {\n notification.readAt = new Date()\n }\n\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.ACTIONED, {\n notificationId: notification.id,\n actionId: input.actionId,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n\n return { notification, result }\n },\n\n async getUnreadCount(ctx) {\n const em = rootEm.fork()\n return em.count(Notification, {\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n status: 'unread',\n $and: [\n buildNotificationReadScopeWhere(ctx),\n inAppVisibleFilter(),\n ],\n })\n },\n\n async getPollData(ctx, since) {\n const em = rootEm.fork()\n const filters: Record<string, unknown> = {\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n $and: [\n buildNotificationReadScopeWhere(ctx),\n inAppVisibleFilter(),\n ],\n }\n\n if (since) {\n filters.createdAt = { $gt: new Date(since) }\n }\n\n const [notifications, unreadCount] = await Promise.all([\n em.find(Notification, filters, {\n orderBy: { createdAt: 'desc' },\n limit: 50,\n }),\n em.count(Notification, {\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n status: 'unread',\n $and: [\n buildNotificationReadScopeWhere(ctx),\n inAppVisibleFilter(),\n ],\n }),\n ])\n\n const recent = notifications.map(toNotificationDto)\n const hasNew = since ? recent.length > 0 : false\n\n return {\n unreadCount,\n recent,\n hasNew,\n lastId: recent[0]?.id,\n }\n },\n\n async cleanupExpired() {\n const em = rootEm.fork()\n const db = getDb(em)\n\n const affectedScopes = await db\n .selectFrom('notifications' as any)\n .select([\n 'tenant_id' as any,\n 'organization_id' as any,\n ])\n .where('expires_at' as any, '<', sql`now()`)\n .where('status' as any, 'not in', ['actioned', 'dismissed'])\n .distinct()\n .execute() as Array<{ tenant_id: string; organization_id: string | null }>\n\n if (!affectedScopes.length) return 0\n\n const updateResult = await db\n .updateTable('notifications' as any)\n .set({\n status: 'dismissed',\n dismissed_at: sql`now()`,\n } as any)\n .where('expires_at' as any, '<', sql`now()`)\n .where('status' as any, 'not in', ['actioned', 'dismissed'])\n .executeTakeFirst() as { numUpdatedRows?: bigint | number } | undefined\n\n for (const scope of affectedScopes) {\n await invalidateNotificationCache(container, {\n tenantId: scope.tenant_id,\n organizationId: scope.organization_id,\n }, 'updated')\n }\n\n return Number(updateResult?.numUpdatedRows ?? 0)\n },\n\n async deleteBySource(sourceEntityType, sourceEntityId, ctx) {\n const em = rootEm.fork()\n const db = getDb(em)\n\n const deleteResult = await db\n .deleteFrom('notifications' as any)\n .where('source_entity_type' as any, '=', sourceEntityType)\n .where('source_entity_id' as any, '=', sourceEntityId)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .executeTakeFirst() as { numDeletedRows?: bigint | number } | undefined\n\n const deletedCount = Number(deleteResult?.numDeletedRows ?? 0)\n if (deletedCount > 0) {\n await invalidateNotificationCache(container, ctx, 'deleted')\n }\n\n return deletedCount\n },\n }\n}\n\n/**\n * Helper to create notification service from a DI container.\n * Use this in API routes and commands to avoid DI resolution issues.\n */\nexport function resolveNotificationService(container: {\n resolve: (name: string) => unknown\n}): NotificationService {\n const em = container.resolve('em') as EntityManager\n const eventBus = container.resolve('eventBus') as { emit: (event: string, payload: unknown) => Promise<void> }\n\n // commandBus may not be registered in all contexts, so resolve it safely\n let commandBus: NotificationServiceDeps['commandBus']\n try {\n commandBus = container.resolve('commandBus') as typeof commandBus\n } catch {\n // commandBus not available - actions with commandId won't work\n commandBus = undefined\n }\n\n return createNotificationService({ em, eventBus, commandBus, container })\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAsB,WAAW;AACjC,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,oBAA6C;AAEtD;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AACP,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AACpC,SAAS,qBAAqB,+BAA+B;AAC7D,SA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AAQ;AAEN,iBAAa;AAAA,EACf;AAEA,SAAO,0BAA0B,EAAE,IAAI,UAAU,YAAY,UAAU,CAAC;AAC1E;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/core",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.7769.1.0e6458bb99",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -266,16 +266,16 @@
|
|
|
266
266
|
"zod": "^4.4.3"
|
|
267
267
|
},
|
|
268
268
|
"peerDependencies": {
|
|
269
|
-
"@open-mercato/ai-assistant": "0.10.1-develop.
|
|
270
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
271
|
-
"@open-mercato/ui": "0.10.1-develop.
|
|
269
|
+
"@open-mercato/ai-assistant": "0.10.1-develop.7769.1.0e6458bb99",
|
|
270
|
+
"@open-mercato/shared": "0.10.1-develop.7769.1.0e6458bb99",
|
|
271
|
+
"@open-mercato/ui": "0.10.1-develop.7769.1.0e6458bb99",
|
|
272
272
|
"react": "^19.0.0",
|
|
273
273
|
"react-dom": "^19.0.0"
|
|
274
274
|
},
|
|
275
275
|
"devDependencies": {
|
|
276
|
-
"@open-mercato/ai-assistant": "0.10.1-develop.
|
|
277
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
278
|
-
"@open-mercato/ui": "0.10.1-develop.
|
|
276
|
+
"@open-mercato/ai-assistant": "0.10.1-develop.7769.1.0e6458bb99",
|
|
277
|
+
"@open-mercato/shared": "0.10.1-develop.7769.1.0e6458bb99",
|
|
278
|
+
"@open-mercato/ui": "0.10.1-develop.7769.1.0e6458bb99",
|
|
279
279
|
"@testing-library/dom": "^10.4.1",
|
|
280
280
|
"@testing-library/jest-dom": "^7.0.1",
|
|
281
281
|
"@testing-library/react": "^16.3.3",
|
|
@@ -66,7 +66,7 @@ export class ApiKey {
|
|
|
66
66
|
@Property({ name: 'session_token', type: 'text', nullable: true })
|
|
67
67
|
sessionToken?: string | null
|
|
68
68
|
|
|
69
|
-
/**
|
|
69
|
+
/** Owner whose effective ACL bounds a delegated MCP or session key. */
|
|
70
70
|
@Property({ name: 'session_user_id', type: 'uuid', nullable: true })
|
|
71
71
|
sessionUserId?: string | null
|
|
72
72
|
|
|
@@ -107,6 +107,7 @@ export type CreateApiKeyInput = {
|
|
|
107
107
|
roles?: string[]
|
|
108
108
|
expiresAt?: Date | null
|
|
109
109
|
createdBy?: string | null
|
|
110
|
+
sessionUserId?: string | null
|
|
110
111
|
}
|
|
111
112
|
|
|
112
113
|
export type ApiKeyWithSecret = {
|
|
@@ -154,6 +155,7 @@ export async function createApiKey(
|
|
|
154
155
|
keyPrefix: prefix,
|
|
155
156
|
rolesJson: roleIds,
|
|
156
157
|
createdBy: input.createdBy ?? null,
|
|
158
|
+
sessionUserId: input.sessionUserId ?? null,
|
|
157
159
|
expiresAt: input.expiresAt ?? null,
|
|
158
160
|
createdAt: new Date(),
|
|
159
161
|
})
|