diff --git a/.changeset/webframe-url-query.md b/.changeset/webframe-url-query.md new file mode 100644 index 000000000..b17e08eb6 --- /dev/null +++ b/.changeset/webframe-url-query.md @@ -0,0 +1,6 @@ +--- +"gitbook": patch +"@gitbook/react-contentkit": patch +--- + +Allow integration webframes with the `site:url:query` scope to read non-reserved parent page query parameters via `state.page.query`, update them in place via `@webframe.updateQuery`, and pass them through `@webframe.navigate`. diff --git a/bun.lock b/bun.lock index f9c69e7cc..fd8bf48db 100644 --- a/bun.lock +++ b/bun.lock @@ -357,7 +357,7 @@ }, "catalog": { "@base-ui/react": "^1.7.0", - "@gitbook/api": "0.216.0", + "@gitbook/api": "0.218.0", "@scalar/api-client-react": "^1.3.46", "@tsconfig/node20": "^20.1.6", "@tsconfig/strictest": "^2.0.6", @@ -725,7 +725,7 @@ "@fortawesome/fontawesome-svg-core": ["@fortawesome/fontawesome-svg-core@7.2.0", "", { "dependencies": { "@fortawesome/fontawesome-common-types": "7.2.0" } }, "sha512-6639htZMjEkwskf3J+e6/iar+4cTNM9qhoWuRfj9F3eJD6r7iCzV1SWnQr2Mdv0QT0suuqU8BoJCZUyCtP9R4Q=="], - "@gitbook/api": ["@gitbook/api@0.216.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-AYByJnI+cZKYGBzxW2SH/lQTogOiRo8xpDFRrQJ6570UlJ9pOrewGs75EeMGWguvU5jO7DNt9thBarr91KPhUQ=="], + "@gitbook/api": ["@gitbook/api@0.218.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-znLZYddV7LOT0TJ1CeSWd39rUA+T8h/2egEmOXDmO/n9utoTIthTOSdo8AaOJdfFMtDpeJaLzngi1Uk7bKJK6g=="], "@gitbook/browser-types": ["@gitbook/browser-types@workspace:packages/browser-types"], diff --git a/package.json b/package.json index 7e97501cc..29362833d 100644 --- a/package.json +++ b/package.json @@ -48,7 +48,7 @@ "@tsconfig/strictest": "^2.0.6", "@tsconfig/node20": "^20.1.6", "@base-ui/react": "^1.7.0", - "@gitbook/api": "0.216.0", + "@gitbook/api": "0.218.0", "@scalar/api-client-react": "^1.3.46", "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", diff --git a/packages/gitbook/src/components/DocumentView/Integration/ContentKitWithClientContext.tsx b/packages/gitbook/src/components/DocumentView/Integration/ContentKitWithClientContext.tsx index 660851c7c..be9572ffe 100644 --- a/packages/gitbook/src/components/DocumentView/Integration/ContentKitWithClientContext.tsx +++ b/packages/gitbook/src/components/DocumentView/Integration/ContentKitWithClientContext.tsx @@ -6,15 +6,18 @@ import React from 'react'; import { ContentKit, type ContentKitClientContextData } from '@gitbook/react-contentkit/client'; import type { WebframePageContext } from './adaptive'; +import { + buildWebframeNavigateQuery, + isAllowedWebframeQuerySource, + mergeWebframeQueryUpdate, + readWebframePageQuery, +} from './webframe-query'; import { useAdaptiveVisitorAsync } from '@/components/Adaptive'; import { NavigationStatusContext } from '@/components/hooks'; import { type GitBookLinker, createLinker } from '@/lib/links'; type ContentKitProps = React.ComponentProps>; -// Query params a webframe may set when navigating: the search/ask widget params (see `useSearch`). -const ALLOWED_NAVIGATE_QUERY_PARAMS = ['q', 'ask', 'scope', 'section']; - /** Serializable inputs to rebuild the tested linker on the client (functions can't cross the RSC boundary). */ export type WebframeLinkerData = Pick< Parameters[0], @@ -23,30 +26,77 @@ export type WebframeLinkerData = Pick< /** * ContentKit wrapper for integration blocks that expose client-only capabilities to webframes: - * the current page, navigation to other pages, and adaptive visitor claims (only when the - * integration is allowed to access them). + * the current page, navigation to other pages, URL query access (scope gated), and adaptive + * visitor claims (scope gated). */ export function ContentKitWithClientContext( props: ContentKitProps & { + /** Integration name owning this block, used to verify webframe query source paths. */ + integrationName: string; + /** Host serving integration webframe content. */ + integrationsContentHost: string; /** Whether visitor claims may be exposed to the webframe (integration scope gated). */ canAccessVisitorClaims: boolean; + /** Whether parent page query parameters may be read and updated (integration scope gated). */ + canAccessUrlQuery: boolean; /** Current page to inject into the webframe, or `null` when unknown. */ page: WebframePageContext | null; /** Data to rebuild the site linker, used to resolve webframe navigation requests. */ linkerData: WebframeLinkerData; } ) { - const { canAccessVisitorClaims, page, linkerData, ...contentKitProps } = props; + const { + integrationName, + integrationsContentHost, + canAccessVisitorClaims, + canAccessUrlQuery, + page, + linkerData, + ...contentKitProps + } = props; const router = useRouter(); const { onNavigationClick } = React.useContext(NavigationStatusContext); const loadAdaptiveVisitorClaims = useAdaptiveVisitorAsync(); + const [queryRevision, setQueryRevision] = React.useState(0); + + // Sync query changes triggered by browser back/forward navigation. + // `history.replaceState` does not fire `popstate`, so webframe writes do not loop back. + React.useEffect(() => { + if (!canAccessUrlQuery) { + return; + } + + const onPopState = () => { + setQueryRevision((revision) => revision + 1); + }; + + window.addEventListener('popstate', onPopState); + return () => { + window.removeEventListener('popstate', onPopState); + }; + }, [canAccessUrlQuery]); const getVisitorContext = React.useCallback(async () => { const visitorClaims = await loadAdaptiveVisitorClaims(); return { visitor: visitorClaims?.visitor ?? null }; }, [loadAdaptiveVisitorClaims]); + const isEligibleQuerySource = React.useCallback( + (sourceUrl: string | undefined) => { + if (!canAccessUrlQuery || !sourceUrl) { + return false; + } + + return isAllowedWebframeQuerySource(sourceUrl, { + contentHost: integrationsContentHost, + integrationName, + allowInsecureHttp: process.env.NODE_ENV !== 'production', + }); + }, + [canAccessUrlQuery, integrationName, integrationsContentHost] + ); + // Rebuild the (tested) linker on the client so navigation resolves paths exactly like the rest // of the app, instead of duplicating the join logic here. const linker = React.useMemo(() => createLinker(linkerData), [linkerData]); @@ -60,25 +110,81 @@ export function ContentKitWithClientContext( }, [onNavigationClick, router] ); - const clientContext = React.useMemo( - () => ({ + const clientContext = React.useMemo(() => { + let getPageContext: ContentKitClientContextData['getPageContext']; + if (page) { + getPageContext = (sourceUrl) => { + // Touch `queryRevision` so back/forward refreshes the pushed page context. + void queryRevision; + if (isEligibleQuerySource(sourceUrl) && typeof window !== 'undefined') { + return { + page: { + ...page, + query: readWebframePageQuery(window.location.search), + }, + }; + } + return { page }; + }; + } + + let updateQuery: ContentKitClientContextData['updateQuery']; + if (canAccessUrlQuery) { + updateQuery = (updates, sourceUrl) => { + if (!isEligibleQuerySource(sourceUrl) || typeof window === 'undefined') { + return; + } + + const nextSearch = mergeWebframeQueryUpdate(window.location.search, updates); + if (nextSearch === null) { + return; + } + + let nextUrl = window.location.pathname; + if (nextSearch) { + nextUrl += `?${nextSearch}`; + } + nextUrl += window.location.hash; + + try { + window.history.replaceState(null, '', nextUrl); + } catch { + // Safari throws SecurityError if replaceState exceeds its rate limit. + } + }; + } + + return { getVisitorContext: canAccessVisitorClaims ? getVisitorContext : undefined, - getPageContext: page ? () => ({ page }) : undefined, - navigate: ({ path, anchor, query }) => { + getPageContext, + updateQuery, + navigate: ({ path, anchor, query }, sourceUrl) => { + // Strip any inline query/hash from `path` so query params always pass through filtering. + const cleanPath = path.split(/[?#]/, 1)[0] ?? ''; // Resolve the requested path relative to the site root so a webframe can navigate // to any section or space within the site (and nowhere outside it). - const params = new URLSearchParams( - Object.entries(query ?? {}).filter(([key]) => - ALLOWED_NAVIGATE_QUERY_PARAMS.includes(key) - ) - ).toString(); - const search = params ? `?${params}` : ''; - const hash = anchor ? `#${anchor}` : ''; - navigateTo(linker.toPathInSite(path) + search + hash); + const params = buildWebframeNavigateQuery(query, isEligibleQuerySource(sourceUrl)); + let search = ''; + if (params) { + search = `?${params}`; + } + let hash = ''; + if (anchor) { + hash = `#${anchor}`; + } + navigateTo(linker.toPathInSite(cleanPath) + search + hash); }, - }), - [canAccessVisitorClaims, getVisitorContext, page, linker, navigateTo] - ); + }; + }, [ + canAccessVisitorClaims, + canAccessUrlQuery, + getVisitorContext, + isEligibleQuerySource, + page, + queryRevision, + linker, + navigateTo, + ]); return ; } diff --git a/packages/gitbook/src/components/DocumentView/Integration/IntegrationBlock.tsx b/packages/gitbook/src/components/DocumentView/Integration/IntegrationBlock.tsx index ef05b6298..70cf426db 100644 --- a/packages/gitbook/src/components/DocumentView/Integration/IntegrationBlock.tsx +++ b/packages/gitbook/src/components/DocumentView/Integration/IntegrationBlock.tsx @@ -100,6 +100,7 @@ export async function IntegrationBlock(props: BlockProps diff --git a/packages/gitbook/src/components/DocumentView/Integration/webframe-query.test.ts b/packages/gitbook/src/components/DocumentView/Integration/webframe-query.test.ts new file mode 100644 index 000000000..a272697df --- /dev/null +++ b/packages/gitbook/src/components/DocumentView/Integration/webframe-query.test.ts @@ -0,0 +1,185 @@ +import { describe, expect, it } from 'bun:test'; + +import { + MAX_WEBFRAME_QUERY_LENGTH, + buildWebframeNavigateQuery, + isAllowedWebframeQuerySource, + isReservedWebframeQueryParam, + mergeWebframeQueryUpdate, + readWebframePageQuery, +} from './webframe-query'; + +describe('isReservedWebframeQueryParam', () => { + it('blocks auth, token, GitBook-owned, prefix, and prototype keys case-insensitively', () => { + const blocked = [ + 'jwt_token', + 'JWT_TOKEN', + 'token', + 'access_token', + 'id_token', + 'code', + 'state', + 'location', + 'q', + 'ask', + 'scope', + 'section', + 'theme', + 'customization', + 'fallback', + 'page', + 'tag', + 'ads_preview', + 'displayAgentInstructions', + 'markdownSource', + 'goal', + 'gitbook.country', + 'GITBOOK.custom', + 'visitor.plan', + 'VISITOR.role', + 'x-gitbook-search-indexation', + 'X-GitBook-Internal', + '__proto__', + 'constructor', + 'prototype', + '', + ' ', + ]; + for (const key of blocked) { + expect(isReservedWebframeQueryParam(key)).toBe(true); + } + }); + + it('allows normal filter parameter names', () => { + expect(isReservedWebframeQueryParam('category')).toBe(false); + expect(isReservedWebframeQueryParam('versionTags')).toBe(false); + expect(isReservedWebframeQueryParam('release_date')).toBe(false); + }); +}); + +describe('isAllowedWebframeQuerySource', () => { + const options = { + contentHost: 'content.gitbookintegrations.com', + integrationName: 'my-explorer', + }; + + it('accepts https URLs on the content host under the integration path', () => { + expect( + isAllowedWebframeQuerySource( + 'https://content.gitbookintegrations.com/v1/integrations/my-explorer/integration/webframe', + options + ) + ).toBe(true); + expect( + isAllowedWebframeQuerySource( + 'https://content.gitbookintegrations.com/v1/integrations/MY-EXPLORER/installations/inst-1/webframe', + options + ) + ).toBe(true); + }); + + it('rejects wrong host, other integration paths, traversal, and insecure http by default', () => { + expect( + isAllowedWebframeQuerySource( + 'https://integrations.gitbook.com/v1/integrations/my-explorer/integration', + options + ) + ).toBe(false); + expect( + isAllowedWebframeQuerySource( + 'https://content.gitbookintegrations.com/v1/integrations/other-app/integration', + options + ) + ).toBe(false); + expect( + isAllowedWebframeQuerySource( + 'https://content.gitbookintegrations.com/v1/integrations/my-explorer-2/integration', + options + ) + ).toBe(false); + expect( + isAllowedWebframeQuerySource( + 'https://content.gitbookintegrations.com/v1/integrations/my-explorer/../other/integration', + options + ) + ).toBe(false); + expect( + isAllowedWebframeQuerySource( + 'http://content.gitbookintegrations.com/v1/integrations/my-explorer/integration', + options + ) + ).toBe(false); + expect( + isAllowedWebframeQuerySource( + 'http://localhost:8080/v1/integrations/my-explorer/integration', + { + contentHost: 'localhost:8080', + integrationName: 'my-explorer', + allowInsecureHttp: true, + } + ) + ).toBe(true); + }); +}); + +describe('readWebframePageQuery', () => { + it('returns non-reserved parameters and strips reserved ones', () => { + const result = readWebframePageQuery( + '?category=a%2Cb&version=12.1&jwt_token=secret&token=abc&q=search&visitor.tier=pro&x-gitbook-flag=1' + ); + expect(result).toEqual({ + category: 'a,b', + version: '12.1', + }); + }); +}); + +describe('mergeWebframeQueryUpdate', () => { + it('sets, updates, and deletes allowed keys while preserving unrelated and reserved params', () => { + const next = mergeWebframeQueryUpdate('?utm_source=docs&theme=dark&category=a&old=1', { + category: 'a,b', + feature: 'api', + old: null, + theme: 'light', + token: 'injected', + }); + expect(next).toBe('utm_source=docs&theme=dark&category=a%2Cb&feature=api'); + }); + + it('deletes keys when set to empty string and returns null on no-op', () => { + expect(mergeWebframeQueryUpdate('?category=a', { category: '' })).toBe(''); + expect(mergeWebframeQueryUpdate('?category=a', { category: 'a' })).toBeNull(); + expect(mergeWebframeQueryUpdate('?theme=dark', { theme: 'light' })).toBeNull(); + }); + + it('enforces the 4 KB cap on growth while still allowing oversized queries to shrink', () => { + const bigValue = 'x'.repeat(MAX_WEBFRAME_QUERY_LENGTH); + expect(mergeWebframeQueryUpdate('', { filters: bigValue })).toBeNull(); + + const alreadyHuge = `?filters=${bigValue}&extra=1`; + expect(mergeWebframeQueryUpdate(alreadyHuge, { more: '2' })).toBeNull(); + expect(mergeWebframeQueryUpdate(alreadyHuge, { extra: null })).toBe(`filters=${bigValue}`); + }); +}); + +describe('buildWebframeNavigateQuery', () => { + it('restricts to search/ask params without site:url:query', () => { + expect( + buildWebframeNavigateQuery({ q: 'hello', category: 'a,b', token: 'secret' }, false) + ).toBe('q=hello'); + }); + + it('allows non-reserved params with site:url:query while keeping reserved params blocked', () => { + expect( + buildWebframeNavigateQuery( + { q: 'hello', category: 'a,b', token: 'secret', theme: 'dark', 'visitor.x': '1' }, + true + ) + ).toBe('q=hello&category=a%2Cb'); + }); + + it('drops extra params if the serialized navigate query exceeds 4 KB', () => { + const oversized = 'a'.repeat(MAX_WEBFRAME_QUERY_LENGTH + 10); + expect(buildWebframeNavigateQuery({ q: 'hi', filters: oversized }, true)).toBe('q=hi'); + }); +}); diff --git a/packages/gitbook/src/components/DocumentView/Integration/webframe-query.ts b/packages/gitbook/src/components/DocumentView/Integration/webframe-query.ts new file mode 100644 index 000000000..3050acb28 --- /dev/null +++ b/packages/gitbook/src/components/DocumentView/Integration/webframe-query.ts @@ -0,0 +1,185 @@ +/** Maximum serialized query string length (without leading `?`) that webframes may write. */ +export const MAX_WEBFRAME_QUERY_LENGTH = 4096; + +// Query params every webframe may set on `@webframe.navigate`: search/ask widget params (see `useSearch`). +const ALLOWED_NAVIGATE_QUERY_PARAMS = new Set(['q', 'ask', 'scope', 'section']); + +// Auth, token, and GitBook-owned query params that webframes may never read or modify. +const RESERVED_QUERY_PARAMS = new Set([ + 'jwt_token', + 'token', + 'access_token', + 'id_token', + 'code', + 'state', + 'location', + 'q', + 'ask', + 'scope', + 'section', + 'theme', + 'customization', + 'fallback', + 'page', + 'tag', + 'ads_preview', + 'displayagentinstructions', + 'markdownsource', + 'goal', + '__proto__', + 'constructor', + 'prototype', +]); + +const RESERVED_QUERY_PARAM_PREFIXES = ['visitor.', 'x-gitbook-', 'gitbook.']; + +/** + * Check whether a query parameter name is reserved and blocked from webframe read/write access. + */ +export function isReservedWebframeQueryParam(key: string): boolean { + const normalized = key.trim().toLowerCase(); + if (!normalized) { + return true; + } + + if (RESERVED_QUERY_PARAMS.has(normalized)) { + return true; + } + + for (const prefix of RESERVED_QUERY_PARAM_PREFIXES) { + if (normalized.startsWith(prefix)) { + return true; + } + } + + return false; +} + +/** + * Check whether a webframe source URL is eligible for parent-page URL query access: + * it must be served from the cookieless integrations content host under its own integration path. + */ +export function isAllowedWebframeQuerySource( + sourceUrl: string, + options: { + contentHost: string; + integrationName: string; + allowInsecureHttp?: boolean; + } +): boolean { + if (!options.contentHost || !options.integrationName) { + return false; + } + + if (!URL.canParse(sourceUrl)) { + return false; + } + + const url = new URL(sourceUrl); + const isHttps = url.protocol === 'https:'; + const isAllowedHttp = options.allowInsecureHttp === true && url.protocol === 'http:'; + if (!isHttps && !isAllowedHttp) { + return false; + } + + if (url.host !== options.contentHost) { + return false; + } + + const prefix = `/v1/integrations/${encodeURIComponent(options.integrationName).toLowerCase()}/`; + return url.pathname.toLowerCase().startsWith(prefix); +} + +/** + * Read non-reserved query parameters from a URL search string into a plain record. + */ +export function readWebframePageQuery(search: string): Record { + const params = new URLSearchParams(search); + const query: Record = {}; + + for (const [key, value] of params.entries()) { + if (isReservedWebframeQueryParam(key) || Object.hasOwn(query, key)) { + continue; + } + query[key] = value; + } + + return query; +} + +/** + * Merge a webframe query update into the current search string, preserving unrelated params, + * skipping reserved keys, and enforcing the 4 KB cap. Returns `null` when nothing should be written. + */ +export function mergeWebframeQueryUpdate( + currentSearch: string, + updates: Record +): string | null { + const params = new URLSearchParams(currentSearch); + const previousSerialized = params.toString(); + + for (const [key, value] of Object.entries(updates)) { + if (isReservedWebframeQueryParam(key)) { + continue; + } + + if (value === null || value === '') { + params.delete(key); + } else { + params.set(key, value); + } + } + + const nextSerialized = params.toString(); + if (nextSerialized === previousSerialized) { + return null; + } + + if ( + nextSerialized.length > MAX_WEBFRAME_QUERY_LENGTH && + nextSerialized.length >= previousSerialized.length + ) { + return null; + } + + return nextSerialized; +} + +/** + * Build the serialized query string (without leading `?`) for `@webframe.navigate`. + * Always permits search/ask params, and permits non-reserved params when `canAccessUrlQuery` is true. + */ +export function buildWebframeNavigateQuery( + query: Record | undefined, + canAccessUrlQuery: boolean +): string { + if (!query) { + return ''; + } + + const params = new URLSearchParams(); + for (const [key, value] of Object.entries(query)) { + if (typeof value !== 'string') { + continue; + } + + if (ALLOWED_NAVIGATE_QUERY_PARAMS.has(key)) { + params.set(key, value); + } else if (canAccessUrlQuery && !isReservedWebframeQueryParam(key)) { + params.set(key, value); + } + } + + const serialized = params.toString(); + if (!canAccessUrlQuery || serialized.length <= MAX_WEBFRAME_QUERY_LENGTH) { + return serialized; + } + + const fallbackParams = new URLSearchParams(); + for (const [key, value] of Object.entries(query)) { + if (typeof value === 'string' && ALLOWED_NAVIGATE_QUERY_PARAMS.has(key)) { + fallbackParams.set(key, value); + } + } + return fallbackParams.toString(); +} diff --git a/packages/react-contentkit/src/ElementWebframe.tsx b/packages/react-contentkit/src/ElementWebframe.tsx index 3412d2705..bd584fcdc 100644 --- a/packages/react-contentkit/src/ElementWebframe.tsx +++ b/packages/react-contentkit/src/ElementWebframe.tsx @@ -27,11 +27,11 @@ export function ElementWebframe(props: ContentKitClientElementProps { - const target = new URL(element.source.url); + const target = parseWebframeUrl(element.source.url); // For security reasons, only iframe from our integrations domains are allowed // to send and receive messages - if (!renderer.security.firstPartyDomains.includes(target.host)) { + if (!target || !renderer.security.firstPartyDomains.includes(target.host)) { return; } @@ -40,11 +40,13 @@ export function ElementWebframe(props: ContentKitClientElementProps !('state' in queued) + ); + } messagesQueueRef.current.push(message); } }, @@ -53,22 +55,20 @@ export function ElementWebframe(props: ContentKitClientElementProps { + const target = parseWebframeUrl(element.source.url); + const callback = (event: MessageEvent) => { - if (!iframeRef.current) { + if (!iframeRef.current || !target) { return; } const message = event.data; - if (!URL.canParse(event.origin)) { - return; - } - - const origin = new URL(event.origin); - - // For security reasons, only iframe from our integrations domains are allowed - // to send and receive messages - if (!renderer.security.firstPartyDomains.includes(origin.host)) { + // Require an exact origin match against the webframe source URL on a trusted domain. + if ( + !renderer.security.firstPartyDomains.includes(target.host) || + event.origin !== target.origin + ) { return; } @@ -98,7 +98,7 @@ export function ElementWebframe(props: ContentKitClientElementProps { window.removeEventListener('message', callback); }; - }, [renderer, sendMessage]); + }, [element.source.url, renderer, sendMessage]); // Send data and client-only context (visitor claims, current page) as state to the webframe. React.useEffect(() => { const abort = { cancelled: false }; sendWebframeState({ elementData: element.data, + sourceUrl: element.source.url, rendererState: renderer.state, clientContext: renderer.clientContext, sendMessage, @@ -175,7 +189,7 @@ export function ElementWebframe(props: ContentKitClientElementProps { abort.cancelled = true; }; - }, [element.data, renderer.state, renderer.clientContext, sendMessage]); + }, [element.data, element.source.url, renderer.state, renderer.clientContext, sendMessage]); const height = size.height ? Math.max(size.height, MIN_HEIGHT) : undefined; @@ -236,14 +250,70 @@ function resolveWebframeState( return state; } +/** + * Parse a webframe URL safely without throwing on malformed input. + */ +function parseWebframeUrl(url: string): URL | null { + if (!URL.canParse(url)) { + return null; + } + + return new URL(url); +} + +/** + * Validate a `@webframe.updateQuery` payload, keeping only string or null entries. + */ +function parseWebframeQueryUpdate(raw: unknown): Record | null { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { + return null; + } + + const result: Record = {}; + for (const [key, value] of Object.entries(raw)) { + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + continue; + } + if (typeof value === 'string' || value === null) { + result[key] = value; + } + } + + return result; +} + +/** + * Validate a `@webframe.navigate` query payload, keeping only string entries. + */ +function parseWebframeNavigateQuery(raw: unknown): Record | undefined { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { + return undefined; + } + + const result: Record = {}; + for (const [key, value] of Object.entries(raw)) { + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + continue; + } + if (typeof value === 'string') { + result[key] = value; + } + } + + return result; +} + /** * Resolve the optional client-only contexts (visitor claims, current page) * to merge into the webframe state. */ -async function resolveClientContexts(clientContext: ContentKitClientContextData | undefined) { +async function resolveClientContexts( + clientContext: ContentKitClientContextData | undefined, + sourceUrl: string +) { return await Promise.all([ clientContext?.getVisitorContext?.(), - clientContext?.getPageContext?.(), + clientContext?.getPageContext?.(sourceUrl), ]); } @@ -252,14 +322,15 @@ async function resolveClientContexts(clientContext: ContentKitClientContextData */ async function sendWebframeState(args: { elementData: ContentKitWebFrame['data']; + sourceUrl: string; rendererState: object; clientContext: ContentKitClientContextData | undefined; sendMessage: (message: object) => void; abort: { cancelled: boolean }; }) { - const { elementData, rendererState, clientContext, sendMessage, abort } = args; + const { elementData, sourceUrl, rendererState, clientContext, sendMessage, abort } = args; const state = resolveWebframeState(elementData, rendererState); - const clientContexts = await resolveClientContexts(clientContext); + const clientContexts = await resolveClientContexts(clientContext, sourceUrl); if (abort.cancelled) { return; diff --git a/packages/react-contentkit/src/context.ts b/packages/react-contentkit/src/context.ts index 9535ac9e0..443ae8722 100644 --- a/packages/react-contentkit/src/context.ts +++ b/packages/react-contentkit/src/context.ts @@ -26,6 +26,8 @@ export type ContentKitWebframePage = { /** Path of the page relative to the site root. */ path: string; title: string; + /** Filtered query parameters from the host page URL, included when query access is granted. */ + query?: Record; }; export type ContentKitClientContextData = { @@ -42,18 +44,29 @@ export type ContentKitClientContextData = { /** * Client-only current-page context, merged into the webframe state. */ - getPageContext?: () => + getPageContext?: ( + sourceUrl?: string + ) => | { page: ContentKitWebframePage } | null | undefined | Promise<{ page: ContentKitWebframePage } | null | undefined>; + /** + * Update query parameters on the host page in place, in response to a webframe + * `@webframe.updateQuery` action. Passing `null` or an empty string deletes a key. + */ + updateQuery?: (query: Record, sourceUrl: string) => void; + /** * Navigate the host page to another page, in response to a webframe `@webframe.navigate` * action. The destination is addressed by `path` (resolved against the site base path); the * host restricts navigation to destinations within the current site. */ - navigate?: (target: { path: string; anchor?: string; query?: Record }) => void; + navigate?: ( + target: { path: string; anchor?: string; query?: Record }, + sourceUrl?: string + ) => void; }; export interface ContentKitClientContextType {