From 26debb528988c3deef1d5ccea78298a3454d651e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:01:13 +0000 Subject: [PATCH 1/7] fix(ui): plugin same-server reads ride the host's authenticated fetch; me/localization carries the stored bearer The share dialog and the chatbot hooks (agents, models, pending actions, in-chat approvals) send through SchemaRendererProvider's apiFetch, the field selector read goes through createAuthenticatedFetch, and the me/localization boot read states the stored bearer in its init on all three legs (index.html, the seed, the provider). Claude-Session: https://claude.ai/code/session_01Utp6Ca6EBDpTBZk8v46Jjv Co-authored-by: Claude --- ui/apps/console/index.html | 9 ++- .../console/src/LocalizationFetchProvider.tsx | 22 +++--- ui/apps/console/src/languageSeed.ts | 68 ++++++++++++++++--- .../src/views/metadata-admin/widgets.tsx | 11 ++- .../components/src/share/ShareDialog.tsx | 26 +++++-- ui/packages/plugin-chatbot/src/useAgents.ts | 26 +++++-- ui/packages/plugin-chatbot/src/useAiModels.ts | 20 +++++- .../plugin-chatbot/src/useHitlInChat.ts | 15 +++- .../plugin-chatbot/src/usePendingActions.ts | 30 ++++++-- 9 files changed, 181 insertions(+), 46 deletions(-) diff --git a/ui/apps/console/index.html b/ui/apps/console/index.html index 009d301217f..dd99021a50e 100644 --- a/ui/apps/console/index.html +++ b/ui/apps/console/index.html @@ -279,7 +279,9 @@ The request is the seed's byte for byte: the same URL (the server origin through the same Vite HTML env substitution as the scripts above), - `credentials: 'include'`, the same `Accept`, and the same + `credentials: 'include'`, the same `Accept`, the stored Bearer from the + same `localStorage` key when there is one (objectstack#37225: a session + held by its bearer alone is otherwise answered as anonymous), and the same `Accept-Language`: the browser's language in the app's own spelling when discovery `locale.supported` lists it, else none (ruling 6915665005, objectstack#34392). "Lists it" is the platform's one locale ladder, @@ -353,6 +355,11 @@ const preferred = browser ? resolveAmong(browser, supported) : undefined; const headers = { Accept: 'application/json' }; if (preferred) headers['Accept-Language'] = preferred; + let token = ''; + try { + token = localStorage.getItem('auth-session-token') || ''; + } catch (_) { /* storage blocked: no Bearer, as in the seed */ } + if (token) headers.Authorization = 'Bearer ' + token; slot.init = { credentials: 'include', headers: headers }; slot.response = fetch(slot.url, slot.init); // The seed reads a failure as its own request's; it is never unhandled. diff --git a/ui/apps/console/src/LocalizationFetchProvider.tsx b/ui/apps/console/src/LocalizationFetchProvider.tsx index 47bddbd992e..879f4a79e32 100644 --- a/ui/apps/console/src/LocalizationFetchProvider.tsx +++ b/ui/apps/console/src/LocalizationFetchProvider.tsx @@ -90,6 +90,15 @@ * lists that language; else the organization's `localization.locale`, then * the app's declared default, decide — the rungs the same ruling puts below * the browser's language, which only the server can read. + * + * ## The stored Bearer rides it (objectstack#37225) + * + * Under a session held by its bearer token alone, a cookie-only read was + * answered `{ authenticated: false }`: no currency, locale or zone of the + * user's. The read's init is `meLocalizationInit` (`languageSeed.ts`), which + * states the stored Bearer exactly as the seed and `index.html`'s parse-time + * request do, so the three still share one request; why the Bearer goes in the + * init rather than through `createAuthenticatedFetch` is written there. */ import { useEffect, useState } from 'react'; import { @@ -100,7 +109,7 @@ import { type LocalizationValue, } from '@object-ui/i18n'; import { getSessionOwnerChangeCount, useAuth } from '@object-ui/auth'; -import { startedPreferredLocale, takeSettledSeedAnswer } from './languageSeed'; +import { meLocalizationInit, startedPreferredLocale, takeSettledSeedAnswer } from './languageSeed'; import { useDataInvalidation } from '@object-ui/react'; import { HttpFetchError, @@ -177,14 +186,9 @@ export function LocalizationFetchProvider({ // before — including `Retry-After` — so the retry policy below is // untouched, and a shared 503 reaches BOTH callers rather than // resolving one of them empty. - const init: RequestInit = { - credentials: 'include', - headers: { - Accept: 'application/json', - ...(preference ? { 'Accept-Language': preference } : {}), - }, - signal: reread?.signal, - }; + // The seed's own init (the stored Bearer included), plus this read's + // signal, which is no part of the in-flight key. + const init: RequestInit = { ...meLocalizationInit(preference), signal: reread?.signal }; // The boot read's first attempt takes the seed's answer to this very // request when it settled earlier in this page load // (objectstack#35455); a re-read never does. diff --git a/ui/apps/console/src/languageSeed.ts b/ui/apps/console/src/languageSeed.ts index 24cff0b1d7a..60bfa3d0c87 100644 --- a/ui/apps/console/src/languageSeed.ts +++ b/ui/apps/console/src/languageSeed.ts @@ -109,6 +109,23 @@ * `sharedGetJson` call, so the race, the in-flight sharing with * `LocalizationFetchProvider` and the hand-off of the settled answer are * unchanged. + * + * ## The stored Bearer rides it (objectstack#37225) + * + * A session held by its bearer token alone (no session cookie: a cross-site + * embed, a blocked third-party cookie) was answered `{ authenticated: false }` + * by a cookie-only read, so its seed and its regional defaults were never the + * user's. Every read of this endpoint states the stored Bearer, through + * {@link meLocalizationInit}: the parse-time request (`index.html` reads the + * same `localStorage` key), the seed and `LocalizationFetchProvider`. + * + * In the init, by hand, and not through `createAuthenticatedFetch`: the + * in-flight key is built from the init, so a header the transport adds would + * not be part of it, and that transport also stamps `` as + * `Accept-Language` on a read that deliberately states none (objectstack#34392). + * The endpoint answers a caller it cannot see `{ authenticated: false }`, never + * `401`, so no session-ended signal is lost. `early-discovery.ts` carries the + * Bearer the same way, for the same parse-time hand-off. */ import { cacheLanguageSeed, readCachedLanguageSeed, readStoredLanguage } from '@object-ui/i18n'; import { getSessionOwnerChangeCount } from '@object-ui/auth'; @@ -129,6 +146,41 @@ interface MeLocalizationResponse { locale?: string | null; } +/** + * The Bearer every console request carries, `''` when there is none or storage + * is blocked: the key `createAuthenticatedFetch` reads (`TokenStorage`), read + * here as `index.html` and `early-discovery.ts` read it. + */ +const TOKEN_KEY = 'auth-session-token'; + +function storedToken(): string { + try { + return localStorage.getItem(TOKEN_KEY) || ''; + } catch { + return ''; + } +} + +/** + * The init every read of `GET /api/v1/auth/me/localization` sends: the cookie + * (`credentials: 'include'`), `Accept`, the stated language when there is one, + * and the stored Bearer when there is one. The seed, `LocalizationFetchProvider` + * and `index.html`'s parse-time request share a request only while their inits + * match (`inflightGetKey`: URL, credentials and headers), so this is the one + * spelling of it in the bundle; `index.html` spells it again by hand. + */ +export function meLocalizationInit(preferred: string | undefined): RequestInit { + const token = storedToken(); + return { + credentials: 'include', + headers: { + Accept: 'application/json', + ...(preferred ? { 'Accept-Language': preferred } : {}), + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + }; +} + /** This page-load's read of the language a choice-less read states, once started. */ let preferredLocale: Promise | null = null; @@ -304,17 +356,11 @@ async function fetchAndCacheSeed(serverBase: string): Promise { // the provider mounts as soon as the race resolves. Sharing is in-flight // only, so on the boots where they do NOT overlap each still fetches. const url = `${serverBase}/api/v1/auth/me/localization`; - const init: RequestInit = { - credentials: 'include', - headers: { - Accept: 'application/json', - // A supported browser language decides the rung below the user's - // own locale (objectstack#33985); otherwise the browser's own header - // goes, and the server's deployment default decides - // (objectstack#34392). - ...(preferred ? { 'Accept-Language': preferred } : {}), - }, - }; + // A supported browser language decides the rung below the user's own + // locale (objectstack#33985); otherwise the browser's own header goes, and + // the server's deployment default decides (objectstack#34392). The stored + // Bearer rides along (objectstack#37225). + const init = meLocalizationInit(preferred); // `index.html` usually sent this very request at parse time // (objectstack#35534): it is taken here as this read's transport, so the // provider still joins it in flight and a failure is this read's own. diff --git a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx index 71e8293c608..5fe4d4f7c79 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx @@ -52,6 +52,7 @@ import { AlertTriangle, ChevronDown, ChevronsUpDown, ChevronUp, Eye, EyeOff, Plu import { iconNames } from 'lucide-react/dynamic.mjs'; import { toast } from 'sonner'; import { useObjectTranslation } from '@object-ui/i18n'; +import { createAuthenticatedFetch } from '@object-ui/auth'; import { useMetadataLocale, t, tFormat } from './i18n.js'; import { fieldHistoryChoiceOf, fieldHistoryOptions, fieldHistoryValueOf } from './fieldHistoryChoice.js'; import { isKnownViewType, viewTypeLabel } from './viewTypeLabels.js'; @@ -1198,9 +1199,17 @@ const EMPTY_FIELD_SELECTOR_OPTIONS: FieldSelectorOption[] = []; * other raw-`fetch` callers in this package already use (`useRecordApprovals`, * `suggestedBindingsApi`, `studio-design/packages-io`): the server's own * message when it sent one, otherwise the status. + * + * The read goes through the console's authenticated fetch, built per call, with + * `credentials: 'include'`: a bare `fetch` with no init sends the session cookie + * alone (the default `same-origin` credentials), so a session held by its bearer + * token alone was answered as anonymous and a `401` never reached the console's + * session-ended check. */ async function fetchFieldSelectorOptions(objectName: string): Promise { - const res = await fetch(`/api/v1/objects/${objectName}/fields`); + const res = await createAuthenticatedFetch()(`/api/v1/objects/${objectName}/fields`, { + credentials: 'include', + }); // Read the body BEFORE branching on `ok`: a refusal usually carries the more // useful sentence, and a non-JSON body must not be mistaken for a refusal // that said nothing (it still throws below — it just cannot add a cause). diff --git a/ui/packages/components/src/share/ShareDialog.tsx b/ui/packages/components/src/share/ShareDialog.tsx index d45bd4397af..2dcb8ef2478 100644 --- a/ui/packages/components/src/share/ShareDialog.tsx +++ b/ui/packages/components/src/share/ShareDialog.tsx @@ -16,9 +16,10 @@ * `apiBase`, `objectName`, and `recordId`. */ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useContext, useEffect, useMemo, useState } from 'react'; import { Copy, Link2, Loader2, ShieldOff, Trash2 } from 'lucide-react'; import { useObjectTranslation } from '@object-ui/i18n'; +import { SchemaRendererContext } from '@object-ui/react'; import type { ShareLink as SpecShareLink, ShareLinkAudience, @@ -199,6 +200,14 @@ export function ShareDialog({ const [error, setError] = useState(null); const [draft, setDraft] = useState(DEFAULT_DRAFT); const [justCopied, setJustCopied] = useState(null); + // Every request rides the host's AUTHENTICATED fetch (`SchemaRendererProvider`'s + // `apiFetch`), the channel the renderers' own reads use: a session held by its + // bearer token alone carries no cookie, so `credentials: 'include'` on the bare + // global fetch read as anonymous and the dialog listed, created and revoked + // nothing, while a `401` never reached the host's session-ended check. Read the + // context directly (not `useSchemaContext`, which throws with no provider): a + // host that mounts none keeps the global fetch, cookies included. + const apiFetch = useContext(SchemaRendererContext)?.apiFetch; const headers = useCallback(async (): Promise> => { const base: Record = { 'Content-Type': 'application/json' }; @@ -220,7 +229,8 @@ export function ShareDialog({ setError(null); try { const h = await headers(); - const res = await fetch(listUrl, { headers: h, credentials: 'include' }); + const doFetch = apiFetch ?? fetch; + const res = await doFetch(listUrl, { headers: h, credentials: 'include' }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const body = (await res.json()) as { links?: ShareLink[]; data?: ShareLink[] }; setLinks(body.links ?? body.data ?? []); @@ -229,7 +239,7 @@ export function ShareDialog({ } finally { setLoading(false); } - }, [listUrl, headers]); + }, [listUrl, headers, apiFetch]); useEffect(() => { if (open) { @@ -247,7 +257,8 @@ export function ShareDialog({ ? undefined : new Date(Date.now() + draft.expiresInDays * 24 * 60 * 60 * 1000).toISOString(); const h = await headers(); - const res = await fetch(`${apiBase.replace(/\/+$/, '')}/v1/share-links`, { + const doFetch = apiFetch ?? fetch; + const res = await doFetch(`${apiBase.replace(/\/+$/, '')}/v1/share-links`, { method: 'POST', headers: h, credentials: 'include', @@ -281,13 +292,14 @@ export function ShareDialog({ } finally { setCreating(false); } - }, [apiBase, headers, objectName, recordId, draft, publicBaseUrl]); + }, [apiBase, headers, objectName, recordId, draft, publicBaseUrl, apiFetch]); const handleRevoke = useCallback( async (link: ShareLink) => { try { const h = await headers(); - const res = await fetch( + const doFetch = apiFetch ?? fetch; + const res = await doFetch( `${apiBase.replace(/\/+$/, '')}/v1/share-links/${encodeURIComponent(link.id)}`, { method: 'DELETE', headers: h, credentials: 'include' }, ); @@ -303,7 +315,7 @@ export function ShareDialog({ setError({ message: err?.message, step: 'revoke' }); } }, - [apiBase, headers], + [apiBase, headers, apiFetch], ); const handleCopy = useCallback( diff --git a/ui/packages/plugin-chatbot/src/useAgents.ts b/ui/packages/plugin-chatbot/src/useAgents.ts index 57a544ccb84..032e8905704 100644 --- a/ui/packages/plugin-chatbot/src/useAgents.ts +++ b/ui/packages/plugin-chatbot/src/useAgents.ts @@ -6,11 +6,13 @@ * (`@objectstack/service-ai`) backend. * * The hook hits `GET {apiBase}/agents` (the canonical endpoint exposed by - * `buildAgentRoutes`) and returns a normalized list. It is intentionally - * dependency-free (uses `fetch`) so the chatbot package can stay light. + * `buildAgentRoutes`) and returns a normalized list. It asks through the host's + * `apiFetch`, else the global `fetch` (see {@link useAgents}), and imports no + * HTTP client, so the chatbot package can stay light. */ -import { useEffect, useRef, useState, useCallback } from 'react'; +import { useContext, useEffect, useRef, useState, useCallback } from 'react'; +import { SchemaRendererContext, type ApiFetch } from '@object-ui/react'; import { resolveAgentParam, isBuildAgent } from './agentAliases'; /** @@ -241,6 +243,7 @@ function fetchAgentsCached( apiBase: string, headers: Record | undefined, force: boolean, + doFetch: ApiFetch, ): Promise { if (force) { agentsCache.delete(apiBase); @@ -255,7 +258,7 @@ function fetchAgentsCached( if (inFlight && !force) return inFlight; const url = `${apiBase.replace(/\/$/, '')}/agents`; - const promise = fetch(url, { + const promise = doFetch(url, { method: 'GET', headers: { Accept: 'application/json', ...(headers ?? {}) }, credentials: 'include', @@ -334,6 +337,13 @@ export function __resetAgentsCatalog(): void { /** * Fetches the active agent catalog from the backend. * + * Every request rides the host's AUTHENTICATED fetch (`SchemaRendererProvider`'s + * `apiFetch`), the channel the renderers' own reads use: a session held by its + * bearer token alone carries no cookie, so `credentials: 'include'` on the bare + * global fetch read as anonymous, and a `401` never reached the host's + * session-ended check. A host that mounts no provider keeps the global fetch, + * cookies included. + * * The request leaves after the first frame has painted (objectui#12980), not * in the mounting commit — see {@link afterCatalogFrame}. * @@ -352,6 +362,12 @@ export function useAgents(options: UseAgentsOptions = {}): UseAgentsReturn { // triggering a refetch on every render. const headersRef = useRef(headers); headersRef.current = headers; + // The host's authenticated fetch, or the global one with no provider: read + // directly (not `useSchemaContext`, which throws with no provider). Held in a + // ref like the headers: the catalog is one answer per `apiBase`. + const apiFetch = useContext(SchemaRendererContext)?.apiFetch; + const fetchRef = useRef(apiFetch ?? fetch); + fetchRef.current = apiFetch ?? fetch; useEffect(() => { if (!enabled || !apiBase) return; @@ -362,7 +378,7 @@ export function useAgents(options: UseAgentsOptions = {}): UseAgentsReturn { setIsLoading(true); setError(undefined); - fetchAgentsCached(apiBase, headersRef.current, reloadToken > 0) + fetchAgentsCached(apiBase, headersRef.current, reloadToken > 0, fetchRef.current) .then((normalized) => { if (cancelled) return; setAgents(normalized.length > 0 ? normalized : fallback); diff --git a/ui/packages/plugin-chatbot/src/useAiModels.ts b/ui/packages/plugin-chatbot/src/useAiModels.ts index 1040d4df22e..e71a5d10822 100644 --- a/ui/packages/plugin-chatbot/src/useAiModels.ts +++ b/ui/packages/plugin-chatbot/src/useAiModels.ts @@ -10,10 +10,12 @@ * default model id. Free / single-model envs return one entry, so the footer * picker (which `ChatbotEnhanced` renders only for 2+ models) stays hidden. * - * Intentionally dependency-free (uses `fetch`), mirroring {@link useAgents}. + * It asks through the host's `apiFetch`, else the global `fetch`, and imports no + * HTTP client, mirroring {@link useAgents}. */ -import { useEffect, useRef, useState, useCallback } from 'react'; +import { useContext, useEffect, useRef, useState, useCallback } from 'react'; +import { SchemaRendererContext, type ApiFetch } from '@object-ui/react'; import type { ChatbotModelOption } from './ChatbotEnhanced'; export interface UseAiModelsOptions { @@ -83,6 +85,13 @@ function normalize(raw: RawModel[]): ChatbotModelOption[] { /** * Fetch the AI-model allowlist for the current environment. * + * Every request rides the host's AUTHENTICATED fetch (`SchemaRendererProvider`'s + * `apiFetch`), the channel the renderers' own reads use: a session held by its + * bearer token alone carries no cookie, so `credentials: 'include'` on the bare + * global fetch read as anonymous, and a `401` never reached the host's + * session-ended check. A host that mounts no provider keeps the global fetch, + * cookies included. + * * @example * const { models, defaultModelId } = useAiModels({ apiBase: '/api/v1/ai' }); */ @@ -99,6 +108,11 @@ export function useAiModels(options: UseAiModelsOptions = {}): UseAiModelsReturn // triggering a refetch on every render. const headersRef = useRef(headers); headersRef.current = headers; + // The host's authenticated fetch, or the global one with no provider (see the + // hook's doc). Held in a ref like the headers. + const apiFetch = useContext(SchemaRendererContext)?.apiFetch; + const fetchRef = useRef(apiFetch ?? fetch); + fetchRef.current = apiFetch ?? fetch; useEffect(() => { if (!enabled || !apiBase) return; @@ -121,7 +135,7 @@ export function useAiModels(options: UseAiModelsOptions = {}): UseAiModelsReturn setIsLoading(true); setError(undefined); try { - const res = await fetch(url, { + const res = await fetchRef.current(url, { method: 'GET', headers: { Accept: 'application/json', ...(headersRef.current ?? {}) }, credentials: 'include', diff --git a/ui/packages/plugin-chatbot/src/useHitlInChat.ts b/ui/packages/plugin-chatbot/src/useHitlInChat.ts index 4d1bcebef98..a8a3f363ec1 100644 --- a/ui/packages/plugin-chatbot/src/useHitlInChat.ts +++ b/ui/packages/plugin-chatbot/src/useHitlInChat.ts @@ -34,8 +34,16 @@ * toolDecisions={hitl.decisions} * /> * ``` + * + * The decision rides the host's AUTHENTICATED fetch (`SchemaRendererProvider`'s + * `apiFetch`), the channel the renderers' own reads use: a session held by its + * bearer token alone carries no cookie, so `credentials: 'include'` on the bare + * global fetch was answered as anonymous, and a `401` never reached the host's + * session-ended check. A host that mounts no provider keeps the global fetch, + * cookies included. */ import * as React from 'react'; +import { SchemaRendererContext } from '@object-ui/react'; import type { ChatbotEnhancedMessage as ChatMessage, ToolDecisionState } from './ChatbotEnhanced'; import type { ApproveOutcome, RejectOutcome } from './usePendingActions'; import { hitlContinuationTag } from './hitlContinuation'; @@ -159,6 +167,8 @@ async function parseJson(response: Response): Promise | export function useHitlInChat(options: UseHitlInChatOptions): UseHitlInChatReturn { const { messages, apiBase, headers, onDecided, continueConversation } = options; const base = normalizeBase(apiBase); + // Read directly, not via `useSchemaContext`, which throws with no provider. + const apiFetch = React.useContext(SchemaRendererContext)?.apiFetch; // Index toolCallId → { pendingActionId, toolName } from the latest // messages. Memoised because messages stream tick-by-tick and we don't @@ -224,7 +234,8 @@ export function useHitlInChat(options: UseHitlInChatOptions): UseHitlInChatRetur approved ? 'approve' : 'reject' }`; const body = approved ? '{}' : JSON.stringify({ reason: reason ?? '' }); - const response = await fetch(url, { + const doFetch = apiFetch ?? fetch; + const response = await doFetch(url, { method: 'POST', credentials: 'include', headers: buildHeaders(headers, true), @@ -319,7 +330,7 @@ export function useHitlInChat(options: UseHitlInChatOptions): UseHitlInChatRetur } } }, - [base, headers, idMap, onDecided, continueConversation, setDecision], + [base, headers, apiFetch, idMap, onDecided, continueConversation, setDecision], ); return { decisions, decide, isDeciding }; diff --git a/ui/packages/plugin-chatbot/src/usePendingActions.ts b/ui/packages/plugin-chatbot/src/usePendingActions.ts index b1dec0e6e0b..d4105048213 100644 --- a/ui/packages/plugin-chatbot/src/usePendingActions.ts +++ b/ui/packages/plugin-chatbot/src/usePendingActions.ts @@ -29,6 +29,7 @@ */ import * as React from 'react'; +import { SchemaRendererContext, type ApiFetch } from '@object-ui/react'; import type { ApproveAiPendingActionResponse, @@ -177,11 +178,12 @@ function buildUrl(base: string, path: string, params?: Record( + doFetch: ApiFetch, url: string, init: RequestInit, extraHeaders: Record | undefined, ): Promise { - const res = await fetch(url, { + const res = await doFetch(url, { credentials: 'include', ...init, headers: { @@ -301,6 +303,13 @@ function settlePoll( * transient failure backs it off, doubling up to a ceiling. A read that * succeeds resumes the normal cadence (objectui#11736; see `ListReadOutcome`). * + * Every request rides the host's AUTHENTICATED fetch (`SchemaRendererProvider`'s + * `apiFetch`), the channel the renderers' own reads use: a session held by its + * bearer token alone carries no cookie, so `credentials: 'include'` on the bare + * global fetch read as anonymous, and a `401` never reached the host's + * session-ended check. A host that mounts no provider keeps the global fetch, + * cookies included. + * * @example * ```tsx * const { items, isLoading, error, approve, reject, refresh } = @@ -331,8 +340,13 @@ export function usePendingActions( // Stash mutable bits in a ref so the polling effect doesn't re-arm on // every header object identity change. - const cfgRef = React.useRef({ apiBase, status, conversationId, limit, headers }); - cfgRef.current = { apiBase, status, conversationId, limit, headers }; + // The transport rides with them: the host's authenticated fetch, or the + // global one with no provider (see the hook's doc). Read directly, not via + // `useSchemaContext`, which throws with no provider. + const apiFetch = React.useContext(SchemaRendererContext)?.apiFetch; + const doFetch: ApiFetch = apiFetch ?? fetch; + const cfgRef = React.useRef({ apiBase, status, conversationId, limit, headers, doFetch }); + cfgRef.current = { apiBase, status, conversationId, limit, headers, doFetch }; const pollRef = React.useRef({ generation: 0, @@ -346,7 +360,7 @@ export function usePendingActions( const refresh = React.useCallback(async function load(): Promise { const poll = pollRef.current; const generation = poll.generation; - const { apiBase, status, conversationId, limit, headers } = cfgRef.current; + const { apiBase, status, conversationId, limit, headers, doFetch } = cfgRef.current; setIsLoading(true); setError(undefined); let outcome: ListReadOutcome = 'ok'; @@ -357,6 +371,7 @@ export function usePendingActions( limit, }); const out = await call<{ items: PendingActionRow[]; total?: number }>( + doFetch, url, { method: 'GET' }, headers, @@ -381,10 +396,10 @@ export function usePendingActions( refreshRef.current = refresh; const approve = React.useCallback(async (id: string): Promise => { - const { apiBase, headers } = cfgRef.current; + const { apiBase, headers, doFetch } = cfgRef.current; const url = buildUrl(apiBase, `/pending-actions/${encodeURIComponent(id)}/approve`); try { - const out = await call(url, { method: 'POST', body: '{}' }, headers); + const out = await call(doFetch, url, { method: 'POST', body: '{}' }, headers); return out; } finally { void refresh(); @@ -392,10 +407,11 @@ export function usePendingActions( }, [refresh]); const reject = React.useCallback(async (id: string, reason?: string): Promise => { - const { apiBase, headers } = cfgRef.current; + const { apiBase, headers, doFetch } = cfgRef.current; const url = buildUrl(apiBase, `/pending-actions/${encodeURIComponent(id)}/reject`); try { const out = await call( + doFetch, url, { method: 'POST', body: JSON.stringify(reason ? { reason } : {}) }, headers, From cbcd3158e291211f53b98c7b7efd003e87f1bce0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:09:42 +0000 Subject: [PATCH 2/7] test(ui): widen the bearer ratchet to every ui package; pin the renderer reads under a bearer-only session Claude-Session: https://claude.ai/code/session_01Utp6Ca6EBDpTBZk8v46Jjv Co-authored-by: Claude --- ...rendererFetch.bearerSession-37225.test.tsx | 184 ++++++++++++++++++ .../sameServerFetch.bearer.ratchet.test.ts | 136 +++++++++++-- 2 files changed, 299 insertions(+), 21 deletions(-) create mode 100644 ui/packages/app-shell/src/console/rendererFetch.bearerSession-37225.test.tsx diff --git a/ui/packages/app-shell/src/console/rendererFetch.bearerSession-37225.test.tsx b/ui/packages/app-shell/src/console/rendererFetch.bearerSession-37225.test.tsx new file mode 100644 index 00000000000..1400c2b6533 --- /dev/null +++ b/ui/packages/app-shell/src/console/rendererFetch.bearerSession-37225.test.tsx @@ -0,0 +1,184 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The renderer packages' same-server requests ride the host's authenticated + * fetch (objectstack#37225): the share dialog (`@object-ui/components`) and the + * chatbot hooks (`@object-ui/plugin-chatbot`) send through + * `SchemaRendererProvider`'s `apiFetch`, which the console builds as + * `createAuthenticatedFetch({ sameOriginOnly: true })` (`ConsoleShell`). + * + * The defect: each sent the bare global `fetch` with `credentials: 'include'`, + * the session cookie and nothing else. A session held by its bearer token alone + * (no cookie: a cross-site embed, a blocked third-party cookie) was answered as + * anonymous: no share links, no agents, no models, no pending approvals, and an + * in-chat approval refused. Against a server that refuses any request without + * the bearer, mounted the way the console mounts them: + * + * - with a token stored, each loads (or decides), and its request carries + * `Authorization: Bearer ` beside the cookie (`credentials: 'include'`), + * and a `401` reaches the console's session-ended check; + * - CONTROL, no token stored (a cookie session): the same requests go out + * cookie-only, as before. + */ + +import type { ReactNode } from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, render, renderHook, screen, waitFor } from '@testing-library/react'; +import { SchemaRendererProvider } from '@object-ui/react'; +import { TokenStorage, createAuthenticatedFetch } from '@object-ui/auth'; +import { sessionEndEvents } from '../../../auth/src/session-end-events'; +import { ShareDialog } from '@object-ui/components'; +import { useAgents, useAiModels, useHitlInChat, usePendingActions } from '@object-ui/plugin-chatbot'; +import { __resetAgentsCatalog } from '../../../plugin-chatbot/src/useAgents'; +import { resetAiModelsSession } from '../../../plugin-chatbot/src/useAiModels'; + +const TOKEN = 'stored-session-token'; +const AI = '/api/v1/ai'; + +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[] = []; + +function answer(path: string, method: string): Response { + if (path === '/api/v1/share-links' && method === 'GET') { + return reply({ links: [{ id: 'sl_1', token: 'tok_1', permission: 'view', audience: 'link_only', label: 'Board review link' }] }); + } + if (path === `${AI}/agents`) return reply({ agents: [{ name: 'helper', label: 'Helper', active: true }] }); + if (path === `${AI}/models`) { + return reply({ models: [{ id: 'm_fast', label: 'Fast' }, { id: 'm_deep', label: 'Deep' }], defaultModelId: 'm_fast' }); + } + if (path === `${AI}/pending-actions` && method === 'GET') { + return reply({ items: [{ id: 'pa_1', toolName: 'delete_record', status: 'pending' }], total: 1 }); + } + if (path === `${AI}/pending-actions/pa_1/approve` && method === 'POST') { + return reply({ id: 'pa_1', status: 'executed', result: { ok: true } }); + } + return reply({ 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 instanceof Request ? input.url : 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: { code: 'UNAUTHENTICATED', message: 'Authentication is required to access this endpoint.' } }, 401); + } + return answer(path, method); +} + +/** The console's composition: the renderers' `apiFetch` is the authenticated fetch (`ConsoleShell`). */ +const hostFetch = createAuthenticatedFetch({ sameOriginOnly: true }); +const wrapper = ({ children }: { children: ReactNode }) => ( + + {children} + +); + +const withBearer = { credentials: 'include', authorization: `Bearer ${TOKEN}` } as const; +const cookieOnly = { credentials: 'include', authorization: null } as const; + +let sessionEnds = 0; +let unsubscribe: () => void = () => {}; + +beforeEach(() => { + sent = []; + sessionEnds = 0; + unsubscribe = sessionEndEvents.subscribe(() => { + sessionEnds += 1; + }); + __resetAgentsCatalog(); + resetAiModelsSession(); + vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => bearerOnlyServer(input, init))); +}); + +afterEach(() => { + cleanup(); + unsubscribe(); + __resetAgentsCatalog(); + resetAiModelsSession(); + vi.unstubAllGlobals(); + TokenStorage.clear(); +}); + +describe('the share dialog (components) under a bearer-only session', () => { + const dialog = () => + render( + {}} objectName="ai_conversations" recordId="c1" apiBase="/api" />, + { wrapper }, + ); + + it("lists the record's links, sending the stored bearer beside the cookie", async () => { + TokenStorage.set(TOKEN); + dialog(); + expect(await screen.findByText('Board review link')).toBeTruthy(); + expect(sent).toEqual([{ path: '/api/v1/share-links', method: 'GET', ...withBearer }]); + }); + + it('CONTROL: with no token stored the read goes out cookie-only, and its 401 reaches the session-ended check', async () => { + dialog(); + expect(await screen.findByTestId('share-dialog-error')).toBeTruthy(); + expect(sent).toEqual([{ path: '/api/v1/share-links', method: 'GET', ...cookieOnly }]); + expect(sessionEnds).toBe(1); + }); +}); + +describe('the chatbot hooks (plugin-chatbot) under a bearer-only session', () => { + it('useAgents loads the agent catalog with the stored bearer', async () => { + TokenStorage.set(TOKEN); + const { result } = renderHook(() => useAgents({ apiBase: AI }), { wrapper }); + await waitFor(() => expect(result.current.agents.map((a) => a.name)).toEqual(['helper'])); + expect(sent).toEqual([{ path: `${AI}/agents`, method: 'GET', ...withBearer }]); + }); + + it('useAiModels loads the model allowlist with the stored bearer', async () => { + TokenStorage.set(TOKEN); + const { result } = renderHook(() => useAiModels({ apiBase: AI }), { wrapper }); + await waitFor(() => expect(result.current.models.map((m) => m.id)).toEqual(['m_fast', 'm_deep'])); + expect(sent).toEqual([{ path: `${AI}/models`, method: 'GET', ...withBearer }]); + }); + + it('usePendingActions lists and approves with the stored bearer', async () => { + TokenStorage.set(TOKEN); + const { result } = renderHook(() => usePendingActions({ apiBase: AI, pollInterval: 0 }), { wrapper }); + await waitFor(() => expect(result.current.items.map((row) => row.id)).toEqual(['pa_1'])); + await act(async () => { + await result.current.approve('pa_1'); + }); + expect(sent.slice(0, 2)).toEqual([ + { path: `${AI}/pending-actions`, method: 'GET', ...withBearer }, + { path: `${AI}/pending-actions/pa_1/approve`, method: 'POST', ...withBearer }, + ]); + expect(sent.every((request) => request.authorization === `Bearer ${TOKEN}`)).toBe(true); + }); + + it('useHitlInChat sends the in-chat approval with the stored bearer', async () => { + TokenStorage.set(TOKEN); + const messages = [ + { + id: 'm1', + role: 'assistant' as const, + content: '', + toolInvocations: [ + { toolCallId: 'call_1', toolName: 'delete_record', pendingActionId: 'pa_1', state: 'approval-requested' as const }, + ], + }, + ]; + const { result } = renderHook(() => useHitlInChat({ messages: messages as never, apiBase: AI }), { wrapper }); + await act(async () => { + await result.current.decide('call_1', true); + }); + expect(sent).toEqual([{ path: `${AI}/pending-actions/pa_1/approve`, method: 'POST', ...withBearer }]); + expect(result.current.decisions.call_1?.state).not.toBe('error'); + }); + + it('CONTROL: with no token stored the agent read goes out cookie-only, refused as before', async () => { + const { result } = renderHook(() => useAgents({ apiBase: AI }), { wrapper }); + await waitFor(() => expect(result.current.error).toBeDefined()); + expect(sent).toEqual([{ path: `${AI}/agents`, method: 'GET', ...cookieOnly }]); + expect(sessionEnds).toBe(1); + }); +}); diff --git a/ui/packages/app-shell/src/sameServerFetch.bearer.ratchet.test.ts b/ui/packages/app-shell/src/sameServerFetch.bearer.ratchet.test.ts index 58d61183e01..88800256e11 100644 --- a/ui/packages/app-shell/src/sameServerFetch.bearer.ratchet.test.ts +++ b/ui/packages/app-shell/src/sameServerFetch.bearer.ratchet.test.ts @@ -9,7 +9,8 @@ /** * 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. + * `fetch`, in the console and in every `ui/packages/*` source tree (app-shell, + * and since objectstack#37225 the renderer packages beside it). * * The defect this closes: a bare `fetch('/api/…', { credentials: 'include' })` * carries the session cookie and nothing else. A session held by its bearer @@ -27,18 +28,32 @@ * 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. + * `credentials: 'include'`. The URL is not judged there: 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. + * Also bare (objectstack#37225): the global `fetch` on a written `/api/` path + * with NO init, or an inline init that names no `credentials` — the default + * `same-origin` credentials send the cookie alone just the same. Here the URL is + * the only evidence the request is the server's, so it has to be written out. + * + * The renderer packages (`components`, `fields`, `plugin-*`, …) do not import + * `@object-ui/auth`: their channel is the host's authenticated fetch, handed + * down as `SchemaRendererProvider`'s `apiFetch` (the console's is + * `createAuthenticatedFetch({ sameOriginOnly: true })`), read straight off + * `SchemaRendererContext` and falling back to the global `fetch` only in a host + * that mounts none. App-shell and the console build `createAuthenticatedFetch` + * per call. + * + * If this fails on a new call: route it through the host's `apiFetch` (a + * renderer package) or `createAuthenticatedFetch` (app-shell, the console; + * `{ 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 { existsSync, readdirSync, readFileSync } from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import ts from 'typescript'; @@ -46,23 +61,34 @@ import ts from 'typescript'; const HERE = path.dirname(fileURLToPath(import.meta.url)); /** `ui/packages/app-shell/src` */ const APP_SHELL_SRC = HERE; +/** `ui/packages`, whose every package's `src` is scanned. */ +const PACKAGES_ROOT = path.resolve(HERE, '../..'); /** `ui/apps/console/src` */ const CONSOLE_SRC = path.resolve(HERE, '../../../apps/console/src'); -/** Both trees' paths are written relative to `ui/`. */ +/** Every tree's paths are written relative to `ui/`. */ const UI_ROOT = path.resolve(HERE, '../../..'); +/** + * The renderer packages objectstack#37225 named: each must be read, so a scan + * that silently lost one of them fails here rather than passing over it. + */ +const RENDERER_PACKAGES = [ + 'components', + 'fields', + 'permissions', + 'plugin-charts', + 'plugin-chatbot', + 'plugin-dashboard', + 'plugin-detail', + 'plugin-grid', + 'plugin-report', +] as const; + /** * 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.', @@ -121,6 +147,16 @@ const ALLOWED: Readonly> = { count: 1, reason: 'the test request of an `api` action preview, sent to the author-written target; its transport is not decided here.', }, + 'packages/auth/src/LoginForm.tsx': { + count: 1, + reason: 'the SSO sign-in request, sent before a session, and so a bearer, exists.', + }, + 'packages/permissions/src/MePermissionsProvider.tsx': { + count: 1, + reason: + 'the fallback of the injected `fetcher` (`fetcher ?? fetch`): the console hands its authenticated fetch ' + + '(`AppContent`), and a host that hands none has only the cookie. The package depends on `@object-ui/types` alone.', + }, }; const GLOBAL_FETCH = new Set(['fetch', 'window.fetch', 'globalThis.fetch', 'self.fetch']); @@ -165,6 +201,33 @@ function isGlobalFetchCallee(callee: ts.Expression, sf: ts.SourceFile): boolean return false; } +/** A URL written out as a literal, read only for whether it names an `/api/` path. */ +function namesApiPath(node: ts.Expression | undefined): boolean { + if (!node) return false; + const n = unwrap(node); + if (ts.isStringLiteralLike(n)) return n.text.includes('/api/'); + if (ts.isTemplateExpression(n)) { + return [n.head.text, ...n.templateSpans.map((span) => span.literal.text)].some((part) => part.includes('/api/')); + } + return false; +} + +/** No init, or an inline one with no `credentials` key: the default `same-origin`, the cookie alone. */ +function defaultsCredentials(init: ts.Expression | undefined): boolean { + if (!init) return true; + const n = unwrap(init); + return ( + ts.isObjectLiteralExpression(n) && + !n.properties.some( + (p) => + ts.isSpreadAssignment(p) || + ((ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)) && + (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) && + p.name.text === 'credentials'), + ) + ); +} + /** The bare cookie-only calls in one source text, as `line :: call` strings. */ function bareCookieOnlyCalls(fileName: string, text: string): string[] { const sf = ts.createSourceFile( @@ -194,6 +257,7 @@ function bareCookieOnlyCalls(fileName: string, text: string): string[] { if (ts.isCallExpression(n)) { const bare = (isGlobalFetchCallee(n.expression, sf) && initIncludes(n.arguments[1])) || + (isGlobalFetchCallee(n.expression, sf) && namesApiPath(n.arguments[0]) && defaultsCredentials(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; @@ -220,19 +284,40 @@ function sourceFiles(root: string): string[] { return out; } +/** Every `ui/packages//src` that exists, by package directory name. */ +function packageSourceRoots(): Map { + const roots = new Map(); + for (const entry of readdirSync(PACKAGES_ROOT, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + const src = path.join(PACKAGES_ROOT, entry.name, 'src'); + if (existsSync(src)) roots.set(entry.name, src); + } + return roots; +} + +let scanned: Map | undefined; + +/** The whole scan, once per run: two cases read it. */ function scan(): Map { + if (scanned) return scanned; const found = new Map(); - for (const file of [...sourceFiles(APP_SHELL_SRC), ...sourceFiles(CONSOLE_SRC)]) { + const files = [...[...packageSourceRoots().values()].flatMap(sourceFiles), ...sourceFiles(CONSOLE_SRC)]; + for (const file of files) { const calls = bareCookieOnlyCalls(file, readFileSync(file, 'utf8')); if (calls.length) found.set(path.relative(UI_ROOT, file).split(path.sep).join('/'), calls); } + scanned = found; return found; } -describe('cookie-only same-server fetch ratchet (app-shell + console)', () => { - it('reads both trees (guards a broken scan path)', () => { +describe('cookie-only same-server fetch ratchet (every ui package + console)', () => { + it('reads every tree (guards a broken scan path)', () => { expect(sourceFiles(APP_SHELL_SRC).length).toBeGreaterThan(500); expect(sourceFiles(CONSOLE_SRC).length).toBeGreaterThan(100); + const roots = packageSourceRoots(); + expect(roots.size).toBeGreaterThan(30); + const unread = RENDERER_PACKAGES.filter((name) => !roots.has(name) || sourceFiles(roots.get(name)!).length === 0); + expect(unread).toEqual([]); }); it('the detector sees every bare spelling, and none of the authenticated ones', () => { @@ -249,7 +334,16 @@ describe('cookie-only same-server fetch ratchet (app-shell + console)', () => { ["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], + // No init, or no `credentials`, on a written `/api/` path: the cookie alone (objectstack#37225). + ["await fetch('/api/v1/x');", 1], + ['await fetch(`/api/v1/objects/${name}/fields`);', 1], + ["await window.fetch(`${base}/api/v1/x`, { method: 'POST', headers: h });", 1], + ["await fetch('/api/v1/x', { credentials: 'same-origin' });", 0], + ["await fetch('/api/v1/x', { ...init });", 0], + ["await fetch(url);", 0], + ["await fetch('https://cdn.example.com/a.json');", 0], + ["await authFetch('/api/v1/x');", 0], + ["await doFetch(`/api/v1/objects/${name}/fields`);", 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`. From 916ded0937f68d8a2e835033714e1c69f83f040b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:22:03 +0000 Subject: [PATCH 3/7] test(ui): pin the field selector and the me/localization legs under a bearer-only session; changesets Claude-Session: https://claude.ai/code/session_01Utp6Ca6EBDpTBZk8v46Jjv Co-authored-by: Claude --- .changeset/37225-chatbot-hooks-bearer.md | 10 ++ .changeset/37225-field-selector-bearer.md | 10 ++ .changeset/37225-localization-bearer.md | 10 ++ .changeset/37225-share-dialog-bearer.md | 10 ++ .../__tests__/sessionCheckBootDedup.test.tsx | 117 +++++++++++++++++- .../FieldSelectorWidget.loadFailure.test.tsx | 57 ++++++++- 6 files changed, 209 insertions(+), 5 deletions(-) create mode 100644 .changeset/37225-chatbot-hooks-bearer.md create mode 100644 .changeset/37225-field-selector-bearer.md create mode 100644 .changeset/37225-localization-bearer.md create mode 100644 .changeset/37225-share-dialog-bearer.md diff --git a/.changeset/37225-chatbot-hooks-bearer.md b/.changeset/37225-chatbot-hooks-bearer.md new file mode 100644 index 00000000000..de2fa192f52 --- /dev/null +++ b/.changeset/37225-chatbot-hooks-bearer.md @@ -0,0 +1,10 @@ +--- +'@object-ui/plugin-chatbot': patch +--- + +fix(plugin-chatbot): the agent list, the model picker, the pending-approvals inbox and in-chat approvals send through the host's authenticated fetch, so a session held by its sign-in token alone sees its agents and can approve + +Clause-②: no +Metadata-protocol: none + +`useAgents`, `useAiModels`, `usePendingActions` and `useHitlInChat` asked the AI service with the session cookie only. A session held by its sign-in (bearer) token alone (a cross-site embed, a cookie the browser blocked as third-party) was refused there: no agents, no models, an empty approvals inbox, and an in-chat approval that failed. They now send through the host's authenticated fetch, the `apiFetch` a host hands `SchemaRendererProvider` (the console's sends the stored token), as the renderers' own reads already do. The session cookie is still sent, a cookie session behaves exactly as before, and in the console a refused request now reaches its session-ended check. A host that mounts no provider keeps the plain `fetch`, as before. The hooks' options, including `headers`, are unchanged. diff --git a/.changeset/37225-field-selector-bearer.md b/.changeset/37225-field-selector-bearer.md new file mode 100644 index 00000000000..4e0d67306c5 --- /dev/null +++ b/.changeset/37225-field-selector-bearer.md @@ -0,0 +1,10 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(app-shell): the metadata form's field picker reads an object's fields with the stored sign-in token, so a session held by its token alone can pick fields + +Clause-②: no +Metadata-protocol: none + +The `field-selector` picker in the metadata forms read an object's field catalog with the session cookie only, so a session held by its sign-in (bearer) token alone was refused and the picker showed a load failure. It now sends the stored token as well, as the other same-server console requests do. The session cookie is still sent, a cookie session behaves exactly as before, and a refused request now reaches the console's session-ended check. diff --git a/.changeset/37225-localization-bearer.md b/.changeset/37225-localization-bearer.md new file mode 100644 index 00000000000..8e6eebd48fd --- /dev/null +++ b/.changeset/37225-localization-bearer.md @@ -0,0 +1,10 @@ +--- +'@object-ui/console': patch +--- + +fix(console): the boot read of the signed-in user's language, currency and time zone sends the stored sign-in token, so a session held by its token alone boots in the user's own language and formats + +Clause-②: no +Metadata-protocol: none + +`GET /api/v1/auth/me/localization` was read with the session cookie only, on all three of its legs: the request `index.html` sends during parse, the language seed before the app mounts, and the regional-defaults provider. A session held by its sign-in (bearer) token alone was answered as signed out, so the console booted in the browser's language and formatted numbers, currencies and dates without the user's own settings. All three now state the stored token, read from the same storage the other console requests read it from, and they still share one request: the three send the same request, and its identity includes the token. With no token stored the request is exactly as before. Nothing changes in what the server accepts. diff --git a/.changeset/37225-share-dialog-bearer.md b/.changeset/37225-share-dialog-bearer.md new file mode 100644 index 00000000000..d64826b122c --- /dev/null +++ b/.changeset/37225-share-dialog-bearer.md @@ -0,0 +1,10 @@ +--- +'@object-ui/components': patch +--- + +fix(components): the share dialog lists, creates and revokes share links through the host's authenticated fetch, so a session held by its sign-in token alone sees its links + +Clause-②: no +Metadata-protocol: none + +`ShareDialog` asked this server for a record's share links (and created and revoked them) with the session cookie only. A session held by its sign-in (bearer) token alone (a cross-site embed, a cookie the browser blocked as third-party) was refused there: the dialog showed an error and no links. It now sends through the host's authenticated fetch, the `apiFetch` a host hands `SchemaRendererProvider` (the console's sends the stored token), as the renderers' own reads already do. The session cookie is still sent, a cookie session behaves exactly as before, and in the console a refused request now reaches its session-ended check. A host that mounts no provider keeps the plain `fetch`, as before. The `fetchHeaders` prop is unchanged. diff --git a/ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx b/ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx index 0472afb441d..e6163134ed4 100644 --- a/ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx +++ b/ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx @@ -27,10 +27,10 @@ import { readConsoleDiscovery } from '../lib/early-discovery'; import { getSharedDiscovery } from '@object-ui/data-objectstack'; import { clearSharedDiscoveryCache } from '../../../../packages/data-objectstack/src/sharedDiscovery'; import { SessionUserScope } from '../../../../packages/auth/src/ActiveOrganizationStorage'; -import { resetInflightGetsForTesting } from '../../../../packages/types/src/http-inflight'; +import { inflightGetKey, resetInflightGetsForTesting } from '../../../../packages/types/src/http-inflight'; import { readCachedLanguageSeed, useLocalization } from '@object-ui/i18n'; import { PLATFORM_LOCALE_READ_ALIASES, PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system'; -import { __resetPreferredLocaleForTests, pickPreferredLocale, seedTenantLanguage } from '../languageSeed'; +import { __resetPreferredLocaleForTests, meLocalizationInit, pickPreferredLocale, seedTenantLanguage } from '../languageSeed'; import { LocalizationFetchProvider } from '../LocalizationFetchProvider'; const TOKEN = 'tok_valid'; @@ -898,3 +898,116 @@ describe("the language seed's me/localization starts at parse time beside discov expect(localizationCalls()).toHaveLength(1); }); }); + +describe('a bearer-only session: the stored Bearer rides me/localization on all three legs, and they still share one request (objectstack#37225)', () => { + const DISCOVERY_SLOT = Symbol.for('objectui.earlyDiscovery'); + const SEED_SLOT = Symbol.for('objectui.earlyLanguageSeed'); + const ME = '/api/v1/auth/me/localization'; + const BEARER = 'tok_bearer_only'; + const SIGNED_IN = { authenticated: true, locale: 'zh-CN', currency: 'CNY', timezone: 'Asia/Shanghai' }; + const localizationCalls = () => fetchStub.mock.calls.filter(([input]) => urlOf(input).includes('/me/localization')); + const authorizationOf = (call: unknown[] | undefined) => + new Headers((call?.[1] as RequestInit | undefined)?.headers).get('Authorization'); + const parse = () => { + runScript('startEarlyDiscovery'); + runScript('startEarlyLanguageSeed'); + }; + const forget = () => { + const holder = globalThis as unknown as Record; + delete holder[DISCOVERY_SLOT]; + delete holder[SEED_SLOT]; + clearSharedDiscoveryCache(); + resetInflightGetsForTesting(); + __resetPreferredLocaleForTests(); + }; + + function Value() { + const { locale, currency } = useLocalization(); + return {`${locale ?? '-'}/${currency ?? '-'}`}; + } + + beforeEach(() => { + forget(); + discoveryAnswer = () => json({ locale: { default: 'en', supported: ['en', 'zh-CN'] } }); + vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('zh-CN'); + // A server that sees only the bearer: no cookie rides in a unit test, so a + // read without it is a caller it cannot see. + localizationAnswer = () => + authorizationOf(fetchStub.mock.lastCall) === `Bearer ${BEARER}` ? json(SIGNED_IN) : json({ authenticated: false }); + }); + afterEach(forget); + + it('one cold load, one me/localization: parse time, seed and provider share it, and it carries the Bearer', async () => { + localStorage.setItem('auth-session-token', BEARER); + parse(); + await settle(); + + await seedTenantLanguage('', 1_000); + expect(readCachedLanguageSeed()).toBe('zh-CN'); + render( + + + , + ); + expect(await screen.findByText('zh-CN/CNY')).toBeTruthy(); + + expect(localizationCalls()).toHaveLength(1); + const [, init] = localizationCalls()[0]!; + expect(init).toMatchObject({ credentials: 'include' }); + expect(authorizationOf(localizationCalls()[0])).toBe(`Bearer ${BEARER}`); + expect(new Headers(init?.headers).get('Accept-Language')).toBe('zh-CN'); + }); + + it("the share key still matches: index.html's request is keyed as the seed's and the provider's init", async () => { + localStorage.setItem('auth-session-token', BEARER); + parse(); + await settle(); + const slot = (globalThis as unknown as Record)[SEED_SLOT]!; + expect(inflightGetKey(slot.url, slot.init)).toBe(inflightGetKey(ME, meLocalizationInit('zh-CN'))); + expect(inflightGetKey(ME, meLocalizationInit('zh-CN'))).toContain(`authorization=Bearer ${BEARER}`); + }); + + it('every later boot (a cached seed): the provider reads alone, with the Bearer, and is answered as the user', async () => { + localStorage.setItem('auth-session-token', BEARER); + localStorage.setItem('objectui-locale-seed', 'zh-CN'); + render( + + + , + ); + expect(await screen.findByText('zh-CN/CNY')).toBeTruthy(); + expect(localizationCalls()).toHaveLength(1); + expect(authorizationOf(localizationCalls()[0])).toBe(`Bearer ${BEARER}`); + }); + + it('CONTROL: no stored token, the cookie session: one request, no Authorization, as before', async () => { + parse(); + await settle(); + await seedTenantLanguage('', 1_000); + render( + + + , + ); + await settle(); + expect(localizationCalls()).toHaveLength(1); + expect(localizationCalls()[0]![1]).toMatchObject({ credentials: 'include' }); + expect(authorizationOf(localizationCalls()[0])).toBeNull(); + // The bearer-only server cannot see it: nothing of the user's is cached or shown. + expect(readCachedLanguageSeed()).toBeNull(); + expect(screen.getByTestId('localization').textContent).toBe('-/-'); + }); + + it('CONTROL: a token stored since parse time is not answered by the parse-time request; the seed asks once itself, with it', async () => { + parse(); + await settle(); + localStorage.setItem('auth-session-token', BEARER); + + await seedTenantLanguage('', 1_000); + + expect(localizationCalls()).toHaveLength(2); + expect(authorizationOf(localizationCalls()[0])).toBeNull(); + expect(authorizationOf(localizationCalls()[1])).toBe(`Bearer ${BEARER}`); + expect(readCachedLanguageSeed()).toBe('zh-CN'); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/FieldSelectorWidget.loadFailure.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/FieldSelectorWidget.loadFailure.test.tsx index 21538d55f94..c4772bfc453 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/FieldSelectorWidget.loadFailure.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/FieldSelectorWidget.loadFailure.test.tsx @@ -61,6 +61,7 @@ import '@testing-library/jest-dom/vitest'; import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, cleanup, waitFor } from '@testing-library/react'; +import { TokenStorage } from '@object-ui/auth'; import { WIDGETS } from './widgets'; import { t } from './i18n'; @@ -82,12 +83,14 @@ const FAILURE_TESTID = 'field-selector-load-failed'; */ const ADD_FIELDS = t('engine.form.addFields', 'en-US'); +// `headers`: the read goes through the console's authenticated fetch, which +// reads a rotated session token off every answer (objectstack#37225). function okResponse(body: unknown): Response { - return { ok: true, status: 200, json: async () => body } as unknown as Response; + return { ok: true, status: 200, headers: new Headers(), json: async () => body } as unknown as Response; } function jsonErrorResponse(status: number, body: unknown): Response { - return { ok: false, status, json: async () => body } as unknown as Response; + return { ok: false, status, headers: new Headers(), json: async () => body } as unknown as Response; } /** A promise the test resolves by hand, so the loading arm is observable. */ @@ -119,6 +122,7 @@ afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.restoreAllMocks(); + TokenStorage.clear(); }); describe('field-selector — a failed field fetch is not an empty field list (objectui#5227)', () => { @@ -146,7 +150,7 @@ describe('field-selector — a failed field fetch is not an empty field list (ob // …and the loading flag cleared. expect(screen.queryByDisplayValue(LOADING_FIELDS)).not.toBeInTheDocument(); - expect(fetchMock).toHaveBeenCalledWith(FIELDS_URL); + expect(fetchMock).toHaveBeenCalledWith(FIELDS_URL, expect.objectContaining({ credentials: 'include' })); }); it('mouth 2: a NON-OK response with a parseable JSON body is a fault, not an empty catalog', async () => { @@ -173,6 +177,7 @@ describe('field-selector — a failed field fetch is not an empty field list (ob const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 500, + headers: new Headers(), // A non-JSON body — the parse throws, and that must not be mistaken for // a refusal that said nothing to report. json: async () => { @@ -279,3 +284,49 @@ describe('field-selector — a failed field fetch is not an empty field list (ob expect(onChange).toHaveBeenCalledWith([]); }); }); + +/** + * objectstack#37225 — the catalog read went out as a bare `fetch` with no init: + * the default `same-origin` credentials, the session cookie alone. A session + * held by its bearer token alone was answered `401` and the picker showed a + * failure for every object. Against a server that refuses any request without + * the bearer, the read now carries it beside the cookie; with no token stored + * (a cookie session) it goes out cookie-only, as before. + */ +describe('field-selector — the catalog read under a bearer-only session (objectstack#37225)', () => { + const TOKEN = 'stored-session-token'; + const sent: Array<{ credentials: RequestCredentials | undefined; authorization: string | null }> = []; + const bearerOnlyServer = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => { + const authorization = new Headers(init?.headers).get('Authorization'); + sent.push({ credentials: init?.credentials, authorization }); + return authorization === `Bearer ${TOKEN}` + ? okResponse({ fields: [{ name: 'name', label: 'Name', type: 'text' }] }) + : jsonErrorResponse(401, { error: { message: 'Authentication is required to access this endpoint.' } }); + }); + + afterEach(() => { + sent.length = 0; + bearerOnlyServer.mockClear(); + }); + + it('loads the catalog, sending the stored bearer beside the cookie', async () => { + TokenStorage.set(TOKEN); + vi.stubGlobal('fetch', bearerOnlyServer); + + renderWidget(); + + await waitFor(() => expect(screen.getByRole('combobox')).toBeEnabled()); + expect(screen.queryByTestId(FAILURE_TESTID)).not.toBeInTheDocument(); + expect(bearerOnlyServer.mock.calls.map(([url]) => url)).toEqual([FIELDS_URL]); + expect(sent).toEqual([{ credentials: 'include', authorization: `Bearer ${TOKEN}` }]); + }); + + it('CONTROL: with no token stored the read goes out cookie-only, and is refused as before', async () => { + vi.stubGlobal('fetch', bearerOnlyServer); + + renderWidget(); + + await waitFor(() => expect(screen.getByTestId(FAILURE_TESTID)).toBeInTheDocument()); + expect(sent).toEqual([{ credentials: 'include', authorization: null }]); + }); +}); From 765f72c3465d9065a37e5ecc522bfbf96ad862d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:30:04 +0000 Subject: [PATCH 4/7] test(console): the cookie control counts the provider's own read of a signed-out answer Claude-Session: https://claude.ai/code/session_01Utp6Ca6EBDpTBZk8v46Jjv Co-authored-by: Claude --- .../src/__tests__/sessionCheckBootDedup.test.tsx | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx b/ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx index e6163134ed4..d93251907be 100644 --- a/ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx +++ b/ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx @@ -980,19 +980,25 @@ describe('a bearer-only session: the stored Bearer rides me/localization on all expect(authorizationOf(localizationCalls()[0])).toBe(`Bearer ${BEARER}`); }); - it('CONTROL: no stored token, the cookie session: one request, no Authorization, as before', async () => { + it('CONTROL: no stored token, the cookie session: no Authorization on any leg, as before', async () => { parse(); await settle(); await seedTenantLanguage('', 1_000); + // The seed took the parse-time request: one so far. + expect(localizationCalls()).toHaveLength(1); render( , ); await settle(); - expect(localizationCalls()).toHaveLength(1); - expect(localizationCalls()[0]![1]).toMatchObject({ credentials: 'include' }); - expect(authorizationOf(localizationCalls()[0])).toBeNull(); + // A signed-out answer is never handed to the provider, which asks itself, + // exactly as before this change. + expect(localizationCalls()).toHaveLength(2); + for (const call of localizationCalls()) { + expect(call[1]).toMatchObject({ credentials: 'include' }); + expect(authorizationOf(call)).toBeNull(); + } // The bearer-only server cannot see it: nothing of the user's is cached or shown. expect(readCachedLanguageSeed()).toBeNull(); expect(screen.getByTestId('localization').textContent).toBe('-/-'); From d82fd0e91481b0e57b148382b5a7a1942f89dcfc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 08:07:51 +0000 Subject: [PATCH 5/7] test(app-shell): field-selector doubles carry the headers a real answer has Claude-Session: https://claude.ai/code/session_01Utp6Ca6EBDpTBZk8v46Jjv Co-authored-by: Claude --- .../src/views/metadata-admin/FormFieldSpec.dependsOn.test.tsx | 2 ++ .../SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx | 2 ++ .../src/views/metadata-admin/selector-placeholder.i18n.test.tsx | 2 ++ 3 files changed, 6 insertions(+) diff --git a/ui/packages/app-shell/src/views/metadata-admin/FormFieldSpec.dependsOn.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/FormFieldSpec.dependsOn.test.tsx index 054ba0b85d6..a82aedf374a 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/FormFieldSpec.dependsOn.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/FormFieldSpec.dependsOn.test.tsx @@ -181,6 +181,8 @@ describe('objectui#5040 — a spec typed as `FormFieldSpec` configures its widge return { ok: true, status: 200, + // The authenticated fetch reads a rotated token off every answer (objectstack#37225). + headers: new Headers(), json: async () => ({ fields: [{ name: 'amount', label: 'Amount' }] }), } as unknown as Response; }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx index 6397ea5721e..0f6057b436b 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx @@ -186,6 +186,8 @@ function stubFetch(mode: 'failed' | 'loaded') { : vi.fn().mockResolvedValue({ ok: true, status: 200, + // The authenticated fetch reads a rotated token off every answer (objectstack#37225). + headers: new Headers(), json: async () => ({ fields: [{ name: 'status', label: 'Status', type: 'text' }] }), } as unknown as Response), ); diff --git a/ui/packages/app-shell/src/views/metadata-admin/selector-placeholder.i18n.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/selector-placeholder.i18n.test.tsx index d53b8482987..43da5431aa0 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/selector-placeholder.i18n.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/selector-placeholder.i18n.test.tsx @@ -62,6 +62,8 @@ describe('metadata-admin selector placeholders (objectui#4387 key collapse)', () vi.fn().mockResolvedValue({ ok: true, status: 200, + // The authenticated fetch reads a rotated token off every answer (objectstack#37225). + headers: new Headers(), json: async () => ({ fields: [{ name: 'name', label: 'Name', type: 'text' }] }), }), ); From b5a55f26fe79b9216a3cad7adaaad20b4ba55a3a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 08:09:37 +0000 Subject: [PATCH 6/7] test(app-shell): the field-picker suites pay its dynamic imports at collection Claude-Session: https://claude.ai/code/session_01Utp6Ca6EBDpTBZk8v46Jjv Co-authored-by: Claude --- .../metadata-admin/FieldSelectorWidget.loadFailure.test.tsx | 4 ++++ .../src/views/metadata-admin/FormFieldSpec.dependsOn.test.tsx | 4 ++++ .../views/metadata-admin/selector-placeholder.i18n.test.tsx | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/ui/packages/app-shell/src/views/metadata-admin/FieldSelectorWidget.loadFailure.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/FieldSelectorWidget.loadFailure.test.tsx index c4772bfc453..cf7d965c7ff 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/FieldSelectorWidget.loadFailure.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/FieldSelectorWidget.loadFailure.test.tsx @@ -58,6 +58,10 @@ * arm by its disabled input, the completed arms by the combobox they render. */ +// The field picker's module graph reaches two dynamic imports (`celAuthoring.ts`); +// their first load is paid at collection, never inside a clocked case (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; import '@testing-library/jest-dom/vitest'; import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, cleanup, waitFor } from '@testing-library/react'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/FormFieldSpec.dependsOn.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/FormFieldSpec.dependsOn.test.tsx index a82aedf374a..dd6d31b921a 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/FormFieldSpec.dependsOn.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/FormFieldSpec.dependsOn.test.tsx @@ -51,6 +51,10 @@ * reader can consume — both index `[0]` and use it as a field NAME). */ +// The field picker's module graph reaches two dynamic imports (`celAuthoring.ts`); +// their first load is paid at collection, never inside a clocked case (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; import '@testing-library/jest-dom/vitest'; import { describe, it, expect, afterEach, vi } from 'vitest'; import { render, screen, cleanup, waitFor } from '@testing-library/react'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/selector-placeholder.i18n.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/selector-placeholder.i18n.test.tsx index 43da5431aa0..d76acfc56a8 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/selector-placeholder.i18n.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/selector-placeholder.i18n.test.tsx @@ -1,5 +1,9 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. +// The field picker's module graph reaches two dynamic imports (`celAuthoring.ts`); +// their first load is paid at collection, never inside a clocked case (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; import { describe, it, expect, afterEach, vi } from 'vitest'; import { render, screen, cleanup } from '@testing-library/react'; import { WIDGETS } from './widgets'; From b0a4db683fb930af97e81a604d4ca5025c07c684 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:51:28 +0000 Subject: [PATCH 7/7] fix(console): me/localization reads the token through TokenStorage; narrow changeset scope The seed and the provider now read the stored token through TokenStorage, so a storage-blocked embed still sends the token sign-in kept in memory (index.html stays on localStorage). Pinned with a memory-fallback case. The changesets now name the scope actually fixed (same-origin), say that split-origin requests still go without the token, and note header precedence. The field selector encodes the object name into its path. Claude-Session: https://claude.ai/code/session_01Utp6Ca6EBDpTBZk8v46Jjv Co-authored-by: Claude --- .changeset/37225-chatbot-hooks-bearer.md | 2 +- .changeset/37225-localization-bearer.md | 2 +- .changeset/37225-share-dialog-bearer.md | 2 +- .../__tests__/sessionCheckBootDedup.test.tsx | 25 ++++++++++++++++++- ui/apps/console/src/languageSeed.ts | 20 +++++++-------- .../src/views/metadata-admin/widgets.tsx | 5 ++-- 6 files changed, 39 insertions(+), 17 deletions(-) diff --git a/.changeset/37225-chatbot-hooks-bearer.md b/.changeset/37225-chatbot-hooks-bearer.md index de2fa192f52..72724b4b3c9 100644 --- a/.changeset/37225-chatbot-hooks-bearer.md +++ b/.changeset/37225-chatbot-hooks-bearer.md @@ -7,4 +7,4 @@ fix(plugin-chatbot): the agent list, the model picker, the pending-approvals inb Clause-②: no Metadata-protocol: none -`useAgents`, `useAiModels`, `usePendingActions` and `useHitlInChat` asked the AI service with the session cookie only. A session held by its sign-in (bearer) token alone (a cross-site embed, a cookie the browser blocked as third-party) was refused there: no agents, no models, an empty approvals inbox, and an in-chat approval that failed. They now send through the host's authenticated fetch, the `apiFetch` a host hands `SchemaRendererProvider` (the console's sends the stored token), as the renderers' own reads already do. The session cookie is still sent, a cookie session behaves exactly as before, and in the console a refused request now reaches its session-ended check. A host that mounts no provider keeps the plain `fetch`, as before. The hooks' options, including `headers`, are unchanged. +`useAgents`, `useAiModels`, `usePendingActions` and `useHitlInChat` asked the AI service with the session cookie only. A session held by its sign-in (bearer) token alone on the console's own origin (for example, a session cookie the browser blocked as third-party) was refused there: no agents, no models, an empty approvals inbox, and an in-chat approval that failed. They now send through the host's authenticated fetch, the `apiFetch` a host hands `SchemaRendererProvider` (the console's sends the stored token), as the renderers' own reads already do. The session cookie is still sent, a cookie session behaves exactly as before, and in the console a refused request now reaches its session-ended check. A host that mounts no provider keeps the plain `fetch`, as before. Where a host points these requests at another origin (an AI service or server URL configured off the page's origin), the host's fetch still sends them without the token; that layout is not fixed here. The hooks' options are unchanged in shape; in the console, a stored token now takes precedence over an `Authorization` passed in `headers`, and the host's tenant and language headers ride these requests too. diff --git a/.changeset/37225-localization-bearer.md b/.changeset/37225-localization-bearer.md index 8e6eebd48fd..6befc81f425 100644 --- a/.changeset/37225-localization-bearer.md +++ b/.changeset/37225-localization-bearer.md @@ -7,4 +7,4 @@ fix(console): the boot read of the signed-in user's language, currency and time Clause-②: no Metadata-protocol: none -`GET /api/v1/auth/me/localization` was read with the session cookie only, on all three of its legs: the request `index.html` sends during parse, the language seed before the app mounts, and the regional-defaults provider. A session held by its sign-in (bearer) token alone was answered as signed out, so the console booted in the browser's language and formatted numbers, currencies and dates without the user's own settings. All three now state the stored token, read from the same storage the other console requests read it from, and they still share one request: the three send the same request, and its identity includes the token. With no token stored the request is exactly as before. Nothing changes in what the server accepts. +`GET /api/v1/auth/me/localization` was read with the session cookie only, on all three of its legs: the request `index.html` sends during parse, the language seed before the app mounts, and the regional-defaults provider. A session held by its sign-in (bearer) token alone was answered as signed out, so the console booted in the browser's language and formatted numbers, currencies and dates without the user's own settings. All three now state the stored token. The seed and the provider read it where the other console requests read it, including a token kept in memory when the browser blocks storage; the parse-time request reads storage only. They still share one request: the three send the same request, and its identity includes the token. With no token stored the request is exactly as before. Nothing changes in what the server accepts. diff --git a/.changeset/37225-share-dialog-bearer.md b/.changeset/37225-share-dialog-bearer.md index d64826b122c..a59efeef6f0 100644 --- a/.changeset/37225-share-dialog-bearer.md +++ b/.changeset/37225-share-dialog-bearer.md @@ -7,4 +7,4 @@ fix(components): the share dialog lists, creates and revokes share links through Clause-②: no Metadata-protocol: none -`ShareDialog` asked this server for a record's share links (and created and revoked them) with the session cookie only. A session held by its sign-in (bearer) token alone (a cross-site embed, a cookie the browser blocked as third-party) was refused there: the dialog showed an error and no links. It now sends through the host's authenticated fetch, the `apiFetch` a host hands `SchemaRendererProvider` (the console's sends the stored token), as the renderers' own reads already do. The session cookie is still sent, a cookie session behaves exactly as before, and in the console a refused request now reaches its session-ended check. A host that mounts no provider keeps the plain `fetch`, as before. The `fetchHeaders` prop is unchanged. +`ShareDialog` asked this server for a record's share links (and created and revoked them) with the session cookie only. A session held by its sign-in (bearer) token alone on the console's own origin (for example, a session cookie the browser blocked as third-party) was refused there: the dialog showed an error and no links. It now sends through the host's authenticated fetch, the `apiFetch` a host hands `SchemaRendererProvider` (the console's sends the stored token), as the renderers' own reads already do. The session cookie is still sent, a cookie session behaves exactly as before, and in the console a refused request now reaches its session-ended check. A host that mounts no provider keeps the plain `fetch`, as before. Where a host points these requests at another origin (an AI service or server URL configured off the page's origin), the host's fetch still sends them without the token; that layout is not fixed here. The `fetchHeaders` prop is unchanged in shape; in the console, a stored token now takes precedence over an `Authorization` passed in it, and the host's tenant and language headers ride these requests too. diff --git a/ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx b/ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx index d93251907be..a1a0e808678 100644 --- a/ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx +++ b/ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx @@ -21,7 +21,7 @@ import indexHtml from '../../index.html?raw'; import mainSource from '../main.tsx?raw'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, act, cleanup } from '@testing-library/react'; -import { AuthGuard, AuthProvider, useAuth } from '@object-ui/auth'; +import { AuthGuard, AuthProvider, TokenStorage, useAuth } from '@object-ui/auth'; import { preflightAuth } from '../lib/auth-preflight'; import { readConsoleDiscovery } from '../lib/early-discovery'; import { getSharedDiscovery } from '@object-ui/data-objectstack'; @@ -1016,4 +1016,27 @@ describe('a bearer-only session: the stored Bearer rides me/localization on all expect(authorizationOf(localizationCalls()[1])).toBe(`Bearer ${BEARER}`); expect(readCachedLanguageSeed()).toBe('zh-CN'); }); + + it('blocked storage (an embed whose localStorage throws): the token sign-in kept in memory still rides the provider read', async () => { + vi.spyOn(window, 'localStorage', 'get').mockImplementation(() => { + throw new DOMException('blocked', 'SecurityError'); + }); + expect(() => window.localStorage.getItem('auth-session-token')).toThrow(); + try { + // Sign-in stores the token; with storage blocked, `TokenStorage` keeps it in memory. + TokenStorage.set(BEARER); + expect(TokenStorage.get()).toBe(BEARER); + expect(new Headers(meLocalizationInit('zh-CN').headers).get('Authorization')).toBe(`Bearer ${BEARER}`); + render( + + + , + ); + expect(await screen.findByText('zh-CN/CNY')).toBeTruthy(); + expect(localizationCalls()).toHaveLength(1); + expect(authorizationOf(localizationCalls()[0])).toBe(`Bearer ${BEARER}`); + } finally { + TokenStorage.clear(); + } + }); }); diff --git a/ui/apps/console/src/languageSeed.ts b/ui/apps/console/src/languageSeed.ts index 60bfa3d0c87..ff348aca21f 100644 --- a/ui/apps/console/src/languageSeed.ts +++ b/ui/apps/console/src/languageSeed.ts @@ -128,7 +128,7 @@ * Bearer the same way, for the same parse-time hand-off. */ import { cacheLanguageSeed, readCachedLanguageSeed, readStoredLanguage } from '@object-ui/i18n'; -import { getSessionOwnerChangeCount } from '@object-ui/auth'; +import { TokenStorage, getSessionOwnerChangeCount } from '@object-ui/auth'; import { inflightGetKey, sharedGetJson } from '@object-ui/types'; import { resolveLocaleAmong } from '@objectstack/spec/system'; import { readConsoleDiscovery } from './lib/early-discovery'; @@ -147,18 +147,16 @@ interface MeLocalizationResponse { } /** - * The Bearer every console request carries, `''` when there is none or storage - * is blocked: the key `createAuthenticatedFetch` reads (`TokenStorage`), read - * here as `index.html` and `early-discovery.ts` read it. + * The Bearer every console request carries, `''` when there is none: read + * through `TokenStorage`, the store `createAuthenticatedFetch` reads, so a + * storage-blocked page (an embed whose `localStorage` throws, itself a + * bearer-only session) still sends the in-memory token the sign-in kept. + * `index.html` runs before the bundle and reads `localStorage` by hand; when + * the two answers differ the inits differ and the provider sends its own read, + * the "token stored after parse" shape. */ -const TOKEN_KEY = 'auth-session-token'; - function storedToken(): string { - try { - return localStorage.getItem(TOKEN_KEY) || ''; - } catch { - return ''; - } + return TokenStorage.get() || ''; } /** diff --git a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx index 5fe4d4f7c79..b0aabaf8c53 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx @@ -1204,10 +1204,11 @@ const EMPTY_FIELD_SELECTOR_OPTIONS: FieldSelectorOption[] = []; * `credentials: 'include'`: a bare `fetch` with no init sends the session cookie * alone (the default `same-origin` credentials), so a session held by its bearer * token alone was answered as anonymous and a `401` never reached the console's - * session-ended check. + * session-ended check. The object name is encoded into the path: the request + * now carries the bearer, so it names exactly the object it was given. */ async function fetchFieldSelectorOptions(objectName: string): Promise { - const res = await createAuthenticatedFetch()(`/api/v1/objects/${objectName}/fields`, { + const res = await createAuthenticatedFetch()(`/api/v1/objects/${encodeURIComponent(objectName)}/fields`, { credentials: 'include', }); // Read the body BEFORE branching on `ok`: a refusal usually carries the more