Files
klz-cables.com/.pnpm-store/v10/files/c1/e017959fb1189ae9858fc02e9341ce1f1f4156f949737a6ee8ecd9ef7b682e52fd79788a193a82450305fbc630dbf3b2c8c96605e64c46aa56f442f7221635
Marc Mintel 5397309103
Some checks failed
Build & Deploy / 🔍 Prepare (push) Successful in 20s
Build & Deploy / 🧪 QA (push) Failing after 34s
Build & Deploy / 🏗️ Build (push) Has started running
Build & Deploy / 🚀 Deploy (push) Has been cancelled
Build & Deploy / 🧪 Smoke Test (push) Has been cancelled
Build & Deploy / ⚡ Lighthouse (push) Has been cancelled
Build & Deploy / 🔔 Notify (push) Has been cancelled
fix(products): fix breadcrumbs and product filtering (backport from main)
2026-02-24 16:04:21 +01:00

1 line
13 KiB
Plaintext

{"version":3,"sources":["../../../src/utilities/getEntityPermissions/getEntityPermissions.ts"],"sourcesContent":["import { isDeepStrictEqual } from 'util'\n\nimport type {\n BlockPermissions,\n CollectionPermission,\n FieldsPermissions,\n GlobalPermission,\n Permission,\n} from '../../auth/types.js'\nimport type { SanitizedCollectionConfig, TypeWithID } from '../../collections/config/types.js'\nimport type { SanitizedGlobalConfig } from '../../globals/config/types.js'\nimport type { BlockSlug, DefaultDocumentIDType } from '../../index.js'\nimport type { AllOperations, JsonObject, PayloadRequest, Where } from '../../types/index.js'\n\nimport { entityDocExists } from './entityDocExists.js'\nimport { populateFieldPermissions } from './populateFieldPermissions.js'\n\ntype WhereQueryCache = { result: Promise<boolean>; where: Where }[]\n\nexport type BlockReferencesPermissions = Record<\n BlockSlug,\n BlockPermissions | Promise<BlockPermissions>\n>\n\nexport type EntityDoc = JsonObject | TypeWithID\n\ntype ReturnType<TEntityType extends 'collection' | 'global'> = TEntityType extends 'global'\n ? GlobalPermission\n : CollectionPermission\n\ntype Args<TEntityType extends 'collection' | 'global'> = {\n blockReferencesPermissions: BlockReferencesPermissions\n /**\n * If the document data is passed, it will be used to check access instead of fetching the document from the database.\n */\n data?: JsonObject\n entity: TEntityType extends 'collection' ? SanitizedCollectionConfig : SanitizedGlobalConfig\n entityType: TEntityType\n /**\n * Operations to check access for\n */\n operations: AllOperations[]\n req: PayloadRequest\n} & (\n | {\n fetchData: false\n id?: never\n }\n | {\n fetchData: true\n id: TEntityType extends 'collection' ? DefaultDocumentIDType : undefined\n }\n)\n\nconst topLevelCollectionPermissions = [\n 'create',\n 'delete',\n 'read',\n 'readVersions',\n 'update',\n 'unlock',\n]\nconst topLevelGlobalPermissions = ['read', 'readVersions', 'update']\n\n/**\n * Build up permissions object for an entity (collection or global).\n * This is not run during any update and reflects the current state of the entity data => doc and data is the same.\n *\n * When `fetchData` is false:\n * - returned `Where` are not run and evaluated as \"does not have permission\".\n * - If req.data is passed: `data` and `doc` is passed to access functions.\n * - If req.data is not passed: `data` and `doc` is not passed to access functions.\n *\n * When `fetchData` is true:\n * - `Where` are run and evaluated as \"has permission\" or \"does not have permission\".\n * - `data` and `doc` are always passed to access functions.\n * - Error is thrown if `entityType` is 'collection' and `id` is not passed.\n *\n * In both cases:\n * We cannot include siblingData or blockData here, as we do not have siblingData available once we reach block or array\n * rows, as we're calculating schema permissions, which do not include individual rows.\n * For consistency, it's thus better to never include the siblingData and blockData\n *\n * @internal\n */\nexport async function getEntityPermissions<TEntityType extends 'collection' | 'global'>(\n args: Args<TEntityType>,\n): Promise<ReturnType<TEntityType>> {\n const {\n id,\n blockReferencesPermissions,\n data: _data,\n entity,\n entityType,\n fetchData,\n operations,\n req,\n } = args\n const { locale: _locale, user } = req\n\n const locale = _locale ? _locale : undefined\n\n if (fetchData && entityType === 'collection' && !id) {\n throw new Error('ID is required when fetching data for a collection')\n }\n\n const hasData = _data && Object.keys(_data).length > 0\n const data: JsonObject | undefined = hasData\n ? _data\n : fetchData\n ? await (async () => {\n if (entityType === 'global') {\n return req.payload.findGlobal({\n slug: entity.slug,\n depth: 0,\n fallbackLocale: null,\n locale,\n overrideAccess: true,\n req,\n })\n }\n\n if (entityType === 'collection') {\n return req.payload.findByID({\n id: id!,\n collection: entity.slug,\n depth: 0,\n fallbackLocale: null,\n locale,\n overrideAccess: true,\n req,\n trash: true,\n })\n }\n })()\n : undefined\n\n const isLoggedIn = !!user\n\n const fieldsPermissions: FieldsPermissions = {}\n\n const entityPermissions: ReturnType<TEntityType> = {\n fields: fieldsPermissions,\n } as ReturnType<TEntityType>\n\n const promises: Promise<void>[] = []\n\n // Phase 1: Resolve all access functions to get where queries\n const accessResults: {\n operation: keyof typeof entity.access\n result: Promise<boolean | Where>\n }[] = []\n\n for (const _operation of operations) {\n const operation = _operation as keyof typeof entity.access\n const accessFunction = entity.access[operation]\n\n if (\n (entityType === 'collection' && topLevelCollectionPermissions.includes(operation)) ||\n (entityType === 'global' && topLevelGlobalPermissions.includes(operation))\n ) {\n if (typeof accessFunction === 'function') {\n accessResults.push({\n operation,\n result: Promise.resolve(accessFunction({ id, data, req })) as Promise<boolean | Where>,\n })\n } else {\n entityPermissions[operation] = {\n permission: isLoggedIn,\n }\n }\n }\n }\n\n // Await all access functions in parallel\n const resolvedAccessResults = await Promise.all(\n accessResults.map(async (item) => ({\n operation: item.operation,\n result: await item.result,\n })),\n )\n\n // Phase 2: Process where queries with cache and resolve in parallel\n const whereQueryCache: WhereQueryCache = []\n const wherePromises: Promise<void>[] = []\n\n for (const { operation, result: accessResult } of resolvedAccessResults) {\n if (typeof accessResult === 'object') {\n processWhereQuery({\n id,\n slug: entity.slug,\n accessResult,\n entityPermissions,\n entityType,\n fetchData,\n locale,\n operation,\n req,\n wherePromises,\n whereQueryCache,\n })\n } else if (entityPermissions[operation]?.permission !== false) {\n entityPermissions[operation] = { permission: !!accessResult }\n }\n }\n\n // Await all where query DB calls in parallel\n await Promise.all(wherePromises)\n\n populateFieldPermissions({\n blockReferencesPermissions,\n data,\n fields: entity.fields,\n operations,\n parentPermissionsObject: entityPermissions,\n permissionsObject: fieldsPermissions,\n promises,\n req,\n })\n\n /**\n * Await all promises in parallel.\n * A promise can add more promises to the promises array (group of fields calls populateFieldPermissions again in their own promise), which will not be\n * awaited in the first run.\n * This is why we need to loop again to process the new promises, until there are no more promises left.\n */\n let iterations = 0\n while (promises.length > 0) {\n const currentPromises = promises.splice(0, promises.length)\n\n await Promise.all(currentPromises)\n\n iterations++\n if (iterations >= 100) {\n throw new Error('Infinite getEntityPermissions promise loop detected.')\n }\n }\n\n return entityPermissions\n}\n\nconst processWhereQuery = ({\n id,\n slug,\n accessResult,\n entityPermissions,\n entityType,\n fetchData,\n locale,\n operation,\n req,\n wherePromises,\n whereQueryCache,\n}: {\n accessResult: Where\n entityPermissions: CollectionPermission | GlobalPermission\n entityType: 'collection' | 'global'\n fetchData: boolean\n id?: DefaultDocumentIDType\n locale?: string\n operation: Extract<keyof (CollectionPermission | GlobalPermission), AllOperations>\n req: PayloadRequest\n slug: string\n wherePromises: Promise<void>[]\n whereQueryCache: WhereQueryCache\n}): void => {\n if (fetchData) {\n // Check cache for identical where query using deep comparison\n let cached = whereQueryCache.find((entry) => isDeepStrictEqual(entry.where, accessResult))\n\n if (!cached) {\n // Cache miss - start DB query (don't await)\n cached = {\n result: entityDocExists({\n id,\n slug,\n entityType,\n locale,\n operation,\n req,\n where: accessResult,\n }),\n where: accessResult,\n }\n whereQueryCache.push(cached)\n }\n\n // Defer resolution to Promise.all (cache hits reuse same promise)\n wherePromises.push(\n cached.result.then((hasPermission) => {\n entityPermissions[operation] = {\n permission: hasPermission,\n where: accessResult,\n } as Permission\n }),\n )\n } else {\n // TODO: 4.0: Investigate defaulting to `false` here, if where query is returned but ignored as we don't\n // have the document data available. This seems more secure.\n // Alternatively, we could set permission to a third state, like 'unknown'.\n // Even after calling sanitizePermissions, the permissions will still be true if the where query is returned but ignored as we don't have the document data available.\n entityPermissions[operation] = { permission: true, where: accessResult } as Permission\n }\n}\n"],"names":["isDeepStrictEqual","entityDocExists","populateFieldPermissions","topLevelCollectionPermissions","topLevelGlobalPermissions","getEntityPermissions","args","id","blockReferencesPermissions","data","_data","entity","entityType","fetchData","operations","req","locale","_locale","user","undefined","Error","hasData","Object","keys","length","payload","findGlobal","slug","depth","fallbackLocale","overrideAccess","findByID","collection","trash","isLoggedIn","fieldsPermissions","entityPermissions","fields","promises","accessResults","_operation","operation","accessFunction","access","includes","push","result","Promise","resolve","permission","resolvedAccessResults","all","map","item","whereQueryCache","wherePromises","accessResult","processWhereQuery","parentPermissionsObject","permissionsObject","iterations","currentPromises","splice","cached","find","entry","where","then","hasPermission"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,OAAM;AAcxC,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,wBAAwB,QAAQ,gCAA+B;AAuCxE,MAAMC,gCAAgC;IACpC;IACA;IACA;IACA;IACA;IACA;CACD;AACD,MAAMC,4BAA4B;IAAC;IAAQ;IAAgB;CAAS;AAEpE;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,eAAeC,qBACpBC,IAAuB;IAEvB,MAAM,EACJC,EAAE,EACFC,0BAA0B,EAC1BC,MAAMC,KAAK,EACXC,MAAM,EACNC,UAAU,EACVC,SAAS,EACTC,UAAU,EACVC,GAAG,EACJ,GAAGT;IACJ,MAAM,EAAEU,QAAQC,OAAO,EAAEC,IAAI,EAAE,GAAGH;IAElC,MAAMC,SAASC,UAAUA,UAAUE;IAEnC,IAAIN,aAAaD,eAAe,gBAAgB,CAACL,IAAI;QACnD,MAAM,IAAIa,MAAM;IAClB;IAEA,MAAMC,UAAUX,SAASY,OAAOC,IAAI,CAACb,OAAOc,MAAM,GAAG;IACrD,MAAMf,OAA+BY,UACjCX,QACAG,YACE,MAAM,AAAC,CAAA;QACL,IAAID,eAAe,UAAU;YAC3B,OAAOG,IAAIU,OAAO,CAACC,UAAU,CAAC;gBAC5BC,MAAMhB,OAAOgB,IAAI;gBACjBC,OAAO;gBACPC,gBAAgB;gBAChBb;gBACAc,gBAAgB;gBAChBf;YACF;QACF;QAEA,IAAIH,eAAe,cAAc;YAC/B,OAAOG,IAAIU,OAAO,CAACM,QAAQ,CAAC;gBAC1BxB,IAAIA;gB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