Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

fix: permission layer follow-ups for restricted roles (settings loader, search) (#1599)

Viktor Holikd293606b4b92
diff --git a/packages/admin/src/__tests__/lazy-route-exports.spec.ts b/packages/admin/src/__tests__/lazy-route-exports.spec.ts
new file mode 100644
index 000000000..d5d37b263
--- /dev/null
+++ b/packages/admin/src/__tests__/lazy-route-exports.spec.ts
@@ -0,0 +1,126 @@
+import fs from "fs"
+import path from "path"
+import { describe, expect, test } from "vitest"
+
+/**
+ * `lazy: () => import("./pages/x")` hands the whole module to React Router, so
+ * every `loader` / `handle` / `Component` it exports becomes part of the route.
+ * A barrel that star-exports a child page leaks that page's loader onto the
+ * parent route, where it runs for members who can't access the child.
+ */
+
+const ROUTE_EXPORTS = [
+ "loader",
+ "action",
+ "handle",
+ "Component",
+ "ErrorBoundary",
+ "HydrateFallback",
+ "shouldRevalidate",
+]
+
+const src = path.resolve(__dirname, "..")
+
+const resolveModule = (from: string, specifier: string) => {
+ const base = path.resolve(from, specifier)
+ const candidates = [
+ `${base}.ts`,
+ `${base}.tsx`,
+ path.join(base, "index.ts"),
+ path.join(base, "index.tsx"),
+ ]
+ const file = candidates.find((candidate) => fs.existsSync(candidate))
+
+ if (!file) {
+ throw new Error(`Cannot resolve ${specifier} from ${from}`)
+ }
+
+ return file
+}
+
+const isDirectoryIndex = (file: string) => /^index\.tsx?$/.test(path.basename(file))
+
+const starTargets = (file: string) =>
+ [
+ ...fs
+ .readFileSync(file, "utf-8")
+ .matchAll(/^export \* from ["']([^"']+)["']/gm),
+ ].map((match) => resolveModule(path.dirname(file), match[1]))
+
+const exportedNames = (file: string, seen = new Set<string>()): Set<string> => {
+ const names = new Set<string>()
+
+ if (seen.has(file)) {
+ return names
+ }
+ seen.add(file)
+
+ const source = fs.readFileSync(file, "utf-8")
+
+ for (const match of source.matchAll(
+ /^export (?:async )?(?:const|let|var|function|class) (\w+)/gm
+ )) {
+ names.add(match[1])
+ }
+
+ for (const match of source.matchAll(/^export \{([^}]*)\}/gm)) {
+ match[1]
+ .split(",")
+ .map((entry) => entry.trim().split(/\s+as\s+/).pop())
+ .filter((name): name is string => !!name)
+ .forEach((name) => names.add(name))
+ }
+
+ for (const target of starTargets(file)) {
+ exportedNames(target, seen).forEach((name) => names.add(name))
+ }
+
+ return names
+}
+
+const leakedRouteExports = (entry: string) =>
+ starTargets(entry)
+ .filter(isDirectoryIndex)
+ .flatMap((target) =>
+ ROUTE_EXPORTS.filter((name) => exportedNames(target).has(name)).map(
+ (name) => `${name} from ${path.relative(src, target)}`
+ )
+ )
+
+const lazyModules = [
+ ...new Set(
+ [
+ ...fs
+ .readFileSync(path.join(src, "get-route-map.tsx"), "utf-8")
+ .matchAll(/lazy:\s*\(\)\s*=>\s*import\(\s*"(\.\/pages\/[^"]+)"\s*\)/g),
+ ].map((match) => match[1])
+ ),
+]
+
+describe("lazily imported route modules", () => {
+ test("the route map lazy-loads page modules", () => {
+ expect(lazyModules.length).toBeGreaterThan(0)
+ })
+
+ test("none inherit route exports from a child page", () => {
+ const leaks = lazyModules.flatMap((specifier) =>
+ leakedRouteExports(resolveModule(src, specifier)).map(
+ (leak) => `${specifier}: ${leak}`
+ )
+ )
+
+ expect(leaks).toEqual([])
+ })
+
+ test("the /settings index route has no loader", () => {
+ const routeMap = fs.readFileSync(path.join(src, "get-route-map.tsx"), "utf-8")
+ const specifier = routeMap.match(
+ /path: "\/settings",[\s\S]*?index: true,[\s\S]*?import\("([^"]+)"\)/
+ )?.[1]
+
+ expect(specifier).toBeDefined()
+ expect(exportedNames(resolveModule(src, specifier!)).has("loader")).toBe(
+ false
+ )
+ })
+})
diff --git a/packages/admin/src/components/search/__tests__/search-area-permissions.spec.ts b/packages/admin/src/components/search/__tests__/search-area-permissions.spec.ts
new file mode 100644
index 000000000..4d6a36a40
--- /dev/null
+++ b/packages/admin/src/components/search/__tests__/search-area-permissions.spec.ts
@@ -0,0 +1,14 @@
+import { describe, expect, test } from "vitest"
+import { SEARCH_AREA_PERMISSIONS, SEARCH_AREAS } from "../constants"
+
+const UNGATED = ["all", "command", "navigation"]
+
+describe("search area permissions", () => {
+ test("every area backed by an API query is gated", () => {
+ const ungated = SEARCH_AREAS.filter(
+ (area) => !UNGATED.includes(area) && !SEARCH_AREA_PERMISSIONS[area]
+ )
+
+ expect(ungated).toEqual([])
+ })
+})
diff --git a/packages/admin/src/components/search/constants.ts b/packages/admin/src/components/search/constants.ts
index 910890766..705c32a52 100644
--- a/packages/admin/src/components/search/constants.ts
+++ b/packages/admin/src/components/search/constants.ts
@@ -1,3 +1,5 @@
+import type { PermissionKey } from "@mercurjs/dashboard-sdk"
+
export const SEARCH_AREAS = [
"all",
"order",
@@ -17,5 +19,23 @@ export const SEARCH_AREAS = [
"navigation",
] as const
+export const SEARCH_AREA_PERMISSIONS: Partial<
+ Record<(typeof SEARCH_AREAS)[number], PermissionKey>
+> = {
+ order: "orders",
+ product: "products",
+ collection: "product_collections",
+ category: "product_categories",
+ inventory: "inventory_items",
+ customer: "customers",
+ seller: "sellers",
+ promotion: "promotions",
+ campaign: "campaigns",
+ priceList: "price_lists",
+ productType: "product_types",
+ productTag: "product_tags",
+ location: "stock_locations",
+}
+
export const DEFAULT_SEARCH_LIMIT = 3
export const SEARCH_LIMIT_INCREMENT = 20
diff --git a/packages/admin/src/components/search/search.tsx b/packages/admin/src/components/search/search.tsx
index 443a615aa..ee54b3255 100644
--- a/packages/admin/src/components/search/search.tsx
+++ b/packages/admin/src/components/search/search.tsx
@@ -43,6 +43,7 @@ import {
SEARCH_LIMIT_INCREMENT,
} from "./constants";
import { SearchArea } from "./types";
+import { useSearchAreaAccess } from "./use-search-area-access";
import { useSearchResults } from "./use-search-results";
import { useDocumentDirection } from "../../hooks/use-document-direction";
@@ -371,6 +372,7 @@ const CommandInput = forwardRef<
const { t } = useTranslation();
const innerRef = useRef<HTMLInputElement>(null);
const direction = useDocumentDirection();
+ const canSearchArea = useSearchAreaAccess();
useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(
ref,
() => innerRef.current,
@@ -401,7 +403,7 @@ const CommandInput = forwardRef<
value={area}
onValueChange={(v) => setArea(v as SearchArea)}
>
- {SEARCH_AREAS.map((area) => (
+ {SEARCH_AREAS.filter(canSearchArea).map((area) => (
<Fragment key={area}>
{area === "command" && <DropdownMenu.Separator />}
<DropdownMenu.RadioItem value={area}>
diff --git a/packages/admin/src/components/search/use-search-area-access.tsx b/packages/admin/src/components/search/use-search-area-access.tsx
new file mode 100644
index 000000000..2c7fd13aa
--- /dev/null
+++ b/packages/admin/src/components/search/use-search-area-access.tsx
@@ -0,0 +1,16 @@
+import { usePermissions } from "@mercurjs/dashboard-shared"
+import { useCallback } from "react"
+import { SEARCH_AREA_PERMISSIONS } from "./constants"
+import { SearchArea } from "./types"
+
+export const useSearchAreaAccess = () => {
+ const { can } = usePermissions()
+
+ return useCallback(
+ (area: SearchArea) => {
+ const key = SEARCH_AREA_PERMISSIONS[area]
+ return !key || can(key, "view")
+ },
+ [can]
+ )
+}
diff --git a/packages/admin/src/components/search/use-search-results.tsx b/packages/admin/src/components/search/use-search-results.tsx
index 5676bc0c4..65435334b 100644
--- a/packages/admin/src/components/search/use-search-results.tsx
+++ b/packages/admin/src/components/search/use-search-results.tsx
@@ -1,4 +1,5 @@
import { HttpTypes } from "@medusajs/types"
+import { usePermissions } from "@mercurjs/dashboard-shared"
import { keepPreviousData } from "@tanstack/react-query"
import { TFunction } from "i18next"
import { useCallback, useEffect, useMemo, useState } from "react"
@@ -20,7 +21,10 @@ import {
} from "../../hooks/api"
import { Shortcut, ShortcutType } from "../../providers/keybind-provider"
import { useGlobalShortcuts } from "../../providers/keybind-provider/hooks"
+import { useSearch } from "../../providers/search-provider"
+import { getRoutePermission } from "../../lib/permissions/route-permissions"
import { DynamicSearchResult, SearchArea } from "./types"
+import { useSearchAreaAccess } from "./use-search-area-access"
type UseSearchProps = {
q?: string
@@ -45,11 +49,17 @@ export const useSearchResults = ({
const useStaticSearchResults = (currentArea: SearchArea) => {
const globalCommands = useGlobalShortcuts()
+ const { hasPermission } = usePermissions()
const results = useMemo(() => {
const groups = new Map<ShortcutType, Shortcut[]>()
globalCommands.forEach((command) => {
+ const permission = command.to && getRoutePermission(command.to)
+ if (permission && !hasPermission(permission)) {
+ return
+ }
+
const group = groups.get(command.type) || []
group.push(command)
groups.set(command.type, group)
@@ -79,7 +89,7 @@ const useStaticSearchResults = (currentArea: SearchArea) => {
title,
items,
}))
- }, [globalCommands, currentArea])
+ }, [globalCommands, currentArea, hasPermission])
return results
}
@@ -92,7 +102,14 @@ const useDynamicSearchResults = (
const { t } = useTranslation()
const debouncedSearch = useDebouncedSearch(q, 300)
- const isSearchEnabled = Boolean(debouncedSearch)
+ const { open } = useSearch()
+ const canSearchArea = useSearchAreaAccess()
+
+ const isQueryEnabled = (area: SearchArea) =>
+ open &&
+ Boolean(debouncedSearch) &&
+ isAreaEnabled(currentArea, area) &&
+ canSearchArea(area)
const orderResponse = useOrders(
{
@@ -101,7 +118,7 @@ const useDynamicSearchResults = (
fields: "id,display_id,email",
},
{
- enabled: isSearchEnabled && isAreaEnabled(currentArea, "order"),
+ enabled: isQueryEnabled("order"),
placeholderData: keepPreviousData,
}
)
@@ -115,7 +132,7 @@ const useDynamicSearchResults = (
"id,title,thumbnail,-type,-collection,-options,-tags,-images,-variants,-sales_channels",
},
{
- enabled: isSearchEnabled && isAreaEnabled(currentArea, "product"),
+ enabled: isQueryEnabled("product"),
placeholderData: keepPreviousData,
}
)
@@ -128,7 +145,7 @@ const useDynamicSearchResults = (
fields: "id,name",
},
{
- enabled: isSearchEnabled && isAreaEnabled(currentArea, "category"),
+ enabled: isQueryEnabled("category"),
placeholderData: keepPreviousData,
}
)
@@ -140,7 +157,7 @@ const useDynamicSearchResults = (
fields: "id,title",
},
{
- enabled: isSearchEnabled && isAreaEnabled(currentArea, "collection"),
+ enabled: isQueryEnabled("collection"),
placeholderData: keepPreviousData,
}
)
@@ -152,7 +169,7 @@ const useDynamicSearchResults = (
fields: "id,email,first_name,last_name",
},
{
- enabled: isSearchEnabled && isAreaEnabled(currentArea, "customer"),
+ enabled: isQueryEnabled("customer"),
placeholderData: keepPreviousData,
}
)
@@ -164,7 +181,7 @@ const useDynamicSearchResults = (
fields: "id,name",
},
{
- enabled: isSearchEnabled && isAreaEnabled(currentArea, "seller"),
+ enabled: isQueryEnabled("seller"),
placeholderData: keepPreviousData,
}
)
@@ -176,7 +193,7 @@ const useDynamicSearchResults = (
fields: "id,title,sku",
},
{
- enabled: isSearchEnabled && isAreaEnabled(currentArea, "inventory"),
+ enabled: isQueryEnabled("inventory"),
placeholderData: keepPreviousData,
}
)
@@ -188,7 +205,7 @@ const useDynamicSearchResults = (
fields: "id,code,status",
},
{
- enabled: isSearchEnabled && isAreaEnabled(currentArea, "promotion"),
+ enabled: isQueryEnabled("promotion"),
placeholderData: keepPreviousData,
}
)
@@ -200,7 +217,7 @@ const useDynamicSearchResults = (
fields: "id,name",
},
{
- enabled: isSearchEnabled && isAreaEnabled(currentArea, "campaign"),
+ enabled: isQueryEnabled("campaign"),
placeholderData: keepPreviousData,
}
)
@@ -212,7 +229,7 @@ const useDynamicSearchResults = (
fields: "id,title",
},
{
- enabled: isSearchEnabled && isAreaEnabled(currentArea, "priceList"),
+ enabled: isQueryEnabled("priceList"),
placeholderData: keepPreviousData,
}
)
@@ -224,7 +241,7 @@ const useDynamicSearchResults = (
fields: "id,value",
},
{
- enabled: isSearchEnabled && isAreaEnabled(currentArea, "productType"),
+ enabled: isQueryEnabled("productType"),
placeholderData: keepPreviousData,
}
)
@@ -236,7 +253,7 @@ const useDynamicSearchResults = (
fields: "id,value",
},
{
- enabled: isSearchEnabled && isAreaEnabled(currentArea, "productTag"),
+ enabled: isQueryEnabled("productTag"),
placeholderData: keepPreviousData,
}
)
@@ -248,7 +265,7 @@ const useDynamicSearchResults = (
fields: "id,name",
},
{
- enabled: isSearchEnabled && isAreaEnabled(currentArea, "location"),
+ enabled: isQueryEnabled("location"),
placeholderData: keepPreviousData,
}
)
@@ -290,7 +307,10 @@ const useDynamicSearchResults = (
const groups = Object.entries(responseMap)
.map(([key, response]) => {
const area = key as SearchArea
- if (isAreaEnabled(currentArea, area) || currentArea === "all") {
+ if (
+ canSearchArea(area) &&
+ (isAreaEnabled(currentArea, area) || currentArea === "all")
+ ) {
return transformDynamicSearchResults(area, limit, t, response)
}
return null
@@ -298,7 +318,7 @@ const useDynamicSearchResults = (
.filter(Boolean) // Remove null values
return groups
- }, [responseMap, currentArea, limit, t])
+ }, [responseMap, currentArea, limit, t, canSearchArea])
const isAreaFetching = useCallback(
(area: SearchArea): boolean => {
diff --git a/packages/vendor/src/__tests__/lazy-route-exports.spec.ts b/packages/vendor/src/__tests__/lazy-route-exports.spec.ts
new file mode 100644
index 000000000..d5d37b263
--- /dev/null
+++ b/packages/vendor/src/__tests__/lazy-route-exports.spec.ts
@@ -0,0 +1,126 @@
+import fs from "fs"
+import path from "path"
+import { describe, expect, test } from "vitest"
+
+/**
+ * `lazy: () => import("./pages/x")` hands the whole module to React Router, so
+ * every `loader` / `handle` / `Component` it exports becomes part of the route.
+ * A barrel that star-exports a child page leaks that page's loader onto the
+ * parent route, where it runs for members who can't access the child.
+ */
+
+const ROUTE_EXPORTS = [
+ "loader",
+ "action",
+ "handle",
+ "Component",
+ "ErrorBoundary",
+ "HydrateFallback",
+ "shouldRevalidate",
+]
+
+const src = path.resolve(__dirname, "..")
+
+const resolveModule = (from: string, specifier: string) => {
+ const base = path.resolve(from, specifier)
+ const candidates = [
+ `${base}.ts`,
+ `${base}.tsx`,
+ path.join(base, "index.ts"),
+ path.join(base, "index.tsx"),
+ ]
+ const file = candidates.find((candidate) => fs.existsSync(candidate))
+
+ if (!file) {
+ throw new Error(`Cannot resolve ${specifier} from ${from}`)
+ }
+
+ return file
+}
+
+const isDirectoryIndex = (file: string) => /^index\.tsx?$/.test(path.basename(file))
+
+const starTargets = (file: string) =>
+ [
+ ...fs
+ .readFileSync(file, "utf-8")
+ .matchAll(/^export \* from ["']([^"']+)["']/gm),
+ ].map((match) => resolveModule(path.dirname(file), match[1]))
+
+const exportedNames = (file: string, seen = new Set<string>()): Set<string> => {
+ const names = new Set<string>()
+
+ if (seen.has(file)) {
+ return names
+ }
+ seen.add(file)
+
+ const source = fs.readFileSync(file, "utf-8")
+
+ for (const match of source.matchAll(
+ /^export (?:async )?(?:const|let|var|function|class) (\w+)/gm
+ )) {
+ names.add(match[1])
+ }
+
+ for (const match of source.matchAll(/^export \{([^}]*)\}/gm)) {
+ match[1]
+ .split(",")
+ .map((entry) => entry.trim().split(/\s+as\s+/).pop())
+ .filter((name): name is string => !!name)
+ .forEach((name) => names.add(name))
+ }
+
+ for (const target of starTargets(file)) {
+ exportedNames(target, seen).forEach((name) => names.add(name))
+ }
+
+ return names
+}
+
+const leakedRouteExports = (entry: string) =>
+ starTargets(entry)
+ .filter(isDirectoryIndex)
+ .flatMap((target) =>
+ ROUTE_EXPORTS.filter((name) => exportedNames(target).has(name)).map(
+ (name) => `${name} from ${path.relative(src, target)}`
+ )
+ )
+
+const lazyModules = [
+ ...new Set(
+ [
+ ...fs
+ .readFileSync(path.join(src, "get-route-map.tsx"), "utf-8")
+ .matchAll(/lazy:\s*\(\)\s*=>\s*import\(\s*"(\.\/pages\/[^"]+)"\s*\)/g),
+ ].map((match) => match[1])
+ ),
+]
+
+describe("lazily imported route modules", () => {
+ test("the route map lazy-loads page modules", () => {
+ expect(lazyModules.length).toBeGreaterThan(0)
+ })
+
+ test("none inherit route exports from a child page", () => {
+ const leaks = lazyModules.flatMap((specifier) =>
+ leakedRouteExports(resolveModule(src, specifier)).map(
+ (leak) => `${specifier}: ${leak}`
+ )
+ )
+
+ expect(leaks).toEqual([])
+ })
+
+ test("the /settings index route has no loader", () => {
+ const routeMap = fs.readFileSync(path.join(src, "get-route-map.tsx"), "utf-8")
+ const specifier = routeMap.match(
+ /path: "\/settings",[\s\S]*?index: true,[\s\S]*?import\("([^"]+)"\)/
+ )?.[1]
+
+ expect(specifier).toBeDefined()
+ expect(exportedNames(resolveModule(src, specifier!)).has("loader")).toBe(
+ false
+ )
+ })
+})
diff --git a/packages/vendor/src/components/search/__tests__/search-area-permissions.spec.ts b/packages/vendor/src/components/search/__tests__/search-area-permissions.spec.ts
new file mode 100644
index 000000000..4d6a36a40
--- /dev/null
+++ b/packages/vendor/src/components/search/__tests__/search-area-permissions.spec.ts
@@ -0,0 +1,14 @@
+import { describe, expect, test } from "vitest"
+import { SEARCH_AREA_PERMISSIONS, SEARCH_AREAS } from "../constants"
+
+const UNGATED = ["all", "command", "navigation"]
+
+describe("search area permissions", () => {
+ test("every area backed by an API query is gated", () => {
+ const ungated = SEARCH_AREAS.filter(
+ (area) => !UNGATED.includes(area) && !SEARCH_AREA_PERMISSIONS[area]
+ )
+
+ expect(ungated).toEqual([])
+ })
+})
diff --git a/packages/vendor/src/components/search/constants.ts b/packages/vendor/src/components/search/constants.ts
index aa6a974b2..83d5c81d6 100644
--- a/packages/vendor/src/components/search/constants.ts
+++ b/packages/vendor/src/components/search/constants.ts
@@ -1,3 +1,5 @@
+import type { PermissionKey } from "@mercurjs/dashboard-sdk"
+
export const SEARCH_AREAS = [
"all",
"order",
@@ -16,5 +18,22 @@ export const SEARCH_AREAS = [
"navigation",
] as const
+export const SEARCH_AREA_PERMISSIONS: Partial<
+ Record<(typeof SEARCH_AREAS)[number], PermissionKey>
+> = {
+ order: "orders",
+ product: "products",
+ collection: "product_collections",
+ category: "product_categories",
+ inventory: "inventory_items",
+ customer: "customers",
+ promotion: "promotions",
+ campaign: "campaigns",
+ priceList: "price_lists",
+ productType: "product_types",
+ productTag: "product_tags",
+ location: "stock_locations",
+}
+
export const DEFAULT_SEARCH_LIMIT = 3
export const SEARCH_LIMIT_INCREMENT = 20
diff --git a/packages/vendor/src/components/search/search.tsx b/packages/vendor/src/components/search/search.tsx
index 443a615aa..ee54b3255 100644
--- a/packages/vendor/src/components/search/search.tsx
+++ b/packages/vendor/src/components/search/search.tsx
@@ -43,6 +43,7 @@ import {
SEARCH_LIMIT_INCREMENT,
} from "./constants";
import { SearchArea } from "./types";
+import { useSearchAreaAccess } from "./use-search-area-access";
import { useSearchResults } from "./use-search-results";
import { useDocumentDirection } from "../../hooks/use-document-direction";
@@ -371,6 +372,7 @@ const CommandInput = forwardRef<
const { t } = useTranslation();
const innerRef = useRef<HTMLInputElement>(null);
const direction = useDocumentDirection();
+ const canSearchArea = useSearchAreaAccess();
useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(
ref,
() => innerRef.current,
@@ -401,7 +403,7 @@ const CommandInput = forwardRef<
value={area}
onValueChange={(v) => setArea(v as SearchArea)}
>
- {SEARCH_AREAS.map((area) => (
+ {SEARCH_AREAS.filter(canSearchArea).map((area) => (
<Fragment key={area}>
{area === "command" && <DropdownMenu.Separator />}
<DropdownMenu.RadioItem value={area}>
diff --git a/packages/vendor/src/components/search/use-search-area-access.tsx b/packages/vendor/src/components/search/use-search-area-access.tsx
new file mode 100644
index 000000000..2c7fd13aa
--- /dev/null
+++ b/packages/vendor/src/components/search/use-search-area-access.tsx
@@ -0,0 +1,16 @@
+import { usePermissions } from "@mercurjs/dashboard-shared"
+import { useCallback } from "react"
+import { SEARCH_AREA_PERMISSIONS } from "./constants"
+import { SearchArea } from "./types"
+
+export const useSearchAreaAccess = () => {
+ const { can } = usePermissions()
+
+ return useCallback(
+ (area: SearchArea) => {
+ const key = SEARCH_AREA_PERMISSIONS[area]
+ return !key || can(key, "view")
+ },
+ [can]
+ )
+}
diff --git a/packages/vendor/src/components/search/use-search-results.tsx b/packages/vendor/src/components/search/use-search-results.tsx
index 1dab82e85..14146cd2e 100644
--- a/packages/vendor/src/components/search/use-search-results.tsx
+++ b/packages/vendor/src/components/search/use-search-results.tsx
@@ -1,4 +1,5 @@
import { HttpTypes } from "@medusajs/types"
+import { usePermissions } from "@mercurjs/dashboard-shared"
import { keepPreviousData } from "@tanstack/react-query"
import { TFunction } from "i18next"
import { useCallback, useEffect, useMemo, useState } from "react"
@@ -19,7 +20,10 @@ import {
} from "../../hooks/api"
import { Shortcut, ShortcutType } from "../../providers/keybind-provider"
import { useGlobalShortcuts } from "../../providers/keybind-provider/hooks"
+import { useSearch } from "../../providers/search-provider"
+import { getRoutePermission } from "../../lib/permissions/route-permissions"
import { DynamicSearchResult, SearchArea } from "./types"
+import { useSearchAreaAccess } from "./use-search-area-access"
type UseSearchProps = {
q?: string
@@ -44,11 +48,17 @@ export const useSearchResults = ({
const useStaticSearchResults = (currentArea: SearchArea) => {
const globalCommands = useGlobalShortcuts()
+ const { hasPermission } = usePermissions()
const results = useMemo(() => {
const groups = new Map<ShortcutType, Shortcut[]>()
globalCommands.forEach((command) => {
+ const permission = command.to && getRoutePermission(command.to)
+ if (permission && !hasPermission(permission)) {
+ return
+ }
+
const group = groups.get(command.type) || []
group.push(command)
groups.set(command.type, group)
@@ -78,7 +88,7 @@ const useStaticSearchResults = (currentArea: SearchArea) => {
title,
items,
}))
- }, [globalCommands, currentArea])
+ }, [globalCommands, currentArea, hasPermission])
return results
}
@@ -91,6 +101,11 @@ const useDynamicSearchResults = (
const { t } = useTranslation()
const debouncedSearch = useDebouncedSearch(q, 300)
+ const { open } = useSearch()
+ const canSearchArea = useSearchAreaAccess()
+
+ const isQueryEnabled = (area: SearchArea) =>
+ open && isAreaEnabled(currentArea, area) && canSearchArea(area)
const orderResponse = useOrders(
{
@@ -99,7 +114,7 @@ const useDynamicSearchResults = (
fields: "id,display_id,email",
},
{
- enabled: isAreaEnabled(currentArea, "order"),
+ enabled: isQueryEnabled("order"),
placeholderData: keepPreviousData,
}
)
@@ -113,7 +128,7 @@ const useDynamicSearchResults = (
"id,title,thumbnail,-type,-collection,-options,-tags,-images,-variants,-sales_channels",
},
{
- enabled: isAreaEnabled(currentArea, "product"),
+ enabled: isQueryEnabled("product"),
placeholderData: keepPreviousData,
}
)
@@ -126,7 +141,7 @@ const useDynamicSearchResults = (
fields: "id,name",
},
{
- enabled: isAreaEnabled(currentArea, "category"),
+ enabled: isQueryEnabled("category"),
placeholderData: keepPreviousData,
}
)
@@ -138,7 +153,7 @@ const useDynamicSearchResults = (
fields: "id,title",
},
{
- enabled: isAreaEnabled(currentArea, "collection"),
+ enabled: isQueryEnabled("collection"),
placeholderData: keepPreviousData,
}
)
@@ -150,7 +165,7 @@ const useDynamicSearchResults = (
fields: "id,email,first_name,last_name",
},
{
- enabled: isAreaEnabled(currentArea, "customer"),
+ enabled: isQueryEnabled("customer"),
placeholderData: keepPreviousData,
}
)
@@ -162,7 +177,7 @@ const useDynamicSearchResults = (
fields: "id,title,sku",
},
{
- enabled: isAreaEnabled(currentArea, "inventory"),
+ enabled: isQueryEnabled("inventory"),
placeholderData: keepPreviousData,
}
)
@@ -174,7 +189,7 @@ const useDynamicSearchResults = (
fields: "id,code,status",
},
{
- enabled: isAreaEnabled(currentArea, "promotion"),
+ enabled: isQueryEnabled("promotion"),
placeholderData: keepPreviousData,
}
)
@@ -186,7 +201,7 @@ const useDynamicSearchResults = (
fields: "id,name",
},
{
- enabled: isAreaEnabled(currentArea, "campaign"),
+ enabled: isQueryEnabled("campaign"),
placeholderData: keepPreviousData,
}
)
@@ -198,7 +213,7 @@ const useDynamicSearchResults = (
fields: "id,title",
},
{
- enabled: isAreaEnabled(currentArea, "priceList"),
+ enabled: isQueryEnabled("priceList"),
placeholderData: keepPreviousData,
}
)
@@ -210,7 +225,7 @@ const useDynamicSearchResults = (
fields: "id,value",
},
{
- enabled: isAreaEnabled(currentArea, "productType"),
+ enabled: isQueryEnabled("productType"),
placeholderData: keepPreviousData,
}
)
@@ -222,7 +237,7 @@ const useDynamicSearchResults = (
fields: "id,value",
},
{
- enabled: isAreaEnabled(currentArea, "productTag"),
+ enabled: isQueryEnabled("productTag"),
placeholderData: keepPreviousData,
}
)
@@ -234,7 +249,7 @@ const useDynamicSearchResults = (
fields: "id,name",
},
{
- enabled: isAreaEnabled(currentArea, "location"),
+ enabled: isQueryEnabled("location"),
placeholderData: keepPreviousData,
}
)
@@ -274,7 +289,10 @@ const useDynamicSearchResults = (
const groups = Object.entries(responseMap)
.map(([key, response]) => {
const area = key as SearchArea
- if (isAreaEnabled(currentArea, area) || currentArea === "all") {
+ if (
+ canSearchArea(area) &&
+ (isAreaEnabled(currentArea, area) || currentArea === "all")
+ ) {
return transformDynamicSearchResults(area, limit, t, response)
}
return null
@@ -282,7 +300,7 @@ const useDynamicSearchResults = (
.filter(Boolean) // Remove null values
return groups
- }, [responseMap, currentArea, limit, t])
+ }, [responseMap, currentArea, limit, t, canSearchArea])
const isAreaFetching = useCallback(
(area: SearchArea): boolean => {
diff --git a/packages/vendor/src/get-route-map.tsx b/packages/vendor/src/get-route-map.tsx
index c4fccacd0..d15f061e5 100644
--- a/packages/vendor/src/get-route-map.tsx
+++ b/packages/vendor/src/get-route-map.tsx
@@ -1184,7 +1184,7 @@ export function getRouteMap({
{
index: true,
errorElement: <ErrorBoundary />,
- lazy: () => import("./pages/settings"),
+ lazy: () => import("./pages/settings/settings"),
},
// PROFILE