diff --git a/.changeset/37080-console-reads-bearer.md b/.changeset/37080-console-reads-bearer.md new file mode 100644 index 00000000000..08e6e34537d --- /dev/null +++ b/.changeset/37080-console-reads-bearer.md @@ -0,0 +1,10 @@ +--- +'@object-ui/console': patch +--- + +fix(console): the developer pages and the device sign-in approval send the stored sign-in token, so a session held by its token alone works there too + +Clause-②: no +Metadata-protocol: none + +The developer integrations page, the agent-connect section (discovery and creating an API key) and the device sign-in approval (claim, approve, deny) asked this server with the session cookie only, so a session held by its sign-in (bearer) token alone was refused there. They now send the stored token as well, as the other same-server console requests do. The session cookie is still sent, so a cookie session behaves exactly as before, and a refused request now reaches the console's session-ended check. Nothing changes in what the server accepts. diff --git a/.changeset/37080-shell-reads-bearer.md b/.changeset/37080-shell-reads-bearer.md new file mode 100644 index 00000000000..5e07905f7ce --- /dev/null +++ b/.changeset/37080-shell-reads-bearer.md @@ -0,0 +1,21 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(app-shell): the package list, Studio, AI chat and draft screens send the stored sign-in token, so a session held by its token alone keeps its packages, Studio and design entries + +Clause-②: no +Metadata-protocol: none + +These screens asked this server for their data with the session cookie only, while the other same-server console requests also send the stored sign-in (bearer) token. A session held by its token alone (a second local runtime on the same host replaced the cookie, the browser blocked it as a third-party cookie, or the cookie jar was cleared) was refused there. The most visible case was the package list behind the sidebar, the app header, the command palette and the Studio entries: every package went missing, and the Studio and design entries with it, with no error shown. + +They now send the token as well: + +- packages: the package list and the package switcher, creating a package's customization package, duplicating a package, a package's customizations, and the package form; +- Studio: the automation status, cloning a flow, cloning a permission set, the flow picker and connector inputs, a flow's run history and node palette, the page preview, the sharing-rule catalog and catalog activation, and the packaged action and flow ledgers in Setup; +- drafts: the pending drafts, the unpublished-app bar, the draft changes panel and its flow checks, and the commit history with its revert; +- AI: the conversation list and conversations, the build-debug report, AI usage, and suggested bindings; +- the inbox bell, the approval feeds and a record's approvals, and changing a record's owner; +- the shell: the no-access state, the deployment notice, the connect-agent widget, the context selectors (only for requests to this server's own origin), the design-mode language list, and the marketplace's install steps on this server. + +The session cookie is still sent, so a cookie session behaves exactly as before, and a refused request now reaches the console's session-ended check. A few requests stay cookie-only for now, among them sign-in, the OAuth hand-off, public forms and calls to the cloud control plane; they are unchanged. Nothing changes in what the server accepts. diff --git a/ui/apps/console/src/components/StudioRoute.searchPalette-11863.test.tsx b/ui/apps/console/src/components/StudioRoute.searchPalette-11863.test.tsx index 02f3dbce4ec..a5904fa7eb0 100644 --- a/ui/apps/console/src/components/StudioRoute.searchPalette-11863.test.tsx +++ b/ui/apps/console/src/components/StudioRoute.searchPalette-11863.test.tsx @@ -42,14 +42,19 @@ function jsonResponse(body: unknown, status = 200): Response { vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), useAuth: () => auth, - createAuthenticatedFetch: () => async () => - jsonResponse({ - authenticated: true, - userId: 'u1', - systemPermissions: ['studio.access'], - objects: {}, - fields: {}, - }), + // The Studio gate's permissions read answers here; every other request (the + // package list included, which goes out through the authenticated fetch too) + // answers from the wire double each case stubs. + createAuthenticatedFetch: () => async (input: RequestInfo | URL, init?: RequestInit) => + String(input).endsWith('/api/v1/auth/me/permissions') + ? jsonResponse({ + authenticated: true, + userId: 'u1', + systemPermissions: ['studio.access'], + objects: {}, + fields: {}, + }) + : fetch(input, init), })); // `AuthGuard` reaches `useAuth` through the auth package's OWN module graph, diff --git a/ui/apps/console/src/pages/auth/DeviceAuthPage.tsx b/ui/apps/console/src/pages/auth/DeviceAuthPage.tsx index 605ed8ea036..f6230d36c76 100644 --- a/ui/apps/console/src/pages/auth/DeviceAuthPage.tsx +++ b/ui/apps/console/src/pages/auth/DeviceAuthPage.tsx @@ -11,7 +11,7 @@ import { useEffect, useState } from 'react'; import { Navigate, useLocation, useNavigate, useSearchParams } from 'react-router-dom'; import { CheckCircle2 } from 'lucide-react'; import { toast } from 'sonner'; -import { useAuth } from '@object-ui/auth'; +import { createAuthenticatedFetch, useAuth } from '@object-ui/auth'; import { useObjectTranslation } from '@object-ui/i18n'; import { getProductName, getLogoUrl } from '@object-ui/app-shell'; import { @@ -23,6 +23,11 @@ import { CardTitle, } from '@object-ui/components'; +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} + const AUTH_BASE = `${import.meta.env.VITE_SERVER_URL || ''}/api/v1/auth`; function PageShell({ children }: { children: React.ReactNode }) { @@ -200,7 +205,7 @@ export function DeviceAuthPage() { // accept approve/deny — without it both return 400 "not been claimed // by a verifying session". Idempotent, so claim right before acting. const claimDevice = async () => { - await fetch(`${AUTH_BASE}/device?user_code=${encodeURIComponent(code)}`, { + await authFetch(`${AUTH_BASE}/device?user_code=${encodeURIComponent(code)}`, { credentials: 'include', }).catch(() => { /* approve below surfaces the real error */ }); }; @@ -210,7 +215,7 @@ export function DeviceAuthPage() { setSubmitting(true); try { await claimDevice(); - const res = await fetch(`${AUTH_BASE}/device/approve`, { + const res = await authFetch(`${AUTH_BASE}/device/approve`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', @@ -250,7 +255,7 @@ export function DeviceAuthPage() { setDenying(true); try { await claimDevice(); - await fetch(`${AUTH_BASE}/device/deny`, { + await authFetch(`${AUTH_BASE}/device/deny`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', diff --git a/ui/apps/console/src/pages/developer/AgentConnectSection.envelopeUserMessage.test.tsx b/ui/apps/console/src/pages/developer/AgentConnectSection.envelopeUserMessage.test.tsx index 3fa23dd2cb5..c4b728eb189 100644 --- a/ui/apps/console/src/pages/developer/AgentConnectSection.envelopeUserMessage.test.tsx +++ b/ui/apps/console/src/pages/developer/AgentConnectSection.envelopeUserMessage.test.tsx @@ -59,13 +59,13 @@ function stubKeysFailure(status: number, body: unknown) { const url = String(input); if (url.includes('/api/v1/discovery')) { return { - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => ({ data: { routes: { mcp: '/api/v1/mcp' } } }), }; } return { - ok: status >= 200 && status < 300, + headers: new Headers(), ok: status >= 200 && status < 300, status, json: async () => body, }; diff --git a/ui/apps/console/src/pages/developer/AgentConnectSection.keylessSuccess-8782.test.tsx b/ui/apps/console/src/pages/developer/AgentConnectSection.keylessSuccess-8782.test.tsx index d77e6ba26ba..5aa4143697f 100644 --- a/ui/apps/console/src/pages/developer/AgentConnectSection.keylessSuccess-8782.test.tsx +++ b/ui/apps/console/src/pages/developer/AgentConnectSection.keylessSuccess-8782.test.tsx @@ -68,10 +68,10 @@ interface KeysAnswer { async function errorTextFor(keys: KeysAnswer): Promise { const fetchMock = vi.fn(async (url: unknown) => { if (String(url).includes('/discovery')) { - return { ok: true, status: 200, json: async () => DISCOVERY } as unknown as Response; + return { headers: new Headers(), ok: true, status: 200, json: async () => DISCOVERY } as unknown as Response; } return { - ok: keys.status >= 200 && keys.status < 300, + headers: new Headers(), ok: keys.status >= 200 && keys.status < 300, status: keys.status, json: async () => { if (!('body' in keys)) throw new SyntaxError('Unexpected token < in JSON at position 0'); diff --git a/ui/apps/console/src/pages/developer/AgentConnectSection.tsx b/ui/apps/console/src/pages/developer/AgentConnectSection.tsx index 44b202ac60a..91ffc47a1ad 100644 --- a/ui/apps/console/src/pages/developer/AgentConnectSection.tsx +++ b/ui/apps/console/src/pages/developer/AgentConnectSection.tsx @@ -50,6 +50,12 @@ import { useObjectTranslation } from '@object-ui/i18n'; import { SLOT, withSlots } from '../../lib/inlineSlots'; import { renderObjectStackSkill } from './objectstack-skill'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} interface GeneratedKey { id?: string; @@ -109,7 +115,7 @@ export function AgentConnectSection() { let cancelled = false; (async () => { try { - const res = await fetch('/api/v1/discovery', { credentials: 'include' }); + const res = await authFetch('/api/v1/discovery', { credentials: 'include' }); const json = await res.json().catch(() => ({})); const route: string | undefined = json?.data?.routes?.mcp ?? json?.routes?.mcp; if (cancelled) return; @@ -135,7 +141,7 @@ export function AgentConnectSection() { setGenerating(true); setError(null); try { - const res = await fetch('/api/v1/keys', { + const res = await authFetch('/api/v1/keys', { method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' }, diff --git a/ui/apps/console/src/pages/developer/IntegrationsPage.tsx b/ui/apps/console/src/pages/developer/IntegrationsPage.tsx index 70105f01b68..802023a0dd2 100644 --- a/ui/apps/console/src/pages/developer/IntegrationsPage.tsx +++ b/ui/apps/console/src/pages/developer/IntegrationsPage.tsx @@ -32,6 +32,12 @@ import { Terminal, Copy, Check, Plug, Database, KeyRound } from 'lucide-react'; import { AgentConnectSection } from './AgentConnectSection'; import { SLOT, withSlots } from '../../lib/inlineSlots'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} interface ConsoleObjectMeta { name: string; @@ -101,7 +107,7 @@ function IntegrationsPageBody() { let cancelled = false; (async () => { try { - const res = await fetch('/api/v1/meta/object', { credentials: 'include' }); + const res = await authFetch('/api/v1/meta/object', { credentials: 'include' }); if (!res.ok) throw new Error(`meta/object ${res.status}`); const json = await res.json(); const raw = (json?.data ?? json?.items ?? json ?? []) as Array>; diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.studioScope-11863.test.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.studioScope-11863.test.tsx index 7bb1cda2ac8..c16fad02273 100644 --- a/ui/packages/app-shell/src/chrome/CommandPalette.studioScope-11863.test.tsx +++ b/ui/packages/app-shell/src/chrome/CommandPalette.studioScope-11863.test.tsx @@ -44,6 +44,9 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({ import { CommandPalette } from './CommandPalette'; import { CommandPaletteProvider } from '../context/CommandPaletteProvider'; +// The source under test reaches a dynamic `import('@object-ui/plugin-detail')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@object-ui/plugin-detail'; /** `GET /api/v1/packages`: two app packages and a kernel one, in both served shapes. */ const PACKAGES_PAYLOAD = { @@ -106,7 +109,7 @@ let fetchMock: ReturnType; beforeEach(() => { fetchMock = vi.fn(async (url: string) => { if (String(url).endsWith('/api/v1/packages')) { - return { ok: true, status: 200, json: async () => PACKAGES_PAYLOAD }; + return { headers: new Headers(), ok: true, status: 200, json: async () => PACKAGES_PAYLOAD }; } throw new Error(`unexpected request: ${url}`); }); diff --git a/ui/packages/app-shell/src/console/AppNoAccessEmptyState.tsx b/ui/packages/app-shell/src/console/AppNoAccessEmptyState.tsx index c999e02971a..bb00c9824c0 100644 --- a/ui/packages/app-shell/src/console/AppNoAccessEmptyState.tsx +++ b/ui/packages/app-shell/src/console/AppNoAccessEmptyState.tsx @@ -55,6 +55,12 @@ import { useObjectTranslation } from '@object-ui/i18n'; import { useServedAppLabel } from '../hooks/useServedAppLabel.js'; import { useCanAuthorMetadata } from '../hooks/useCanAuthorMetadata.js'; import { studioHomePath } from '../views/studio-design/studioAddress.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} export interface AppNoAccessEmptyStateProps { /** The active app, as the console's metadata list carries it (`_packageId` as served). */ @@ -95,7 +101,7 @@ function useStoredMenuEmpty(appName: string, packageId: string | null, ask: bool React.useEffect(() => { if (!ask || !packageId) return; let cancelled = false; - fetch(`/api/v1/meta/app/${encodeURIComponent(appName)}/layers?package=${encodeURIComponent(packageId)}`, { + authFetch(`/api/v1/meta/app/${encodeURIComponent(appName)}/layers?package=${encodeURIComponent(packageId)}`, { credentials: 'include', headers: { Accept: 'application/json' }, cache: 'no-store', diff --git a/ui/packages/app-shell/src/console/ai/__tests__/BuildDebugDrawer.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/BuildDebugDrawer.test.tsx index 0bb72b9186a..ee6c48e31e0 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/BuildDebugDrawer.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/BuildDebugDrawer.test.tsx @@ -40,7 +40,7 @@ describe('BuildDebugDrawer', () => { beforeEach(() => { vi.stubGlobal( 'fetch', - vi.fn(async () => ({ ok: true, status: 200, json: async () => REPORT })), + vi.fn(async () => ({ headers: new Headers(), ok: true, status: 200, json: async () => REPORT })), ); }); afterEach(() => { @@ -60,10 +60,14 @@ describe('BuildDebugDrawer', () => { }); it('hits the debug endpoint for the conversation', async () => { - const spy = vi.fn(async () => ({ ok: true, status: 200, json: async () => REPORT })); + const spy = vi.fn(async () => ({ headers: new Headers(), ok: true, status: 200, json: async () => REPORT })); vi.stubGlobal('fetch', spy); renderDrawer(); await screen.findByText(/Proposed but never applied/); - expect(spy).toHaveBeenCalledWith('/api/v1/ai/conversations/conv_x/debug', { credentials: 'include' }); + // The authenticated fetch hands the wire a `Headers` (the bearer, when one is stored). + expect(spy).toHaveBeenCalledWith('/api/v1/ai/conversations/conv_x/debug', { + credentials: 'include', + headers: expect.any(Headers), + }); }); }); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/aiFaces.displayLocale-9909.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/aiFaces.displayLocale-9909.test.tsx index 749244ee158..0fbefe932f4 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/aiFaces.displayLocale-9909.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/aiFaces.displayLocale-9909.test.tsx @@ -122,7 +122,7 @@ const SURFACES: Surface[] = [ { name: 'BuildDebugDrawer — token count', read: async (locale) => { - vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, json: async () => REPORT }))); + vi.stubGlobal('fetch', vi.fn(async () => ({ headers: new Headers(), ok: true, status: 200, json: async () => REPORT }))); render(session(locale, {}} />)); const line = await screen.findByText(/tok/); const text = line.textContent ?? ''; diff --git a/ui/packages/app-shell/src/console/ai/__tests__/buildDoctor.drawerBody-10969.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/buildDoctor.drawerBody-10969.test.tsx index 91e57854210..21d376d993e 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/buildDoctor.drawerBody-10969.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/buildDoctor.drawerBody-10969.test.tsx @@ -50,8 +50,8 @@ function answer(report: BuildDebugReport | null) { 'fetch', vi.fn(async () => report - ? { ok: true, status: 200, json: async () => report } - : { ok: false, status: 404, json: async () => ({}) }, + ? { headers: new Headers(), ok: true, status: 200, json: async () => report } + : { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }, ), ); } diff --git a/ui/packages/app-shell/src/console/ai/buildDebugApi.ts b/ui/packages/app-shell/src/console/ai/buildDebugApi.ts index 93dcf84716e..2e104ba1d50 100644 --- a/ui/packages/app-shell/src/console/ai/buildDebugApi.ts +++ b/ui/packages/app-shell/src/console/ai/buildDebugApi.ts @@ -8,9 +8,16 @@ * This fetches the server-side reconciliation — agent-CLAIMED vs LIVE * `sys_metadata` — so a signed-in admin can diagnose a build that "went wrong" * from the browser, with no DB credentials. Mirrors `fetchConversation`'s - * same-origin cookie auth. + * same-origin cookie auth, and sends the stored bearer token beside it. */ +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} + export interface ArtifactRef { type: string; name: string; @@ -77,7 +84,7 @@ export interface BuildDebugReport { * empty state instead of throwing. */ export async function fetchBuildDebug(apiBase: string, conversationId: string): Promise { - const res = await fetch(`${apiBase}/conversations/${encodeURIComponent(conversationId)}/debug`, { + const res = await authFetch(`${apiBase}/conversations/${encodeURIComponent(conversationId)}/debug`, { credentials: 'include', }); if (res.status === 404 || res.status === 403 || res.status === 401) return null; diff --git a/ui/packages/app-shell/src/console/connect/ConnectAgentWidget.tsx b/ui/packages/app-shell/src/console/connect/ConnectAgentWidget.tsx index 3743dc2ce9a..8449df6cb15 100644 --- a/ui/packages/app-shell/src/console/connect/ConnectAgentWidget.tsx +++ b/ui/packages/app-shell/src/console/connect/ConnectAgentWidget.tsx @@ -87,7 +87,7 @@ import { AlertCircle, Sparkles, } from 'lucide-react'; -import { TokenStorage } from '@object-ui/auth'; +import { createAuthenticatedFetch, TokenStorage } from '@object-ui/auth'; import { formatDateTime, useObjectTranslation } from '@object-ui/i18n'; import { ComponentRegistry } from '@object-ui/core'; import { notifyDataChanged } from '@object-ui/react'; @@ -104,6 +104,11 @@ import { AuthorizedAccessList } from './AuthorizedAccessList.js'; import { DeveloperNamespaceGate } from './DeveloperNamespaceGate.js'; import { useConnectedAccess, type ConnectedEntry } from './connectedAccess.js'; +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} + const SERVER_URL = (import.meta.env.VITE_SERVER_URL || '').replace(/\/$/, ''); /** Same-origin API calls need the Bearer token (see marketplaceApi.ts). */ @@ -295,7 +300,7 @@ function ConnectAgentBody() { useEffect(() => { (async () => { try { - const res = await fetch(`${SERVER_URL}/api/v1/discovery`, { credentials: 'include' }); + const res = await authFetch(`${SERVER_URL}/api/v1/discovery`, { credentials: 'include' }); const json = await res.json().catch(() => ({})); const routes = (json?.data ?? json)?.routes ?? {}; setMcpUrl(typeof routes.mcp === 'string' ? absoluteUrl(routes.mcp) : null); @@ -338,7 +343,7 @@ function ConnectAgentBody() { setMinting(true); setMintError(null); try { - const res = await fetch(`${SERVER_URL}/api/v1/keys`, { + const res = await authFetch(`${SERVER_URL}/api/v1/keys`, { method: 'POST', credentials: 'include', headers: withEnvAuth({ 'content-type': 'application/json' }), diff --git a/ui/packages/app-shell/src/console/deployment-notice/__tests__/DeploymentNotice.test.tsx b/ui/packages/app-shell/src/console/deployment-notice/__tests__/DeploymentNotice.test.tsx index 78b48fc7c1d..59d7fd83572 100644 --- a/ui/packages/app-shell/src/console/deployment-notice/__tests__/DeploymentNotice.test.tsx +++ b/ui/packages/app-shell/src/console/deployment-notice/__tests__/DeploymentNotice.test.tsx @@ -46,7 +46,7 @@ const DRAWN_IDS = NOTICE.findings.map((f) => f.id).filter((id) => id !== 'email_ const envelope = (data: unknown) => ({ success: true, data }); const json = (status: number, body: unknown) => - ({ ok: status >= 200 && status < 300, status, json: async () => body }) as unknown as Response; + ({ headers: new Headers(), ok: status >= 200 && status < 300, status, json: async () => body }) as unknown as Response; let fetchMock: ReturnType; diff --git a/ui/packages/app-shell/src/console/deployment-notice/deploymentNoticeState.ts b/ui/packages/app-shell/src/console/deployment-notice/deploymentNoticeState.ts index 1d69f58e1bf..5945f28a06d 100644 --- a/ui/packages/app-shell/src/console/deployment-notice/deploymentNoticeState.ts +++ b/ui/packages/app-shell/src/console/deployment-notice/deploymentNoticeState.ts @@ -32,6 +32,12 @@ */ import { bearerAuthHeaders } from '../../utils/authToken.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} export type DeploymentFindingId = | 'database_local_file' @@ -91,7 +97,7 @@ export function parseDeploymentNotice(body: unknown): DeploymentNoticeState | nu export async function fetchDeploymentNotice(): Promise { try { - const res = await fetch(`${serverUrl()}${NOTICE_PATH}`, { + const res = await authFetch(`${serverUrl()}${NOTICE_PATH}`, { credentials: 'include', headers: { Accept: 'application/json', ...bearerAuthHeaders() }, }); @@ -107,7 +113,7 @@ export type HideAnswer = 'hidden' | 'no-audit-log' | 'changed' | 'failed'; export async function hideDeploymentNotice(fingerprint: string): Promise { try { - const res = await fetch(`${serverUrl()}${NOTICE_PATH}/hide`, { + const res = await authFetch(`${serverUrl()}${NOTICE_PATH}/hide`, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...bearerAuthHeaders() }, diff --git a/ui/packages/app-shell/src/console/home/__tests__/HomePage.draftsReadGate-25894.test.tsx b/ui/packages/app-shell/src/console/home/__tests__/HomePage.draftsReadGate-25894.test.tsx index 4bb8ef6c9fc..9f837efc281 100644 --- a/ui/packages/app-shell/src/console/home/__tests__/HomePage.draftsReadGate-25894.test.tsx +++ b/ui/packages/app-shell/src/console/home/__tests__/HomePage.draftsReadGate-25894.test.tsx @@ -113,8 +113,8 @@ beforeEach(() => { vi.fn(async (input: unknown) => { const url = String(input); fetchCalls.push(url); - if (routeOf(url) === DRAFTS_ROUTE) return { ok: true, status: 200, json: async () => ({ drafts: DRAFTS }) }; - return { ok: false, status: 404, json: async () => ({}) }; + if (routeOf(url) === DRAFTS_ROUTE) return { headers: new Headers(), ok: true, status: 200, json: async () => ({ drafts: DRAFTS }) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }), ); }); diff --git a/ui/packages/app-shell/src/console/home/__tests__/HomePage.pendingDraftsPackageName-13136.test.tsx b/ui/packages/app-shell/src/console/home/__tests__/HomePage.pendingDraftsPackageName-13136.test.tsx index b6943db4360..ce941c5b6ea 100644 --- a/ui/packages/app-shell/src/console/home/__tests__/HomePage.pendingDraftsPackageName-13136.test.tsx +++ b/ui/packages/app-shell/src/console/home/__tests__/HomePage.pendingDraftsPackageName-13136.test.tsx @@ -127,6 +127,9 @@ vi.mock('../../../hooks/useInboxBell', () => ({ useInboxBell: () => ({ markRead: vi.mock('../../deployment-notice/DeploymentNotice', () => ({ DeploymentNotice: () => null })); import { HomePage } from '../HomePage'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; const DRAFTS_ROUTE = '/api/v1/meta/_drafts'; const PACKAGES_ROUTE = '/api/v1/packages'; @@ -172,13 +175,13 @@ beforeEach(() => { vi.fn(async (input: unknown) => { const url = String(input); fetchCalls.push(url); - if (routeOf(url) === DRAFTS_ROUTE) return { ok: true, status: 200, json: async () => ({ drafts }) }; + if (routeOf(url) === DRAFTS_ROUTE) return { headers: new Headers(), ok: true, status: 200, json: async () => ({ drafts }) }; if (routeOf(url) === PACKAGES_ROUTE) { if (packagesGate) await packagesGate; const { ok, status, body } = packagesAnswer; - return { ok, status, json: async () => body }; + return { headers: new Headers(), ok, status, json: async () => body }; } - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }), ); }); diff --git a/ui/packages/app-shell/src/console/marketplace/marketplaceApi.ts b/ui/packages/app-shell/src/console/marketplace/marketplaceApi.ts index 265444006aa..a9b86f86f44 100644 --- a/ui/packages/app-shell/src/console/marketplace/marketplaceApi.ts +++ b/ui/packages/app-shell/src/console/marketplace/marketplaceApi.ts @@ -23,10 +23,12 @@ const API_BASE = `${SERVER_URL}/api/v1/marketplace`; /** * The console's authenticated fetch — the stored bearer token beside the * session cookie — for the calls to THIS runtime's own server: the local - * install ledger (`/marketplace/install-local*`) and the cloud-connection - * reads the Packages page makes. ⛔ Never for a request to the cloud control - * plane's own origin (`getCloudBase()`), which must not see this runtime's - * bearer; the browse calls keep `credentials: 'omit'` in {@link call}. + * install ledger (`/marketplace/install-local*`), the same-origin + * `/cloud-connection/*` routes, and the control plane's own install and + * installed-state routes when this runtime IS the control plane. ⛔ Never for + * a request to the cloud control plane's own origin (`getCloudBase()`), which + * must not see this runtime's bearer; the browse calls keep + * `credentials: 'omit'` in {@link call}. */ function serverFetch(input: RequestInfo | URL, init?: RequestInit): Promise { return createAuthenticatedFetch()(input, init); @@ -512,7 +514,7 @@ export async function installPackage(input: { if (cloudBase) { // objectstack#29119 — the install lands in THIS environment, so its // package list reads from before it are forgotten however it ends. - const res = await fetch(`/api/v1/cloud-connection/install`, { + const res = await serverFetch(`/api/v1/cloud-connection/install`, { method: 'POST', credentials: 'include', headers: withEnvAuth({ 'Accept': 'application/json', 'Content-Type': 'application/json' }), @@ -541,7 +543,7 @@ export async function installPackage(input: { // ── Cloud control-plane path (runtime IS cloud) ─────────────────────── // Same-origin direct call to the install action. const base = SERVER_URL; - const res = await fetch(`${base}/api/v1/actions/sys_package/install_package`, { + const res = await serverFetch(`${base}/api/v1/actions/sys_package/install_package`, { method: 'POST', credentials: 'include', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, @@ -595,7 +597,7 @@ export async function installPackage(input: { export async function getInstallNamespace(packageId: string): Promise { if (!packageId) return null; try { - const res = await fetch( + const res = await serverFetch( `/api/v1/cloud-connection/install-namespace?package_id=${encodeURIComponent(packageId)}`, { credentials: 'include', headers: withEnvAuth({ 'Accept': 'application/json' }) }, ); @@ -794,7 +796,7 @@ export async function getCloudInstallationInfo( const cloudBase = getCloudBase(); if (cloudBase) { try { - const res = await fetch( + const res = await serverFetch( `/api/v1/cloud-connection/installation?package_id=${encodeURIComponent(packageId)}`, { credentials: 'include', headers: withEnvAuth({ 'Accept': 'application/json' }) }, ); @@ -823,7 +825,7 @@ export async function getCloudInstallationInfo( if (!environmentId) return null; const base = SERVER_URL; try { - const res = await fetch( + const res = await serverFetch( `${base}/api/v1/cloud/environments/${encodeURIComponent(environmentId)}/installations/${encodeURIComponent(packageId)}`, { credentials: 'include', headers: { 'Accept': 'application/json' } }, ); diff --git a/ui/packages/app-shell/src/hooks/__tests__/useAiUsage.test.ts b/ui/packages/app-shell/src/hooks/__tests__/useAiUsage.test.ts index 6af71ae0a3a..ae495680005 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useAiUsage.test.ts +++ b/ui/packages/app-shell/src/hooks/__tests__/useAiUsage.test.ts @@ -19,7 +19,7 @@ const POOL = { planType: 'free', fraction: 0.5, unmetered: false, resetKind: 'we const RESP = { pool: POOL, breakdown: { build: 0.3, dataChat: 0.2 } }; function okResponse(body: unknown) { - return { ok: true, status: 200, json: async () => body } as unknown as Response; + return { headers: new Headers(), ok: true, status: 200, json: async () => body } as unknown as Response; } describe('useAiUsage', () => { diff --git a/ui/packages/app-shell/src/hooks/__tests__/useConversationList.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useConversationList.test.tsx index c5d1aa30500..d85d8bd7205 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useConversationList.test.tsx +++ b/ui/packages/app-shell/src/hooks/__tests__/useConversationList.test.tsx @@ -64,7 +64,8 @@ describe('useConversationList', () => { expect(result.current.conversations[0]?.title).toBeUndefined(); expect(fetchMock).toHaveBeenCalledWith( `${API_BASE}/conversations/conv-a`, - { credentials: 'include' }, + // The authenticated fetch hands the wire a `Headers` (the bearer, when one is stored). + { credentials: 'include', headers: expect.any(Headers) }, ); }); }); diff --git a/ui/packages/app-shell/src/hooks/sharedUserFeeds.ts b/ui/packages/app-shell/src/hooks/sharedUserFeeds.ts index 23fb4bfd6a0..924d48a5f2f 100644 --- a/ui/packages/app-shell/src/hooks/sharedUserFeeds.ts +++ b/ui/packages/app-shell/src/hooks/sharedUserFeeds.ts @@ -101,7 +101,7 @@ * @module */ import { useEffect, useMemo, useRef, useSyncExternalStore } from 'react'; -import { useAuth } from '@object-ui/auth'; +import { createAuthenticatedFetch, useAuth } from '@object-ui/auth'; import { usePermissions } from '@object-ui/permissions'; import { errorCodeIs } from '@object-ui/types'; // The refused-read verdict the record activity panel reads (objectui#11195), @@ -122,6 +122,11 @@ import type { ActivityItem } from '../layout/ActivityFeed.js'; import { activityRowToActivityItem } from '../layout/activityItemType.js'; import type { InboxNotification } from '../layout/inboxGrouping.js'; +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} + /** * Approvals poll cadence. Polling is the FALLBACK of a push channel * (objectstack#27626, see "A push channel replaces the poll" above), so it is @@ -1024,7 +1029,7 @@ export async function fetchPendingApprovalPage( }); let res: Response; try { - res = await fetch(`${serverUrl}/api/v1/approvals/requests?${qs}`, { + res = await authFetch(`${serverUrl}/api/v1/approvals/requests?${qs}`, { credentials: 'include', // Bearer too — see utils/authToken (#2548 split-origin fix). headers: bearerAuthHeaders(), diff --git a/ui/packages/app-shell/src/hooks/useAiUsage.ts b/ui/packages/app-shell/src/hooks/useAiUsage.ts index fdc525d6f48..0243c65efda 100644 --- a/ui/packages/app-shell/src/hooks/useAiUsage.ts +++ b/ui/packages/app-shell/src/hooks/useAiUsage.ts @@ -32,6 +32,12 @@ */ import * as React from 'react'; import { AI_USAGE_REFRESH_EVENT } from '@object-ui/plugin-chatbot/core'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** * The binding window. `weekly` and `fiveHour` are the cloud quota policy's two @@ -171,7 +177,7 @@ export function useAiUsage(options: UseAiUsageOptions = {}): UseAiUsageReturn { let cancelled = false; const url = `${apiBase!.replace(/\/$/, '')}/usage`; setLoading(true); - fetch(url, { method: 'GET', headers: { Accept: 'application/json' }, credentials: 'include' }) + authFetch(url, { method: 'GET', headers: { Accept: 'application/json' }, credentials: 'include' }) .then(async (res) => { if (!res.ok) throw new Error(`Failed to load AI usage (${res.status})`); return res.json(); diff --git a/ui/packages/app-shell/src/hooks/useChatConversation.ts b/ui/packages/app-shell/src/hooks/useChatConversation.ts index 8a712bf9092..d819a5b9dcb 100644 --- a/ui/packages/app-shell/src/hooks/useChatConversation.ts +++ b/ui/packages/app-shell/src/hooks/useChatConversation.ts @@ -25,6 +25,12 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react import { chartAnswerParts, detectPendingApproval } from '@object-ui/plugin-chatbot/core'; // Type-only, so it is erased and pulls no barrel closure into the hook. import type { AnswerSource } from '@object-ui/plugin-chatbot'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** Minimal UIMessage shape compatible with `@ai-sdk/react`'s `useChat`. */ export interface HydratedUIMessagePart { @@ -854,7 +860,7 @@ export function aiMessageRowsToServerMessages(rows: RawAiMessageRow[] | undefine } export async function fetchConversation(apiBase: string, id: string): Promise { - const res = await fetch(`${apiBase}/conversations/${encodeURIComponent(id)}`, { + const res = await authFetch(`${apiBase}/conversations/${encodeURIComponent(id)}`, { credentials: 'include', }); if (res.status === 404 || res.status === 403) return null; @@ -863,7 +869,7 @@ export async function fetchConversation(apiBase: string, id: string): Promise { - const res = await fetch(`${apiBase}/conversations`, { + const res = await authFetch(`${apiBase}/conversations`, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, @@ -879,7 +885,7 @@ function notSentCreateError(message: string, status?: number): Error { } async function deleteConversation(apiBase: string, id: string): Promise { - await fetch(`${apiBase}/conversations/${encodeURIComponent(id)}`, { + await authFetch(`${apiBase}/conversations/${encodeURIComponent(id)}`, { method: 'DELETE', credentials: 'include', }).catch(() => { diff --git a/ui/packages/app-shell/src/hooks/useConversationList.ts b/ui/packages/app-shell/src/hooks/useConversationList.ts index cc50410bb61..b1a5786a90d 100644 --- a/ui/packages/app-shell/src/hooks/useConversationList.ts +++ b/ui/packages/app-shell/src/hooks/useConversationList.ts @@ -11,6 +11,12 @@ import { useCallback, useEffect, useState } from 'react'; import { publishPlanApprovalPending } from '../assistant/assistantBus.js'; import { isHitlContinuation } from '@object-ui/plugin-chatbot/core'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** * One row of the conversation-history list. @@ -143,7 +149,7 @@ async function fetchConversationDetail( apiBase: string, id: string, ): Promise { - const res = await fetch(`${apiBase}/conversations/${encodeURIComponent(id)}`, { + const res = await authFetch(`${apiBase}/conversations/${encodeURIComponent(id)}`, { credentials: 'include', }); if (!res.ok) return undefined; @@ -168,7 +174,7 @@ export function useConversationList( const remove = useCallback( async (id: string) => { try { - await fetch(`${apiBase}/conversations/${encodeURIComponent(id)}`, { + await authFetch(`${apiBase}/conversations/${encodeURIComponent(id)}`, { method: 'DELETE', credentials: 'include', }); @@ -189,7 +195,7 @@ export function useConversationList( setConversations((rows) => rows.map((r) => (r.id === id ? { ...r, title: trimmed || undefined } : r)), ); - const res = await fetch(`${apiBase}/conversations/${encodeURIComponent(id)}`, { + const res = await authFetch(`${apiBase}/conversations/${encodeURIComponent(id)}`, { method: 'PATCH', credentials: 'include', headers: { 'Content-Type': 'application/json' }, @@ -216,7 +222,7 @@ export function useConversationList( setError(undefined); (async () => { try { - const res = await fetch( + const res = await authFetch( `${apiBase}/conversations?limit=${encodeURIComponent(String(limit))}`, { credentials: 'include' }, ); diff --git a/ui/packages/app-shell/src/hooks/useInboxBell.ts b/ui/packages/app-shell/src/hooks/useInboxBell.ts index a25c67c0615..7debc7c2344 100644 --- a/ui/packages/app-shell/src/hooks/useInboxBell.ts +++ b/ui/packages/app-shell/src/hooks/useInboxBell.ts @@ -40,6 +40,12 @@ import { } from './sharedUserFeeds.js'; import { useInboxArrivalNotifier } from './useInboxArrivalNotifier.js'; import type { InboxNotification } from '../layout/inboxGrouping.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** * Write read receipts through the framework's dedicated REST surface @@ -50,7 +56,7 @@ import type { InboxNotification } from '../layout/inboxGrouping.js'; */ export async function postInboxReadReceipts(subPath: 'read' | 'read/all', notificationIds?: string[]): Promise { const serverUrl = (import.meta.env?.VITE_SERVER_URL || '').replace(/\/$/, ''); - await fetch(`${serverUrl}/api/v1/notifications/${subPath}`, { + await authFetch(`${serverUrl}/api/v1/notifications/${subPath}`, { method: 'POST', credentials: 'include', // Bearer too — see utils/authToken (#2548 split-origin fix). diff --git a/ui/packages/app-shell/src/hooks/useRecordApprovals.quorum.test.tsx b/ui/packages/app-shell/src/hooks/useRecordApprovals.quorum.test.tsx index 2fc2ac4b3f8..9d2a29257a3 100644 --- a/ui/packages/app-shell/src/hooks/useRecordApprovals.quorum.test.tsx +++ b/ui/packages/app-shell/src/hooks/useRecordApprovals.quorum.test.tsx @@ -81,14 +81,14 @@ function stubApi(detail: unknown, opts: { detailStatus?: number } = {}) { gets.push(u); if (/\/approvals\/requests\/[^?]+$/.test(u)) { if (opts.detailStatus) { - return { ok: false, status: opts.detailStatus, json: async () => ({ error: 'nope' }) } as any; + return { headers: new Headers(), ok: false, status: opts.detailStatus, json: async () => ({ error: 'nope' }) } as any; } - return { ok: true, json: async () => detail } as any; + return { headers: new Headers(), ok: true, json: async () => detail } as any; } const list = (detail as any)?.id === PER_GROUP_DETAIL.id ? { ...LIST_ROW, id: PER_GROUP_DETAIL.id } : LIST_ROW; - return { ok: true, json: async () => ({ data: [list] }) } as any; + return { headers: new Headers(), ok: true, json: async () => ({ data: [list] }) } as any; }), ); } @@ -156,7 +156,7 @@ describe('useRecordApprovals — quorum progress (objectstack#4478)', () => { 'fetch', vi.fn(async (url: string) => { gets.push(String(url)); - return { ok: true, json: async () => ({ data: [{ ...LIST_ROW, status: 'approved' }] }) } as any; + return { headers: new Headers(), ok: true, json: async () => ({ data: [{ ...LIST_ROW, status: 'approved' }] }) } as any; }), ); const { result } = mount(); diff --git a/ui/packages/app-shell/src/hooks/useRecordApprovals.ts b/ui/packages/app-shell/src/hooks/useRecordApprovals.ts index 8f1f195e286..d1121c3215c 100644 --- a/ui/packages/app-shell/src/hooks/useRecordApprovals.ts +++ b/ui/packages/app-shell/src/hooks/useRecordApprovals.ts @@ -46,6 +46,12 @@ import { createQuietHttpLogger } from '@object-ui/data-objectstack'; import { useAdapter } from '../providers/AdapterProvider.js'; import { bearerAuthHeaders } from '../utils/authToken.js'; import type { DecisionOutputDef } from '../utils/decisionOutputParams.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} export interface ApprovalRequestLite { id: string; @@ -361,7 +367,7 @@ function apiBase() { } async function fetchJson(path: string, init?: RequestInit): Promise { - const res = await fetch(`${apiBase()}${path}`, { + const res = await authFetch(`${apiBase()}${path}`, { credentials: 'include', headers: { 'Content-Type': 'application/json', diff --git a/ui/packages/app-shell/src/layout/ContextSelectors.tsx b/ui/packages/app-shell/src/layout/ContextSelectors.tsx index 3bd6f313088..8ea8f46b0a9 100644 --- a/ui/packages/app-shell/src/layout/ContextSelectors.tsx +++ b/ui/packages/app-shell/src/layout/ContextSelectors.tsx @@ -44,6 +44,7 @@ import { SelectTrigger, SelectValue, } from '@object-ui/components'; +import { createAuthenticatedFetch } from '@object-ui/auth'; import { getIcon } from '../utils/getIcon.js'; import { resolveKeyedI18nLabel } from '../utils/index.js'; @@ -210,7 +211,10 @@ function useSelectorOptions(def: ContextSelectorDef): { options: Option[]; refet // dropdown-open and on a global `objectui:packages-changed` signal. const load = React.useCallback(async () => { try { - const res = await fetch(endpoint, { + // The console's authenticated fetch, built per call. The endpoint is + // author-written (`optionsSource.endpoint`) and may name another host, so + // `sameOriginOnly` keeps the stored bearer token to this server's requests. + const res = await createAuthenticatedFetch({ sameOriginOnly: true })(endpoint, { credentials: 'include', headers: { Accept: 'application/json' }, }); diff --git a/ui/packages/app-shell/src/layout/__tests__/AiUsageIndicator.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AiUsageIndicator.test.tsx index 9806665dafa..0b850a4bfdd 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AiUsageIndicator.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AiUsageIndicator.test.tsx @@ -190,7 +190,7 @@ describe('AiUsageIndicator', () => { // The wire payload through the REAL parser into the component — the path // that went blank when the endpoint became one pool (objectui#8524). describe('through the real hook', () => { - const okResponse = (body: unknown) => ({ ok: true, status: 200, json: async () => body }) as unknown as Response; + const okResponse = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }) as unknown as Response; // What the real hook last handed the component — read to know the fetch has // settled, so an empty DOM is a reading and not the pre-fetch first frame. let last: ReturnType | undefined; @@ -322,7 +322,7 @@ describe('AiUsageIndicator — declared upgradeUrl (objectstack#34622)', () => { async function serveRuntimeConfig(payload: Record) { const realFetch = globalThis.fetch; - globalThis.fetch = vi.fn(async () => ({ ok: true, json: async () => payload })) as unknown as typeof fetch; + globalThis.fetch = vi.fn(async () => ({ headers: new Headers(), ok: true, json: async () => payload })) as unknown as typeof fetch; try { await initRuntimeConfig(); } finally { diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.appBarLeftGroup-12461.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.appBarLeftGroup-12461.test.tsx index 4fbe2fa2ad3..15de58a4d45 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.appBarLeftGroup-12461.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.appBarLeftGroup-12461.test.tsx @@ -210,7 +210,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => String(url).endsWith('/api/v1/packages') diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.appIdentity-12201.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.appIdentity-12201.test.tsx index 97538b76e64..e6809b81550 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.appIdentity-12201.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.appIdentity-12201.test.tsx @@ -220,7 +220,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => String(url).endsWith('/api/v1/packages') diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.centeredSearch-12472.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.centeredSearch-12472.test.tsx index 76996b13b7f..aefdf0b1d6e 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.centeredSearch-12472.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.centeredSearch-12472.test.tsx @@ -193,7 +193,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => String(url).endsWith('/api/v1/packages') diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.designInStudioNeedsAuthoring-10899.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.designInStudioNeedsAuthoring-10899.test.tsx index 74559b044fc..244db0a0573 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.designInStudioNeedsAuthoring-10899.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.designInStudioNeedsAuthoring-10899.test.tsx @@ -190,7 +190,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => String(url).endsWith('/api/v1/packages') diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.editAppFollowsPackagePosture-12615.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.editAppFollowsPackagePosture-12615.test.tsx index fa7c37488b7..50258df220a 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.editAppFollowsPackagePosture-12615.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.editAppFollowsPackagePosture-12615.test.tsx @@ -216,9 +216,9 @@ function serve(answer: () => Promise) { const fetchMock = vi.fn(async (url: unknown) => { if (String(url).endsWith('/api/v1/packages')) { const body = await answer(); - return { ok: true, status: 200, json: async () => body }; + return { headers: new Headers(), ok: true, status: 200, json: async () => body }; } - return { ok: true, status: 200, json: async () => ({ data: [] }) }; + return { headers: new Headers(), ok: true, status: 200, json: async () => ({ data: [] }) }; }); vi.stubGlobal('fetch', fetchMock); return fetchMock; @@ -333,8 +333,8 @@ describe('no verdict, no pencil (objectui#12615)', () => { it('a failed list read draws no pencil', async () => { vi.stubGlobal('fetch', vi.fn(async (url: unknown) => String(url).endsWith('/api/v1/packages') - ? { ok: false, status: 403, json: async () => ({ success: false, error: { code: 'FORBIDDEN', message: 'no' } }) } - : { ok: true, status: 200, json: async () => ({ data: [] }) }, + ? { headers: new Headers(), ok: false, status: 403, json: async () => ({ success: false, error: { code: 'FORBIDDEN', message: 'no' } }) } + : { headers: new Headers(), ok: true, status: 200, json: async () => ({ data: [] }) }, )); expect(await editAppOn(BASE_ROUTE)).toEqual({ pencil: null, eye: null, switcherRow: '', switcherPosture: '' }); }); diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.pageRouteNoAuthoringHandles-12198.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.pageRouteNoAuthoringHandles-12198.test.tsx index 916c05c3f03..01c1f02c948 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.pageRouteNoAuthoringHandles-12198.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.pageRouteNoAuthoringHandles-12198.test.tsx @@ -305,7 +305,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => String(url).endsWith('/api/v1/packages') diff --git a/ui/packages/app-shell/src/layout/__tests__/ContextSelectors.autoSelectRace.test.tsx b/ui/packages/app-shell/src/layout/__tests__/ContextSelectors.autoSelectRace.test.tsx index fe1c052b481..eb693b591ef 100644 --- a/ui/packages/app-shell/src/layout/__tests__/ContextSelectors.autoSelectRace.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/ContextSelectors.autoSelectRace.test.tsx @@ -169,7 +169,7 @@ function atOptionsCommit() { beforeEach(() => { sessionStorage.clear(); - vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ROWS }))); + vi.stubGlobal('fetch', vi.fn(async () => ({ headers: new Headers(), ok: true, json: async () => ROWS }))); }); afterEach(() => { diff --git a/ui/packages/app-shell/src/layout/__tests__/ContextSelectors.persist.test.tsx b/ui/packages/app-shell/src/layout/__tests__/ContextSelectors.persist.test.tsx index 28eeada6fe6..1775d0f5b54 100644 --- a/ui/packages/app-shell/src/layout/__tests__/ContextSelectors.persist.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/ContextSelectors.persist.test.tsx @@ -159,7 +159,7 @@ function query() { beforeEach(() => { sessionStorage.clear(); - vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ROWS }))); + vi.stubGlobal('fetch', vi.fn(async () => ({ headers: new Headers(), ok: true, json: async () => ROWS }))); }); afterEach(() => { diff --git a/ui/packages/app-shell/src/layout/__tests__/ContextSelectors.scopeKey.test.tsx b/ui/packages/app-shell/src/layout/__tests__/ContextSelectors.scopeKey.test.tsx index cd72777cea5..a564d3d92e5 100644 --- a/ui/packages/app-shell/src/layout/__tests__/ContextSelectors.scopeKey.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/ContextSelectors.scopeKey.test.tsx @@ -147,7 +147,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: string) => ({ - ok: true, + headers: new Headers(), ok: true, json: async () => ROWS[String(url)] ?? [], })), ); diff --git a/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx b/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx index 6c95e33cd90..abffc2dbe7c 100644 --- a/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/SidebarAppMenu-36112.test.tsx @@ -141,7 +141,7 @@ function stubPackageList() { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => String(url).endsWith('/api/v1/packages') diff --git a/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu-12427.test.tsx b/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu-12427.test.tsx index 6bfabf69b15..75d13dd03f1 100644 --- a/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu-12427.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu-12427.test.tsx @@ -129,7 +129,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => String(url).endsWith('/api/v1/packages') diff --git a/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu.designAsksUnsaved-13231.test.tsx b/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu.designAsksUnsaved-13231.test.tsx index 693db91d594..a059309b024 100644 --- a/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu.designAsksUnsaved-13231.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu.designAsksUnsaved-13231.test.tsx @@ -114,7 +114,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => String(url).endsWith('/api/v1/packages') diff --git a/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu.designFollowsPackagePosture-12615.test.tsx b/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu.designFollowsPackagePosture-12615.test.tsx index 9a3bd7664df..255c46f86e4 100644 --- a/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu.designFollowsPackagePosture-12615.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu.designFollowsPackagePosture-12615.test.tsx @@ -110,7 +110,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => (String(url).endsWith('/api/v1/packages') ? PACKAGES : { data: [] }), })), diff --git a/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu.designOpensStudio-12520.test.tsx b/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu.designOpensStudio-12520.test.tsx index a8b37fabb98..2d98356806f 100644 --- a/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu.designOpensStudio-12520.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/SidebarItemMenu.designOpensStudio-12520.test.tsx @@ -215,7 +215,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => String(url).endsWith('/api/v1/packages') diff --git a/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.favoritesMenu-12427.test.tsx b/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.favoritesMenu-12427.test.tsx index f1a6d3a6ebd..a08bd99f930 100644 --- a/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.favoritesMenu-12427.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.favoritesMenu-12427.test.tsx @@ -216,7 +216,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => String(url).endsWith('/api/v1/packages') diff --git a/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.hiddenCollapse-35062.test.tsx b/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.hiddenCollapse-35062.test.tsx index 38dfa074c87..3bf14ee348d 100644 --- a/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.hiddenCollapse-35062.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.hiddenCollapse-35062.test.tsx @@ -714,7 +714,7 @@ describe('the float carries the app menu, and its 「Design layout」 enters the vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => String(url).endsWith('/api/v1/packages') diff --git a/ui/packages/app-shell/src/layout/designModeMenuSave.ts b/ui/packages/app-shell/src/layout/designModeMenuSave.ts index 061708a586b..df6cbd13ae4 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuSave.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuSave.ts @@ -95,6 +95,12 @@ import { type Menu, type MenuLabelLanguage, } from './designModeMenuModel.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** The doors the save goes through; the defaults are the console's own. */ export interface AppMenuSaveDoors { @@ -478,7 +484,7 @@ export function fetchDeploymentLocales(): Promise { if (localesRead) return localesRead; localesRead = (async () => { try { - const res = await fetch('/api/v1/i18n/locales', { credentials: 'include' }); + const res = await authFetch('/api/v1/i18n/locales', { credentials: 'include' }); if (!res.ok) return null; const json = (await res.json()) as { data?: Record } & Record; const body = isRecord(json?.data) ? json.data : json; diff --git a/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx b/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx index d9fce524b78..c5c177446e0 100644 --- a/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx +++ b/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx @@ -118,6 +118,12 @@ import { readDraftChecks, type DraftCheck } from './flowDraftChecks.js'; import { clearPublishChecksShown, markPublishChecksShown } from './publishChecksShown.js'; // objectstack#27835 — a property by its label on the item type's form. import { formKeyLabel, labelSpellsKey } from './changeKeyLabels.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} export interface DraftChangeEntry { /** @@ -213,7 +219,7 @@ function entryKey(entry: Pick): st */ async function publishedNamesOf(type: string): Promise> { // `type` is already the canonical singular — folded in `listPendingDrafts`. - const res = await fetch(`/api/v1/meta/${encodeURIComponent(type)}`, { + const res = await authFetch(`/api/v1/meta/${encodeURIComponent(type)}`, { credentials: 'include', headers: { Accept: 'application/json' }, cache: 'no-store', @@ -285,7 +291,7 @@ async function fetchItemRead( // type with no members, and refuse a blank one. if (opts.member) params.push(`member=${encodeURIComponent(opts.member)}`); const qs = params.length ? `?${params.join('&')}` : ''; - const res = await fetch( + const res = await authFetch( `/api/v1/meta/${encodeURIComponent(type)}/${encodeURIComponent(name)}${qs}`, { credentials: 'include', headers: { Accept: 'application/json' }, cache: 'no-store' }, ); diff --git a/ui/packages/app-shell/src/preview/UnpublishedAppBar.tsx b/ui/packages/app-shell/src/preview/UnpublishedAppBar.tsx index c6d6169fcbf..04e655a6cd9 100644 --- a/ui/packages/app-shell/src/preview/UnpublishedAppBar.tsx +++ b/ui/packages/app-shell/src/preview/UnpublishedAppBar.tsx @@ -60,6 +60,12 @@ import { emitPublishReceipt } from '../assistant/assistantBus.js'; import { matchAppBySegment } from '../utils/appRoute.js'; import { CommitTimeline } from './CommitTimeline.js'; import { usePreviewDrafts } from './PreviewModeContext.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} export function UnpublishedAppBar() { const preview = usePreviewDrafts(); @@ -113,7 +119,7 @@ export function UnpublishedAppBar() { // published from the served copy. const stored = adapter?.getAuthoredItem ? await adapter.getAuthoredItem('app', appKey) : null; if (!stored) throw new Error(`app/${appKey}`); - const res = await fetch(`/api/v1/meta/app/${encodeURIComponent(appKey)}`, { + const res = await authFetch(`/api/v1/meta/app/${encodeURIComponent(appKey)}`, { method: 'PUT', credentials: 'include', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, diff --git a/ui/packages/app-shell/src/preview/__tests__/CommitTimeline.bundleMember-12271.test.tsx b/ui/packages/app-shell/src/preview/__tests__/CommitTimeline.bundleMember-12271.test.tsx index 5aa3e67e0b2..10371f7ed3a 100644 --- a/ui/packages/app-shell/src/preview/__tests__/CommitTimeline.bundleMember-12271.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/CommitTimeline.bundleMember-12271.test.tsx @@ -33,7 +33,7 @@ afterEach(() => { function mockCommits(commits: unknown[]) { global.fetch = vi.fn(async () => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => ({ commits }), })) as unknown as typeof fetch; diff --git a/ui/packages/app-shell/src/preview/__tests__/CommitTimeline.itemCountAgreement-9266.test.tsx b/ui/packages/app-shell/src/preview/__tests__/CommitTimeline.itemCountAgreement-9266.test.tsx index d761e8c108c..cf1da9db500 100644 --- a/ui/packages/app-shell/src/preview/__tests__/CommitTimeline.itemCountAgreement-9266.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/CommitTimeline.itemCountAgreement-9266.test.tsx @@ -96,7 +96,7 @@ const AT_THREE: Record = Object.fromEntries( function mockCommits(itemCount: number) { global.fetch = vi.fn(async () => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => [{ id: 'c1', operation: 'apply', message: 'M', itemCount }], })) as unknown as typeof fetch; diff --git a/ui/packages/app-shell/src/preview/__tests__/CommitTimeline.test.tsx b/ui/packages/app-shell/src/preview/__tests__/CommitTimeline.test.tsx index accc1d45f03..cc3b2a1d32d 100644 --- a/ui/packages/app-shell/src/preview/__tests__/CommitTimeline.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/CommitTimeline.test.tsx @@ -52,7 +52,7 @@ const OUTAGE_ENVELOPE = { function mockCommitsResponse(status: number, body: unknown | null) { global.fetch = vi.fn(async () => ({ - ok: status >= 200 && status < 300, + headers: new Headers(), ok: status >= 200 && status < 300, status, json: async () => { if (body === null) throw new SyntaxError('not JSON'); diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.accessibleNames-12510.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.accessibleNames-12510.test.tsx index 5593e35554b..5c640656083 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.accessibleNames-12510.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.accessibleNames-12510.test.tsx @@ -30,6 +30,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ })); import { DraftChangesPanel } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; const DRAFT_ROWS = [ { type: 'permission', name: 'qa_readers', packageId: 'com.x', label: 'QA Readers' }, @@ -40,12 +43,12 @@ const DRAFT_ROWS = [ const fetchMock = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) return ok({ drafts: DRAFT_ROWS }); if (/\/meta\/object(\?|$)/.test(url)) return ok([{ name: 'laneawf_qa_wf_obj', label: 'QA WF Object' }]); if (/\/meta\/page(\?|$)/.test(url)) return ok([]); if (/\/meta\/permission(\?|$)/.test(url)) return ok([]); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }); afterEach(() => { diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.agentSource-27176.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.agentSource-27176.test.tsx index ee5f0b020e5..9233e780789 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.agentSource-27176.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.agentSource-27176.test.tsx @@ -37,7 +37,7 @@ import { DraftChangesPanel, draftAgentSources } from '../DraftChangesPanel'; const PKG = 'com.x'; const AT = '2026-10-28T10:00:00.000Z'; -const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); +const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); let draftChanges: unknown = undefined; diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.backfill-12929.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.backfill-12929.test.tsx index c8502f90ffd..d69ef4969b8 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.backfill-12929.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.backfill-12929.test.tsx @@ -39,6 +39,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ })); import { DraftChangesPanel, backfillCandidates, type DraftPublishOptions } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; const PACKAGE_ID = 'com.x'; @@ -64,7 +67,7 @@ const DRAFT_TICKET = { const DRAFT_QUEUE = { name: 'st_queue', fields: { open: { type: 'boolean', defaultValue: true } } }; function ok(body: unknown) { - return { ok: true, status: 200, json: async () => body }; + return { headers: new Headers(), ok: true, status: 200, json: async () => body }; } const fetchMock = vi.fn(async (input: RequestInfo | URL) => { @@ -74,7 +77,7 @@ const fetchMock = vi.fn(async (input: RequestInfo | URL) => { const isDraft = url.includes('state=draft'); if (url.includes('/meta/object/st_ticket')) return ok(isDraft ? DRAFT_TICKET : PUBLISHED_TICKET); if (url.includes('/meta/object/st_queue') && isDraft) return ok(DRAFT_QUEUE); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }); let find: ReturnType; diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.bundleMember-12271.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.bundleMember-12271.test.tsx index 13a737b000b..def8757e571 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.bundleMember-12271.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.bundleMember-12271.test.tsx @@ -38,6 +38,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ })); import { DraftChangesPanel } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; afterEach(() => { vi.restoreAllMocks(); @@ -58,8 +61,8 @@ function mockServer(fx: Fixture): string[] { global.fetch = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); urls.push(url); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); - const missing = { ok: false, status: 404, json: async () => ({}) }; + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); + const missing = { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; if (url.includes('/_drafts')) { return ok({ drafts: fx.drafts.map((d) => ({ diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.changeNote.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.changeNote.test.tsx index 686978e9ac7..592c7895a4c 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.changeNote.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.changeNote.test.tsx @@ -38,6 +38,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ })); import { DraftChangesPanel, type DraftPublishOptions } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; const PACKAGE_ID = 'com.x'; @@ -49,7 +52,7 @@ const DRAFT_TICKET = { }; function ok(body: unknown) { - return { ok: true, status: 200, json: async () => body }; + return { headers: new Headers(), ok: true, status: 200, json: async () => body }; } const fetchMock = vi.fn(async (input: RequestInfo | URL) => { @@ -57,7 +60,7 @@ const fetchMock = vi.fn(async (input: RequestInfo | URL) => { if (url.includes('/_drafts')) return ok({ drafts: DRAFT_ROWS }); if (/\/meta\/object(\?|$)/.test(url)) return ok([{ name: 'st_ticket' }]); if (url.includes('/meta/object/st_ticket')) return ok(url.includes('state=draft') ? DRAFT_TICKET : PUBLISHED_TICKET); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }); const find = vi.fn(async () => ({ data: [], total: 3 })); diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.containerViewUpdate-32755.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.containerViewUpdate-32755.test.tsx index 0a953c7263c..114c8186d0b 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.containerViewUpdate-32755.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.containerViewUpdate-32755.test.tsx @@ -68,7 +68,7 @@ function mockServer(byName: Record = published) { global.fetch = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); requests.push(url); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) { return ok([CONTAINER, LISTED, FRESH].map((name) => ({ type: 'view', name, packageId: 'com.x' }))); } @@ -78,11 +78,11 @@ function mockServer(byName: Record = published) { if (!name) return ok([{ name: 'ebqu_claim.form' }, { name: LISTED }]); const decoded = decodeURIComponent(name); if (url.includes('state=draft')) { - return draft[decoded] ? ok({ type: 'view', name: decoded, item: draft[decoded] }) : { ok: false, status: 404, json: async () => ({}) }; + return draft[decoded] ? ok({ type: 'view', name: decoded, item: draft[decoded] }) : { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; } const body = byName[decoded]; - if (body === 'fail') return { ok: false, status: 500, json: async () => ({}) }; - return body ? ok(body) : { ok: false, status: 404, json: async () => ({}) }; + if (body === 'fail') return { headers: new Headers(), ok: false, status: 500, json: async () => ({}) }; + return body ? ok(body) : { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }) as unknown as typeof fetch; } diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.entryNote-26730.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.entryNote-26730.test.tsx index fd83d2a1020..717d7fda1f5 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.entryNote-26730.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.entryNote-26730.test.tsx @@ -24,6 +24,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ })); import { DraftChangesPanel, type DraftChangeEntry } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; // `flows`: a stored plural spelling, which the sheet folds before the host sees it. const DRAFT_ROWS = [ @@ -33,10 +36,10 @@ const DRAFT_ROWS = [ const fetchMock = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) return ok({ drafts: DRAFT_ROWS }); if (/\/meta\/[a-z_]+(\?|$)/.test(url)) return ok([]); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }); afterEach(() => { diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.fieldOrder-27516.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.fieldOrder-27516.test.tsx index ad5c2777249..47108750e2a 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.fieldOrder-27516.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.fieldOrder-27516.test.tsx @@ -35,6 +35,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ })); import { DraftChangesPanel, computeChangeDetail } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; const NO_CHANGE = 'No differences detected — the draft matches the published version.'; const ORDER_ROW = '~ Field order changed'; @@ -130,7 +133,7 @@ type Body = Record; function mockServer(published: Body, draft: Body): void { global.fetch = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) return ok([{ type: 'object', name: 'asset', packageId: 'com.x' }]); const [type, name] = url.split('?')[0].replace('/api/v1/meta/', '').split('/'); if (!name) return ok([{ name: 'asset' }]); diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.fieldRows-13125.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.fieldRows-13125.test.tsx index f59750c3d96..cfd3887686d 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.fieldRows-13125.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.fieldRows-13125.test.tsx @@ -52,6 +52,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ })); import { DraftChangesPanel, computeChangeDetail } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; /** `provisionSearchCompanion`'s literal (description shortened; not read). */ const SEARCH_COMPANION_DEF = { @@ -220,7 +223,7 @@ const TICKET_DRAFT = { }; function stubServer() { - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); const fetchMock = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); if (url.includes('/_drafts')) { @@ -235,7 +238,7 @@ function stubServer() { const draft = url.includes('state=draft'); if (/\/meta\/object\/crm_visit\b/.test(url) && draft) return ok({ item: VISIT_DRAFT }); if (/\/meta\/object\/crm_ticket\b/.test(url)) return ok(draft ? { item: TICKET_DRAFT } : TICKET_PUBLISHED); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }); vi.stubGlobal('fetch', fetchMock as unknown as typeof fetch); } diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.flowChecks-34818.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.flowChecks-34818.test.tsx index d18e1ab4b0a..a1edfea8231 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.flowChecks-34818.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.flowChecks-34818.test.tsx @@ -51,7 +51,7 @@ const ADVISORY_ZH = function mockRoutes(warnings: Array<{ path?: string; message: string }>) { const fetchMock = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) { return ok([{ type: 'flow', name: 'xin_huiyi_tixing', packageId: 'app.minutes', label: '会议提醒' }]); } @@ -69,7 +69,7 @@ function mockRoutes(warnings: Array<{ path?: string; message: string }>) { }); } if (/\/meta\/flow(\?|$)/.test(url)) return ok([]); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }); global.fetch = fetchMock as unknown as typeof fetch; return fetchMock; @@ -90,9 +90,10 @@ describe('DraftChangesPanel — the flow publish checks, before the publish (obj expect(block.textContent).not.toMatch(/flow-decision-unconditional-branch|xin_huiyi_tixing/); // The read that fed it stated the console's language. const draftCall = fetchMock.mock.calls.find( - ([u, init]) => String(u).includes('state=draft') && (init?.headers as Record | undefined)?.['Accept-Language'], + ([u, init]) => String(u).includes('state=draft') && new Headers(init?.headers as HeadersInit | undefined).get('Accept-Language'), ); - expect((draftCall![1]!.headers as Record)['Accept-Language']).toBe('zh-CN'); + // The authenticated fetch hands the wire a `Headers`; the language the read stated is read off it. + expect(new Headers(draftCall![1]!.headers as HeadersInit).get('Accept-Language')).toBe('zh-CN'); }); it('reports without blocking — the Publish button stays live', async () => { diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.flowNodeRows-27356.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.flowNodeRows-27356.test.tsx index dd76f459a9b..5f536d613c6 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.flowNodeRows-27356.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.flowNodeRows-27356.test.tsx @@ -30,6 +30,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ })); import { DraftChangesPanel, computeChangeDetail } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; const START = { id: 'start', type: 'start', label: 'Start' }; const END = { id: 'end', type: 'end', label: 'End' }; @@ -113,7 +116,7 @@ describe("computeChangeDetail names a flow's nodes (objectstack#27356)", () => { /* ─────────────── the panel ─────────────── */ function stubServer() { - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); vi.stubGlobal( 'fetch', vi.fn(async (input: RequestInfo | URL) => { @@ -123,7 +126,7 @@ function stubServer() { } if (/\/meta\/flow(\?|$)/.test(url)) return ok([{ name: 'case_follow_up' }]); if (/\/meta\/flow\/case_follow_up\b/.test(url)) return ok(url.includes('state=draft') ? { item: DRAFT } : PUBLISHED); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }) as unknown as typeof fetch, ); } diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.generatedGroup-25890.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.generatedGroup-25890.test.tsx index 30850241d38..1bd8a254b36 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.generatedGroup-25890.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.generatedGroup-25890.test.tsx @@ -46,6 +46,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ })); import { DraftChangesPanel, computeChangeDetail } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; /** The read's zh-CN labels for the injected columns (`SYSTEM_FIELD_LABELS`). */ const ZH_LABELS: Record = { @@ -167,7 +170,7 @@ describe('computeChangeDetail — what the platform wrote is not an author row ( * default is the card's NEW object. */ function stubServer(published: Record | null = null) { - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); vi.stubGlobal( 'fetch', vi.fn(async (input: RequestInfo | URL) => { @@ -180,7 +183,7 @@ function stubServer(published: Record | null = null) { return ok({ item: REPAIR_TICKET_DRAFT }); } if (published && url.includes(`/meta/object/${AUTHORED.name}`)) return ok(published); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }) as unknown as typeof fetch, ); } diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.groupHeading-13221.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.groupHeading-13221.test.tsx index a8db07eade0..dd71682d579 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.groupHeading-13221.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.groupHeading-13221.test.tsx @@ -25,6 +25,9 @@ import { cleanup, render, screen, waitFor } from '@testing-library/react'; import { createI18n, I18nProvider } from '@object-ui/i18n'; import { DraftChangesPanel } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; type Row = { type: string; name: string }; @@ -34,12 +37,12 @@ function stubFetch(rows: Row[]) { 'fetch', vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) return ok({ drafts }); if (url.includes('state=draft')) return ok({ name: 'x' }); // Every published-list read: nothing is published, so every row is New. if (/\/meta\/\w+(\?|$)/.test(url)) return ok([]); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }) as unknown as typeof fetch, ); } diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.labelFirst-11862.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.labelFirst-11862.test.tsx index 19f24260b0e..7125f38351f 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.labelFirst-11862.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.labelFirst-11862.test.tsx @@ -43,6 +43,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ })); import { DraftChangesPanel } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; const DRAFT_ROWS = [ { type: 'permission', name: 'qa_readers', packageId: 'com.x', label: 'QA Readers' }, @@ -53,12 +56,12 @@ const DRAFT_ROWS = [ const fetchMock = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) return ok({ drafts: DRAFT_ROWS }); if (/\/meta\/object(\?|$)/.test(url)) return ok([{ name: 'laneawf_qa_wf_obj', label: 'QA WF Object' }]); if (/\/meta\/page(\?|$)/.test(url)) return ok([]); if (/\/meta\/permission(\?|$)/.test(url)) return ok([]); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }); afterEach(() => { diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.namedChanges-27835.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.namedChanges-27835.test.tsx index 75380baca64..9c632ddec30 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.namedChanges-27835.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.namedChanges-27835.test.tsx @@ -35,6 +35,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ import { DraftChangesPanel, computeChangeDetail } from '../DraftChangesPanel'; import { formKeyLabel } from '../changeKeyLabels'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; const HOURS_RULE = { name: 'hours_over_40', @@ -164,7 +167,7 @@ describe('computeChangeDetail compares a view inside its body (objectstack#27835 /* ─────────────── the panel ─────────────── */ function stubServer(type: string, name: string, label: string, published: unknown, draft: unknown) { - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); vi.stubGlobal( 'fetch', vi.fn(async (input: RequestInfo | URL) => { @@ -173,9 +176,9 @@ function stubServer(type: string, name: string, label: string, published: unknow if (new RegExp(`/meta/${type}s?(\\?|$)`).test(url)) return ok(published ? [{ name }] : []); if (new RegExp(`/meta/${type}s?/${name}\\b`).test(url)) { if (url.includes('state=draft')) return ok({ item: draft }); - return published ? ok(published) : { ok: false, status: 404, json: async () => ({}) }; + return published ? ok(published) : { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; } - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }) as unknown as typeof fetch, ); } diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.newEntryNoPublishedRead-25894.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.newEntryNoPublishedRead-25894.test.tsx index c4f59354387..aafb4307a00 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.newEntryNoPublishedRead-25894.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.newEntryNoPublishedRead-25894.test.tsx @@ -33,6 +33,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ })); import { DraftChangesPanel } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; const PKG = 'com.x'; // `st_ticket` is draft-only (NEW); `st_queue` overwrites a published object. @@ -41,8 +44,8 @@ const DRAFT_ROWS = [ { type: 'object', name: 'st_queue', packageId: PKG, label: 'Queue' }, ]; -const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); -const notFound = () => ({ ok: false, status: 404, json: async () => ({}) }); +const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); +const notFound = () => ({ headers: new Headers(), ok: false, status: 404, json: async () => ({}) }); let publishedList: () => Promise = async () => ok([{ name: 'st_queue' }]); const requests: string[] = []; @@ -115,7 +118,7 @@ describe('objectstack-ai/objectstack#25894 — a NEW draft is not asked for its }); it('CONTROL: a type whose classification fails is read both ways, as before', async () => { - publishedList = async () => ({ ok: false, status: 500, json: async () => ({}) }); + publishedList = async () => ({ headers: new Headers(), ok: false, status: 500, json: async () => ({}) }); renderConfirm(); await waitFor(() => expect(publishedReads('st_ticket')).toHaveLength(1)); await waitFor(() => expect(publishedReads('st_queue')).toHaveLength(1)); diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.noChangeAndKeySplit-11807.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.noChangeAndKeySplit-11807.test.tsx index 3bdb085d3d8..17da12ee60b 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.noChangeAndKeySplit-11807.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.noChangeAndKeySplit-11807.test.tsx @@ -44,6 +44,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ })); import { DraftChangesPanel, computeChangeDetail } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; const NO_CHANGE = 'No differences detected — the draft matches the published version.'; @@ -87,8 +90,8 @@ function mockServer(fx: Fixture): string[] { global.fetch = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); urls.push(url); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); - const missing = { ok: false, status: 404, json: async () => ({}) }; + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); + const missing = { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; if (url.includes('/_drafts')) { return ok(fx.drafts.map((d) => ({ ...d, packageId: 'com.x' }))); } diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.packageLessNote-11591.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.packageLessNote-11591.test.tsx index 0d9f5701c47..7476b709d77 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.packageLessNote-11591.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.packageLessNote-11591.test.tsx @@ -31,6 +31,9 @@ import { cleanup, render, screen, waitFor } from '@testing-library/react'; import { createI18n, I18nProvider } from '@object-ui/i18n'; import { DraftChangesPanel } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; afterEach(() => { cleanup(); @@ -43,10 +46,10 @@ type Draft = { type: string; name: string; packageId: string | null }; function serveDrafts(drafts: Draft[]) { global.fetch = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) return ok(drafts); if (/\/meta\/flow(\?|$)/.test(url)) return ok([]); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }) as unknown as typeof fetch; } diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.picklistServedOptions-29899.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.picklistServedOptions-29899.test.tsx index 43afa6893d1..52d459fde55 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.picklistServedOptions-29899.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.picklistServedOptions-29899.test.tsx @@ -42,6 +42,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => { }); import { DraftChangesPanel, computeChangeDetail } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; afterEach(() => { vi.restoreAllMocks(); @@ -63,8 +66,8 @@ const SERVED_TIER = { ...STORED_TIER, options: TIER_OPTIONS }; function mockRoutes(type: string, name: string, draft: Body, published: Body) { global.fetch = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); - const notFound = { ok: false, status: 404, json: async () => ({}) }; + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); + const notFound = { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; if (url.includes('/_drafts')) return ok([{ type, name, packageId: 'com.test.showcase' }]); if (url.includes('state=draft')) return ok({ type, name, item: { ...draft, _draft: true } }); if (url.includes(`/meta/${type}/${name}`)) return ok({ type, name, item: published }); diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.posture-12517.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.posture-12517.test.tsx index dc8879c0ea5..c8bb930165e 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.posture-12517.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.posture-12517.test.tsx @@ -35,6 +35,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ })); import { DraftChangesPanel, type DraftChangesPosture } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; // Three drafts of two types: the summary line has something to count. const DRAFT_ROWS = [ @@ -45,12 +48,12 @@ const DRAFT_ROWS = [ const fetchMock = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) return ok({ drafts: DRAFT_ROWS }); if (/\/meta\/object(\?|$)/.test(url)) return ok([{ name: 'st_queue' }]); if (/\/meta\/page(\?|$)/.test(url)) return ok([]); if (url.includes('state=draft')) return ok({ name: 'x', label: 'Draft label' }); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }); afterEach(() => { diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.protectionEnvelope-12594.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.protectionEnvelope-12594.test.tsx index cc256384cfd..b0ef11ee207 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.protectionEnvelope-12594.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.protectionEnvelope-12594.test.tsx @@ -48,6 +48,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => { }); import { DraftChangesPanel, computeChangeDetail } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; afterEach(() => { vi.restoreAllMocks(); @@ -69,8 +72,8 @@ type Body = Record; function mockRoutes(type: string, name: string, draft: Body, published: Body | null) { global.fetch = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); - const notFound = { ok: false, status: 404, json: async () => ({}) }; + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); + const notFound = { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; if (url.includes('/_drafts')) return ok([{ type, name, packageId: 'com.test.crmext' }]); if (url.includes('state=draft')) return ok({ type, name, item: { ...draft, _draft: true } }); if (url.includes(`/meta/${type}/${name}`)) return published ? ok({ type, name, item: published }) : notFound; diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.readDecorationStrip.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.readDecorationStrip.test.tsx index 4e265ae8235..523d8898bac 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.readDecorationStrip.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.readDecorationStrip.test.tsx @@ -54,6 +54,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => { }); import { DraftChangesPanel } from '../DraftChangesPanel'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; afterEach(() => { vi.restoreAllMocks(); @@ -80,7 +83,7 @@ const DRAFT = { function mockRoutes() { global.fetch = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) { return ok([{ type: 'object', name: 'crmext_visit', packageId: 'com.test.crmext' }]); } @@ -91,7 +94,7 @@ function mockRoutes() { return ok({ type: 'object', name: 'crmext_visit', item: PUBLISHED }); } if (/\/meta\/object(\?|$)/.test(url)) return ok([{ name: 'crmext_visit' }]); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }) as unknown as typeof fetch; } @@ -126,7 +129,7 @@ describe('DraftChangesPanel — read decorations never reach the review diff (ob // it was "Also changed: _diagnostics, _draft". global.fetch = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); const AUTHORED = { name: 'crmext_visit', label: 'Visit', fields: { name: { type: 'text' } } }; if (url.includes('/_drafts')) { return ok([{ type: 'object', name: 'crmext_visit', packageId: 'com.test.crmext' }]); @@ -146,7 +149,7 @@ describe('DraftChangesPanel — read decorations never reach the review diff (ob }); } if (/\/meta\/object(\?|$)/.test(url)) return ok([{ name: 'crmext_visit' }]); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }) as unknown as typeof fetch; render( diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.securityLink.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.securityLink.test.tsx index e797ddbfaba..2d9d684aacc 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.securityLink.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.securityLink.test.tsx @@ -62,7 +62,7 @@ const OWD_LESS_VISIT = { function mockRoutes() { global.fetch = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) { return ok([{ type: 'object', name: 'crmext_visit', packageId: 'com.test.crmext' }]); } @@ -70,7 +70,7 @@ function mockRoutes() { return ok({ type: 'object', name: 'crmext_visit', item: OWD_LESS_VISIT }); } if (/\/meta\/object(\?|$)/.test(url)) return ok([]); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }) as unknown as typeof fetch; } diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.securityProblems.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.securityProblems.test.tsx index 3af1f21b564..a1ece1d9bce 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.securityProblems.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.securityProblems.test.tsx @@ -56,7 +56,7 @@ const OWD_LESS_VISIT = { function mockRoutes(draftBody: Record) { global.fetch = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) { return ok([{ type: 'object', name: 'crmext_visit', packageId: 'com.test.crmext' }]); } @@ -64,7 +64,7 @@ function mockRoutes(draftBody: Record) { return ok({ type: 'object', name: 'crmext_visit', item: draftBody }); } if (/\/meta\/object(\?|$)/.test(url)) return ok([]); // nothing published yet — a NEW item - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }) as unknown as typeof fetch; } diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.summaryPlural-13147.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.summaryPlural-13147.test.tsx index 8028ce9a7de..2bc5bbb08a9 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.summaryPlural-13147.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.summaryPlural-13147.test.tsx @@ -39,12 +39,12 @@ function stubFetch(rows: Row[], draftBody: Record = { name: 'x' 'fetch', vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) return ok({ drafts }); if (url.includes('state=draft')) return ok(draftBody); // Every published-list read: nothing is published, so every row is New. if (/\/meta\/\w+(\?|$)/.test(url)) return ok([]); - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }) as unknown as typeof fetch, ); } diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.test.tsx index 4dc35ee4f32..63ac79ab2d7 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.test.tsx @@ -28,6 +28,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => { import { createI18n, I18nProvider } from '@object-ui/i18n'; import { DraftChangesPanel, computeChangeDetail } from '../DraftChangesPanel'; import { PACKAGE_EXPORT_COMMAND, customizationEnvironmentText } from '../savedToCustomization'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; afterEach(() => { vi.restoreAllMocks(); @@ -111,7 +114,7 @@ const DRAFT_TICKET = { function mockRoutes() { global.fetch = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) { return ok([{ type: 'object', name: 'ticket', packageId: 'com.x' }]); } @@ -124,7 +127,7 @@ function mockRoutes() { if (/\/meta\/object(\?|$)/.test(url)) { return ok([{ name: 'ticket' }]); } - return { ok: false, status: 404, json: async () => ({}) }; + return { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }; }) as unknown as typeof fetch; } @@ -192,7 +195,7 @@ function mockRoutesRecording( global.fetch = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); urls.push(url); - const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + const ok = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); if (url.includes('/_drafts')) { return ok(drafts.map((d) => ({ packageId: 'com.x', ...d }))); } diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftPreviewBar.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftPreviewBar.test.tsx index 3f06c6c93ef..a1ff1d8d97c 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftPreviewBar.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftPreviewBar.test.tsx @@ -47,7 +47,7 @@ function renderBar() { } function mockDrafts(list: unknown) { - global.fetch = vi.fn(async () => ({ ok: true, json: async () => list })) as unknown as typeof fetch; + global.fetch = vi.fn(async () => ({ headers: new Headers(), ok: true, json: async () => list })) as unknown as typeof fetch; } afterEach(() => { @@ -110,7 +110,7 @@ describe('DraftPreviewBar', () => { }); it('keeps Publish visible but promises no sample data when the draft count is unknown (fetch failed) — only a known zero relaxes', async () => { - global.fetch = vi.fn(async () => ({ ok: false, json: async () => null })) as unknown as typeof fetch; + global.fetch = vi.fn(async () => ({ headers: new Headers(), ok: false, json: async () => null })) as unknown as typeof fetch; renderBar(); // pendingCount stays null → not known-zero → safe default keeps the publish path. await waitFor(() => { diff --git a/ui/packages/app-shell/src/preview/__tests__/UnpublishedAppBar.test.tsx b/ui/packages/app-shell/src/preview/__tests__/UnpublishedAppBar.test.tsx index ec7517b4c59..09febcd9ada 100644 --- a/ui/packages/app-shell/src/preview/__tests__/UnpublishedAppBar.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/UnpublishedAppBar.test.tsx @@ -82,7 +82,7 @@ function renderBar(path = '/apps/crm') { } function mockPutOk() { - global.fetch = vi.fn(async () => ({ ok: true, json: async () => ({}) })) as unknown as typeof fetch; + global.fetch = vi.fn(async () => ({ headers: new Headers(), ok: true, json: async () => ({}) })) as unknown as typeof fetch; } /** The single `PUT /api/v1/meta/app/:name` the Publish button fires. */ diff --git a/ui/packages/app-shell/src/preview/__tests__/commitHistory.test.ts b/ui/packages/app-shell/src/preview/__tests__/commitHistory.test.ts index a5f66e4b113..042fac2fa96 100644 --- a/ui/packages/app-shell/src/preview/__tests__/commitHistory.test.ts +++ b/ui/packages/app-shell/src/preview/__tests__/commitHistory.test.ts @@ -42,7 +42,7 @@ afterEach(() => { /** A response whose body is JSON. */ function jsonResponse(status: number, body: unknown) { - return { ok: status >= 200 && status < 300, status, json: async () => body }; + return { headers: new Headers(), ok: status >= 200 && status < 300, status, json: async () => body }; } /** @@ -51,7 +51,7 @@ function jsonResponse(status: number, body: unknown) { */ function unparseableResponse(status: number) { return { - ok: false, + headers: new Headers(), ok: false, status, json: async () => { throw new SyntaxError('Unexpected token < in JSON at position 0'); diff --git a/ui/packages/app-shell/src/preview/__tests__/draftPreview-12968.test.tsx b/ui/packages/app-shell/src/preview/__tests__/draftPreview-12968.test.tsx index 58771370f37..01808fa2891 100644 --- a/ui/packages/app-shell/src/preview/__tests__/draftPreview-12968.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/draftPreview-12968.test.tsx @@ -84,7 +84,7 @@ describe('draftPreviewPath — the deep-link table (objectui#12968)', () => { }); function mockDrafts(list: unknown) { - global.fetch = vi.fn(async () => ({ ok: true, json: async () => list })) as unknown as typeof fetch; + global.fetch = vi.fn(async () => ({ headers: new Headers(), ok: true, json: async () => list })) as unknown as typeof fetch; } function renderBarAt(path: string) { diff --git a/ui/packages/app-shell/src/preview/commitHistory.ts b/ui/packages/app-shell/src/preview/commitHistory.ts index c0d535683ad..121d0f162f4 100644 --- a/ui/packages/app-shell/src/preview/commitHistory.ts +++ b/ui/packages/app-shell/src/preview/commitHistory.ts @@ -13,8 +13,8 @@ * the metadata history. The history-not-confirm model: you don't approve each * publish — you review this timeline and revert if a change was wrong. These * helpers read the timeline (`GET /packages/:id/commits`) and revert one - * commit (`POST /packages/:id/commits/:cid/revert`). Cookie-authenticated like - * every console call; tolerant of the `{ data: ... }` / bare envelope shapes. + * commit (`POST /packages/:id/commits/:cid/revert`). Authenticated like every + * console call (the stored bearer token beside the session cookie); tolerant of the `{ data: ... }` / bare envelope shapes. * * ## Failures carry their KIND, not just a number (objectui#3529) * @@ -72,6 +72,13 @@ * alone is sufficient to produce the retryable reading. */ +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} + /** * A commit-store call that failed, carrying enough for a caller to tell the * dispositions apart without re-parsing anything. @@ -194,7 +201,7 @@ function memberItemsOf(raw: unknown): CommitMemberItem[] | undefined { } export async function fetchCommits(packageId: string): Promise { - const res = await fetch(`/api/v1/packages/${encodeURIComponent(packageId)}/commits`, { + const res = await authFetch(`/api/v1/packages/${encodeURIComponent(packageId)}/commits`, { credentials: 'include', headers: { Accept: 'application/json' }, cache: 'no-store', @@ -229,7 +236,7 @@ export async function fetchCommits(packageId: string): Promise { } export async function revertCommit(packageId: string, commitId: string): Promise { - const res = await fetch( + const res = await authFetch( `/api/v1/packages/${encodeURIComponent(packageId)}/commits/${encodeURIComponent(commitId)}/revert`, { method: 'POST', diff --git a/ui/packages/app-shell/src/preview/flowDraftChecks.ts b/ui/packages/app-shell/src/preview/flowDraftChecks.ts index c0de4e1eabd..f968aa480fe 100644 --- a/ui/packages/app-shell/src/preview/flowDraftChecks.ts +++ b/ui/packages/app-shell/src/preview/flowDraftChecks.ts @@ -29,6 +29,8 @@ * can be exercised directly. */ +import { createAuthenticatedFetch } from '@object-ui/auth'; + /** The draft types whose read carries the publish gate's advisories (the server's `DRAFT_ADVISORY_TYPES`). */ export const DRAFT_CHECK_TYPES: ReadonlySet = new Set(['flow']); @@ -97,7 +99,9 @@ export async function readDraftChecks( drafts: readonly DraftCheckTarget[], opts: { language?: string; fetchImpl?: typeof fetch } = {}, ): Promise { - const doFetch = opts.fetchImpl ?? globalThis.fetch; + // The console's authenticated fetch unless the caller hands its own: the + // stored bearer token beside the session cookie, built per call. + const doFetch = opts.fetchImpl ?? createAuthenticatedFetch(); const targets = drafts.filter((d) => DRAFT_CHECK_TYPES.has(d.type)); const perDraft = await Promise.all( targets.map(async (target) => { diff --git a/ui/packages/app-shell/src/preview/usePendingDrafts.afterSave-11787.test.tsx b/ui/packages/app-shell/src/preview/usePendingDrafts.afterSave-11787.test.tsx index 1cad61bab60..2f32ce468a8 100644 --- a/ui/packages/app-shell/src/preview/usePendingDrafts.afterSave-11787.test.tsx +++ b/ui/packages/app-shell/src/preview/usePendingDrafts.afterSave-11787.test.tsx @@ -39,7 +39,7 @@ function heldFetch() { held.push({ url: String(input), respond: (status, body) => - resolve({ ok: status >= 200 && status < 300, status, json: async () => body }), + resolve({ headers: new Headers(), ok: status >= 200 && status < 300, status, json: async () => body }), }); }), ), diff --git a/ui/packages/app-shell/src/preview/usePendingDrafts.inflightShare-11797.test.tsx b/ui/packages/app-shell/src/preview/usePendingDrafts.inflightShare-11797.test.tsx index 3f291171f2f..30866d522e5 100644 --- a/ui/packages/app-shell/src/preview/usePendingDrafts.inflightShare-11797.test.tsx +++ b/ui/packages/app-shell/src/preview/usePendingDrafts.inflightShare-11797.test.tsx @@ -49,7 +49,7 @@ function heldFetch() { held.push({ url: String(input), respond: (status, body) => - resolve({ ok: status >= 200 && status < 300, status, json: async () => body }), + resolve({ headers: new Headers(), ok: status >= 200 && status < 300, status, json: async () => body }), }); }), ), diff --git a/ui/packages/app-shell/src/preview/usePendingDrafts.test.tsx b/ui/packages/app-shell/src/preview/usePendingDrafts.test.tsx index d6c7f71b494..c817bec5edb 100644 --- a/ui/packages/app-shell/src/preview/usePendingDrafts.test.tsx +++ b/ui/packages/app-shell/src/preview/usePendingDrafts.test.tsx @@ -24,7 +24,7 @@ import { __resetHiddenTabClock } from '../hooks/hiddenTabPollStop.js'; const draftsRow = { type: 'object', name: 'task', packageId: 'app.k9qk' }; function stubFetch(payload: unknown, ok = true) { - const fn = vi.fn(async () => ({ ok, status: ok ? 200 : 500, json: async () => payload })); + const fn = vi.fn(async () => ({ headers: new Headers(), ok, status: ok ? 200 : 500, json: async () => payload })); vi.stubGlobal('fetch', fn); return fn; } @@ -120,7 +120,7 @@ describe('a change made outside the tab reaches the hook without a reload (objec document.dispatchEvent(new Event('visibilitychange')); } function stubLedger() { - const fn = vi.fn(async () => ({ ok: true, status: 200, json: async () => ({ drafts: ledger }) })); + const fn = vi.fn(async () => ({ headers: new Headers(), ok: true, status: 200, json: async () => ({ drafts: ledger }) })); vi.stubGlobal('fetch', fn); return fn; } diff --git a/ui/packages/app-shell/src/preview/usePendingDrafts.ts b/ui/packages/app-shell/src/preview/usePendingDrafts.ts index 5db49ba2d99..623f3f0ba1a 100644 --- a/ui/packages/app-shell/src/preview/usePendingDrafts.ts +++ b/ui/packages/app-shell/src/preview/usePendingDrafts.ts @@ -56,6 +56,12 @@ import type { I18nLabel } from '@objectstack/spec/ui'; import { customizationBasePackageId, customizationPackageId } from '@objectstack/spec/kernel'; import { emitMetadataRefresh, subscribeMetadataRefresh } from '../assistant/assistantBus.js'; import { isPollingSuspended } from '../hooks/hiddenTabPollStop.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} export interface PendingDraftEntry { /** Raw stored type — callers that build `/meta` URLs must fold it themselves. */ @@ -172,7 +178,7 @@ function readDraftsAnswer(url: string): Promise { const pending = reads.get(url); if (pending) return pending; const read = (async (): Promise => { - const res = await fetch(url, { + const res = await authFetch(url, { credentials: 'include', headers: { Accept: 'application/json' }, cache: 'no-store', diff --git a/ui/packages/app-shell/src/sameServerFetch.bearer.ratchet.test.ts b/ui/packages/app-shell/src/sameServerFetch.bearer.ratchet.test.ts new file mode 100644 index 00000000000..58d61183e01 --- /dev/null +++ b/ui/packages/app-shell/src/sameServerFetch.bearer.ratchet.test.ts @@ -0,0 +1,282 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * Ratchet — a request that sends the session cookie (`credentials: 'include'`) + * goes through the console's authenticated fetch, never the bare global + * `fetch`, in app-shell and the console. + * + * The defect this closes: a bare `fetch('/api/…', { credentials: 'include' })` + * carries the session cookie and nothing else. A session held by its bearer + * token alone (the cookie replaced by a second local runtime on the same host, + * blocked as a third-party cookie, or cleared) is answered `401` there, while + * every other console request works: the shell's package list went missing + * this way, and with it the Studio and design entries, the AI chat lists and + * the studio-design writes. `createAuthenticatedFetch` (`@object-ui/auth`) + * sends the stored bearer token beside the cookie, and a `401` reaches the + * console's session-ended check. Build it per call + * (`createAuthenticatedFetch()(input, init)`), keeping `credentials: 'include'`. + * + * What counts as bare: a call whose transport is the global `fetch` (`fetch`, + * `window.fetch`, `globalThis.fetch`, `self.fetch`, or one of those as the + * fallback of `??` / `||`), and `sharedGetJson` without its transport argument + * (its default is the global `fetch`), when the init it is handed — written + * inline, or a `const` of this file named as the argument — carries + * `credentials: 'include'`. The URL is not judged: a request to another origin + * that must not see the bearer is an allow-list row with that reason. + * + * If this fails on a new call: route it through `createAuthenticatedFetch` + * (`{ sameOriginOnly: true }` when the URL is author-written and may name + * another host). If the call must stay bare, add a row to {@link ALLOWED} with + * the reason. If it fails on a row: a row whose count went down is shrunk or + * deleted in the same change. ⛔ Never raise a count to make room. + */ + +import { describe, it, expect } from 'vitest'; +import { readdirSync, readFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import ts from 'typescript'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +/** `ui/packages/app-shell/src` */ +const APP_SHELL_SRC = HERE; +/** `ui/apps/console/src` */ +const CONSOLE_SRC = path.resolve(HERE, '../../../apps/console/src'); +/** Both trees' paths are written relative to `ui/`. */ +const UI_ROOT = path.resolve(HERE, '../../..'); + +/** + * The bare cookie-only calls left, per file, with the reason each stays. + * SHRINK-ONLY: a row's count only goes down, a row only goes away. + */ +const ALLOWED: Readonly> = { + 'apps/console/src/LocalizationFetchProvider.tsx': { + count: 1, + reason: + 'the boot read of `/api/v1/auth/me/localization`, shared in flight with the language seed and the early ' + + 'request `index.html` sends, by a key built from this init; a session it cannot see reads ' + + '`authenticated: false` and falls back to the browser language rather than failing. Its transport is its own decision.', + }, + 'apps/console/src/components/FormPage.tsx': { + count: 1, + reason: 'the channel is the bare global fetch on the PUBLIC form route on purpose; the internal route hands the authenticated fetch.', + }, + 'apps/console/src/lib/auth-preflight.ts': { + count: 1, + reason: 'the session probe sets the bearer header itself, on purpose: it reads whether the stored token is stale.', + }, + 'apps/console/src/lib/early-discovery.ts': { + count: 1, + reason: 'sets the bearer header itself; the request mirrors, byte for byte, the one `index.html` sends early.', + }, + 'apps/console/src/pages/auth/OAuthConsentPage.tsx': { + count: 3, + reason: 'the OAuth hand-off, whose authorize step is a top-level navigation that can only carry the cookie.', + }, + 'apps/console/src/pages/auth/followAuthorize.ts': { + count: 1, + reason: 'the OAuth authorize step; its fallback is a top-level navigation that can only carry the cookie.', + }, + 'apps/console/src/pages/auth/handoffClientName.ts': { + count: 1, + reason: 'the OAuth hand-off sign-in page, read before a session exists.', + }, + 'apps/console/src/pages/auth/SetupPage.tsx': { + count: 1, + reason: 'the bootstrap-status read of the first-run setup page, answered without a session.', + }, + 'apps/console/src/pages/auth/VerifyEmailPage.tsx': { + count: 1, + reason: 'the email-verification link, which proves itself with its own token and is opened without a session.', + }, + 'packages/app-shell/src/chrome/ConditionalAuthWrapper.tsx': { + count: 1, + reason: 'the public discovery read that decides whether the auth provider mounts at all, answered without a session.', + }, + 'packages/app-shell/src/console/auth/bootstrapStatus.ts': { + count: 1, + reason: 'the bootstrap-status read, answered without a session.', + }, + 'packages/app-shell/src/console/ai/AiChatPage.tsx': { + count: 1, + reason: 'the object read of the AI chat page; an open pull request edits this file, so its call moves with that work.', + }, + 'packages/app-shell/src/console/marketplace/marketplaceApi.ts': { + count: 5, + reason: + 'each targets `getCloudBase() || SERVER_URL`: the cloud control plane\'s own origin whenever one is configured, ' + + 'which must never see this runtime\'s bearer.', + }, + 'packages/app-shell/src/runtime-config.ts': { + count: 1, + reason: 'the public runtime-config read, answered without a session and shared with the early request `index.html` sends.', + }, + 'packages/app-shell/src/views/metadata-admin/previews/ActionPreview.tsx': { + count: 1, + reason: 'the test request of an `api` action preview, sent to the author-written target; its transport is not decided here.', + }, +}; + +const GLOBAL_FETCH = new Set(['fetch', 'window.fetch', 'globalThis.fetch', 'self.fetch']); + +function carriesInclude(node: ts.Node | undefined): boolean { + return ( + !!node && + ts.isObjectLiteralExpression(node) && + node.properties.some( + (p) => + ts.isPropertyAssignment(p) && + (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) && + p.name.text === 'credentials' && + isIncludeLiteral(unwrap(p.initializer)), + ) + ); +} + +/** `'include'`, also written `'include' as const`. */ +function isIncludeLiteral(node: ts.Expression): boolean { + return ts.isStringLiteralLike(node) && node.text === 'include'; +} + +function unwrap(node: ts.Expression): ts.Expression { + let n = node; + while (ts.isParenthesizedExpression(n) || ts.isAsExpression(n) || ts.isSatisfiesExpression(n) || ts.isNonNullExpression(n)) { + n = n.expression; + } + return n; +} + +/** True when the call's transport is the global `fetch`, directly or as a `??` / `||` fallback. */ +function isGlobalFetchCallee(callee: ts.Expression, sf: ts.SourceFile): boolean { + const c = unwrap(callee); + if (GLOBAL_FETCH.has(c.getText(sf))) return true; + if ( + ts.isBinaryExpression(c) && + (c.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken || c.operatorToken.kind === ts.SyntaxKind.BarBarToken) + ) { + return GLOBAL_FETCH.has(unwrap(c.right).getText(sf)); + } + return false; +} + +/** The bare cookie-only calls in one source text, as `line :: call` strings. */ +function bareCookieOnlyCalls(fileName: string, text: string): string[] { + const sf = ts.createSourceFile( + fileName, + text, + ts.ScriptTarget.Latest, + true, + fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS, + ); + // A `const NAME = { credentials: 'include', … }` anywhere in the file: an + // init handed to the call by name. + const includeConsts = new Set(); + const collect = (n: ts.Node): void => { + if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.initializer && carriesInclude(unwrap(n.initializer))) { + includeConsts.add(n.name.text); + } + ts.forEachChild(n, collect); + }; + collect(sf); + const initIncludes = (arg: ts.Expression | undefined): boolean => { + if (!arg) return false; + const a = unwrap(arg); + return carriesInclude(a) || (ts.isIdentifier(a) && includeConsts.has(a.text)); + }; + const out: string[] = []; + const visit = (n: ts.Node): void => { + if (ts.isCallExpression(n)) { + const bare = + (isGlobalFetchCallee(n.expression, sf) && initIncludes(n.arguments[1])) || + (unwrap(n.expression).getText(sf) === 'sharedGetJson' && n.arguments.length < 3 && initIncludes(n.arguments[1])); + if (bare) { + const line = sf.getLineAndCharacterOfPosition(n.getStart(sf)).line + 1; + out.push(`${line} :: ${n.expression.getText(sf)}(${n.arguments[0]?.getText(sf) ?? ''}, …)`); + } + } + ts.forEachChild(n, visit); + }; + visit(sf); + return out; +} + +function sourceFiles(root: string): string[] { + const out: string[] = []; + const walk = (dir: string): void => { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name === '__tests__' || entry.name === '__mocks__') continue; + const full = path.join(dir, entry.name); + if (entry.isDirectory()) walk(full); + else if (/\.tsx?$/.test(entry.name) && !/\.(test|spec)\.tsx?$/.test(entry.name) && !entry.name.endsWith('.d.ts')) out.push(full); + } + }; + walk(root); + return out; +} + +function scan(): Map { + const found = new Map(); + for (const file of [...sourceFiles(APP_SHELL_SRC), ...sourceFiles(CONSOLE_SRC)]) { + const calls = bareCookieOnlyCalls(file, readFileSync(file, 'utf8')); + if (calls.length) found.set(path.relative(UI_ROOT, file).split(path.sep).join('/'), calls); + } + return found; +} + +describe('cookie-only same-server fetch ratchet (app-shell + console)', () => { + it('reads both trees (guards a broken scan path)', () => { + expect(sourceFiles(APP_SHELL_SRC).length).toBeGreaterThan(500); + expect(sourceFiles(CONSOLE_SRC).length).toBeGreaterThan(100); + }); + + it('the detector sees every bare spelling, and none of the authenticated ones', () => { + const cases: Array<[string, number]> = [ + ["await fetch('/api/v1/packages', { credentials: 'include' });", 1], + ["await window.fetch('/api/v1/x', { method: 'POST', credentials: 'include' });", 1], + ["await globalThis.fetch(u, { credentials: 'include' } as RequestInit);", 1], + ["await (apiFetch ?? fetch)('/api/v1/x', { credentials: 'include' });", 1], + ["const init: RequestInit = { credentials: 'include' }; await fetch(u, init);", 1], + ["const opts = { credentials: 'include' as const }; await fetch(u, opts);", 1], + ["await sharedGetJson(u, { credentials: 'include' });", 1], + ["await authFetch('/api/v1/packages', { credentials: 'include' });", 0], + ["await createAuthenticatedFetch()('/api/v1/x', { credentials: 'include' });", 0], + ["await (apiFetch ?? createAuthenticatedFetch())('/api/v1/x', { credentials: 'include' });", 0], + ["await sharedGetJson(u, { credentials: 'include' }, authFetch);", 0], + ["await fetch('https://cdn.example.com/a.json', { credentials: 'omit' });", 0], + ["await fetch('/api/v1/x');", 0], + ]; + for (const [code, expected] of cases) { + // Inside an async function: at a script's top level `await (x)(…)` parses as a call of `await`. + const found = bareCookieOnlyCalls('case.ts', `async function run() { ${code} }`).length; + expect({ code, found }).toEqual({ code, found: expected }); + } + }); + + it('every bare cookie-only call is a counted row of the shrink-only allow-list', () => { + const found = scan(); + const unlisted: string[] = []; + const over: string[] = []; + for (const [file, calls] of found) { + const row = ALLOWED[file]; + if (!row) unlisted.push(...calls.map((c) => `${file}:${c}`)); + else if (calls.length > row.count) over.push(`${file}: ${calls.length} found, ${row.count} allowed\n ${calls.join('\n ')}`); + } + // Route these through createAuthenticatedFetch (see the header). + expect(unlisted).toEqual([]); + expect(over).toEqual([]); + }); + + it('every allow-list row is still exact (shrink the row when its file sheds a call)', () => { + const found = scan(); + const stale = Object.entries(ALLOWED) + .filter(([file, row]) => (found.get(file)?.length ?? 0) !== row.count) + .map(([file, row]) => `${file}: ${found.get(file)?.length ?? 0} found, ${row.count} allowed`); + expect(stale).toEqual([]); + }); +}); diff --git a/ui/packages/app-shell/src/services/suggestedBindingsApi.ts b/ui/packages/app-shell/src/services/suggestedBindingsApi.ts index f27d0408722..d60b072b430 100644 --- a/ui/packages/app-shell/src/services/suggestedBindingsApi.ts +++ b/ui/packages/app-shell/src/services/suggestedBindingsApi.ts @@ -18,7 +18,12 @@ * marketplaceApi raw-fetch pattern: Bearer token + `credentials: 'include'`. */ -import { TokenStorage } from '@object-ui/auth'; +import { createAuthenticatedFetch, TokenStorage } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} const SERVER_URL = (import.meta.env.VITE_SERVER_URL || '').replace(/\/$/, ''); const API_BASE = `${SERVER_URL}/api/v1/security/suggested-bindings`; @@ -90,7 +95,7 @@ export async function listSuggestedBindings(filter: { if (filter.status) params.set('status', filter.status); if (filter.packageId) params.set('packageId', filter.packageId); const qs = params.toString(); - const res = await fetch(`${API_BASE}${qs ? `?${qs}` : ''}`, { + const res = await authFetch(`${API_BASE}${qs ? `?${qs}` : ''}`, { credentials: 'include', headers: authHeaders(), }); @@ -107,7 +112,7 @@ export async function listSuggestedBindings(filter: { * signal that tells an acceptance in force from one merely recorded. */ export async function confirmSuggestedBinding(id: string): Promise { - const res = await fetch(`${API_BASE}/${encodeURIComponent(id)}/confirm`, { + const res = await authFetch(`${API_BASE}/${encodeURIComponent(id)}/confirm`, { method: 'POST', credentials: 'include', headers: authHeaders({ 'Content-Type': 'application/json' }), @@ -122,7 +127,7 @@ export async function confirmSuggestedBinding(id: string): Promise { - const res = await fetch(`${API_BASE}/${encodeURIComponent(id)}/dismiss`, { + const res = await authFetch(`${API_BASE}/${encodeURIComponent(id)}/dismiss`, { method: 'POST', credentials: 'include', headers: authHeaders({ 'Content-Type': 'application/json' }), @@ -141,7 +146,7 @@ export async function dismissSuggestedBinding(id: string): Promise { - const res = await fetch(`${API_BASE}/${encodeURIComponent(id)}/reopen`, { + const res = await authFetch(`${API_BASE}/${encodeURIComponent(id)}/reopen`, { method: 'POST', credentials: 'include', headers: authHeaders({ 'Content-Type': 'application/json' }), diff --git a/ui/packages/app-shell/src/views/RecordApprovalsPanel.actionStepLabel-13248.test.tsx b/ui/packages/app-shell/src/views/RecordApprovalsPanel.actionStepLabel-13248.test.tsx index ec1d04aa26f..ac82a27bae6 100644 --- a/ui/packages/app-shell/src/views/RecordApprovalsPanel.actionStepLabel-13248.test.tsx +++ b/ui/packages/app-shell/src/views/RecordApprovalsPanel.actionStepLabel-13248.test.tsx @@ -34,7 +34,8 @@ import type { ApprovalRequestLite } from '../hooks/useRecordApprovals'; vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), - createAuthenticatedFetch: () => vi.fn(), + // The wire is the global `fetch` this file stubs; the authenticated fetch hands its requests to it. + createAuthenticatedFetch: () => (input: RequestInfo | URL, init?: RequestInit) => fetch(input, init), })); vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }), diff --git a/ui/packages/app-shell/src/views/RecordApprovalsPanel.displayLocale-9909.test.tsx b/ui/packages/app-shell/src/views/RecordApprovalsPanel.displayLocale-9909.test.tsx index 8dcd310f5b6..2529d3fd6d0 100644 --- a/ui/packages/app-shell/src/views/RecordApprovalsPanel.displayLocale-9909.test.tsx +++ b/ui/packages/app-shell/src/views/RecordApprovalsPanel.displayLocale-9909.test.tsx @@ -28,7 +28,8 @@ import type { ApprovalRequestLite } from '../hooks/useRecordApprovals'; vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), - createAuthenticatedFetch: () => vi.fn(), + // The wire is the global `fetch` this file stubs; the authenticated fetch hands its requests to it. + createAuthenticatedFetch: () => (input: RequestInfo | URL, init?: RequestInit) => fetch(input, init), })); vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) })); diff --git a/ui/packages/app-shell/src/views/RecordApprovalsPanel.test.tsx b/ui/packages/app-shell/src/views/RecordApprovalsPanel.test.tsx index d8f9f9ff3df..a3bb758d714 100644 --- a/ui/packages/app-shell/src/views/RecordApprovalsPanel.test.tsx +++ b/ui/packages/app-shell/src/views/RecordApprovalsPanel.test.tsx @@ -30,7 +30,8 @@ import { builtInLocales } from '@object-ui/i18n/locales'; vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), - createAuthenticatedFetch: () => vi.fn(), + // The wire is the global `fetch` this file stubs; the authenticated fetch hands its requests to it. + createAuthenticatedFetch: () => (input: RequestInfo | URL, init?: RequestInit) => fetch(input, init), })); vi.mock('sonner', () => ({ diff --git a/ui/packages/app-shell/src/views/RecordApprovalsPanel.viaOverrideMarker.test.tsx b/ui/packages/app-shell/src/views/RecordApprovalsPanel.viaOverrideMarker.test.tsx index 7cf0fcfac5d..a66f21f4dd3 100644 --- a/ui/packages/app-shell/src/views/RecordApprovalsPanel.viaOverrideMarker.test.tsx +++ b/ui/packages/app-shell/src/views/RecordApprovalsPanel.viaOverrideMarker.test.tsx @@ -70,7 +70,8 @@ import type { ApprovalRequestLite } from '../hooks/useRecordApprovals'; vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), - createAuthenticatedFetch: () => vi.fn(), + // The wire is the global `fetch` this file stubs; the authenticated fetch hands its requests to it. + createAuthenticatedFetch: () => (input: RequestInfo | URL, init?: RequestInit) => fetch(input, init), })); vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }), diff --git a/ui/packages/app-shell/src/views/RecordDetailView.accessEndedAfterDecision-26589.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.accessEndedAfterDecision-26589.test.tsx index 7ba350586e6..a79727ef10d 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.accessEndedAfterDecision-26589.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.accessEndedAfterDecision-26589.test.tsx @@ -39,7 +39,10 @@ import { MemoryRouter, Routes, Route } from 'react-router-dom'; // record answers 404 to a viewer whose only read was the pending step's. let readEnded = false; let revokesOnDecision = true; -const authFetchSpy = vi.fn(async (url: string) => { +const authFetchSpy = vi.fn(async (url: string, init?: RequestInit) => { + // The approvals reads go out through the authenticated fetch too; they answer + // from the file's wire double below, as before. + if (String(url).includes('/approvals/requests')) return fetch(url, init); if (revokesOnDecision && /\/actions\/sys_approval_request\/approval_(approve|reject)$/.test(String(url))) readEnded = true; return new Response(JSON.stringify({ data: {} }), { status: 200, diff --git a/ui/packages/app-shell/src/views/RecordDetailView.approvalDeclaredActions.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.approvalDeclaredActions.test.tsx index fa61a92ada6..b86e9afbd20 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.approvalDeclaredActions.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.approvalDeclaredActions.test.tsx @@ -42,11 +42,15 @@ import { MemoryRouter } from 'react-router-dom'; // test clock running. import { RecordHeaderStateContext } from '@object-ui/components'; -const authFetchSpy = vi.fn(async () => - new Response(JSON.stringify({ data: {} }), { - status: 200, - headers: { 'content-type': 'application/json' }, - }), +// The approvals reads go out through the authenticated fetch too; they answer from +// the file's wire double below, as before. +const authFetchSpy = vi.fn(async (url: string, init?: RequestInit) => + String(url).includes('/approvals/requests') + ? fetch(url, init) + : new Response(JSON.stringify({ data: {} }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }), ); vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), diff --git a/ui/packages/app-shell/src/views/RecordDetailView.approvalLock-12220.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.approvalLock-12220.test.tsx index 76225064bf6..770d31fa8ac 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.approvalLock-12220.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.approvalLock-12220.test.tsx @@ -32,11 +32,15 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, waitFor, cleanup, act } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; -const authFetchSpy = vi.fn(async () => - new Response(JSON.stringify({ data: {} }), { - status: 200, - headers: { 'content-type': 'application/json' }, - }), +// The approvals reads go out through the authenticated fetch too; they answer from +// the file's wire double, as before. +const authFetchSpy = vi.fn(async (url: string, init?: RequestInit) => + String(url).includes('/approvals/requests') + ? fetch(url, init) + : new Response(JSON.stringify({ data: {} }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }), ); vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), diff --git a/ui/packages/app-shell/src/views/RecordDetailView.approvalLock-25934.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.approvalLock-25934.test.tsx index 20fac10b1a2..d9b5c6ec076 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.approvalLock-25934.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.approvalLock-25934.test.tsx @@ -34,11 +34,15 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, waitFor, cleanup } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; -const authFetchSpy = vi.fn(async () => - new Response(JSON.stringify({ data: {} }), { - status: 200, - headers: { 'content-type': 'application/json' }, - }), +// The approvals reads go out through the authenticated fetch too; they answer from +// the file's wire double, as before. +const authFetchSpy = vi.fn(async (url: string, init?: RequestInit) => + String(url).includes('/approvals/') + ? fetch(url, init) + : new Response(JSON.stringify({ data: {} }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }), ); vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), diff --git a/ui/packages/app-shell/src/views/RecordDetailView.approvalRecallGate.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.approvalRecallGate.test.tsx index a89fc84434d..6a544ad3df7 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.approvalRecallGate.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.approvalRecallGate.test.tsx @@ -31,11 +31,15 @@ import { MemoryRouter } from 'react-router-dom'; const SIGNED_IN_USER = 'u_qcdir'; -const authFetchSpy = vi.fn(async () => - new Response(JSON.stringify({ data: {} }), { - status: 200, - headers: { 'content-type': 'application/json' }, - }), +// The approvals reads go out through the authenticated fetch too; they answer from +// the wire double each case stubs (`stubApprovalsApi`), as before. +const authFetchSpy = vi.fn(async (url: string, init?: RequestInit) => + String(url).includes('/approvals/requests') + ? fetch(url, init) + : new Response(JSON.stringify({ data: {} }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }), ); vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), diff --git a/ui/packages/app-shell/src/views/RecordDetailView.editLockedByState-32756.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.editLockedByState-32756.test.tsx index 0dfbea02dfd..c6c113fd3ee 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.editLockedByState-32756.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.editLockedByState-32756.test.tsx @@ -31,7 +31,8 @@ import { MemoryRouter } from 'react-router-dom'; vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), useAuth: () => ({ user: { id: 'u1', name: 'Ada', image: null }, activeOrganization: null }), - createAuthenticatedFetch: () => vi.fn(), + // The wire is the global `fetch` this file stubs; the authenticated fetch hands its requests to it. + createAuthenticatedFetch: () => (input: RequestInfo | URL, init?: RequestInit) => fetch(input, init), })); vi.mock('@object-ui/collaboration', async (importOriginal) => ({ diff --git a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx index 2b71010e06b..46a047aeb66 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx @@ -66,7 +66,8 @@ import { usePageCommands, type PublishedPageCommand } from '../chrome/paletteCom vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), useAuth: () => ({ user: { id: 'u1', name: 'Ada', image: null }, activeOrganization: null }), - createAuthenticatedFetch: () => vi.fn(), + // The wire is the global `fetch` this file stubs; the authenticated fetch hands its requests to it. + createAuthenticatedFetch: () => (input: RequestInfo | URL, init?: RequestInit) => fetch(input, init), })); vi.mock('@object-ui/collaboration', async (importOriginal) => ({ diff --git a/ui/packages/app-shell/src/views/RecordDetailView.headerApiInterpolation.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.headerApiInterpolation.test.tsx index 33b3c6e371f..d043b41deca 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.headerApiInterpolation.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.headerApiInterpolation.test.tsx @@ -285,8 +285,13 @@ describe("RecordDetailView api handler — `{field}` target interpolation (objec }); }); - expect(authFetchSpy).toHaveBeenCalledTimes(1); - const [url, init] = authFetchSpy.mock.calls[0] as unknown as [string, RequestInit]; + // Exactly one trigger goes out. The page's own reads after it (they share the + // authenticated fetch) are not this handler's calls. + const triggers = (authFetchSpy.mock.calls as unknown as Array<[string, RequestInit]>).filter(([u]) => + String(u).includes('/trigger'), + ); + expect(triggers).toHaveLength(1); + const [url, init] = triggers[0]; expect(url).toContain('/api/v1/automation/copy_plan_flow/trigger'); const body = JSON.parse(String(init.body)); expect(body.params).toEqual({ comment: 'hi' }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.phoneFace-27058.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.phoneFace-27058.test.tsx index bea28659ebe..c055be3ea8a 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.phoneFace-27058.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.phoneFace-27058.test.tsx @@ -44,7 +44,8 @@ import { RelatedCountStore } from '@object-ui/components'; vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), useAuth: () => ({ user: { id: 'u1', name: 'Ada', image: null }, activeOrganization: null }), - createAuthenticatedFetch: () => vi.fn(), + // The wire is the global `fetch` this file stubs; the authenticated fetch hands its requests to it. + createAuthenticatedFetch: () => (input: RequestInfo | URL, init?: RequestInit) => fetch(input, init), })); vi.mock('@object-ui/collaboration', async (importOriginal) => ({ diff --git a/ui/packages/app-shell/src/views/RecordDetailView.userActionPredicates.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.userActionPredicates.test.tsx index 0a214cbd452..442e061e5ee 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.userActionPredicates.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.userActionPredicates.test.tsx @@ -65,7 +65,8 @@ import { MemoryRouter } from 'react-router-dom'; vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), useAuth: () => ({ user: { id: 'u1', name: 'Ada', image: null }, activeOrganization: null }), - createAuthenticatedFetch: () => vi.fn(), + // The wire is the global `fetch` this file stubs; the authenticated fetch hands its requests to it. + createAuthenticatedFetch: () => (input: RequestInfo | URL, init?: RequestInit) => fetch(input, init), })); vi.mock('@object-ui/collaboration', async (importOriginal) => ({ diff --git a/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioFollowsPackagePosture-12615.test.tsx b/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioFollowsPackagePosture-12615.test.tsx index 3cc77d3ed6e..a554a100f96 100644 --- a/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioFollowsPackagePosture-12615.test.tsx +++ b/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioFollowsPackagePosture-12615.test.tsx @@ -111,9 +111,9 @@ function serve(answer: () => Promise<{ ok: boolean; status: number; body: unknow vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => { - if (!String(url).endsWith('/api/v1/packages')) return { ok: true, status: 200, json: async () => ({ data: [] }) }; + if (!String(url).endsWith('/api/v1/packages')) return { headers: new Headers(), ok: true, status: 200, json: async () => ({ data: [] }) }; const { ok, status, body } = await answer(); - return { ok, status, json: async () => body }; + return { headers: new Headers(), ok, status, json: async () => body }; }), ); } diff --git a/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioNeedsAuthoring-10899.test.tsx b/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioNeedsAuthoring-10899.test.tsx index 0c19a55f9d5..74d6bf95ffb 100644 --- a/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioNeedsAuthoring-10899.test.tsx +++ b/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioNeedsAuthoring-10899.test.tsx @@ -129,7 +129,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => String(url).endsWith('/api/v1/packages') diff --git a/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioOpensStudio-12540.test.tsx b/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioOpensStudio-12540.test.tsx index f8fb479927f..bf93a320555 100644 --- a/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioOpensStudio-12540.test.tsx +++ b/ui/packages/app-shell/src/views/__tests__/PageView.editInStudioOpensStudio-12540.test.tsx @@ -124,7 +124,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => String(url).endsWith('/api/v1/packages') diff --git a/ui/packages/app-shell/src/views/__tests__/RecordTabsConfig-36499.test.tsx b/ui/packages/app-shell/src/views/__tests__/RecordTabsConfig-36499.test.tsx index d00d5b97a89..5b07c48c2f6 100644 --- a/ui/packages/app-shell/src/views/__tests__/RecordTabsConfig-36499.test.tsx +++ b/ui/packages/app-shell/src/views/__tests__/RecordTabsConfig-36499.test.tsx @@ -154,7 +154,7 @@ beforeEach(() => { __resetDefaultLocale(); vi.stubGlobal( 'fetch', - vi.fn(async () => ({ ok: true, json: async () => ({ data: { locales: [{ code: session.defaultLocale, isDefault: true }] } }) })), + vi.fn(async () => ({ headers: new Headers(), ok: true, json: async () => ({ data: { locales: [{ code: session.defaultLocale, isDefault: true }] } }) })), ); }); afterEach(() => { diff --git a/ui/packages/app-shell/src/views/__tests__/objectViewHeaderChrome.objectSettings-36487.test.tsx b/ui/packages/app-shell/src/views/__tests__/objectViewHeaderChrome.objectSettings-36487.test.tsx index f2418723291..764bb967897 100644 --- a/ui/packages/app-shell/src/views/__tests__/objectViewHeaderChrome.objectSettings-36487.test.tsx +++ b/ui/packages/app-shell/src/views/__tests__/objectViewHeaderChrome.objectSettings-36487.test.tsx @@ -110,7 +110,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => (String(url).endsWith('/api/v1/packages') ? PACKAGES : { data: [] }), })), diff --git a/ui/packages/app-shell/src/views/changeOwner-35403.test.tsx b/ui/packages/app-shell/src/views/changeOwner-35403.test.tsx index 9d88129ceeb..23eea7b55c6 100644 --- a/ui/packages/app-shell/src/views/changeOwner-35403.test.tsx +++ b/ui/packages/app-shell/src/views/changeOwner-35403.test.tsx @@ -466,7 +466,7 @@ describe("a list asks the explain engine's transfer verdict for the object, once asked = []; vi.stubGlobal('fetch', vi.fn(async (url: string, init?: { body?: string }) => { asked.push({ url: String(url), body: JSON.parse(String(init?.body ?? '{}')) }); - return { ok, status: ok ? 200 : 403, json: async () => ({ allowed }) }; + return { headers: new Headers(), ok, status: ok ? 200 : 403, json: async () => ({ allowed }) }; })); } beforeEach(() => __clearObjectTransferVerdicts()); @@ -565,7 +565,7 @@ describe('the Change Owner dialog offers the declared cascades as ticks (objects vi.stubGlobal('fetch', vi.fn(async (_url: string, init?: { body?: string }) => { const body = JSON.parse(String(init?.body ?? '{}')) as { object: string; operation: string }; explained.push(`${body.object}:${body.operation}`); - return { ok: true, status: 200, json: async () => ({ allowed: allow.includes(body.object) }) }; + return { headers: new Headers(), ok: true, status: 200, json: async () => ({ allowed: allow.includes(body.object) }) }; })); } diff --git a/ui/packages/app-shell/src/views/changeOwner.ts b/ui/packages/app-shell/src/views/changeOwner.ts index 3cdd5b75378..fc8881922c6 100644 --- a/ui/packages/app-shell/src/views/changeOwner.ts +++ b/ui/packages/app-shell/src/views/changeOwner.ts @@ -29,6 +29,7 @@ import { partitionRowsByPredicate } from '@object-ui/core'; import { SchemaRendererContext, useRowPredicate } from '@object-ui/react'; import { usePermissions } from '@object-ui/permissions'; import { useRecordVerdict } from '@object-ui/plugin-detail'; +import { createAuthenticatedFetch } from '@object-ui/auth'; /** The record's owner column, as the spec names it. */ export const CHANGE_OWNER_FIELD: typeof SystemFieldName.OWNER_ID = SystemFieldName.OWNER_ID; @@ -171,7 +172,7 @@ function askObjectTransfer( if (known) return known; const answer = (async (): Promise => { try { - const res = await (apiFetch ?? fetch)('/api/v1/security/explain', { + const res = await (apiFetch ?? createAuthenticatedFetch())('/api/v1/security/explain', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', diff --git a/ui/packages/app-shell/src/views/metadata-admin/EditPackageDialog.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/EditPackageDialog.test.tsx index 89b6bbd29c1..d5c7b20a636 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/EditPackageDialog.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/EditPackageDialog.test.tsx @@ -4,6 +4,10 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, fireEvent, waitFor } from '@testing-library/react'; import { EditPackageDialog, type InstalledPackageRow } from './PackagesPage'; +// The source under test reaches a dynamic `import('@objectstack/formula')` and `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; // EditPackageDialog is now a thin wrapper over the spec-driven PackageFormDialog // (edit mode). It renders the manifest form via SchemaForm and PATCHes name / @@ -32,7 +36,7 @@ beforeEach(() => { const body = init.body ? JSON.parse(init.body as string) : {}; const updated: InstalledPackageRow = { ...PKG, manifest: { ...PKG.manifest, ...body } }; return { - ok: true, + headers: new Headers(), ok: true, status: 200, text: async () => JSON.stringify({ success: true, data: updated }), } as Response; @@ -72,7 +76,7 @@ describe('EditPackageDialog (spec-form wrapper)', () => { vi.stubGlobal( 'fetch', vi.fn(async () => ({ - ok: false, + headers: new Headers(), ok: false, status: 400, text: async () => JSON.stringify({ success: false, error: { message: 'version must be semantic (e.g. 1.0.0)' } }), diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.createScope-12869.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.createScope-12869.test.tsx index de1dfefbf9e..566ed178b14 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.createScope-12869.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.createScope-12869.test.tsx @@ -18,6 +18,10 @@ import { render, screen, fireEvent, waitFor, within } from '@testing-library/rea import { PackageFormDialog } from './PackageFormDialog'; import { getPackageForm } from './package-schema'; import { t } from './i18n'; +// The source under test reaches a dynamic `import('@objectstack/formula')` and `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; // The one stand-in: a create form that still carries the `scope` row, so a // draft can hold a picked scope and the POST body is measured on its own. @@ -46,7 +50,7 @@ beforeEach(() => { const body = init.body ? JSON.parse(init.body as string) : {}; posts.push(body.manifest ?? body); return { - ok: true, + headers: new Headers(), ok: true, status: 201, text: async () => JSON.stringify({ success: true, data: { manifest: body.manifest } }), } as Response; diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.dependenciesEditor-13278.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.dependenciesEditor-13278.test.tsx index 240b5039bce..3e704177d16 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.dependenciesEditor-13278.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.dependenciesEditor-13278.test.tsx @@ -23,6 +23,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { PackageFormDialog, type ManifestRecord } from './PackageFormDialog'; +// The source under test reaches a dynamic `import('@objectstack/formula')` and `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; vi.mock('./i18n', async (importOriginal) => ({ ...(await importOriginal>()), @@ -48,7 +52,7 @@ function stubFetch() { vi.fn(async (url: string, init: RequestInit = {}) => { calls.push({ url, init }); return { - ok: true, + headers: new Headers(), ok: true, status: 200, text: async () => JSON.stringify({ success: true, data: { manifest: MANIFEST } }), } as Response; diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.editDependencies-13121.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.editDependencies-13121.test.tsx index c2a99a5793d..5332bd887b4 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.editDependencies-13121.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.editDependencies-13121.test.tsx @@ -27,6 +27,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { PackageFormDialog, type ManifestRecord } from './PackageFormDialog'; +// The source under test reaches a dynamic `import('@objectstack/formula')` and `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; vi.mock('./i18n', async (importOriginal) => ({ ...(await importOriginal>()), @@ -53,7 +57,7 @@ function stubFetch(status: number, body: unknown) { vi.fn(async (url: string, init: RequestInit = {}) => { calls.push({ url, init }); return { - ok: status >= 200 && status < 300, + headers: new Headers(), ok: status >= 200 && status < 300, status, text: async () => JSON.stringify(body), } as Response; diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.envelopeUserMessage.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.envelopeUserMessage.test.tsx index 5886da09489..ac6152ad643 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.envelopeUserMessage.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.envelopeUserMessage.test.tsx @@ -49,6 +49,10 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react'; import { PackageFormDialog } from './PackageFormDialog'; import { t } from './i18n'; +// The source under test reaches a dynamic `import('@objectstack/formula')` and `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; // Only `useMetadataLocale` is replaced — the `t` resolver and both string // tables stay real, so §8 asserts against the strings the product ships. @@ -74,7 +78,7 @@ function stubBody(status: number, body: unknown) { vi.stubGlobal( 'fetch', vi.fn(async () => ({ - ok: status >= 200 && status < 300, + headers: new Headers(), ok: status >= 200 && status < 300, status, text: async () => JSON.stringify(body), })) as unknown as typeof fetch, diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.idDerive-11792.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.idDerive-11792.test.tsx index 77b3a979228..b9ce09aedde 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.idDerive-11792.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.idDerive-11792.test.tsx @@ -30,6 +30,10 @@ await loadStudioCatalogue('zh'); // The pinyin dictionary a Chinese name derives through, resident before any // case, as it is once a Console door has fetched it (objectstack#29690). import { loadHanRomanizer } from './romanizeHan'; +// The source under test reaches a dynamic `import('@objectstack/formula')` and `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; await loadHanRomanizer(); let localeFixture: 'en-US' | 'zh-CN' = 'en-US'; @@ -60,7 +64,7 @@ beforeEach(() => { const body = init.body ? JSON.parse(init.body as string) : {}; const manifest = body.manifest ?? body; return { - ok: true, + headers: new Headers(), ok: true, status: 201, text: async () => JSON.stringify({ success: true, data: { manifest } }), } as Response; diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.test.tsx index b01ef39415b..909e184253b 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.test.tsx @@ -41,7 +41,7 @@ function stubOk() { const body = init.body ? JSON.parse(init.body as string) : {}; const manifest = body.manifest ?? body; return { - ok: true, + headers: new Headers(), ok: true, status: 201, text: async () => JSON.stringify({ success: true, data: { manifest, status: 'installed' } }), } as Response; @@ -85,7 +85,7 @@ describe('PackageFormDialog — create mode', () => { vi.stubGlobal( 'fetch', vi.fn(async () => ({ - ok: false, + headers: new Headers(), ok: false, status: 409, text: async () => JSON.stringify({ success: false, error: { message: "Package 'com.acme.new' already exists" } }), })), @@ -120,7 +120,7 @@ function stubRefusal(status: number, message: string) { vi.stubGlobal( 'fetch', vi.fn(async () => ({ - ok: false, + headers: new Headers(), ok: false, status, text: async () => JSON.stringify({ success: false, error: { message } }), })), diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.tsx index 0e1015a2548..4ba25e2f126 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.tsx @@ -47,7 +47,7 @@ import * as React from 'react'; import { AlertTriangle, ChevronDown } from 'lucide-react'; import { toast } from 'sonner'; import { ManifestSchema, deriveNamespaceFromPackageId } from '@objectstack/spec/kernel'; -import { useAuth } from '@object-ui/auth'; +import { createAuthenticatedFetch, useAuth } from '@object-ui/auth'; import { NAMESPACE_RE, isSpecPackageId } from '../studio-design/packages-io.js'; import { PackageIdInput } from '../studio-design/PackageIdInput.js'; import { @@ -73,6 +73,11 @@ import { romanizeHan, romanizerPending, useHanRomanizer } from './romanizeHan.js import { readEnvelopeFailureText } from '../../utils/apiErrorEnvelope.js'; import type { NewAppStep } from '../studio-design/newAppDoor.js'; +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} + const API = '/api/v1/packages'; /** @@ -356,7 +361,7 @@ function readEnvelopeUserMessage(payload: unknown): string { type ApiJsonError = Error & { status: number; userMessage: string }; async function apiJson(path: string, init?: RequestInit): Promise { - const res = await fetch(path, { + const res = await authFetch(path, { credentials: 'include', headers: { Accept: 'application/json', ...(init?.headers || {}) }, ...init, diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.duplicateIdRule-11855.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.duplicateIdRule-11855.test.tsx index 1dd36cfa619..526f5240b45 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.duplicateIdRule-11855.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.duplicateIdRule-11855.test.tsx @@ -24,6 +24,10 @@ import { ManifestSchema } from '@objectstack/spec/kernel'; import { PackageDetailSheet, type InstalledPackageRow } from './PackagesPage'; import { t, tFormat } from './i18n'; +// The source under test reaches a dynamic `import('@objectstack/formula')` and `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; const PKG_ID = 'com.acme.crm'; const PKG: InstalledPackageRow = { @@ -40,7 +44,7 @@ let calls: Call[]; function respond(body: unknown, status = 200) { const text = JSON.stringify(body); return { - ok: status >= 200 && status < 300, + headers: new Headers(), ok: status >= 200 && status < 300, status, text: async () => text, json: async () => JSON.parse(text), diff --git a/ui/packages/app-shell/src/views/metadata-admin/catalog-activation.ts b/ui/packages/app-shell/src/views/metadata-admin/catalog-activation.ts index 7c97899d49b..6265a21cc55 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/catalog-activation.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/catalog-activation.ts @@ -70,6 +70,12 @@ import { type PermissionSetHolder, type PermissionSetHolding, } from './permission-set-holder.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** * Item name → switched on, for every item of the type the ledger holds a row @@ -167,7 +173,7 @@ export function isCatalogHolderActive( */ export async function readCatalogLedger(type: string, signal?: AbortSignal): Promise { if (!hasCatalogActivation(type)) return { states: new Map(), permissionRows: [] }; - const res = await fetch(`${apiBase()}/data/sys_metadata_activation?top=${LEDGER_PAGE_SIZE}`, { + const res = await authFetch(`${apiBase()}/data/sys_metadata_activation?top=${LEDGER_PAGE_SIZE}`, { credentials: 'include', headers: JSON_HEADERS, cache: 'no-store', @@ -222,7 +228,7 @@ export async function writeCatalogActivation( ): Promise { if (!hasCatalogActivation(type)) throw new Error(`No activation for metadata type '${type}'`); const query = type === 'permission' ? packageQuery(packageId) : ''; - const res = await fetch( + const res = await authFetch( `${apiBase()}/security/_activation/${encodeURIComponent(type)}/${encodeURIComponent(name)}${query}`, { method: 'POST', diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowReferenceField.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowReferenceField.tsx index f174cafcba0..e482fdd501c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowReferenceField.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowReferenceField.tsx @@ -66,6 +66,12 @@ import { type RegistryAndDataValueSource, } from '../../../utils/approverValueSources.js'; import { isStudioHiddenSystemField } from '../../studio-design/studioHiddenSystemField.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** Context the reference picker needs to resolve dynamic option sources. */ export interface FlowReferenceContext { @@ -526,7 +532,7 @@ function useConnectorActionOptions(connectorName: string | undefined): { options } let cancelled = false; setState((s) => ({ ...s, loading: true })); - fetch('/api/v1/automation/connectors', { credentials: 'include', headers: { Accept: 'application/json' } }) + authFetch('/api/v1/automation/connectors', { credentials: 'include', headers: { Accept: 'application/json' } }) .then((r) => (r.ok ? r.json() : null)) .then((payload) => { if (cancelled) return; @@ -564,7 +570,7 @@ function useConnectorListOptions(enabled: boolean, locale: SupportedLocale): { o return; } let cancelled = false; - fetch('/api/v1/automation/connectors', { credentials: 'include', headers: { Accept: 'application/json' } }) + authFetch('/api/v1/automation/connectors', { credentials: 'include', headers: { Accept: 'application/json' } }) .then((r) => (r.ok ? r.json() : null)) .then((payload) => { if (cancelled) return; diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/connector-input-fields.ts b/ui/packages/app-shell/src/views/metadata-admin/inspectors/connector-input-fields.ts index e9f3dd5c3bc..f9fc2f0179d 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/connector-input-fields.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/connector-input-fields.ts @@ -81,6 +81,12 @@ import * as React from 'react'; import { jsonSchemaToFlowFields } from './json-schema-to-fields.js'; import type { FlowConfigField } from './flow-node-config.js'; import { apiBase } from '../previews/useFlowNodePalette.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** Where a connector node's mapped inputs live on the node (spec-structured). */ export const CONNECTOR_INPUT_PATH: readonly string[] = ['connectorConfig', 'input']; @@ -322,7 +328,7 @@ export function useConnectorRegistry(enabled: boolean): unknown[] { const controller = new AbortController(); (async () => { try { - const res = await fetch(`${apiBase()}/automation/connectors`, { + const res = await authFetch(`${apiBase()}/automation/connectors`, { credentials: 'include', headers: { Accept: 'application/json' }, signal: controller.signal, diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/inspectorStrings.i18n-10586.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/inspectorStrings.i18n-10586.test.tsx index 80968b5cd43..540b25296ad 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/inspectorStrings.i18n-10586.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/inspectorStrings.i18n-10586.test.tsx @@ -100,8 +100,8 @@ vi.stubGlobal( 'fetch', (async (url: string) => String(url).includes('/api/v1/automation/connectors') - ? { ok: true, json: async () => ({ data: { connectors: CONNECTORS } }) } - : { ok: false, json: async () => null }) as unknown as typeof globalThis.fetch, + ? { headers: new Headers(), ok: true, json: async () => ({ data: { connectors: CONNECTORS } }) } + : { headers: new Headers(), ok: false, json: async () => null }) as unknown as typeof globalThis.fetch, ); type Lang = 'en' | 'zh'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/permission-set-clone.ts b/ui/packages/app-shell/src/views/metadata-admin/permission-set-clone.ts index cf707829ef4..b61fa105a82 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/permission-set-clone.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/permission-set-clone.ts @@ -58,6 +58,12 @@ import { apiBase } from '../../utils/apiBase.js'; import { envelopeData, envelopeRefused } from '../setup/packagedFlows.js'; import { t, tFormat } from './i18n.js'; import { holderCandidatesOf, packageQuery, PermissionSetHolderConflict } from './permission-set-holder.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** What a clone that the server accepted reports back. */ export interface PermissionSetCloned { @@ -123,7 +129,7 @@ export async function clonePermissionSet( sourcePackage?: string, ): Promise { const url = `${apiBase()}/security/permission-sets/${encodeURIComponent(source)}/clone${packageQuery(sourcePackage)}`; - const res = await fetch(url, { + const res = await authFetch(url, { method: 'POST', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/FlowRunsPanel.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowRunsPanel.tsx index b6a355c8c90..bb127584959 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/FlowRunsPanel.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowRunsPanel.tsx @@ -26,6 +26,12 @@ import { collectFlowGraphs } from '@objectstack/spec/automation'; import { apiBase } from './useFlowNodePalette.js'; import { t as tr, tFormat } from '../i18n.js'; import { flowNodeDisplayName } from './flow-canvas-parts.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** An error on a run/step. The engine sends the run-level `error` as a plain * string (`ExecutionLog.error`) while a step-level error is a `{code,message}` @@ -236,7 +242,7 @@ type LoadState = 'loading' | 'ready' | 'unavailable'; /** Fetch a flow's run history. Exposed for tests. */ export async function fetchFlowRuns(flowName: string, signal?: AbortSignal): Promise { try { - const res = await fetch( + const res = await authFetch( `${apiBase()}/automation/${encodeURIComponent(flowName)}/runs?limit=25`, { credentials: 'include', headers: { 'Content-Type': 'application/json' }, signal }, ); diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.authoredDetailsValues-27177.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.authoredDetailsValues-27177.test.tsx index 7e53523b743..f872a31fdd0 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.authoredDetailsValues-27177.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.authoredDetailsValues-27177.test.tsx @@ -113,10 +113,10 @@ function fullCreateSeed(): Record { function stubFetch() { vi.stubGlobal('fetch', vi.fn(async (url: string) => { - if (url.startsWith('/api/v1/meta/object/')) return { ok: true, json: async () => ({ item: OBJECT_DEF }) } as any; - if (url.startsWith(`/api/v1/data/${OBJECT}`)) return { ok: true, json: async () => ({ records: [RECORD] }) } as any; + if (url.startsWith('/api/v1/meta/object/')) return { headers: new Headers(), ok: true, json: async () => ({ item: OBJECT_DEF }) } as any; + if (url.startsWith(`/api/v1/data/${OBJECT}`)) return { headers: new Headers(), ok: true, json: async () => ({ records: [RECORD] }) } as any; // The record-edit probe and anything else the real blocks ask for. - return { ok: true, json: async () => ({}) } as any; + return { headers: new Headers(), ok: true, json: async () => ({}) } as any; })); } diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.expandFls-7429.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.expandFls-7429.test.tsx index aec65b2ecc7..e835abf8fc8 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.expandFls-7429.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.expandFls-7429.test.tsx @@ -98,6 +98,9 @@ vi.mock('@object-ui/react', async (importOriginal) => ({ })); import { PagePreview } from './PagePreview'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; const OBJECT = 'showcase_account'; @@ -130,13 +133,13 @@ function stubFetch() { const dataCalls: string[] = []; const fn = vi.fn(async (url: string) => { if (url.startsWith('/api/v1/meta/object/')) { - return { json: async () => ({ item: { name: OBJECT, fields: OBJECT_FIELDS } }) } as any; + return { headers: new Headers(), json: async () => ({ item: { name: OBJECT, fields: OBJECT_FIELDS } }) } as any; } if (url.startsWith('/api/v1/data/')) { dataCalls.push(url); - return { json: async () => ({ records: [] }) } as any; + return { headers: new Headers(), json: async () => ({ records: [] }) } as any; } - return { json: async () => ({}) } as any; + return { headers: new Headers(), json: async () => ({}) } as any; }); vi.stubGlobal('fetch', fn); return { fn, dataCalls }; diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.sharedSelect-11865.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.sharedSelect-11865.test.tsx index 7a34ca4bd61..ad350031547 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.sharedSelect-11865.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.sharedSelect-11865.test.tsx @@ -58,6 +58,9 @@ vi.mock('@object-ui/react', async (importOriginal) => ({ })); import { PagePreview } from './PagePreview'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; /** Each object's sample records; one keyed by `_id`, one by `name` alone. */ const RECORDS: Record = { @@ -73,7 +76,7 @@ const RECORDS: Record = { ], }; -const answer = (body: unknown) => ({ json: async () => body }) as unknown as Response; +const answer = (body: unknown) => ({ headers: new Headers(), json: async () => body }) as unknown as Response; function stubFetch(): void { vi.stubGlobal( diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.slottedDefault-27054.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.slottedDefault-27054.test.tsx index 75f6b4f74c3..283ddcbbf70 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.slottedDefault-27054.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.slottedDefault-27054.test.tsx @@ -77,9 +77,9 @@ function stubFetch(schemaGate?: Promise) { vi.stubGlobal('fetch', vi.fn(async (url: string) => { if (url.startsWith('/api/v1/meta/object/')) { if (schemaGate) await schemaGate; - return { json: async () => ({ item: { name: OBJECT, fields: FIELDS } }) } as any; + return { headers: new Headers(), json: async () => ({ item: { name: OBJECT, fields: FIELDS } }) } as any; } - return { json: async () => ({ records: [] }) } as any; + return { headers: new Headers(), json: async () => ({ records: [] }) } as any; })); } @@ -221,6 +221,7 @@ describe('PagePreview — Convert to full page heads the ungrouped bucket, trans function stubGroupedFetch() { vi.stubGlobal('fetch', vi.fn(async (url: string) => ({ + headers: new Headers(), json: async () => (url.startsWith('/api/v1/meta/object/') ? { item: GROUPED } : { records: [] }), }) as any)); } @@ -285,6 +286,7 @@ describe('PagePreview — Convert to full page heads More details, translated (o function stubFlatFetch() { vi.stubGlobal('fetch', vi.fn(async (url: string) => ({ + headers: new Headers(), json: async () => (url.startsWith('/api/v1/meta/object/') ? { item: FLAT } : { records: [] }), }) as any)); } diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.test.tsx index d23e06376c6..b3f3002fb62 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.test.tsx @@ -87,7 +87,7 @@ describe('PagePreview — slotted record page synthesis', () => { // Record binding fetches the object schema + sample records. Resolve both // to empty so the effect settles deterministically; synthesis falls back to // a def-less default page (structure only), which is all this test asserts. - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({}) })); + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ headers: new Headers(), json: async () => ({}) })); }); afterEach(() => { vi.unstubAllGlobals(); }); @@ -197,6 +197,7 @@ describe('PagePreview — slotted record page detail sections (objectui#12442)', /** Serve `def` as the object schema; no sample records. */ function serve(def: unknown) { vi.stubGlobal('fetch', vi.fn(async (url: string) => ({ + headers: new Headers(), json: async () => (url.startsWith('/api/v1/meta/object/') ? { item: def } : { records: [] }), }))); } diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.tsx index 00b44a63903..e3c9e8f9ae6 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/PagePreview.tsx @@ -29,6 +29,12 @@ import { import { PageBlockCanvas } from './PageBlockCanvas.js'; import { InterfaceListPage } from '../../InterfaceListPage.js'; import { t as tr, tFormat } from '../i18n.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} interface Block { type?: string; id?: string; children?: Block[]; [k: string]: unknown } @@ -204,7 +210,7 @@ export function PagePreview({ draft, editing, selection, onSelectionChange, onPa // can `$expand` them. Without expansion record:details/highlights would // show raw foreign-key IDs (e.g. "O4VKrNesnsj2JYMa") instead of display // names — the runtime RecordDetailView $expands for exactly this reason. - const schemaRes = await fetch(`/api/v1/meta/object/${encodeURIComponent(recordObject)}`, opts); + const schemaRes = await authFetch(`/api/v1/meta/object/${encodeURIComponent(recordObject)}`, opts); const schemaJson = await schemaRes.json().catch(() => null); const schema = schemaJson?.item ?? schemaJson?.data ?? schemaJson; // [objectui#7429] FIELD-LEVEL SECURITY ON `$expand` — the same gate @@ -262,7 +268,7 @@ export function PagePreview({ draft, editing, selection, onSelectionChange, onPa const query = expand.length > 0 ? `?$top=50&$expand=${encodeURIComponent(expand.join(','))}` : `?$top=50`; - const recsRes = await fetch(`/api/v1/data/${encodeURIComponent(recordObject)}${query}`, opts); + const recsRes = await authFetch(`/api/v1/data/${encodeURIComponent(recordObject)}${query}`, opts); const recsJson = await recsRes.json().catch(() => null); // The REST data endpoint returns `{ object, records, total, hasMore }`; // tolerate the other common envelopes too. diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/__tests__/page-preview-record-type-10482.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/__tests__/page-preview-record-type-10482.test.tsx index 17869c9d21d..6d3506cf3c6 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/__tests__/page-preview-record-type-10482.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/__tests__/page-preview-record-type-10482.test.tsx @@ -44,6 +44,9 @@ vi.mock('@object-ui/react', async (importOriginal) => ({ })); import { PagePreview } from '../PagePreview'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; const OBJECT = 'showcase_account'; const REGIONS = [{ name: 'main', components: [{ type: 'record:details' }] }]; @@ -57,8 +60,8 @@ const ALIAS_CONTRADICTS_TYPE = { name: 'acct_conflict', label: 'Account', type: /** Second control: a non-record page kind with an object stays unbound. */ const APP_PAGE = { name: 'acct_app', label: 'Account', type: 'app', object: OBJECT, regions: REGIONS }; -/** A `fetch` answer carrying only the `json()` this component reads. */ -const answer = (body: unknown) => ({ json: async () => body }) as unknown as Response; +/** A `fetch` answer carrying the `json()` this component reads, and the `headers` the authenticated fetch reads. */ +const answer = (body: unknown) => ({ headers: new Headers(), json: async () => body }) as unknown as Response; /** Serve both reads the record binding makes; record every URL asked for. */ function stubFetch(): string[] { diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/dataPreviews.i18n-10862-s3.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/dataPreviews.i18n-10862-s3.test.tsx index 1189c87fad8..94ed5ec7028 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/dataPreviews.i18n-10862-s3.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/dataPreviews.i18n-10862-s3.test.tsx @@ -151,6 +151,9 @@ import type { ObjectFieldInfo } from './useObjectFields'; // namespace, whose `zh` catalogue is fetched on demand (objectstack#25922). // Resident before any case, so the zh rows below read synchronously. import { loadStudioCatalogue } from '@object-ui/i18n/namespaces/studio'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; await loadStudioCatalogue('zh'); const realFetch = globalThis.fetch; @@ -278,7 +281,7 @@ function expectHint(lang: Lang, key: string, vars?: Vars) { } /** A `fetch` answer carrying only the `json()` the previews read. */ -const answer = (body: unknown) => ({ ok: true, json: async () => body }) as unknown as Response; +const answer = (body: unknown) => ({ headers: new Headers(), ok: true, json: async () => body }) as unknown as Response; // ─── ObjectPreview ─────────────────────────────────────────────────────────── diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/useFlowNodePalette.ts b/ui/packages/app-shell/src/views/metadata-admin/previews/useFlowNodePalette.ts index 62b1c81259c..7ec7e4dd1f2 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/useFlowNodePalette.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/useFlowNodePalette.ts @@ -23,6 +23,12 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { NODE_PALETTE, nodeCategory, type PaletteItem } from './flow-canvas-parts.js'; import { apiBase } from '../../../utils/apiBase.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** Minimal shape of an engine action descriptor we consume. */ interface ActionDescriptorLite { @@ -99,7 +105,7 @@ export function useActionDescriptors(): ActionDescriptorLite[] { const controller = new AbortController(); (async () => { try { - const res = await fetch(`${apiBase()}/automation/actions`, { + const res = await authFetch(`${apiBase()}/automation/actions`, { credentials: 'include', headers: { 'Content-Type': 'application/json' }, signal: controller.signal, diff --git a/ui/packages/app-shell/src/views/metadata-admin/sharing-rule-catalog.ts b/ui/packages/app-shell/src/views/metadata-admin/sharing-rule-catalog.ts index 03b2ef54990..781c8811731 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/sharing-rule-catalog.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/sharing-rule-catalog.ts @@ -48,6 +48,12 @@ import { actionErrorDetail } from '@object-ui/core'; import { apiBase } from '../../utils/apiBase.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** The registry type of a declared sharing rule. */ export const DECLARED_SHARING_RULE_TYPE = 'sharing_rule'; @@ -89,7 +95,7 @@ export async function readSharingRuleProjection( name: string, signal?: AbortSignal, ): Promise { - const res = await fetch(`${apiBase()}/sharing/rules/${encodeURIComponent(name)}`, { + const res = await authFetch(`${apiBase()}/sharing/rules/${encodeURIComponent(name)}`, { credentials: 'include', headers: { Accept: 'application/json' }, cache: 'no-store', diff --git a/ui/packages/app-shell/src/views/objectViewPageHeader.objectSettings-36487.test.tsx b/ui/packages/app-shell/src/views/objectViewPageHeader.objectSettings-36487.test.tsx index a1039f40a30..7a0453d41a0 100644 --- a/ui/packages/app-shell/src/views/objectViewPageHeader.objectSettings-36487.test.tsx +++ b/ui/packages/app-shell/src/views/objectViewPageHeader.objectSettings-36487.test.tsx @@ -121,7 +121,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: unknown) => ({ - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => (String(url).endsWith('/api/v1/packages') ? PACKAGES : { data: [] }), })), diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.pendingDraftsPulse-13139.test.tsx b/ui/packages/app-shell/src/views/runtime-metadata-persistence.pendingDraftsPulse-13139.test.tsx index ccc9ad04aa1..f222dc56e7b 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.pendingDraftsPulse-13139.test.tsx +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.pendingDraftsPulse-13139.test.tsx @@ -68,7 +68,7 @@ function fakeServer(initial: Array<{ type: string; name: string }> = []) { const draftsReads = vi.fn(async (input: RequestInfo | URL) => { expect(String(input)).toBe('/api/v1/meta/_drafts'); const answer = [...ledger.values()].map((d) => ({ ...d, packageId: PACKAGE })); - return { ok: true, status: 200, json: async () => answer }; + return { headers: new Headers(), ok: true, status: 200, json: async () => answer }; }); vi.stubGlobal('fetch', draftsReads); const metadataClient = { diff --git a/ui/packages/app-shell/src/views/setup/packagedActionLedger.ts b/ui/packages/app-shell/src/views/setup/packagedActionLedger.ts index 1109db6e4bf..abfcd6a4aa2 100644 --- a/ui/packages/app-shell/src/views/setup/packagedActionLedger.ts +++ b/ui/packages/app-shell/src/views/setup/packagedActionLedger.ts @@ -39,6 +39,12 @@ import { fetchPackages, type PkgEntry } from '../studio-design/packages-io.js'; import { envelopeData, envelopeRefused } from './packagedFlows.js'; import { ledgerPageTruncated, readActionActivation, readDataRecords } from './packagedActions.js'; import { useFlowLedgerWalledReadOnly, type FlowDoorFallbacks } from './packagedFlowLedger.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** * How many ledger rows one read asks for. The ledger holds a row only for an @@ -62,7 +68,7 @@ async function readJson(res: Response): Promise { * `HTTP ` load errors are), never with a partial map. */ export async function fetchActionLedger(signal?: AbortSignal): Promise> { - const res = await fetch(`${apiBase()}/data/sys_metadata_activation?top=${ACTION_LEDGER_PAGE_SIZE}`, { + const res = await authFetch(`${apiBase()}/data/sys_metadata_activation?top=${ACTION_LEDGER_PAGE_SIZE}`, { credentials: 'include', headers: { Accept: 'application/json' }, cache: 'no-store', @@ -94,7 +100,7 @@ export async function requestActionToggle( fallbacks: FlowDoorFallbacks, ): Promise { try { - const res = await fetch( + const res = await authFetch( `${apiBase()}/actions/_activation/${encodeURIComponent(objectName)}/${encodeURIComponent(name)}`, { method: 'POST', diff --git a/ui/packages/app-shell/src/views/setup/packagedFlowLedger.ts b/ui/packages/app-shell/src/views/setup/packagedFlowLedger.ts index a75a01bbe1e..1be22c483b8 100644 --- a/ui/packages/app-shell/src/views/setup/packagedFlowLedger.ts +++ b/ui/packages/app-shell/src/views/setup/packagedFlowLedger.ts @@ -17,13 +17,18 @@ * for it ({@link flowLedgerWalledReadOnly}), never a client copy of its sentence. */ -import { useAuth } from '@object-ui/auth'; +import { createAuthenticatedFetch, useAuth } from '@object-ui/auth'; import type { TenancyPosture } from '@object-ui/auth'; import { actionErrorDetail } from '@object-ui/core'; import { postureHasOrgWall, useTenancyPosture } from '../../hooks/useTenancyPosture.js'; import { apiBase } from '../../utils/apiBase.js'; import { envelopeData, envelopeRefused } from './packagedFlows.js'; +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} + const JSON_HEADERS = { Accept: 'application/json', 'Content-Type': 'application/json' } as const; /** The caller's own words for a refusal that carried no message. */ @@ -57,7 +62,7 @@ export async function requestFlowToggle( fallbacks: FlowDoorFallbacks, ): Promise { try { - const res = await fetch(`${apiBase()}/automation/${encodeURIComponent(name)}/toggle`, { + const res = await authFetch(`${apiBase()}/automation/${encodeURIComponent(name)}/toggle`, { method: 'POST', credentials: 'include', headers: JSON_HEADERS, diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx index 51e284e306f..87cc9ed3120 100644 --- a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx @@ -158,6 +158,12 @@ import { } from './StudioCustomizeControls.js'; import { SavedToCustomizationNote } from '../../preview/savedToCustomization.js'; import { toast } from 'sonner'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** * objectstack#34818 — the names of the flows that have a published version in @@ -539,7 +545,7 @@ export function AutomationsPillar({ let cancelled = false; (async () => { try { - const res = await fetch('/api/v1/automation/_status', { credentials: 'include', headers: { Accept: 'application/json' } }); + const res = await authFetch('/api/v1/automation/_status', { credentials: 'include', headers: { Accept: 'application/json' } }); if (!res.ok) return; const payload = (await res.json().catch(() => null)) as { data?: { flows?: FlowRuntimeState[] }; flows?: FlowRuntimeState[] } | null; const list = payload?.data?.flows ?? payload?.flows ?? []; diff --git a/ui/packages/app-shell/src/views/studio-design/BuilderLanding.customizationCounts-28566.test.tsx b/ui/packages/app-shell/src/views/studio-design/BuilderLanding.customizationCounts-28566.test.tsx index 95b7b83109d..7bcae5254fc 100644 --- a/ui/packages/app-shell/src/views/studio-design/BuilderLanding.customizationCounts-28566.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/BuilderLanding.customizationCounts-28566.test.tsx @@ -84,7 +84,7 @@ function stubWire(answers: Record, objects: Record(() => {}); if (!answer) throw new Error(`unexpected request ${url}`); return { - ok: answer.status >= 200 && answer.status < 300, + headers: new Headers(), ok: answer.status >= 200 && answer.status < 300, status: answer.status, json: async () => answer.body, text: async () => JSON.stringify(answer.body), diff --git a/ui/packages/app-shell/src/views/studio-design/BuilderLanding.duplicateIdRule-11855.test.tsx b/ui/packages/app-shell/src/views/studio-design/BuilderLanding.duplicateIdRule-11855.test.tsx index b7d0afdd7e5..cc6f6aab6bf 100644 --- a/ui/packages/app-shell/src/views/studio-design/BuilderLanding.duplicateIdRule-11855.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/BuilderLanding.duplicateIdRule-11855.test.tsx @@ -37,6 +37,9 @@ vi.mock('./packages-io', async (importOriginal) => { vi.mock('../metadata-admin/PackageFormDialog', () => ({ PackageFormDialog: () => null })); import { BuilderLanding } from './BuilderLanding'; +// The source under test reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; type Call = { url: string; method: string; body: unknown }; let calls: Call[]; @@ -50,7 +53,7 @@ beforeEach(() => { const body = typeof init.body === 'string' && init.body ? JSON.parse(init.body) : undefined; calls.push({ url, method, body }); const text = JSON.stringify({ success: true, data: { success: true, copiedCount: 3, failedCount: 0 } }); - return { ok: true, status: 200, json: async () => JSON.parse(text), text: async () => text } as Response; + return { headers: new Headers(), ok: true, status: 200, json: async () => JSON.parse(text), text: async () => text } as Response; }), ); }); diff --git a/ui/packages/app-shell/src/views/studio-design/BuilderLanding.envCustomizations-34714.test.tsx b/ui/packages/app-shell/src/views/studio-design/BuilderLanding.envCustomizations-34714.test.tsx index 349cd687c2d..573e5626904 100644 --- a/ui/packages/app-shell/src/views/studio-design/BuilderLanding.envCustomizations-34714.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/BuilderLanding.envCustomizations-34714.test.tsx @@ -107,7 +107,7 @@ function stubWire(answers: Record) { const answer = m ? answers[decodeURIComponent(m[1])] : undefined; if (!answer) throw new Error(`unexpected request ${url}`); return { - ok: answer.status >= 200 && answer.status < 300, + headers: new Headers(), ok: answer.status >= 200 && answer.status < 300, status: answer.status, json: async () => answer.body, text: async () => JSON.stringify(answer.body), diff --git a/ui/packages/app-shell/src/views/studio-design/BuilderLanding.packagesDoor-35196.test.tsx b/ui/packages/app-shell/src/views/studio-design/BuilderLanding.packagesDoor-35196.test.tsx index e903ad37d45..4c43536b0dc 100644 --- a/ui/packages/app-shell/src/views/studio-design/BuilderLanding.packagesDoor-35196.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/BuilderLanding.packagesDoor-35196.test.tsx @@ -65,7 +65,7 @@ vi.mock('../metadata-admin/PackageFormDialog', () => ({ PackageFormDialog: () => import { BuilderLanding, STUDIO_ALL_PACKAGES_PATH } from './BuilderLanding'; const json = (body: unknown, status = 200) => - ({ ok: status < 400, status, json: async () => body, text: async () => JSON.stringify(body) }) as Response; + ({ headers: new Headers(), ok: status < 400, status, json: async () => body, text: async () => JSON.stringify(body) }) as Response; afterEach(() => { cleanup(); diff --git a/ui/packages/app-shell/src/views/studio-design/FlowItemMoreMenu.tsx b/ui/packages/app-shell/src/views/studio-design/FlowItemMoreMenu.tsx index d790779fcd7..94bec0f81f5 100644 --- a/ui/packages/app-shell/src/views/studio-design/FlowItemMoreMenu.tsx +++ b/ui/packages/app-shell/src/views/studio-design/FlowItemMoreMenu.tsx @@ -56,6 +56,12 @@ import { t, tFormat, translateMetadataType } from '../metadata-admin/i18n.js'; import { envelopeData, envelopeRefused } from '../setup/packagedFlows.js'; import { apiBase } from '../../utils/apiBase.js'; import { STUDIO_HEADER_ICON_BUTTON } from './studio-tokens.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** What the clone door saved: the copy's name, the package it names, and its sentence. */ export interface FlowCopied { @@ -96,7 +102,7 @@ async function requestFlowNewSimilar( fallbacks: { http: (status: number) => string; network: string }, ): Promise { try { - const res = await fetch(`${apiBase()}/automation/${encodeURIComponent(source)}/clone`, { + const res = await authFetch(`${apiBase()}/automation/${encodeURIComponent(source)}/clone`, { method: 'POST', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.ledgerSwitch-34724.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.ledgerSwitch-34724.test.tsx index 5a44f4e8ce1..564338258a2 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.ledgerSwitch-34724.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.ledgerSwitch-34724.test.tsx @@ -93,7 +93,7 @@ beforeEach(() => { toggleAnswer = ok({ success: true, data: { enabled: false } }); fetchMock = vi.fn(async (url: string) => { const answer = String(url).includes('/actions/_activation/') ? toggleAnswer : ledgerAnswer; - return { ok: answer.status < 400, status: answer.status, json: async () => answer.body } as Response; + return { headers: new Headers(), ok: answer.status < 400, status: answer.status, json: async () => answer.body } as Response; }); vi.stubGlobal('fetch', fetchMock); vi.mocked(toast.success).mockClear(); diff --git a/ui/packages/app-shell/src/views/studio-design/PackageSwitcher.tsx b/ui/packages/app-shell/src/views/studio-design/PackageSwitcher.tsx index eb26391cc0a..bf71c54e3b4 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageSwitcher.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageSwitcher.tsx @@ -12,6 +12,12 @@ import type { InstalledPackageRow } from '../metadata-admin/PackagesPage.js'; import { STUDIO_ROOT_PATH } from './studioAddress.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** * One sonner id for EVERY `fetchPackages()` failure on this surface @@ -36,7 +42,7 @@ export const STUDIO_LANDING_PATH = STUDIO_ROOT_PATH; * landing cards' Manage (objectstack#35196). */ export async function fetchInstalledPackageRow(id: string): Promise { - const res = await fetch('/api/v1/packages', { + const res = await authFetch('/api/v1/packages', { credentials: 'include', headers: { Accept: 'application/json' }, cache: 'no-store', diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.entryReadsOnce-11797.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.entryReadsOnce-11797.test.tsx index 7ba3e3ebbbe..15072648ca8 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.entryReadsOnce-11797.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.entryReadsOnce-11797.test.tsx @@ -63,6 +63,9 @@ vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => nul // The console's preview and authoring code loads `@objectstack/lint` lazily; // warmed here so its first load is paid at import, not inside a test's clock. import '@objectstack/lint'; +// The surface mounts the command palette, whose record preview reaches the +// `lazy()` detail entry: its first load is paid here too, not in a test's clock. +import '@object-ui/plugin-detail'; import { StudioDesignSurface } from './StudioDesignSurface'; window.matchMedia = ((query: string) => ({ @@ -91,7 +94,7 @@ interface Held { let held: Held[] = []; let requested: string[] = []; -const answer = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); +const answer = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); beforeEach(() => { held = []; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemDraftLine-12725.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemDraftLine-12725.test.tsx index df87a421601..b1d27368769 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemDraftLine-12725.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemDraftLine-12725.test.tsx @@ -106,6 +106,9 @@ vi.mock('../../preview/DraftChangesPanel', () => ({ // The console's preview and authoring code loads `@objectstack/lint` lazily; // warmed here so its first load is paid at import, not inside a test's clock. import '@objectstack/lint'; +// The surface mounts the command palette, whose record preview reaches the +// `lazy()` detail entry: its first load is paid here too, not in a test's clock. +import '@object-ui/plugin-detail'; import { StudioDesignSurface } from './StudioDesignSurface'; import { t, tFormat } from '../metadata-admin/i18n'; import { emitMetadataRefresh } from '../../assistant/assistantBus'; @@ -113,7 +116,7 @@ import { createEmptyDataSource } from './__tests__/emptyDataSource'; const dataSource = createEmptyDataSource(); -const answer = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); +const answer = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); beforeEach(() => { server.drafts = []; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx index 6020aa1c95d..91988cb9c01 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx @@ -119,7 +119,7 @@ import '@objectstack/lint'; // record preview's `lazy()` detail entry: its first load is paid here too. import '@object-ui/plugin-detail'; -const answer = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); +const answer = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); /** The package list as the server serves it: one writable app package and one kernel package. */ function servePackages() { diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx index 4ec52d0ba6f..04bd55d4e18 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx @@ -81,13 +81,13 @@ vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => nul import { StudioDesignSurface } from './StudioDesignSurface'; import { t, tFormat } from '../metadata-admin/i18n'; -const answer = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); +const answer = (body: unknown) => ({ headers: new Headers(), ok: true, status: 200, json: async () => body }); /** The package list as the server serves it: one app package and one kernel package. */ function servePackages(opts: { fail?: boolean } = {}) { const fetchMock = vi.fn(async (input: unknown) => { if (String(input) !== '/api/v1/packages') return answer([]); - if (opts.fail) return { ok: false, status: 502, json: async () => null }; + if (opts.fail) return { headers: new Headers(), ok: false, status: 502, json: async () => null }; return answer({ success: true, data: { diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyPosture-12453.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyPosture-12453.test.tsx index 3bfad306c6e..009e6aa979c 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyPosture-12453.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyPosture-12453.test.tsx @@ -71,11 +71,13 @@ const READ_ONLY = t('engine.studio.pkg.readonly', 'en'); function servePackage(writable: boolean) { vi.stubGlobal( 'fetch', - vi.fn(async (input: unknown) => - String(input) === '/api/v1/packages' + // The headers a real Response carries: the package list reads them through the authenticated fetch. + vi.fn(async (input: unknown) => ({ + headers: new Headers(), + ...(String(input) === '/api/v1/packages' ? answer({ success: true, data: { packages: [{ manifest: { id: PACKAGE_ID, name: 'Field Ops' }, writable }] } }) - : answer([]), - ), + : answer([])), + })), ); } diff --git a/ui/packages/app-shell/src/views/studio-design/StudioPaletteGroups.surfaceScope-36900.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioPaletteGroups.surfaceScope-36900.test.tsx index 5b25536bda0..d970058258a 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioPaletteGroups.surfaceScope-36900.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioPaletteGroups.surfaceScope-36900.test.tsx @@ -155,6 +155,7 @@ beforeEach(() => { fetchMock = vi.fn(async (url: string) => { if (String(url).endsWith('/api/v1/packages')) { return { + headers: new Headers(), ok: true, status: 200, json: async () => ({ diff --git a/ui/packages/app-shell/src/views/studio-design/fetchInstalledPackageRow-7881.test.ts b/ui/packages/app-shell/src/views/studio-design/fetchInstalledPackageRow-7881.test.ts index 403a2ad28af..47ab2a6406a 100644 --- a/ui/packages/app-shell/src/views/studio-design/fetchInstalledPackageRow-7881.test.ts +++ b/ui/packages/app-shell/src/views/studio-design/fetchInstalledPackageRow-7881.test.ts @@ -31,7 +31,8 @@ const MARKED = 'Publishing is temporarily unavailable. Nothing was changed.'; function answer(response: { ok: boolean; status: number; json: () => Promise }): void { vi.stubGlobal( 'fetch', - vi.fn(async () => response), + // With the headers a real Response carries: the list read goes through the authenticated fetch. + vi.fn(async () => ({ headers: new Headers(), ...response })), ); } const listOk = (packages: unknown[]) => diff --git a/ui/packages/app-shell/src/views/studio-design/packageCustomizations-io.ts b/ui/packages/app-shell/src/views/studio-design/packageCustomizations-io.ts index 319a6306a8c..ee7726cf454 100644 --- a/ui/packages/app-shell/src/views/studio-design/packageCustomizations-io.ts +++ b/ui/packages/app-shell/src/views/studio-design/packageCustomizations-io.ts @@ -31,6 +31,12 @@ import { } from '@objectstack/spec/api'; import { isCustomizationPackage } from '@objectstack/spec/kernel'; import { readEnvelopeFailureText } from '../../utils/apiErrorEnvelope.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} /** What the landing draws for one base: two served numbers, and which switched-off items are actions. */ export interface PackageCustomizationCounts { @@ -67,7 +73,7 @@ export async function fetchPackageCustomizations(baseId: string): Promise` beside the cookie + * (`credentials: 'include'`); + * - with no token stored (a cookie session), the same calls go out + * cookie-only, as before. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { TokenStorage } from '@object-ui/auth'; +import { duplicatePackage, fetchListedPackageIds, fetchPackages, forgetPackageListReads } from './packages-io'; +import { fetchCommits, revertCommit } from '../../preview/commitHistory'; +import { listSuggestedBindings } from '../../services/suggestedBindingsApi'; +import { fetchBuildDebug } from '../../console/ai/buildDebugApi'; + +const TOKEN = 'stored-session-token'; + +const reply = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + +type Sent = { path: string; method: string; credentials: RequestCredentials | undefined; authorization: string | null }; +let sent: Sent[] = []; + +const PACKAGES = { + success: true, + data: { packages: [{ manifest: { id: 'com.example.crm', name: 'CRM' } }, { id: 'app.helpdesk', name: 'Helpdesk' }] }, +}; + +function answer(path: string, method: string): Response { + if (path === '/api/v1/packages') return reply(PACKAGES); + if (path.endsWith('/duplicate') && method === 'POST') return reply({ success: true, data: { success: true } }); + if (path.endsWith('/commits') && method === 'GET') return reply({ success: true, data: { commits: [] } }); + if (path.endsWith('/revert') && method === 'POST') return reply({ success: true, data: { success: true } }); + if (path.startsWith('/api/v1/security/suggested-bindings')) return reply({ success: true, data: { suggestions: [] } }); + if (path.endsWith('/debug')) return reply({ conversationId: 'c1', findings: [] }); + return reply({ success: false, error: { code: 'NOT_FOUND', message: `no route ${method} ${path}` } }, 404); +} + +/** A server that answers only the bearer: no cookie rides in a unit test, so a request without it is refused. */ +function bearerOnlyServer(input: RequestInfo | URL, init?: RequestInit): Response { + const path = new URL(String(input), 'http://console.test').pathname; + const method = (init?.method ?? 'GET').toUpperCase(); + const authorization = new Headers(init?.headers).get('Authorization'); + sent.push({ path, method, credentials: init?.credentials, authorization }); + if (authorization !== `Bearer ${TOKEN}`) { + return reply({ error: 'UNAUTHENTICATED', code: 'UNAUTHENTICATED', message: 'Authentication is required to access this endpoint.' }, 401); + } + return answer(path, method); +} + +beforeEach(() => { + sent = []; + forgetPackageListReads(); + vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => bearerOnlyServer(input, init))); +}); + +afterEach(() => { + forgetPackageListReads(); + vi.unstubAllGlobals(); + TokenStorage.clear(); +}); + +describe('the held package list under a bearer-only session', () => { + it('loads the package list, sending the stored bearer beside the cookie', async () => { + TokenStorage.set(TOKEN); + const packages = await fetchPackages(); + expect(packages.map((p) => p.id)).toEqual(['com.example.crm', 'app.helpdesk']); + expect(sent).toEqual([ + { path: '/api/v1/packages', method: 'GET', credentials: 'include', authorization: `Bearer ${TOKEN}` }, + ]); + }); + + it('answers the listed-id read from the same authenticated request', async () => { + TokenStorage.set(TOKEN); + const ids = await fetchListedPackageIds(); + expect([...ids].sort()).toEqual(['app.helpdesk', 'com.example.crm']); + expect(sent.every((s) => s.authorization === `Bearer ${TOKEN}` && s.credentials === 'include')).toBe(true); + }); + + it('a cookie session (no token stored) still goes out cookie-only', async () => { + await expect(fetchPackages()).rejects.toThrow(); + expect(sent).toEqual([{ path: '/api/v1/packages', method: 'GET', credentials: 'include', authorization: null }]); + }); +}); + +/** The studio-design write, the timeline and the AI doors converted beside the list read. */ +const CALLS: Array<[string, () => Promise]> = [ + ['studio-design: duplicate a package', () => duplicatePackage('com.example.crm', 'com.example.crm_copy')], + ['timeline: commit history', () => fetchCommits('com.example.crm')], + ['timeline: revert a commit', () => revertCommit('com.example.crm', 'c-1')], + ['access: suggested bindings', () => listSuggestedBindings()], + ['ai: build debug report', () => fetchBuildDebug('/api/v1/ai', 'c1')], +]; + +describe('the converted doors send the stored bearer token', () => { + it.each(CALLS)('%s: carries the bearer beside the cookie and is answered', async (_name, call) => { + TokenStorage.set(TOKEN); + await call(); + expect(sent.length).toBeGreaterThan(0); + for (const s of sent) { + expect(s).toMatchObject({ credentials: 'include', authorization: `Bearer ${TOKEN}` }); + } + }); + + it.each(CALLS)('%s: a cookie session (no token stored) sends no Authorization header', async (_name, call) => { + await call().catch(() => undefined); + expect(sent.length).toBeGreaterThan(0); + for (const s of sent) { + expect(s).toMatchObject({ credentials: 'include', authorization: null }); + } + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/packages-io.duplicateEnvelope.test.ts b/ui/packages/app-shell/src/views/studio-design/packages-io.duplicateEnvelope.test.ts index 03fb3ea25b2..e4f68c32de7 100644 --- a/ui/packages/app-shell/src/views/studio-design/packages-io.duplicateEnvelope.test.ts +++ b/ui/packages/app-shell/src/views/studio-design/packages-io.duplicateEnvelope.test.ts @@ -34,13 +34,13 @@ import { duplicatePackage } from './packages-io'; /** The dispatcher's success envelope: the operation result under `data`. */ function envelope(data: unknown, status = 200) { - return { ok: status >= 200 && status < 300, status, json: async () => ({ success: true, data }) } as unknown as Response; + return { headers: new Headers(), ok: status >= 200 && status < 300, status, json: async () => ({ success: true, data }) } as unknown as Response; } /** The dispatcher's error envelope — top-level, with no `data` to unwrap. */ function errorEnvelope(status: number, message: string) { return { - ok: false, + headers: new Headers(), ok: false, status, json: async () => ({ success: false, error: { message, code: 'PERMISSION_DENIED', status } }), } as unknown as Response; @@ -177,7 +177,7 @@ describe('duplicatePackage — the operation verdict lives under `data`', () => it('falls back to the status when a non-2xx carries no readable body', async () => { stubFetch({ - ok: false, + headers: new Headers(), ok: false, status: 502, json: async () => { throw new SyntaxError('Unexpected token < in JSON at position 0'); diff --git a/ui/packages/app-shell/src/views/studio-design/packages-io.envelopeUserMessage.test.ts b/ui/packages/app-shell/src/views/studio-design/packages-io.envelopeUserMessage.test.ts index 679705b0b7c..fe5d59421aa 100644 --- a/ui/packages/app-shell/src/views/studio-design/packages-io.envelopeUserMessage.test.ts +++ b/ui/packages/app-shell/src/views/studio-design/packages-io.envelopeUserMessage.test.ts @@ -75,7 +75,7 @@ const CAPABILITY = 'Reading packages requires the `studio.access` or `setup.acce /** A failure exactly as `sendError` writes it — `{ code, message, ...extra }` under `error`. */ function failure(status: number, error: Record): Response { return { - ok: false, + headers: new Headers(), ok: false, status, json: async () => ({ success: false, error }), } as unknown as Response; @@ -84,7 +84,7 @@ function failure(status: number, error: Record): Response { /** The success shape: `sendOk` wraps the handler's `{ packages, total }`. */ function listOk(packages: unknown[]): Response { return { - ok: true, + headers: new Headers(), ok: true, status: 200, json: async () => ({ success: true, data: { packages, total: packages.length } }), } as unknown as Response; @@ -215,7 +215,7 @@ describe('fetchPackages — negative controls (GREEN with the fix reverted)', () */ it('§7 an unparseable body still names the status', async () => { stubFetch({ - ok: false, + headers: new Headers(), ok: false, status: 502, json: async () => { throw new SyntaxError("Unexpected token '<', \"\"... is not valid JSON"); @@ -271,7 +271,7 @@ describe('duplicatePackage — the same envelope, the same rule (#7959)', () => it('still falls back to the status when the body is unreadable', async () => { stubFetch({ - ok: false, + headers: new Headers(), ok: false, status: 502, json: async () => { throw new SyntaxError('Unexpected token < in JSON at position 0'); diff --git a/ui/packages/app-shell/src/views/studio-design/packages-io.ts b/ui/packages/app-shell/src/views/studio-design/packages-io.ts index 79e97774988..d3c93d77134 100644 --- a/ui/packages/app-shell/src/views/studio-design/packages-io.ts +++ b/ui/packages/app-shell/src/views/studio-design/packages-io.ts @@ -39,6 +39,12 @@ import { } from '@objectstack/spec/kernel'; import { readEnvelopeFailureText } from '../../utils/apiErrorEnvelope.js'; import { whenQuiet } from '../../observability/settleSignal.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} export interface PkgEntry { id: string; @@ -279,7 +285,7 @@ export interface EnsuredCustomizationPackage { * else in the app announces it. */ export async function ensureCustomizationPackage(baseId: string): Promise { - const res = await fetch(`/api/v1/packages/${encodeURIComponent(baseId)}/ensure-customization`, { + const res = await authFetch(`/api/v1/packages/${encodeURIComponent(baseId)}/ensure-customization`, { method: 'POST', credentials: 'include', headers: { Accept: 'application/json' }, @@ -389,7 +395,7 @@ function readPackagesPayload(): Promise { const pending = pendingPackageReads.get(transport); if (pending) return pending; const read = (async () => { - const res = await fetch('/api/v1/packages', { + const res = await authFetch('/api/v1/packages', { credentials: 'include', headers: { Accept: 'application/json' }, cache: 'no-store', @@ -576,7 +582,7 @@ export async function duplicatePackage(sourceId: string, targetId: string, targe // before it, so a read asked after it must not join that one, nor be answered // by the session's held list (objectstack#29119). Forgotten however // the write ends: a failed duplicate may still have copied part of a package. - const res = await fetch(`/api/v1/packages/${encodeURIComponent(sourceId)}/duplicate`, { + const res = await authFetch(`/api/v1/packages/${encodeURIComponent(sourceId)}/duplicate`, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json', Accept: 'application/json' },