Skip to content
Merged
10 changes: 10 additions & 0 deletions .changeset/37225-chatbot-hooks-bearer.md
Original file line number Diff line number Diff line change
@@ -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 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.
10 changes: 10 additions & 0 deletions .changeset/37225-field-selector-bearer.md
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 10 additions & 0 deletions .changeset/37225-localization-bearer.md
Original file line number Diff line number Diff line change
@@ -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. 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.
10 changes: 10 additions & 0 deletions .changeset/37225-share-dialog-bearer.md
Original file line number Diff line number Diff line change
@@ -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 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.
9 changes: 8 additions & 1 deletion ui/apps/console/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down
22 changes: 13 additions & 9 deletions ui/apps/console/src/LocalizationFetchProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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,
Expand Down Expand Up @@ -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.
Expand Down
148 changes: 145 additions & 3 deletions ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ 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';
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';
Expand Down Expand Up @@ -898,3 +898,145 @@ 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<symbol, unknown>;
delete holder[DISCOVERY_SLOT];
delete holder[SEED_SLOT];
clearSharedDiscoveryCache();
resetInflightGetsForTesting();
__resetPreferredLocaleForTests();
};

function Value() {
const { locale, currency } = useLocalization();
return <span data-testid="localization">{`${locale ?? '-'}/${currency ?? '-'}`}</span>;
}

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(
<LocalizationFetchProvider endpoint={ME}>
<Value />
</LocalizationFetchProvider>,
);
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<symbol, { url: string; init: RequestInit }>)[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(
<LocalizationFetchProvider endpoint={ME}>
<Value />
</LocalizationFetchProvider>,
);
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: 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(
<LocalizationFetchProvider endpoint={ME}>
<Value />
</LocalizationFetchProvider>,
);
await settle();
// 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('-/-');
});

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');
});

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(
<LocalizationFetchProvider endpoint={ME}>
<Value />
</LocalizationFetchProvider>,
);
expect(await screen.findByText('zh-CN/CNY')).toBeTruthy();
expect(localizationCalls()).toHaveLength(1);
expect(authorizationOf(localizationCalls()[0])).toBe(`Bearer ${BEARER}`);
} finally {
TokenStorage.clear();
}
});
});
Loading
Loading