Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Harden mobile organization settings

rcourtman8fbbed4d05c5
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 33fdd95e51..55e15b1473 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -3827,20 +3827,62 @@
},
{
"id": "RA34",
- "summary": "Every authenticated Pulse product and Settings page remains usable at supported phone widths: page-level overflow stays contained; dense tables and tab rails scroll instead of compressing or wrapping; active destinations, expanded inline detail, and Settings navigation remain visible; primary touch actions keep a 40-pixel mobile floor; and exact-route browser proof must not count redirects as audited pages.",
+ "summary": "Every authenticated Pulse product and Settings page remains usable at supported phone widths, including capability-gated organization and hosted-administration surfaces rendered under their real runtime modes: page-level overflow stays contained; dense tables and tab rails scroll instead of compressing or wrapping; active destinations, expanded inline detail, and Settings navigation remain visible; primary touch actions keep a 40-pixel mobile floor; and exact-route browser proof must not count redirects as audited pages.",
"kind": "invariant",
"blocking_level": "repo-ready",
"proof_type": "automated",
"lane_ids": [
+ "L3",
+ "L6",
"L8",
- "L10"
+ "L10",
+ "L14"
],
"subsystem_ids": [
+ "api-contracts",
+ "cloud-paid",
"frontend-primitives",
+ "organization-settings",
"performance-and-scalability"
],
"release_gate_ids": [],
"proof_commands": [
+ {
+ "id": "hosted-billing-admin-mobile-browser-proof",
+ "run": [
+ "env",
+ "PULSE_E2E_USE_LOCAL_BACKEND=true",
+ "PULSE_HOSTED_MODE=true",
+ "PULSE_MULTI_TENANT_ENABLED=true",
+ "PULSE_E2E_ENTITLEMENT_PROFILE=multi-tenant",
+ "npm",
+ "--prefix",
+ "tests/integration",
+ "test",
+ "--",
+ "tests/05-settings-mobile-audit.spec.ts",
+ "--project=mobile-chrome",
+ "--grep",
+ "billing-admin"
+ ]
+ },
+ {
+ "id": "multi-tenant-settings-mobile-browser-proof",
+ "run": [
+ "env",
+ "PULSE_MULTI_TENANT_ENABLED=true",
+ "PULSE_E2E_ENTITLEMENT_PROFILE=multi-tenant",
+ "npm",
+ "--prefix",
+ "tests/integration",
+ "test",
+ "--",
+ "tests/05-settings-mobile-audit.spec.ts",
+ "--project=mobile-chrome",
+ "--grep",
+ "/settings/organization"
+ ]
+ },
{
"id": "route-wide-mobile-browser-proof",
"run": [
@@ -3856,6 +3898,16 @@
}
],
"evidence": [
+ {
+ "repo": "pulse",
+ "path": "frontend-modern/src/api/billingAdmin.ts",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "frontend-modern/src/api/orgs.ts",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "frontend-modern/src/components/Settings/SettingsPageShell.tsx",
@@ -3876,6 +3928,11 @@
"path": "frontend-modern/src/features/platformPage/sharedPlatformPage.tsx",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "frontend-modern/src/utils/apiClient.ts",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "tests/integration/tests/04-mobile.spec.ts",
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 21ed6a8a88..4fe3304bb5 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -7197,3 +7197,11 @@ they differ only in skipping the fpdf/csv stage. Test stubs
implementing the Engine interface must implement these methods so
the contract is honoured across the entire interface surface, not
just the export-shaped subset.
+
+The shared frontend API client now exposes explicit session-preferred request
+selection for user-facing organization administration. When a valid browser
+session and a stored API token coexist, organization and hosted billing clients
+must omit the token and let the session cookie satisfy session-only authority;
+when no session cookie exists, the same request may retain the API-token
+fallback for scoped read access. This prevents first-run token persistence from
+silently converting session administration calls into rejected token calls.
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 9e207ad65b..cf52bd1955 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -1325,6 +1325,13 @@ nullable until the formatting edge, but it must normalize the message through
the shared monitored-system presentation helper instead of branching on
demo/billing state inside settings panels or inventing a second mock-only
license explanation path.
+
+Hosted organization and Billing Admin browser clients must prefer an active
+`pulse_session` cookie when the same browser also retains an API token from
+first-run setup. Platform-admin and session-required organization operations
+must not let that ambient token override the authenticated administrator
+session. Token-only browser clients retain their existing scoped fallback when
+no session cookie is present.
That same cloud-paid/browser boundary now also governs public demo posture.
`DEMO_MODE` may run against a real internal entitlement, but public demo
surfaces must not reveal self-hosted license metadata, hosted billing state,
diff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.md
index 3530b01c71..564b8a7c29 100644
--- a/docs/release-control/v6/internal/subsystems/organization-settings.md
+++ b/docs/release-control/v6/internal/subsystems/organization-settings.md
@@ -330,3 +330,12 @@ The hidden-upgrade posture also applies to locked-card titles and bodies
themselves: RBAC gates may show neutral unavailable-capability copy, but must
not keep `(Pro)`, plan-tier labels, or paid-action wording after the CTA is
suppressed.
+
+Organization Settings is a browser-session administration surface even when
+first-run also leaves a generated API token in browser storage. Its API client
+must prefer the active session cookie for organization reads, invitations,
+membership, sharing, ownership, and billing administration, while preserving
+token fallback only when no session exists. Mobile proof must render Overview,
+Access, Sharing, and Billing with populated multitenant fixtures at supported
+phone widths; hosted Billing Admin requires a real hosted-mode capability
+runtime and expanded-row proof rather than being counted through a redirect.
diff --git a/frontend-modern/src/api/__tests__/billingAdmin.test.ts b/frontend-modern/src/api/__tests__/billingAdmin.test.ts
index d05f5baaeb..cc0edb7e56 100644
--- a/frontend-modern/src/api/__tests__/billingAdmin.test.ts
+++ b/frontend-modern/src/api/__tests__/billingAdmin.test.ts
@@ -32,6 +32,7 @@ describe('BillingAdminAPI', () => {
const result = await BillingAdminAPI.listOrganizations();
expect(apiFetchJSON).toHaveBeenCalledWith('/api/hosted/organizations', {
+ preferSessionAuth: true,
skipOrgContext: true,
});
expect(result).toEqual(mockOrgs);
@@ -50,6 +51,7 @@ describe('BillingAdminAPI', () => {
const result = await BillingAdminAPI.getBillingState('org-1');
expect(apiFetchJSON).toHaveBeenCalledWith('/api/admin/orgs/org-1/billing-state', {
+ preferSessionAuth: true,
skipOrgContext: true,
});
expect(result).toEqual(mockState);
@@ -61,6 +63,7 @@ describe('BillingAdminAPI', () => {
await BillingAdminAPI.getBillingState('org/1');
expect(apiFetchJSON).toHaveBeenCalledWith('/api/admin/orgs/org%2F1/billing-state', {
+ preferSessionAuth: true,
skipOrgContext: true,
});
});
@@ -82,6 +85,7 @@ describe('BillingAdminAPI', () => {
expect.objectContaining({
method: 'PUT',
body: JSON.stringify(mockState),
+ preferSessionAuth: true,
skipOrgContext: true,
}),
);
diff --git a/frontend-modern/src/api/__tests__/orgs.test.ts b/frontend-modern/src/api/__tests__/orgs.test.ts
index c36573d510..a12fd23a65 100644
--- a/frontend-modern/src/api/__tests__/orgs.test.ts
+++ b/frontend-modern/src/api/__tests__/orgs.test.ts
@@ -18,7 +18,10 @@ describe('OrgsAPI', () => {
const result = await OrgsAPI.list();
- expect(apiFetchJSON).toHaveBeenCalledWith('/api/orgs', { skipOrgContext: true });
+ expect(apiFetchJSON).toHaveBeenCalledWith('/api/orgs', {
+ preferSessionAuth: true,
+ skipOrgContext: true,
+ });
expect(result).toEqual(mockOrgs);
});
});
@@ -35,6 +38,7 @@ describe('OrgsAPI', () => {
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ id: 'org-new', displayName: 'New Org' }),
+ preferSessionAuth: true,
skipOrgContext: true,
}),
);
@@ -49,7 +53,10 @@ describe('OrgsAPI', () => {
const result = await OrgsAPI.get('org-1');
- expect(apiFetchJSON).toHaveBeenCalledWith('/api/orgs/org-1', { skipOrgContext: true });
+ expect(apiFetchJSON).toHaveBeenCalledWith('/api/orgs/org-1', {
+ preferSessionAuth: true,
+ skipOrgContext: true,
+ });
expect(result).toEqual(mockOrg);
});
});
@@ -65,6 +72,7 @@ describe('OrgsAPI', () => {
expect.objectContaining({
method: 'PUT',
body: JSON.stringify({ displayName: 'Updated' }),
+ preferSessionAuth: true,
skipOrgContext: true,
}),
);
@@ -79,7 +87,11 @@ describe('OrgsAPI', () => {
expect(apiFetchJSON).toHaveBeenCalledWith(
'/api/orgs/org-1',
- expect.objectContaining({ method: 'DELETE', skipOrgContext: true }),
+ expect.objectContaining({
+ method: 'DELETE',
+ preferSessionAuth: true,
+ skipOrgContext: true,
+ }),
);
});
});
@@ -92,6 +104,7 @@ describe('OrgsAPI', () => {
const result = await OrgsAPI.listMembers('org-1');
expect(apiFetchJSON).toHaveBeenCalledWith('/api/orgs/org-1/members', {
+ preferSessionAuth: true,
skipOrgContext: true,
});
expect(result).toEqual(mockMembers);
@@ -106,6 +119,7 @@ describe('OrgsAPI', () => {
const result = await OrgsAPI.listPendingInvitations('org-1');
expect(apiFetchJSON).toHaveBeenCalledWith('/api/orgs/org-1/invitations', {
+ preferSessionAuth: true,
skipOrgContext: true,
});
expect(result).toEqual(mockInvitations);
@@ -120,6 +134,7 @@ describe('OrgsAPI', () => {
const result = await OrgsAPI.listMyInvitations();
expect(apiFetchJSON).toHaveBeenCalledWith('/api/org-invitations', {
+ preferSessionAuth: true,
skipOrgContext: true,
});
expect(result).toEqual(mockInvitations);
@@ -141,6 +156,7 @@ describe('OrgsAPI', () => {
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ userId: 'user-1', role: 'viewer' }),
+ preferSessionAuth: true,
skipOrgContext: true,
}),
);
@@ -159,6 +175,7 @@ describe('OrgsAPI', () => {
'/api/org-invitations/org-1/accept',
expect.objectContaining({
method: 'POST',
+ preferSessionAuth: true,
skipOrgContext: true,
}),
);
@@ -176,6 +193,7 @@ describe('OrgsAPI', () => {
'/api/org-invitations/org-1',
expect.objectContaining({
method: 'DELETE',
+ preferSessionAuth: true,
skipOrgContext: true,
}),
);
@@ -192,6 +210,7 @@ describe('OrgsAPI', () => {
'/api/orgs/org-1/invitations/user-1',
expect.objectContaining({
method: 'DELETE',
+ preferSessionAuth: true,
skipOrgContext: true,
}),
);
@@ -206,7 +225,11 @@ describe('OrgsAPI', () => {
expect(apiFetchJSON).toHaveBeenCalledWith(
'/api/orgs/org-1/members/user-1',
- expect.objectContaining({ method: 'DELETE', skipOrgContext: true }),
+ expect.objectContaining({
+ method: 'DELETE',
+ preferSessionAuth: true,
+ skipOrgContext: true,
+ }),
);
});
});
@@ -218,7 +241,10 @@ describe('OrgsAPI', () => {
const result = await OrgsAPI.listShares('org-1');
- expect(apiFetchJSON).toHaveBeenCalledWith('/api/orgs/org-1/shares', { skipOrgContext: true });
+ expect(apiFetchJSON).toHaveBeenCalledWith('/api/orgs/org-1/shares', {
+ preferSessionAuth: true,
+ skipOrgContext: true,
+ });
expect(result).toEqual(mockShares);
});
});
@@ -231,6 +257,7 @@ describe('OrgsAPI', () => {
const result = await OrgsAPI.listIncomingShares('org-1');
expect(apiFetchJSON).toHaveBeenCalledWith('/api/orgs/org-1/shares/incoming', {
+ preferSessionAuth: true,
skipOrgContext: true,
});
expect(result).toEqual(mockShares);
@@ -253,6 +280,7 @@ describe('OrgsAPI', () => {
'/api/orgs/org-1/shares',
expect.objectContaining({
method: 'POST',
+ preferSessionAuth: true,
skipOrgContext: true,
}),
);
@@ -269,7 +297,11 @@ describe('OrgsAPI', () => {
expect(apiFetchJSON).toHaveBeenCalledWith(
'/api/orgs/org-1/shares/incoming/share-1/accept',
- expect.objectContaining({ method: 'POST', skipOrgContext: true }),
+ expect.objectContaining({
+ method: 'POST',
+ preferSessionAuth: true,
+ skipOrgContext: true,
+ }),
);
expect(result).toEqual(mockShare);
});
@@ -283,7 +315,11 @@ describe('OrgsAPI', () => {
expect(apiFetchJSON).toHaveBeenCalledWith(
'/api/orgs/org-1/shares/incoming/share-1',
- expect.objectContaining({ method: 'DELETE', skipOrgContext: true }),
+ expect.objectContaining({
+ method: 'DELETE',
+ preferSessionAuth: true,
+ skipOrgContext: true,
+ }),
);
});
});
@@ -296,7 +332,11 @@ describe('OrgsAPI', () => {
expect(apiFetchJSON).toHaveBeenCalledWith(
'/api/orgs/org-1/shares/share-1',
- expect.objectContaining({ method: 'DELETE', skipOrgContext: true }),
+ expect.objectContaining({
+ method: 'DELETE',
+ preferSessionAuth: true,
+ skipOrgContext: true,
+ }),
);
});
});
diff --git a/frontend-modern/src/api/billingAdmin.ts b/frontend-modern/src/api/billingAdmin.ts
index 9323653468..d8e4a61012 100644
--- a/frontend-modern/src/api/billingAdmin.ts
+++ b/frontend-modern/src/api/billingAdmin.ts
@@ -25,11 +25,13 @@ export interface BillingState {
export const BillingAdminAPI = {
listOrganizations: () =>
apiFetchJSON<HostedOrganizationSummary[]>('/api/hosted/organizations', {
+ preferSessionAuth: true,
skipOrgContext: true,
}),
getBillingState: (orgID: string) =>
apiFetchJSON<BillingState>(`/api/admin/orgs/${encodeURIComponent(orgID)}/billing-state`, {
+ preferSessionAuth: true,
skipOrgContext: true,
}),
@@ -37,6 +39,7 @@ export const BillingAdminAPI = {
apiFetchJSON<BillingState>(`/api/admin/orgs/${encodeURIComponent(orgID)}/billing-state`, {
method: 'PUT',
body: JSON.stringify(payload),
+ preferSessionAuth: true,
skipOrgContext: true,
}),
};
diff --git a/frontend-modern/src/api/orgs.ts b/frontend-modern/src/api/orgs.ts
index 1a2c301bd7..ee72d9eb66 100644
--- a/frontend-modern/src/api/orgs.ts
+++ b/frontend-modern/src/api/orgs.ts
@@ -64,6 +64,7 @@ export interface IncomingOrganizationShare extends OrganizationShare {
export const OrgsAPI = {
list: () =>
apiFetchJSON<Organization[]>('/api/orgs', {
+ preferSessionAuth: true,
skipOrgContext: true,
}),
@@ -71,11 +72,13 @@ export const OrgsAPI = {
apiFetchJSON<Organization>('/api/orgs', {
method: 'POST',
body: JSON.stringify(payload),
+ preferSessionAuth: true,
skipOrgContext: true,
}),
get: (id: string) =>
apiFetchJSON<Organization>(`/api/orgs/${encodeURIComponent(id)}`, {
+ preferSessionAuth: true,
skipOrgContext: true,
}),
@@ -83,27 +86,32 @@ export const OrgsAPI = {
apiFetchJSON<Organization>(`/api/orgs/${encodeURIComponent(id)}`, {
method: 'PUT',
body: JSON.stringify(payload),
+ preferSessionAuth: true,
skipOrgContext: true,
}),
remove: (id: string) =>
apiFetchJSON<void>(`/api/orgs/${encodeURIComponent(id)}`, {
method: 'DELETE',
+ preferSessionAuth: true,
skipOrgContext: true,
}),
listMembers: (id: string) =>
apiFetchJSON<OrganizationMember[]>(`/api/orgs/${encodeURIComponent(id)}/members`, {
+ preferSessionAuth: true,
skipOrgContext: true,
}),
listPendingInvitations: (id: string) =>
apiFetchJSON<OrganizationInvitation[]>(`/api/orgs/${encodeURIComponent(id)}/invitations`, {
+ preferSessionAuth: true,
skipOrgContext: true,
}),
listMyInvitations: () =>
apiFetchJSON<UserOrganizationInvitation[]>('/api/org-invitations', {
+ preferSessionAuth: true,
skipOrgContext: true,
}),
@@ -111,6 +119,7 @@ export const OrgsAPI = {
apiFetchJSON<OrganizationAccessMutationResult>(`/api/orgs/${encodeURIComponent(id)}/members`, {
method: 'POST',
body: JSON.stringify(payload),
+ preferSessionAuth: true,
skipOrgContext: true,
}),
@@ -119,6 +128,7 @@ export const OrgsAPI = {
`/api/org-invitations/${encodeURIComponent(id)}/accept`,
{
method: 'POST',
+ preferSessionAuth: true,
skipOrgContext: true,
},
),
@@ -126,6 +136,7 @@ export const OrgsAPI = {
declineMyInvitation: (id: string) =>
apiFetchJSON<void>(`/api/org-invitations/${encodeURIComponent(id)}`, {
method: 'DELETE',
+ preferSessionAuth: true,
skipOrgContext: true,
}),
@@ -133,6 +144,7 @@ export const OrgsAPI = {
apiFetchJSON<OrganizationAccessMutationResult>(`/api/orgs/${encodeURIComponent(id)}/members`, {
method: 'POST',
body: JSON.stringify(payload),
+ preferSessionAuth: true,
skipOrgContext: true,
}),
@@ -141,6 +153,7 @@ export const OrgsAPI = {
`/api/orgs/${encodeURIComponent(id)}/invitations/${encodeURIComponent(userId)}`,
{
method: 'DELETE',
+ preferSessionAuth: true,
skipOrgContext: true,
},
),
@@ -150,12 +163,14 @@ export const OrgsAPI = {
`/api/orgs/${encodeURIComponent(id)}/members/${encodeURIComponent(userId)}`,
{
method: 'DELETE',
+ preferSessionAuth: true,
skipOrgContext: true,
},
),
listShares: (id: string) =>
apiFetchJSON<OrganizationShare[]>(`/api/orgs/${encodeURIComponent(id)}/shares`, {
+ preferSessionAuth: true,
skipOrgContext: true,
}),
@@ -163,6 +178,7 @@ export const OrgsAPI = {
apiFetchJSON<IncomingOrganizationShare[]>(
`/api/orgs/${encodeURIComponent(id)}/shares/incoming`,
{
+ preferSessionAuth: true,
skipOrgContext: true,
},
),
@@ -172,6 +188,7 @@ export const OrgsAPI = {
`/api/orgs/${encodeURIComponent(id)}/shares/incoming/${encodeURIComponent(shareId)}/accept`,
{
method: 'POST',
+ preferSessionAuth: true,
skipOrgContext: true,
},
),
@@ -181,6 +198,7 @@ export const OrgsAPI = {
`/api/orgs/${encodeURIComponent(id)}/shares/incoming/${encodeURIComponent(shareId)}`,
{
method: 'DELETE',
+ preferSessionAuth: true,
skipOrgContext: true,
},
),
@@ -198,6 +216,7 @@ export const OrgsAPI = {
apiFetchJSON<OrganizationShare>(`/api/orgs/${encodeURIComponent(id)}/shares`, {
method: 'POST',
body: JSON.stringify(payload),
+ preferSessionAuth: true,
skipOrgContext: true,
}),
@@ -206,6 +225,7 @@ export const OrgsAPI = {
`/api/orgs/${encodeURIComponent(id)}/shares/${encodeURIComponent(shareId)}`,
{
method: 'DELETE',
+ preferSessionAuth: true,
skipOrgContext: true,
},
),
diff --git a/frontend-modern/src/utils/__tests__/apiClient.org.test.ts b/frontend-modern/src/utils/__tests__/apiClient.org.test.ts
index 4074f6827f..d0dfedfb75 100644
--- a/frontend-modern/src/utils/__tests__/apiClient.org.test.ts
+++ b/frontend-modern/src/utils/__tests__/apiClient.org.test.ts
@@ -109,6 +109,35 @@ describe('apiClient org context', () => {
expect(headers['X-Pulse-Org-ID']).toBe('default');
});
+ it('prefers a browser session over a stored API token when requested', async () => {
+ mockFetch.mockResolvedValue(new Response('[]', { status: 200 }));
+ setApiToken('stored-api-token');
+
+ await apiFetch('/api/org-invitations', { preferSessionAuth: true });
+
+ const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
+ const headers = options.headers as Record<string, string>;
+ expect(headers['X-API-Token']).toBeUndefined();
+ expect(options.credentials).toBe('include');
+ });
+
+ it('falls back to a stored API token when no browser session is available', async () => {
+ mockFetch
+ .mockResolvedValueOnce(new Response('{}', { status: 401 }))
+ .mockResolvedValueOnce(new Response('[]', { status: 200 }));
+ setApiToken('stored-api-token');
+
+ await apiFetch('/api/orgs', { preferSessionAuth: true });
+
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ const [, firstOptions] = mockFetch.mock.calls[0] as [string, RequestInit];
+ const firstHeaders = firstOptions.headers as Record<string, string>;
+ expect(firstHeaders['X-API-Token']).toBeUndefined();
+ const [, retryOptions] = mockFetch.mock.calls[1] as [string, RequestInit];
+ const retryHeaders = retryOptions.headers as Record<string, string>;
+ expect(retryHeaders['X-API-Token']).toBe('stored-api-token');
+ });
+
it('does not treat intentional unauthenticated 401 responses as expired sessions', async () => {
document.cookie = 'pulse_csrf=csrf-token; Path=/';
mockFetch.mockResolvedValue(
@@ -209,7 +238,9 @@ describe('apiClient org context', () => {
}),
);
- await expect(apiFetchJSON('/api/security/tokens', { method: 'POST', body: '{}' })).rejects.toMatchObject({
+ await expect(
+ apiFetchJSON('/api/security/tokens', { method: 'POST', body: '{}' }),
+ ).rejects.toMatchObject({
message: 'missing_scope',
status: 403,
requiredScope: 'settings:write',
diff --git a/frontend-modern/src/utils/apiClient.ts b/frontend-modern/src/utils/apiClient.ts
index 8a47da47ac..5b3a839ddd 100644
--- a/frontend-modern/src/utils/apiClient.ts
+++ b/frontend-modern/src/utils/apiClient.ts
@@ -73,6 +73,7 @@ const getSessionStorage = (): Storage | undefined => {
interface FetchOptions extends Omit<RequestInit, 'headers'> {
headers?: Record<string, string>;
+ preferSessionAuth?: boolean;
skipAuth?: boolean;
skipOrgContext?: boolean;
}
@@ -577,7 +578,13 @@ class ApiClient {
// Main fetch wrapper that adds authentication
async fetch(url: string, options: FetchOptions = {}): Promise<Response> {
- const { skipAuth = false, skipOrgContext = false, headers = {}, ...fetchOptions } = options;
+ const {
+ preferSessionAuth = false,
+ skipAuth = false,
+ skipOrgContext = false,
+ headers = {},
+ ...fetchOptions
+ } = options;
// Build headers object
const finalHeaders: Record<string, string> = { ...headers };
@@ -603,7 +610,7 @@ class ApiClient {
// Add authentication if available and not skipped
if (!skipAuth) {
- if (this.apiToken) {
+ if (this.apiToken && !preferSessionAuth) {
finalHeaders['X-API-Token'] = this.apiToken;
}
}
@@ -629,7 +636,27 @@ class ApiClient {
credentials: 'include', // Important for session cookies
};
- const response = await fetch(url, finalOptions);
+ let response = await fetch(url, finalOptions);
+
+ // Session-preferred reads intentionally omit the API token on their first
+ // attempt because HttpOnly session cookies cannot be detected from browser
+ // JavaScript. Token-only clients still retain scoped read access by
+ // retrying an unauthenticated idempotent response once with their token.
+ if (
+ response.status === 401 &&
+ preferSessionAuth &&
+ !skipAuth &&
+ this.apiToken &&
+ IDEMPOTENT_METHODS.has(method)
+ ) {
+ response = await fetch(url, {
+ ...finalOptions,
+ headers: {
+ ...finalHeaders,
+ 'X-API-Token': this.apiToken,
+ },
+ });
+ }
// Handle stale/invalid org context by clearing it and retrying once against default org.
if (
diff --git a/tests/integration/tests/05-settings-mobile-audit.spec.ts b/tests/integration/tests/05-settings-mobile-audit.spec.ts
index ea2b1b47dd..8fc39e7347 100644
--- a/tests/integration/tests/05-settings-mobile-audit.spec.ts
+++ b/tests/integration/tests/05-settings-mobile-audit.spec.ts
@@ -2,14 +2,22 @@ import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { test as base, expect } from "@playwright/test";
-import { createAuthenticatedStorageState } from "./helpers";
+import {
+ apiRequest,
+ createAuthenticatedStorageState,
+ createOrg,
+} from "./helpers";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
type WorkerFixtures = {
authStorageStatePath: string;
};
-const SETTINGS_ROUTES = [
+const MULTI_TENANT_ENABLED = process.env.PULSE_MULTI_TENANT_ENABLED === "true";
+const HOSTED_BILLING_ADMIN_ENABLED =
+ MULTI_TENANT_ENABLED && process.env.PULSE_HOSTED_MODE === "true";
+
+const STANDARD_SETTINGS_ROUTES = [
"/settings/infrastructure",
"/settings/monitoring/availability",
"/settings/pulse-intelligence/provider",
@@ -35,6 +43,23 @@ const SETTINGS_ROUTES = [
"/settings/security-webhooks",
] as const;
+const ORGANIZATION_SETTINGS_ROUTES = [
+ "/settings/organization",
+ "/settings/organization/access",
+ "/settings/organization/sharing",
+ "/settings/organization/billing",
+] as const;
+
+const HOSTED_SETTINGS_ROUTES = [
+ "/settings/organization/billing-admin",
+] as const;
+
+const SETTINGS_ROUTES = [
+ ...STANDARD_SETTINGS_ROUTES,
+ ...(MULTI_TENANT_ENABLED ? ORGANIZATION_SETTINGS_ROUTES : []),
+ ...(HOSTED_BILLING_ADMIN_ENABLED ? HOSTED_SETTINGS_ROUTES : []),
+] as const;
+
const SETTINGS_ROUTE_REDIRECTS = [
{
route: "/settings/pulse-intelligence/discovery",
@@ -44,23 +69,20 @@ const SETTINGS_ROUTE_REDIRECTS = [
route: "/settings/pulse-intelligence/billing/usage",
expectedPath: "/settings/pulse-intelligence/billing/plan",
},
- { route: "/settings/organization", expectedPath: "/settings/infrastructure" },
- {
- route: "/settings/organization/access",
- expectedPath: "/settings/infrastructure",
- },
- {
- route: "/settings/organization/sharing",
- expectedPath: "/settings/infrastructure",
- },
- {
- route: "/settings/organization/billing",
- expectedPath: "/settings/infrastructure",
- },
- {
- route: "/settings/organization/billing-admin",
- expectedPath: "/settings/infrastructure",
- },
+ ...(!MULTI_TENANT_ENABLED
+ ? ORGANIZATION_SETTINGS_ROUTES.map((route) => ({
+ route,
+ expectedPath: "/settings/infrastructure",
+ }))
+ : []),
+ ...(!HOSTED_BILLING_ADMIN_ENABLED
+ ? [
+ {
+ route: "/settings/organization/billing-admin",
+ expectedPath: "/settings/infrastructure",
+ } as const,
+ ]
+ : []),
] as const;
const MOBILE_VIEWPORTS = [
@@ -68,6 +90,72 @@ const MOBILE_VIEWPORTS = [
{ width: 390, height: 844, label: "modern phone" },
] as const;
+const prepareOrganizationAuditFixture = async (
+ page: import("@playwright/test").Page,
+ route: string,
+): Promise<string[]> => {
+ if (!(ORGANIZATION_SETTINGS_ROUTES as readonly string[]).includes(route))
+ return [];
+
+ await page.goto("/settings/infrastructure", {
+ waitUntil: "domcontentloaded",
+ });
+ const createdOrgIDs: string[] = [];
+ let targetOrgID = "";
+
+ if (route === "/settings/organization/sharing") {
+ const target = await createOrg(page, "Mobile Audit Target");
+ targetOrgID = target.id;
+ createdOrgIDs.push(target.id);
+ }
+
+ const source = await createOrg(page, "Mobile Audit Organization");
+ createdOrgIDs.push(source.id);
+ await page.reload({ waitUntil: "domcontentloaded" });
+ const organizationSwitcher = page.getByRole("combobox", {
+ name: "Organization",
+ });
+ await expect(organizationSwitcher).toBeVisible({ timeout: 20000 });
+ await organizationSwitcher.selectOption(source.id);
+ await expect(organizationSwitcher).toHaveValue(source.id, {
+ timeout: 20000,
+ });
+
+ if (route === "/settings/organization/access") {
+ const invitation = await apiRequest(
+ page,
+ `/api/orgs/${encodeURIComponent(source.id)}/members`,
+ {
+ method: "POST",
+ data: { userId: "mobile-audit-viewer", role: "viewer" },
+ headers: { "Content-Type": "application/json" },
+ },
+ );
+ expect(invitation.ok(), "mobile access fixture invitation").toBeTruthy();
+ }
+
+ if (route === "/settings/organization/sharing") {
+ const share = await apiRequest(
+ page,
+ `/api/orgs/${encodeURIComponent(source.id)}/shares`,
+ {
+ method: "POST",
+ data: {
+ targetOrgId: targetOrgID,
+ resourceType: "view",
+ resourceId: "mobile-audit-view",
+ resourceName: "Mobile Audit Shared View",
+ accessRole: "viewer",
+ },
+ headers: { "Content-Type": "application/json" },
+ },
+ );
+ expect(share.ok(), "mobile sharing fixture").toBeTruthy();
+ }
+
+ return createdOrgIDs;
+};
+
const test = base.extend<{}, WorkerFixtures>({
storageState: async ({ authStorageStatePath }, use) => {
await use(authStorageStatePath);
@@ -175,38 +263,96 @@ test.describe("Settings mobile optimization audit", () => {
test(`no horizontal overflow after full scroll on ${route}`, async ({
page,
}) => {
- for (const viewport of MOBILE_VIEWPORTS) {
- await page.setViewportSize(viewport);
- await page.goto(route, { waitUntil: "domcontentloaded" });
- await page.waitForURL((url) => url.pathname === route, {
- timeout: 15000,
- });
- expect(
- new URL(page.url()).pathname,
- `${route} must remain the surface being audited rather than silently redirecting`,
- ).toBe(route);
- await expect(page.locator("#root")).toBeVisible();
- await page.waitForTimeout(600);
-
- await scrollToBottom(page);
- const atBottom = await page.evaluate(() => {
- const scrollTop = window.scrollY;
- const maxScrollTop = Math.max(
- 0,
- document.documentElement.scrollHeight - window.innerHeight,
+ const createdOrgIDs = await prepareOrganizationAuditFixture(page, route);
+ try {
+ for (const viewport of MOBILE_VIEWPORTS) {
+ await page.setViewportSize(viewport);
+ await page.goto(route, { waitUntil: "domcontentloaded" });
+ await page.waitForURL((url) => url.pathname === route, {
+ timeout: 15000,
+ });
+ expect(
+ new URL(page.url()).pathname,
+ `${route} must remain the surface being audited rather than silently redirecting`,
+ ).toBe(route);
+ await expect(page.locator("#root")).toBeVisible();
+ await page.waitForTimeout(1500);
+
+ const loadFailure = page
+ .getByRole("alert")
+ .filter({ hasText: /^Unable to load .* settings\.$/ });
+ await expect(
+ loadFailure,
+ `${route} must render its real settings state instead of an API-error shell`,
+ ).toHaveCount(0);
+
+ if (
+ route === "/settings/organization/billing-admin" &&
+ viewport.width === MOBILE_VIEWPORTS[0].width
+ ) {
+ const organizationToggle = page
+ .locator("tbody button")
+ .filter({ hasText: "default" });
+ await expect(organizationToggle).toHaveCount(1);
+ await organizationToggle.click();
+ await expect(
+ page.getByText("Billing state JSON", { exact: true }),
+ ).toBeVisible();
+ }
+
+ await scrollToBottom(page);
+ const atBottom = await page.evaluate(() => {
+ const scrollTop = window.scrollY;
+ const maxScrollTop = Math.max(
+ 0,
+ document.documentElement.scrollHeight - window.innerHeight,
+ );
+ return scrollTop >= maxScrollTop - 3;
+ });
+ expect(
+ atBottom,
+ `Expected to reach the bottom while auditing ${route} on a ${viewport.label}`,
+ ).toBeTruthy();
+
+ const audit = await auditHorizontalOverflow(page);
+ expect(
+ audit.pageWidth,
+ `Mobile overflow on ${route} at ${viewport.width}px (viewport=${audit.viewportWidth}, page=${audit.pageWidth}, offenders=${JSON.stringify(audit.offenders)})`,
+ ).toBeLessThanOrEqual(audit.viewportWidth + 1);
+ }
+ } finally {
+ if (createdOrgIDs.length > 0) {
+ const organizationSwitcher = page.getByRole("combobox", {
+ name: "Organization",
+ });
+ if (await organizationSwitcher.isVisible().catch(() => false)) {
+ await organizationSwitcher.selectOption("default");
+ await expect(organizationSwitcher).toHaveValue("default", {
+ timeout: 20000,
+ });
+ await page.reload({ waitUntil: "domcontentloaded" });
+ await expect(
+ page.getByRole("combobox", { name: "Organization" }),
+ ).toHaveValue("default", { timeout: 20000 });
+ }
+ }
+ for (const orgID of [...createdOrgIDs].reverse()) {
+ const response = await apiRequest(
+ page,
+ `/api/orgs/${encodeURIComponent(orgID)}`,
+ {
+ method: "DELETE",
+ headers: {
+ "X-Org-ID": "default",
+ "X-Pulse-Org-ID": "default",
+ },
+ },
);
- return scrollTop >= maxScrollTop - 3;
- });
- expect(
- atBottom,
- `Expected to reach the bottom while auditing ${route} on a ${viewport.label}`,
- ).toBeTruthy();
-
- const audit = await auditHorizontalOverflow(page);
- expect(
- audit.pageWidth,
- `Mobile overflow on ${route} at ${viewport.width}px (viewport=${audit.viewportWidth}, page=${audit.pageWidth}, offenders=${JSON.stringify(audit.offenders)})`,
- ).toBeLessThanOrEqual(audit.viewportWidth + 1);
+ expect(
+ [204, 404].includes(response.status()),
+ `cleanup organization ${orgID}`,
+ ).toBeTruthy();
+ }
}
});
}