📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
fix: Password-protected websites don't work when embedded as iframe
Blue Mouse9d5e1ddaae14
diff --git a/web/app/api/v2/client.ts b/web/app/api/v2/client.tsindex bd8af4b1b..ced73e100 100644--- a/web/app/api/v2/client.ts+++ b/web/app/api/v2/client.ts@@ -1,3 +1,5 @@+import { getProjectPassword } from '~/pages/Project/View/utils/cache'+import { V2Envelope } from './types'class V2ApiError extends Error {@@ -48,13 +50,27 @@ const serializeParams = (params: V2QueryParams): string => {return qs ? `?${qs}` : ''}+const V2_PID_REGEX = /^projects\/([^/]+)/+export async function fetchV2<T>(path: string,params: V2QueryParams = {},signal?: AbortSignal,): Promise<V2Envelope<T>> {+ // Pass the project password as a header: the swx_pp_* cookie is not sent by+ // browsers when the dashboard is embedded in a cross-site iframe.+ const headers: Record<string, string> = {}+ const pid = path.match(V2_PID_REGEX)?.[1]+ if (pid) {+ const password = getProjectPassword(pid)+ if (password) {+ headers['x-password'] = password+ }+ }+const response = await fetch(`/api/v2/${path}${serializeParams(params)}`, {signal,+ headers,})let body: any = nulldiff --git a/web/app/hooks/useAnalyticsProxy.ts b/web/app/hooks/useAnalyticsProxy.tsindex dd0b01f25..5a839ed98 100644--- a/web/app/hooks/useAnalyticsProxy.ts+++ b/web/app/hooks/useAnalyticsProxy.ts@@ -25,6 +25,7 @@ import type {AnalyticsParams as ServerAnalyticsParams,} from '~/api/api.server'import type { V2Filter } from '~/api/v2/types'+import { getProjectPassword } from '~/pages/Project/View/utils/cache'type ClientAnalyticsParams = Partial<Omit<ServerAnalyticsParams, 'password'>@@ -41,10 +42,28 @@ interface ProxyResponse<T> {error: string | null}-async function postAnalytics<T>(payload: unknown): Promise<ProxyResponse<T>> {+// Pass the project password as a header: the swx_pp_* cookie is not sent by+// browsers when the dashboard is embedded in a cross-site iframe.+const withPasswordHeader = (+ projectId: string | undefined,+ headers: Record<string, string> = {},+): Record<string, string> => {+ const password = projectId ? getProjectPassword(projectId) : null+ if (password) {+ headers['x-password'] = password+ }+ return headers+}++async function postAnalytics<T>(payload: {+ projectId?: string+ [key: string]: unknown+}): Promise<ProxyResponse<T>> {const response = await fetch('/api/analytics', {method: 'POST',- headers: { 'Content-Type': 'application/json' },+ headers: withPasswordHeader(payload.projectId, {+ 'Content-Type': 'application/json',+ }),body: JSON.stringify(payload),})@@ -197,7 +216,9 @@ export function useSessionReplayExportProxy() {) => {const response = await fetch('/api/session-replay-export', {method: 'POST',- headers: { 'Content-Type': 'application/json' },+ headers: withPasswordHeader(projectId, {+ 'Content-Type': 'application/json',+ }),signal,body: JSON.stringify({ projectId, psid, replayId }),})@@ -212,6 +233,7 @@ export function useSessionReplayExportProxy() {const query = new URLSearchParams({ projectId, exportId })const response = await fetch(`/api/session-replay-export?${query}`, {signal,+ headers: withPasswordHeader(projectId),})return parseExportProxyResponse(response)diff --git a/web/app/pages/Project/View/utils/cache.ts b/web/app/pages/Project/View/utils/cache.tsindex ce728616a..6ca0637d0 100644--- a/web/app/pages/Project/View/utils/cache.ts+++ b/web/app/pages/Project/View/utils/cache.ts@@ -7,6 +7,19 @@ export const PROJECT_PASSWORD_UPDATED_EVENT = 'swx-project-password-updated'const getAllProjectPasswords = () =>getItemJSON(LS_PROJECTS_PROTECTED_KEY) || {}+// Reads the password the same way useProjectPassword does (URL param first,+// then localStorage). Used to attach x-password headers to proxy requests, as+// cookies are unreliable when the dashboard is embedded in a cross-site iframe.+export const getProjectPassword = (id: Project['id']): string | null => {+ if (!isBrowser) {+ return null+ }++ const fromQuery = new URLSearchParams(window.location.search).get('password')++ return fromQuery || getAllProjectPasswords()[id] || null+}+export const setProjectPassword = (id: Project['id'], password: string) => {setItem(LS_PROJECTS_PROTECTED_KEY,diff --git a/web/app/routes/api.analytics.ts b/web/app/routes/api.analytics.tsindex c050a20f1..96efe3327 100644--- a/web/app/routes/api.analytics.ts+++ b/web/app/routes/api.analytics.ts@@ -138,7 +138,10 @@ export async function action({ request }: ActionFunctionArgs) {const { action, projectId, pids, params } = body- const password = getProjectPasswordCookie(request, projectId)+ // Prefer the header: cookies are not sent in cross-site iframe embeds+ const password =+ request.headers.get('x-password') ||+ getProjectPasswordCookie(request, projectId)const analyticsParams: AnalyticsParams & {take?: numberdiff --git a/web/app/routes/api.session-replay-export.ts b/web/app/routes/api.session-replay-export.tsindex 9a516f0f9..76b8f9daa 100644--- a/web/app/routes/api.session-replay-export.ts+++ b/web/app/routes/api.session-replay-export.ts@@ -48,7 +48,10 @@ export async function action({ request }: ActionFunctionArgs) {)}- const password = getProjectPasswordCookie(request, body.projectId)+ // Prefer the header: cookies are not sent in cross-site iframe embeds+ const password =+ request.headers.get('x-password') ||+ getProjectPasswordCookie(request, body.projectId)const headers: Record<string, string> = {}if (password) headers['x-password'] = password@@ -92,7 +95,9 @@ export async function loader({ request }: LoaderFunctionArgs) {)}- const password = getProjectPasswordCookie(request, projectId)+ const password =+ request.headers.get('x-password') ||+ getProjectPasswordCookie(request, projectId)const headers: Record<string, string> = {}if (password) headers['x-password'] = passworddiff --git a/web/app/routes/api.v2.$.ts b/web/app/routes/api.v2.$.tsindex 21c8698bd..87b335e22 100644--- a/web/app/routes/api.v2.$.ts+++ b/web/app/routes/api.v2.$.ts@@ -24,7 +24,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}const pid = match[1]- const password = getProjectPasswordCookie(request, pid)+ // Prefer the header: cookies are not sent in cross-site iframe embeds+ const password =+ request.headers.get('x-password') || getProjectPasswordCookie(request, pid)const { search } = new URL(request.url)const result = await serverFetch(request, `v2/${path}${search}`, {diff --git a/web/app/utils/session.server.ts b/web/app/utils/session.server.tsindex a0d5bbeab..0e74b6d83 100644--- a/web/app/utils/session.server.ts+++ b/web/app/utils/session.server.ts@@ -98,6 +98,7 @@ function buildCookieHeader(secure?: booleanhttpOnly?: booleandomain?: string+ partitioned?: boolean} = {},): string {const {@@ -107,6 +108,7 @@ function buildCookieHeader(secure = isSecureCookie(),httpOnly = true,domain = getCookieDomain(),+ partitioned = false,} = optionslet cookie = `${name}=${encodeURIComponent(value)}; Path=${path}; SameSite=${sameSite}`@@ -129,6 +131,12 @@ function buildCookieHeader(cookie += `; Domain=${domain}`}+ // CHIPS: partitioned cookies are allowed in cross-site iframes (keyed by the+ // embedding top-level site). Only valid alongside Secure.+ if (partitioned && secure) {+ cookie += '; Partitioned'+ }+return cookie}@@ -216,12 +224,18 @@ export function createProjectPasswordCookie(projectId: string,password: string,): string {+ // SameSite=None + Partitioned so the cookie keeps working when the dashboard+ // is embedded in a cross-site iframe. SameSite=None requires Secure, so fall+ // back to Lax on non-HTTPS (dev / self-hosted) environments.+ const secure = isSecureCookie()+return buildCookieHeader(`${PROJECT_PASSWORD_COOKIE_PREFIX}${projectId}`,password,{maxAge: PROJECT_PASSWORD_MAX_AGE,- sameSite: 'Lax',+ sameSite: secure ? 'None' : 'Lax',+ partitioned: secure,},)}