@open-mercato/core 0.11.1-develop.8537.1.dd5134f251 → 0.11.1-develop.8541.1.955f210e1d
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/.turbo/turbo-build.log +1 -1
- package/dist/modules/auth/services/rbacService.js +11 -12
- package/dist/modules/auth/services/rbacService.js.map +2 -2
- package/dist/modules/directory/utils/organizationScope.js +3 -2
- package/dist/modules/directory/utils/organizationScope.js.map +2 -2
- package/dist/modules/entities/api/encryption.js +13 -2
- package/dist/modules/entities/api/encryption.js.map +2 -2
- package/dist/modules/entities/api/records.js +4 -3
- package/dist/modules/entities/api/records.js.map +2 -2
- package/dist/modules/entities/backend/entities/user/[entityId]/records/page.js +22 -38
- package/dist/modules/entities/backend/entities/user/[entityId]/records/page.js.map +2 -2
- package/dist/modules/progress/api/active/route.js +11 -3
- package/dist/modules/progress/api/active/route.js.map +2 -2
- package/dist/modules/progress/api/jobPermissions.js +42 -0
- package/dist/modules/progress/api/jobPermissions.js.map +7 -0
- package/dist/modules/progress/api/jobs/[id]/route.js +6 -11
- package/dist/modules/progress/api/jobs/[id]/route.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/auth/services/rbacService.ts +12 -34
- package/src/modules/directory/utils/organizationScope.ts +3 -2
- package/src/modules/entities/api/encryption.ts +14 -2
- package/src/modules/entities/api/records.ts +4 -3
- package/src/modules/entities/backend/entities/user/[entityId]/records/page.tsx +25 -31
- package/src/modules/entities/i18n/de.json +20 -1
- package/src/modules/entities/i18n/en.json +20 -1
- package/src/modules/entities/i18n/es.json +20 -1
- package/src/modules/entities/i18n/ko.json +20 -1
- package/src/modules/entities/i18n/pl.json +20 -1
- package/src/modules/progress/api/active/route.ts +18 -3
- package/src/modules/progress/api/jobPermissions.ts +50 -0
- package/src/modules/progress/api/jobs/[id]/route.ts +7 -20
|
@@ -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 { z } from 'zod'\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 organizationIdSchema = z.guid()\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\nfunction isMalformedOrganizationSelection(selection: string | null): boolean {\n return selection !== null && !isAllOrganizationsSelection(selection) && !organizationIdSchema.safeParse(selection).success\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 ? null : normalizedRequestedSelection\n const malformedSelection = isMalformedOrganizationSelection(normalizedSelectedId)\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 && !malformedSelection ? [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) : malformedSelection ? [] : 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 const rawSelected = selectedId !== undefined ? selectedId : (request ? getSelectedOrganizationFromRequest(request) : null)\n const normalizedSelectedId = normalizeOrganizationId(rawSelected)\n const malformedSelection = isMalformedOrganizationSelection(normalizedSelectedId)\n if (!em || !rbac) {\n if (malformedSelection) {\n return {\n selectedId: null,\n filterIds: [],\n allowedIds: [],\n tenantId: normalizeString(auth.tenantId),\n selectionRejected: true,\n }\n }\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 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: malformedSelection ? '[malformed]' : 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 ...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,SAAS;AAClB,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,mCAAmC;AAI5C,SAAS,uBAAuB,0BAA8C;AAC9E,SAAS,iCAAiC,iCAAiC;AAC3E,SAAS,oBAAoB;AAE7B,MAAM,uBAAuB,EAAE,KAAK;AAEpC,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,MAA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,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 { z } from 'zod'\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 organizationIdSchema = z.guid()\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\nfunction isMalformedOrganizationSelection(selection: string | null): boolean {\n return selection !== null && !isAllOrganizationsSelection(selection) && !organizationIdSchema.safeParse(selection).success\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 ? null : normalizedRequestedSelection\n const malformedSelection = isMalformedOrganizationSelection(normalizedSelectedId)\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 && !malformedSelection ? [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) : malformedSelection ? [] : 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 const rawSelected = selectedId !== undefined ? selectedId : (request ? getSelectedOrganizationFromRequest(request) : null)\n const normalizedSelectedId = normalizeOrganizationId(rawSelected)\n const malformedSelection = isMalformedOrganizationSelection(normalizedSelectedId)\n if (!em || !rbac) {\n if (malformedSelection) {\n return {\n selectedId: null,\n filterIds: [],\n allowedIds: [],\n tenantId: normalizeString(auth.tenantId),\n selectionRejected: true,\n }\n }\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 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: malformedSelection ? '[malformed]' : 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 let 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 )).sort((left, right) => left.localeCompare(right))\n scope = {\n ...scope,\n selectedId: null,\n filterIds: approvedOrganizationIds,\n allowedIds: approvedOrganizationIds,\n tenantId: scope.tenantId,\n }\n if (!organizationId) organizationId = resolveFeatureCheckOrganizationId(scope, auth)\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,SAAS;AAClB,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,mCAAmC;AAI5C,SAAS,uBAAuB,0BAA8C;AAC9E,SAAS,iCAAiC,iCAAiC;AAC3E,SAAS,oBAAoB;AAE7B,MAAM,uBAAuB,EAAE,KAAK;AAEpC,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,kBAA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AAkC,OAAO,IAAI;AAAA,IACrF;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;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -4,7 +4,8 @@ import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
|
|
|
4
4
|
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
|
|
5
5
|
import { EncryptionMap } from "@open-mercato/core/modules/entities/data/entities";
|
|
6
6
|
import { upsertEncryptionMapSchema } from "@open-mercato/core/modules/entities/data/validators";
|
|
7
|
-
import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
7
|
+
import { CrudHttpError, forbidden, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
8
|
+
import { isExplicitlyEmptyOrganizationScope } from "@open-mercato/shared/lib/auth/organizationScope";
|
|
8
9
|
import {
|
|
9
10
|
buildOptimisticLockConflictBody,
|
|
10
11
|
enforceCommandOptimisticLock,
|
|
@@ -54,6 +55,10 @@ async function GET(req) {
|
|
|
54
55
|
if (!auth?.tenantId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
55
56
|
const container = await createRequestContainer();
|
|
56
57
|
const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
|
|
58
|
+
if (isExplicitlyEmptyOrganizationScope(scope)) {
|
|
59
|
+
const denied = forbidden();
|
|
60
|
+
return NextResponse.json(denied.body, { status: denied.status });
|
|
61
|
+
}
|
|
57
62
|
const tenantId = scope.tenantId ?? auth.tenantId;
|
|
58
63
|
const organizationId = scope.selectedId;
|
|
59
64
|
const em = container.resolve("em");
|
|
@@ -96,6 +101,7 @@ async function POST(req) {
|
|
|
96
101
|
const payload = parsed.data;
|
|
97
102
|
const container = await createRequestContainer();
|
|
98
103
|
const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
|
|
104
|
+
if (isExplicitlyEmptyOrganizationScope(scope)) throw forbidden();
|
|
99
105
|
if (scope.selectionRejected) {
|
|
100
106
|
return NextResponse.json(
|
|
101
107
|
{
|
|
@@ -200,6 +206,7 @@ const conflictResponseSchema = z.object({
|
|
|
200
206
|
currentUpdatedAt: z.string(),
|
|
201
207
|
expectedUpdatedAt: z.string()
|
|
202
208
|
});
|
|
209
|
+
const forbiddenResponseSchema = z.object({ error: z.string() });
|
|
203
210
|
const organizationSelectionInvalidResponseSchema = z.object({
|
|
204
211
|
error: z.string(),
|
|
205
212
|
code: z.literal("organization_selection_invalid")
|
|
@@ -212,7 +219,10 @@ const openApi = {
|
|
|
212
219
|
summary: "Fetch encryption map",
|
|
213
220
|
description: "Returns the encrypted field map for the current tenant/organization scope.",
|
|
214
221
|
query: z.object({ entityId: z.string() }),
|
|
215
|
-
responses: [
|
|
222
|
+
responses: [
|
|
223
|
+
{ status: 200, description: "Map", schema: z.object({ entityId: z.string(), fields: z.array(z.object({ field: z.string(), hashField: z.string().nullable().optional() })), isActive: z.boolean().optional(), updatedAt: z.string().nullable().optional() }) },
|
|
224
|
+
{ status: 403, description: "Caller can see no organization", schema: forbiddenResponseSchema }
|
|
225
|
+
]
|
|
216
226
|
},
|
|
217
227
|
POST: {
|
|
218
228
|
summary: "Upsert encryption map",
|
|
@@ -220,6 +230,7 @@ const openApi = {
|
|
|
220
230
|
requestBody: { contentType: "application/json", schema: upsertEncryptionMapSchema },
|
|
221
231
|
responses: [
|
|
222
232
|
{ status: 200, description: "Saved", schema: z.object({ ok: z.boolean(), updatedAt: z.string().nullable().optional() }) },
|
|
233
|
+
{ status: 403, description: "Caller can see no organization", schema: forbiddenResponseSchema },
|
|
223
234
|
{ status: 409, description: "Optimistic-lock conflict (stale write)", schema: conflictResponseSchema },
|
|
224
235
|
{ status: 422, description: "Selected organization is unavailable", schema: organizationSelectionInvalidResponseSchema }
|
|
225
236
|
]
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/entities/api/encryption.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { EncryptionMap } from '@open-mercato/core/modules/entities/data/entities'\nimport { upsertEncryptionMapSchema } from '@open-mercato/core/modules/entities/data/validators'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n buildOptimisticLockConflictBody,\n enforceCommandOptimisticLock,\n readOptimisticLockExpected,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { normalizeIsoToken, parseOptimisticLockEnv } from '@open-mercato/shared/lib/crud/optimistic-lock'\nimport { OPTIMISTIC_LOCK_ENV_VAR } from '@open-mercato/shared/lib/crud/optimistic-lock-headers'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport {\n EncryptionMapVersionConflictError,\n resolveCanonicalEncryptionMap,\n upsertCanonicalEncryptionMap,\n} from '@open-mercato/core/modules/entities/lib/encryption-maps'\n\nconst ENCRYPTION_MAP_RESOURCE_KIND = 'entities.encryption_map'\n\nconst logger = createLogger('entities').child({ component: 'encryption-map-api' })\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n POST: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n}\n\nfunction shouldEnforceVersionOnWrite(req: Request): boolean {\n const expected = readOptimisticLockExpected(req)\n if (!expected || normalizeIsoToken(expected) == null) return false\n const config = parseOptimisticLockEnv(process.env[OPTIMISTIC_LOCK_ENV_VAR])\n if (config.mode === 'off') return false\n return config.mode === 'all' || config.entities.has(ENCRYPTION_MAP_RESOURCE_KIND)\n}\n\nfunction toIsoOrNull(value: Date | string | null | undefined): string | null {\n if (value == null) return null\n if (value instanceof Date) {\n const ms = value.getTime()\n return Number.isFinite(ms) ? new Date(ms).toISOString() : null\n }\n const trimmed = String(value).trim()\n return trimmed.length ? trimmed : null\n}\n\nexport async function GET(req: Request) {\n const url = new URL(req.url)\n const entityId = url.searchParams.get('entityId') || ''\n if (!entityId) return NextResponse.json({ error: 'entityId is required' }, { status: 400 })\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const tenantId = scope.tenantId ?? auth.tenantId\n const organizationId = scope.selectedId\n const em = container.resolve('em') as any\n const repo = em.getRepository(EncryptionMap)\n // Prefer tenant+org, then tenant-global, then global\n const candidates = [\n { entityId, tenantId, organizationId },\n { entityId, tenantId, organizationId: null },\n { entityId, tenantId: null, organizationId: null },\n ]\n let record: ReturnType<typeof resolveCanonicalEncryptionMap> = null\n for (const where of candidates) {\n const found = await repo.find(\n { ...where, deletedAt: null },\n { orderBy: { createdAt: 'asc', id: 'asc' } },\n )\n const canonical = resolveCanonicalEncryptionMap(found)\n if (canonical) {\n record = canonical\n break\n }\n }\n\n return NextResponse.json({\n entityId,\n tenantId,\n organizationId,\n fields: record?.fieldsJson ?? [],\n isActive: record?.isActive ?? true,\n updatedAt: toIsoOrNull(record?.updatedAt),\n })\n}\n\nexport async function POST(req: Request) {\n try {\n const body = await req.json().catch(() => ({}))\n const parsed = upsertEncryptionMapSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid payload', details: parsed.error.flatten() }, { status: 400 })\n }\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const payload = parsed.data\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n if (scope.selectionRejected) {\n return NextResponse.json(\n {\n error: 'Your selected organization is no longer available. Please re-select an organization and try again.',\n code: 'organization_selection_invalid',\n },\n { status: 422 },\n )\n }\n const tenantId = scope.tenantId ?? auth.tenantId\n const organizationId = scope.selectedId\n const em = container.resolve('em') as any\n const repo = em.getRepository(EncryptionMap)\n const existingRecords = await repo.find(\n { entityId: payload.entityId, tenantId, organizationId, deletedAt: null },\n { orderBy: { createdAt: 'asc', id: 'asc' } },\n )\n const existing = resolveCanonicalEncryptionMap(existingRecords)\n\n // Reject stale writes: a save started from an older tab must not silently\n // overwrite a newer encryption configuration. No-op when the client did not\n // send the expected-version header (strictly additive).\n if (existing) {\n enforceCommandOptimisticLock({\n resourceKind: ENCRYPTION_MAP_RESOURCE_KIND,\n resourceId: existing.id,\n current: existing.updatedAt,\n request: req,\n })\n }\n\n // Mutation-guard contract for custom write routes. The resource is the\n // encryption map for this entity scoped to the tenant/organization.\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId,\n organizationId,\n userId: auth.sub,\n resourceKind: ENCRYPTION_MAP_RESOURCE_KIND,\n resourceId: existing?.id ?? payload.entityId,\n operation: existing ? 'update' : 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: payload,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n let saved: Awaited<ReturnType<typeof upsertCanonicalEncryptionMap>>\n try {\n saved = await upsertCanonicalEncryptionMap(em, {\n entityId: payload.entityId,\n tenantId,\n organizationId,\n fields: payload.fields,\n isActive: payload.isActive ?? true,\n // The version check above is advisory; this makes the write itself conditional so a\n // concurrent save that lands between that read and this upsert is not overwritten.\n expectedUpdatedAt: existing && shouldEnforceVersionOnWrite(req) ? existing.updatedAt : null,\n })\n } catch (err) {\n if (err instanceof EncryptionMapVersionConflictError) {\n const expectedIso = err.expectedUpdatedAt.toISOString()\n const currentIso = err.currentUpdatedAt ? err.currentUpdatedAt.toISOString() : expectedIso\n throw new CrudHttpError(409, buildOptimisticLockConflictBody(currentIso, expectedIso))\n }\n throw err\n }\n\n // The map row is committed and every reader resolves policy from it, so a failure to drop\n // this process's per-request memo must not turn a successful write into an error response.\n try {\n const svc = container.resolve('tenantEncryptionService') as { invalidateMap?: (e: string, t: string | null, o: string | null) => Promise<void> }\n if (!svc || typeof svc.invalidateMap !== 'function') {\n throw new Error('[internal] Tenant encryption service cannot invalidate map caches')\n }\n await svc.invalidateMap(payload.entityId, tenantId, organizationId)\n } catch (err) {\n logger.warn('Encryption map saved but post-commit invalidation failed', {\n entityId: payload.entityId,\n err,\n })\n getTelemetryRuntime()?.reportError(err, {\n module: 'entities',\n code: 'entities.encryption_map_invalidation_failed',\n attributes: { entityId: payload.entityId },\n })\n }\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId,\n organizationId,\n userId: auth.sub,\n resourceKind: ENCRYPTION_MAP_RESOURCE_KIND,\n resourceId: saved.id,\n operation: existing ? 'update' : 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return NextResponse.json({ ok: true, updatedAt: toIsoOrNull(saved.updatedAt) })\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n throw err\n }\n}\n\nconst conflictResponseSchema = z.object({\n error: z.string(),\n code: z.string(),\n currentUpdatedAt: z.string(),\n expectedUpdatedAt: z.string(),\n})\n\nconst organizationSelectionInvalidResponseSchema = z.object({\n error: z.string(),\n code: z.literal('organization_selection_invalid'),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Entities',\n summary: 'Manage encryption maps',\n methods: {\n GET: {\n summary: 'Fetch encryption map',\n description: 'Returns the encrypted field map for the current tenant/organization scope.',\n query: z.object({ entityId: z.string() }),\n responses: [{ status: 200, description: 'Map', schema: z.object({ entityId: z.string(), fields: z.array(z.object({ field: z.string(), hashField: z.string().nullable().optional() })), isActive: z.boolean().optional(), updatedAt: z.string().nullable().optional() }) }],\n },\n POST: {\n summary: 'Upsert encryption map',\n description: 'Creates or updates the encryption map for the current tenant/organization scope. Enforces optimistic locking when the caller sends the expected version header.',\n requestBody: { contentType: 'application/json', schema: upsertEncryptionMapSchema },\n responses: [\n { status: 200, description: 'Saved', schema: z.object({ ok: z.boolean(), updatedAt: z.string().nullable().optional() }) },\n { status: 409, description: 'Optimistic-lock conflict (stale write)', schema: conflictResponseSchema },\n { status: 422, description: 'Selected organization is unavailable', schema: organizationSelectionInvalidResponseSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,iCAAiC;AAC1C,SAAS,eAAe,uBAAuB;
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { EncryptionMap } from '@open-mercato/core/modules/entities/data/entities'\nimport { upsertEncryptionMapSchema } from '@open-mercato/core/modules/entities/data/validators'\nimport { CrudHttpError, forbidden, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { isExplicitlyEmptyOrganizationScope } from '@open-mercato/shared/lib/auth/organizationScope'\nimport {\n buildOptimisticLockConflictBody,\n enforceCommandOptimisticLock,\n readOptimisticLockExpected,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { normalizeIsoToken, parseOptimisticLockEnv } from '@open-mercato/shared/lib/crud/optimistic-lock'\nimport { OPTIMISTIC_LOCK_ENV_VAR } from '@open-mercato/shared/lib/crud/optimistic-lock-headers'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport {\n EncryptionMapVersionConflictError,\n resolveCanonicalEncryptionMap,\n upsertCanonicalEncryptionMap,\n} from '@open-mercato/core/modules/entities/lib/encryption-maps'\n\nconst ENCRYPTION_MAP_RESOURCE_KIND = 'entities.encryption_map'\n\nconst logger = createLogger('entities').child({ component: 'encryption-map-api' })\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n POST: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n}\n\nfunction shouldEnforceVersionOnWrite(req: Request): boolean {\n const expected = readOptimisticLockExpected(req)\n if (!expected || normalizeIsoToken(expected) == null) return false\n const config = parseOptimisticLockEnv(process.env[OPTIMISTIC_LOCK_ENV_VAR])\n if (config.mode === 'off') return false\n return config.mode === 'all' || config.entities.has(ENCRYPTION_MAP_RESOURCE_KIND)\n}\n\nfunction toIsoOrNull(value: Date | string | null | undefined): string | null {\n if (value == null) return null\n if (value instanceof Date) {\n const ms = value.getTime()\n return Number.isFinite(ms) ? new Date(ms).toISOString() : null\n }\n const trimmed = String(value).trim()\n return trimmed.length ? trimmed : null\n}\n\nexport async function GET(req: Request) {\n const url = new URL(req.url)\n const entityId = url.searchParams.get('entityId') || ''\n if (!entityId) return NextResponse.json({ error: 'entityId is required' }, { status: 400 })\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n if (isExplicitlyEmptyOrganizationScope(scope)) {\n const denied = forbidden()\n return NextResponse.json(denied.body, { status: denied.status })\n }\n const tenantId = scope.tenantId ?? auth.tenantId\n const organizationId = scope.selectedId\n const em = container.resolve('em') as any\n const repo = em.getRepository(EncryptionMap)\n // Prefer tenant+org, then tenant-global, then global\n const candidates = [\n { entityId, tenantId, organizationId },\n { entityId, tenantId, organizationId: null },\n { entityId, tenantId: null, organizationId: null },\n ]\n let record: ReturnType<typeof resolveCanonicalEncryptionMap> = null\n for (const where of candidates) {\n const found = await repo.find(\n { ...where, deletedAt: null },\n { orderBy: { createdAt: 'asc', id: 'asc' } },\n )\n const canonical = resolveCanonicalEncryptionMap(found)\n if (canonical) {\n record = canonical\n break\n }\n }\n\n return NextResponse.json({\n entityId,\n tenantId,\n organizationId,\n fields: record?.fieldsJson ?? [],\n isActive: record?.isActive ?? true,\n updatedAt: toIsoOrNull(record?.updatedAt),\n })\n}\n\nexport async function POST(req: Request) {\n try {\n const body = await req.json().catch(() => ({}))\n const parsed = upsertEncryptionMapSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid payload', details: parsed.error.flatten() }, { status: 400 })\n }\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const payload = parsed.data\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n if (isExplicitlyEmptyOrganizationScope(scope)) throw forbidden()\n if (scope.selectionRejected) {\n return NextResponse.json(\n {\n error: 'Your selected organization is no longer available. Please re-select an organization and try again.',\n code: 'organization_selection_invalid',\n },\n { status: 422 },\n )\n }\n const tenantId = scope.tenantId ?? auth.tenantId\n const organizationId = scope.selectedId\n const em = container.resolve('em') as any\n const repo = em.getRepository(EncryptionMap)\n const existingRecords = await repo.find(\n { entityId: payload.entityId, tenantId, organizationId, deletedAt: null },\n { orderBy: { createdAt: 'asc', id: 'asc' } },\n )\n const existing = resolveCanonicalEncryptionMap(existingRecords)\n\n // Reject stale writes: a save started from an older tab must not silently\n // overwrite a newer encryption configuration. No-op when the client did not\n // send the expected-version header (strictly additive).\n if (existing) {\n enforceCommandOptimisticLock({\n resourceKind: ENCRYPTION_MAP_RESOURCE_KIND,\n resourceId: existing.id,\n current: existing.updatedAt,\n request: req,\n })\n }\n\n // Mutation-guard contract for custom write routes. The resource is the\n // encryption map for this entity scoped to the tenant/organization.\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId,\n organizationId,\n userId: auth.sub,\n resourceKind: ENCRYPTION_MAP_RESOURCE_KIND,\n resourceId: existing?.id ?? payload.entityId,\n operation: existing ? 'update' : 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: payload,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n let saved: Awaited<ReturnType<typeof upsertCanonicalEncryptionMap>>\n try {\n saved = await upsertCanonicalEncryptionMap(em, {\n entityId: payload.entityId,\n tenantId,\n organizationId,\n fields: payload.fields,\n isActive: payload.isActive ?? true,\n // The version check above is advisory; this makes the write itself conditional so a\n // concurrent save that lands between that read and this upsert is not overwritten.\n expectedUpdatedAt: existing && shouldEnforceVersionOnWrite(req) ? existing.updatedAt : null,\n })\n } catch (err) {\n if (err instanceof EncryptionMapVersionConflictError) {\n const expectedIso = err.expectedUpdatedAt.toISOString()\n const currentIso = err.currentUpdatedAt ? err.currentUpdatedAt.toISOString() : expectedIso\n throw new CrudHttpError(409, buildOptimisticLockConflictBody(currentIso, expectedIso))\n }\n throw err\n }\n\n // The map row is committed and every reader resolves policy from it, so a failure to drop\n // this process's per-request memo must not turn a successful write into an error response.\n try {\n const svc = container.resolve('tenantEncryptionService') as { invalidateMap?: (e: string, t: string | null, o: string | null) => Promise<void> }\n if (!svc || typeof svc.invalidateMap !== 'function') {\n throw new Error('[internal] Tenant encryption service cannot invalidate map caches')\n }\n await svc.invalidateMap(payload.entityId, tenantId, organizationId)\n } catch (err) {\n logger.warn('Encryption map saved but post-commit invalidation failed', {\n entityId: payload.entityId,\n err,\n })\n getTelemetryRuntime()?.reportError(err, {\n module: 'entities',\n code: 'entities.encryption_map_invalidation_failed',\n attributes: { entityId: payload.entityId },\n })\n }\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId,\n organizationId,\n userId: auth.sub,\n resourceKind: ENCRYPTION_MAP_RESOURCE_KIND,\n resourceId: saved.id,\n operation: existing ? 'update' : 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return NextResponse.json({ ok: true, updatedAt: toIsoOrNull(saved.updatedAt) })\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n throw err\n }\n}\n\nconst conflictResponseSchema = z.object({\n error: z.string(),\n code: z.string(),\n currentUpdatedAt: z.string(),\n expectedUpdatedAt: z.string(),\n})\n\nconst forbiddenResponseSchema = z.object({ error: z.string() })\n\nconst organizationSelectionInvalidResponseSchema = z.object({\n error: z.string(),\n code: z.literal('organization_selection_invalid'),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Entities',\n summary: 'Manage encryption maps',\n methods: {\n GET: {\n summary: 'Fetch encryption map',\n description: 'Returns the encrypted field map for the current tenant/organization scope.',\n query: z.object({ entityId: z.string() }),\n responses: [\n { status: 200, description: 'Map', schema: z.object({ entityId: z.string(), fields: z.array(z.object({ field: z.string(), hashField: z.string().nullable().optional() })), isActive: z.boolean().optional(), updatedAt: z.string().nullable().optional() }) },\n { status: 403, description: 'Caller can see no organization', schema: forbiddenResponseSchema },\n ],\n },\n POST: {\n summary: 'Upsert encryption map',\n description: 'Creates or updates the encryption map for the current tenant/organization scope. Enforces optimistic locking when the caller sends the expected version header.',\n requestBody: { contentType: 'application/json', schema: upsertEncryptionMapSchema },\n responses: [\n { status: 200, description: 'Saved', schema: z.object({ ok: z.boolean(), updatedAt: z.string().nullable().optional() }) },\n { status: 403, description: 'Caller can see no organization', schema: forbiddenResponseSchema },\n { status: 409, description: 'Optimistic-lock conflict (stale write)', schema: conflictResponseSchema },\n { status: 422, description: 'Selected organization is unavailable', schema: organizationSelectionInvalidResponseSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,iCAAiC;AAC1C,SAAS,eAAe,WAAW,uBAAuB;AAC1D,SAAS,0CAA0C;AACnD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB,8BAA8B;AAC1D,SAAS,+BAA+B;AACxC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,0CAA0C;AACnD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,+BAA+B;AAErC,MAAM,SAAS,aAAa,UAAU,EAAE,MAAM,EAAE,WAAW,qBAAqB,CAAC;AAE1E,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,6BAA6B,EAAE;AAAA,EAC3E,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,6BAA6B,EAAE;AAC9E;AAEA,SAAS,4BAA4B,KAAuB;AAC1D,QAAM,WAAW,2BAA2B,GAAG;AAC/C,MAAI,CAAC,YA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AAQ,KAAK,aAAa,kCAAkC,QAAQ,wBAAwB;AAAA,QAC9F,EAAE,QAAQ,KAAK,aAAa,0CAA0C,QAAQ,uBAAuB;AAAA,QACrG,EAAE,QAAQ,KAAK,aAAa,wCAAwC,QAAQ,2CAA2C;AAAA,MACzH;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -3,7 +3,7 @@ import { z } from "zod";
|
|
|
3
3
|
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
|
|
4
4
|
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
|
|
5
5
|
import { normalizeExportFormat, serializeExport, defaultExportFilename, ensureColumns } from "@open-mercato/shared/lib/crud/exporters";
|
|
6
|
-
import { resolveOrganizationScope, getSelectedOrganizationFromRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
|
|
6
|
+
import { resolveOrganizationScope, resolveOrganizationScopeForRequest, getSelectedOrganizationFromRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
|
|
7
7
|
import { resolveSingleOrganizationIdOrDeny } from "@open-mercato/core/modules/directory/utils/organizationScopeFilter";
|
|
8
8
|
import { SYSTEM_ENTITY_RECORDS_BLOCKED_CODE } from "@open-mercato/shared/lib/data/engine";
|
|
9
9
|
import { parseBooleanToken, parseBooleanWithDefault } from "@open-mercato/shared/lib/boolean";
|
|
@@ -99,11 +99,12 @@ async function GET(req) {
|
|
|
99
99
|
qpEntries.push([key, val]);
|
|
100
100
|
}
|
|
101
101
|
try {
|
|
102
|
-
const
|
|
102
|
+
const container = await createRequestContainer();
|
|
103
|
+
const { resolve } = container;
|
|
103
104
|
const qe = resolve("queryEngine");
|
|
104
105
|
const em = resolve("em");
|
|
105
106
|
const rbac = resolve("rbacService");
|
|
106
|
-
const scope = await
|
|
107
|
+
const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
|
|
107
108
|
let organizationIds = scope.filterIds;
|
|
108
109
|
const { kind: entityKind, restricted: isRestricted } = await classifyRecordsEntity(em, entityId, { tenantId: auth.tenantId ?? null, organizationId: resolveSingleOrganizationIdOrDeny(scope, auth) ?? null });
|
|
109
110
|
if (entityKind === "system") return systemEntityRecordsRejection(entityId);
|