Skip to content

Commit 26debb5

Browse files
committed
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 <noreply@anthropic.com>
1 parent a46efa8 commit 26debb5

9 files changed

Lines changed: 181 additions & 46 deletions

File tree

‎ui/apps/console/index.html‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,9 @@
279279
280280
The request is the seed's byte for byte: the same URL (the server origin
281281
through the same Vite HTML env substitution as the scripts above),
282-
`credentials: 'include'`, the same `Accept`, and the same
282+
`credentials: 'include'`, the same `Accept`, the stored Bearer from the
283+
same `localStorage` key when there is one (objectstack#37225: a session
284+
held by its bearer alone is otherwise answered as anonymous), and the same
283285
`Accept-Language`: the browser's language in the app's own spelling when
284286
discovery `locale.supported` lists it, else none (ruling 6915665005,
285287
objectstack#34392). "Lists it" is the platform's one locale ladder,
@@ -353,6 +355,11 @@
353355
const preferred = browser ? resolveAmong(browser, supported) : undefined;
354356
const headers = { Accept: 'application/json' };
355357
if (preferred) headers['Accept-Language'] = preferred;
358+
let token = '';
359+
try {
360+
token = localStorage.getItem('auth-session-token') || '';
361+
} catch (_) { /* storage blocked: no Bearer, as in the seed */ }
362+
if (token) headers.Authorization = 'Bearer ' + token;
356363
slot.init = { credentials: 'include', headers: headers };
357364
slot.response = fetch(slot.url, slot.init);
358365
// The seed reads a failure as its own request's; it is never unhandled.

‎ui/apps/console/src/LocalizationFetchProvider.tsx‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,15 @@
9090
* lists that language; else the organization's `localization.locale`, then
9191
* the app's declared default, decide — the rungs the same ruling puts below
9292
* the browser's language, which only the server can read.
93+
*
94+
* ## The stored Bearer rides it (objectstack#37225)
95+
*
96+
* Under a session held by its bearer token alone, a cookie-only read was
97+
* answered `{ authenticated: false }`: no currency, locale or zone of the
98+
* user's. The read's init is `meLocalizationInit` (`languageSeed.ts`), which
99+
* states the stored Bearer exactly as the seed and `index.html`'s parse-time
100+
* request do, so the three still share one request; why the Bearer goes in the
101+
* init rather than through `createAuthenticatedFetch` is written there.
93102
*/
94103
import { useEffect, useState } from 'react';
95104
import {
@@ -100,7 +109,7 @@ import {
100109
type LocalizationValue,
101110
} from '@object-ui/i18n';
102111
import { getSessionOwnerChangeCount, useAuth } from '@object-ui/auth';
103-
import { startedPreferredLocale, takeSettledSeedAnswer } from './languageSeed';
112+
import { meLocalizationInit, startedPreferredLocale, takeSettledSeedAnswer } from './languageSeed';
104113
import { useDataInvalidation } from '@object-ui/react';
105114
import {
106115
HttpFetchError,
@@ -177,14 +186,9 @@ export function LocalizationFetchProvider({
177186
// before — including `Retry-After` — so the retry policy below is
178187
// untouched, and a shared 503 reaches BOTH callers rather than
179188
// resolving one of them empty.
180-
const init: RequestInit = {
181-
credentials: 'include',
182-
headers: {
183-
Accept: 'application/json',
184-
...(preference ? { 'Accept-Language': preference } : {}),
185-
},
186-
signal: reread?.signal,
187-
};
189+
// The seed's own init (the stored Bearer included), plus this read's
190+
// signal, which is no part of the in-flight key.
191+
const init: RequestInit = { ...meLocalizationInit(preference), signal: reread?.signal };
188192
// The boot read's first attempt takes the seed's answer to this very
189193
// request when it settled earlier in this page load
190194
// (objectstack#35455); a re-read never does.

‎ui/apps/console/src/languageSeed.ts‎

Lines changed: 57 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,23 @@
109109
* `sharedGetJson` call, so the race, the in-flight sharing with
110110
* `LocalizationFetchProvider` and the hand-off of the settled answer are
111111
* unchanged.
112+
*
113+
* ## The stored Bearer rides it (objectstack#37225)
114+
*
115+
* A session held by its bearer token alone (no session cookie: a cross-site
116+
* embed, a blocked third-party cookie) was answered `{ authenticated: false }`
117+
* by a cookie-only read, so its seed and its regional defaults were never the
118+
* user's. Every read of this endpoint states the stored Bearer, through
119+
* {@link meLocalizationInit}: the parse-time request (`index.html` reads the
120+
* same `localStorage` key), the seed and `LocalizationFetchProvider`.
121+
*
122+
* In the init, by hand, and not through `createAuthenticatedFetch`: the
123+
* in-flight key is built from the init, so a header the transport adds would
124+
* not be part of it, and that transport also stamps `<html lang>` as
125+
* `Accept-Language` on a read that deliberately states none (objectstack#34392).
126+
* The endpoint answers a caller it cannot see `{ authenticated: false }`, never
127+
* `401`, so no session-ended signal is lost. `early-discovery.ts` carries the
128+
* Bearer the same way, for the same parse-time hand-off.
112129
*/
113130
import { cacheLanguageSeed, readCachedLanguageSeed, readStoredLanguage } from '@object-ui/i18n';
114131
import { getSessionOwnerChangeCount } from '@object-ui/auth';
@@ -129,6 +146,41 @@ interface MeLocalizationResponse {
129146
locale?: string | null;
130147
}
131148

149+
/**
150+
* The Bearer every console request carries, `''` when there is none or storage
151+
* is blocked: the key `createAuthenticatedFetch` reads (`TokenStorage`), read
152+
* here as `index.html` and `early-discovery.ts` read it.
153+
*/
154+
const TOKEN_KEY = 'auth-session-token';
155+
156+
function storedToken(): string {
157+
try {
158+
return localStorage.getItem(TOKEN_KEY) || '';
159+
} catch {
160+
return '';
161+
}
162+
}
163+
164+
/**
165+
* The init every read of `GET /api/v1/auth/me/localization` sends: the cookie
166+
* (`credentials: 'include'`), `Accept`, the stated language when there is one,
167+
* and the stored Bearer when there is one. The seed, `LocalizationFetchProvider`
168+
* and `index.html`'s parse-time request share a request only while their inits
169+
* match (`inflightGetKey`: URL, credentials and headers), so this is the one
170+
* spelling of it in the bundle; `index.html` spells it again by hand.
171+
*/
172+
export function meLocalizationInit(preferred: string | undefined): RequestInit {
173+
const token = storedToken();
174+
return {
175+
credentials: 'include',
176+
headers: {
177+
Accept: 'application/json',
178+
...(preferred ? { 'Accept-Language': preferred } : {}),
179+
...(token ? { Authorization: `Bearer ${token}` } : {}),
180+
},
181+
};
182+
}
183+
132184
/** This page-load's read of the language a choice-less read states, once started. */
133185
let preferredLocale: Promise<string | undefined> | null = null;
134186

@@ -304,17 +356,11 @@ async function fetchAndCacheSeed(serverBase: string): Promise<void> {
304356
// the provider mounts as soon as the race resolves. Sharing is in-flight
305357
// only, so on the boots where they do NOT overlap each still fetches.
306358
const url = `${serverBase}/api/v1/auth/me/localization`;
307-
const init: RequestInit = {
308-
credentials: 'include',
309-
headers: {
310-
Accept: 'application/json',
311-
// A supported browser language decides the rung below the user's
312-
// own locale (objectstack#33985); otherwise the browser's own header
313-
// goes, and the server's deployment default decides
314-
// (objectstack#34392).
315-
...(preferred ? { 'Accept-Language': preferred } : {}),
316-
},
317-
};
359+
// A supported browser language decides the rung below the user's own
360+
// locale (objectstack#33985); otherwise the browser's own header goes, and
361+
// the server's deployment default decides (objectstack#34392). The stored
362+
// Bearer rides along (objectstack#37225).
363+
const init = meLocalizationInit(preferred);
318364
// `index.html` usually sent this very request at parse time
319365
// (objectstack#35534): it is taken here as this read's transport, so the
320366
// provider still joins it in flight and a failure is this read's own.

‎ui/packages/app-shell/src/views/metadata-admin/widgets.tsx‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import { AlertTriangle, ChevronDown, ChevronsUpDown, ChevronUp, Eye, EyeOff, Plu
5252
import { iconNames } from 'lucide-react/dynamic.mjs';
5353
import { toast } from 'sonner';
5454
import { useObjectTranslation } from '@object-ui/i18n';
55+
import { createAuthenticatedFetch } from '@object-ui/auth';
5556
import { useMetadataLocale, t, tFormat } from './i18n.js';
5657
import { fieldHistoryChoiceOf, fieldHistoryOptions, fieldHistoryValueOf } from './fieldHistoryChoice.js';
5758
import { isKnownViewType, viewTypeLabel } from './viewTypeLabels.js';
@@ -1198,9 +1199,17 @@ const EMPTY_FIELD_SELECTOR_OPTIONS: FieldSelectorOption[] = [];
11981199
* other raw-`fetch` callers in this package already use (`useRecordApprovals`,
11991200
* `suggestedBindingsApi`, `studio-design/packages-io`): the server's own
12001201
* message when it sent one, otherwise the status.
1202+
*
1203+
* The read goes through the console's authenticated fetch, built per call, with
1204+
* `credentials: 'include'`: a bare `fetch` with no init sends the session cookie
1205+
* alone (the default `same-origin` credentials), so a session held by its bearer
1206+
* token alone was answered as anonymous and a `401` never reached the console's
1207+
* session-ended check.
12011208
*/
12021209
async function fetchFieldSelectorOptions(objectName: string): Promise<FieldSelectorOption[]> {
1203-
const res = await fetch(`/api/v1/objects/${objectName}/fields`);
1210+
const res = await createAuthenticatedFetch()(`/api/v1/objects/${objectName}/fields`, {
1211+
credentials: 'include',
1212+
});
12041213
// Read the body BEFORE branching on `ok`: a refusal usually carries the more
12051214
// useful sentence, and a non-JSON body must not be mistaken for a refusal
12061215
// that said nothing (it still throws below — it just cannot add a cause).

‎ui/packages/components/src/share/ShareDialog.tsx‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,10 @@
1616
* `apiBase`, `objectName`, and `recordId`.
1717
*/
1818

19-
import { useCallback, useEffect, useMemo, useState } from 'react';
19+
import { useCallback, useContext, useEffect, useMemo, useState } from 'react';
2020
import { Copy, Link2, Loader2, ShieldOff, Trash2 } from 'lucide-react';
2121
import { useObjectTranslation } from '@object-ui/i18n';
22+
import { SchemaRendererContext } from '@object-ui/react';
2223
import type {
2324
ShareLink as SpecShareLink,
2425
ShareLinkAudience,
@@ -199,6 +200,14 @@ export function ShareDialog({
199200
const [error, setError] = useState<ShareDialogFailure | null>(null);
200201
const [draft, setDraft] = useState<CreateLinkDraft>(DEFAULT_DRAFT);
201202
const [justCopied, setJustCopied] = useState<string | null>(null);
203+
// Every request rides the host's AUTHENTICATED fetch (`SchemaRendererProvider`'s
204+
// `apiFetch`), the channel the renderers' own reads use: a session held by its
205+
// bearer token alone carries no cookie, so `credentials: 'include'` on the bare
206+
// global fetch read as anonymous and the dialog listed, created and revoked
207+
// nothing, while a `401` never reached the host's session-ended check. Read the
208+
// context directly (not `useSchemaContext`, which throws with no provider): a
209+
// host that mounts none keeps the global fetch, cookies included.
210+
const apiFetch = useContext(SchemaRendererContext)?.apiFetch;
202211

203212
const headers = useCallback(async (): Promise<Record<string, string>> => {
204213
const base: Record<string, string> = { 'Content-Type': 'application/json' };
@@ -220,7 +229,8 @@ export function ShareDialog({
220229
setError(null);
221230
try {
222231
const h = await headers();
223-
const res = await fetch(listUrl, { headers: h, credentials: 'include' });
232+
const doFetch = apiFetch ?? fetch;
233+
const res = await doFetch(listUrl, { headers: h, credentials: 'include' });
224234
if (!res.ok) throw new Error(`HTTP ${res.status}`);
225235
const body = (await res.json()) as { links?: ShareLink[]; data?: ShareLink[] };
226236
setLinks(body.links ?? body.data ?? []);
@@ -229,7 +239,7 @@ export function ShareDialog({
229239
} finally {
230240
setLoading(false);
231241
}
232-
}, [listUrl, headers]);
242+
}, [listUrl, headers, apiFetch]);
233243

234244
useEffect(() => {
235245
if (open) {
@@ -247,7 +257,8 @@ export function ShareDialog({
247257
? undefined
248258
: new Date(Date.now() + draft.expiresInDays * 24 * 60 * 60 * 1000).toISOString();
249259
const h = await headers();
250-
const res = await fetch(`${apiBase.replace(/\/+$/, '')}/v1/share-links`, {
260+
const doFetch = apiFetch ?? fetch;
261+
const res = await doFetch(`${apiBase.replace(/\/+$/, '')}/v1/share-links`, {
251262
method: 'POST',
252263
headers: h,
253264
credentials: 'include',
@@ -281,13 +292,14 @@ export function ShareDialog({
281292
} finally {
282293
setCreating(false);
283294
}
284-
}, [apiBase, headers, objectName, recordId, draft, publicBaseUrl]);
295+
}, [apiBase, headers, objectName, recordId, draft, publicBaseUrl, apiFetch]);
285296

286297
const handleRevoke = useCallback(
287298
async (link: ShareLink) => {
288299
try {
289300
const h = await headers();
290-
const res = await fetch(
301+
const doFetch = apiFetch ?? fetch;
302+
const res = await doFetch(
291303
`${apiBase.replace(/\/+$/, '')}/v1/share-links/${encodeURIComponent(link.id)}`,
292304
{ method: 'DELETE', headers: h, credentials: 'include' },
293305
);
@@ -303,7 +315,7 @@ export function ShareDialog({
303315
setError({ message: err?.message, step: 'revoke' });
304316
}
305317
},
306-
[apiBase, headers],
318+
[apiBase, headers, apiFetch],
307319
);
308320

309321
const handleCopy = useCallback(

‎ui/packages/plugin-chatbot/src/useAgents.ts‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,13 @@
66
* (`@objectstack/service-ai`) backend.
77
*
88
* The hook hits `GET {apiBase}/agents` (the canonical endpoint exposed by
9-
* `buildAgentRoutes`) and returns a normalized list. It is intentionally
10-
* dependency-free (uses `fetch`) so the chatbot package can stay light.
9+
* `buildAgentRoutes`) and returns a normalized list. It asks through the host's
10+
* `apiFetch`, else the global `fetch` (see {@link useAgents}), and imports no
11+
* HTTP client, so the chatbot package can stay light.
1112
*/
1213

13-
import { useEffect, useRef, useState, useCallback } from 'react';
14+
import { useContext, useEffect, useRef, useState, useCallback } from 'react';
15+
import { SchemaRendererContext, type ApiFetch } from '@object-ui/react';
1416
import { resolveAgentParam, isBuildAgent } from './agentAliases';
1517

1618
/**
@@ -241,6 +243,7 @@ function fetchAgentsCached(
241243
apiBase: string,
242244
headers: Record<string, string> | undefined,
243245
force: boolean,
246+
doFetch: ApiFetch,
244247
): Promise<AgentDescriptor[]> {
245248
if (force) {
246249
agentsCache.delete(apiBase);
@@ -255,7 +258,7 @@ function fetchAgentsCached(
255258
if (inFlight && !force) return inFlight;
256259

257260
const url = `${apiBase.replace(/\/$/, '')}/agents`;
258-
const promise = fetch(url, {
261+
const promise = doFetch(url, {
259262
method: 'GET',
260263
headers: { Accept: 'application/json', ...(headers ?? {}) },
261264
credentials: 'include',
@@ -334,6 +337,13 @@ export function __resetAgentsCatalog(): void {
334337
/**
335338
* Fetches the active agent catalog from the backend.
336339
*
340+
* Every request rides the host's AUTHENTICATED fetch (`SchemaRendererProvider`'s
341+
* `apiFetch`), the channel the renderers' own reads use: a session held by its
342+
* bearer token alone carries no cookie, so `credentials: 'include'` on the bare
343+
* global fetch read as anonymous, and a `401` never reached the host's
344+
* session-ended check. A host that mounts no provider keeps the global fetch,
345+
* cookies included.
346+
*
337347
* The request leaves after the first frame has painted (objectui#12980), not
338348
* in the mounting commit — see {@link afterCatalogFrame}.
339349
*
@@ -352,6 +362,12 @@ export function useAgents(options: UseAgentsOptions = {}): UseAgentsReturn {
352362
// triggering a refetch on every render.
353363
const headersRef = useRef(headers);
354364
headersRef.current = headers;
365+
// The host's authenticated fetch, or the global one with no provider: read
366+
// directly (not `useSchemaContext`, which throws with no provider). Held in a
367+
// ref like the headers: the catalog is one answer per `apiBase`.
368+
const apiFetch = useContext(SchemaRendererContext)?.apiFetch;
369+
const fetchRef = useRef<ApiFetch>(apiFetch ?? fetch);
370+
fetchRef.current = apiFetch ?? fetch;
355371

356372
useEffect(() => {
357373
if (!enabled || !apiBase) return;
@@ -362,7 +378,7 @@ export function useAgents(options: UseAgentsOptions = {}): UseAgentsReturn {
362378
setIsLoading(true);
363379
setError(undefined);
364380

365-
fetchAgentsCached(apiBase, headersRef.current, reloadToken > 0)
381+
fetchAgentsCached(apiBase, headersRef.current, reloadToken > 0, fetchRef.current)
366382
.then((normalized) => {
367383
if (cancelled) return;
368384
setAgents(normalized.length > 0 ? normalized : fallback);

‎ui/packages/plugin-chatbot/src/useAiModels.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@
1010
* default model id. Free / single-model envs return one entry, so the footer
1111
* picker (which `ChatbotEnhanced` renders only for 2+ models) stays hidden.
1212
*
13-
* Intentionally dependency-free (uses `fetch`), mirroring {@link useAgents}.
13+
* It asks through the host's `apiFetch`, else the global `fetch`, and imports no
14+
* HTTP client, mirroring {@link useAgents}.
1415
*/
1516

16-
import { useEffect, useRef, useState, useCallback } from 'react';
17+
import { useContext, useEffect, useRef, useState, useCallback } from 'react';
18+
import { SchemaRendererContext, type ApiFetch } from '@object-ui/react';
1719
import type { ChatbotModelOption } from './ChatbotEnhanced';
1820

1921
export interface UseAiModelsOptions {
@@ -83,6 +85,13 @@ function normalize(raw: RawModel[]): ChatbotModelOption[] {
8385
/**
8486
* Fetch the AI-model allowlist for the current environment.
8587
*
88+
* Every request rides the host's AUTHENTICATED fetch (`SchemaRendererProvider`'s
89+
* `apiFetch`), the channel the renderers' own reads use: a session held by its
90+
* bearer token alone carries no cookie, so `credentials: 'include'` on the bare
91+
* global fetch read as anonymous, and a `401` never reached the host's
92+
* session-ended check. A host that mounts no provider keeps the global fetch,
93+
* cookies included.
94+
*
8695
* @example
8796
* const { models, defaultModelId } = useAiModels({ apiBase: '/api/v1/ai' });
8897
*/
@@ -99,6 +108,11 @@ export function useAiModels(options: UseAiModelsOptions = {}): UseAiModelsReturn
99108
// triggering a refetch on every render.
100109
const headersRef = useRef(headers);
101110
headersRef.current = headers;
111+
// The host's authenticated fetch, or the global one with no provider (see the
112+
// hook's doc). Held in a ref like the headers.
113+
const apiFetch = useContext(SchemaRendererContext)?.apiFetch;
114+
const fetchRef = useRef<ApiFetch>(apiFetch ?? fetch);
115+
fetchRef.current = apiFetch ?? fetch;
102116

103117
useEffect(() => {
104118
if (!enabled || !apiBase) return;
@@ -121,7 +135,7 @@ export function useAiModels(options: UseAiModelsOptions = {}): UseAiModelsReturn
121135
setIsLoading(true);
122136
setError(undefined);
123137
try {
124-
const res = await fetch(url, {
138+
const res = await fetchRef.current(url, {
125139
method: 'GET',
126140
headers: { Accept: 'application/json', ...(headersRef.current ?? {}) },
127141
credentials: 'include',

0 commit comments

Comments
 (0)