Skip to content

Commit 5f34d65

Browse files
fix(ui): plugin same-server reads and me/localization carry the stored bearer (#37489)
Fixes #37225 Clause-②: no Metadata-protocol: none ## 维护者速读 - 只用登录令牌、没有会话 Cookie 的用户(例如嵌入在别的网站里、浏览器拦了第三方 Cookie):分享链接、AI 助手列表、模型列表、待审批操作、对话内审批、字段选择器和界面语言,以前都被当成未登录,现在能正常加载。 - 属于“会话凭证统一携带”这条线:插件和控制台的早期请求之前漏带了令牌,这次补齐,并让守卫覆盖全部前端包。 - 若出错,影响的是上述几个面板仍显示为空或未登录;改动只在前端请求里多带一个请求头,可直接撤回。控制台与接口不同源的部署这次还没覆盖,已另立跟进卡。 - 无 ## What changes The renderer packages' same-server reads sent the bare global fetch with the cookie only, so a session held by its bearer token alone was answered as anonymous. Every site the card lists is now converted or recorded with its reason: - **components / ShareDialog** (3 calls: list, create, revoke) and **plugin-chatbot** (useAgents, useAiModels, usePendingActions, useHitlInChat) send through the host's `SchemaRendererContext.apiFetch` (the console builds it as `createAuthenticatedFetch({ sameOriginOnly: true })`), falling back to the global fetch with no host. `credentials: 'include'` stays, so cookie sessions are unchanged. No renderer package gains a dependency on `@object-ui/auth` (layering per `ui/AGENTS.md`; no cycle introduced). - **app-shell / field selector widget** (`fetchFieldSelectorOptions`) goes through `createAuthenticatedFetch()`; app-shell already depends on auth. - **console / me-localization**: the stored bearer rides all three legs, the early `index.html` seed request, `languageSeed.fetchAndCacheSeed`, and `LocalizationFetchProvider`. Both TS legs build the init through one helper, `meLocalizationInit(preferred)`, so the in-flight share key (`inflightGetKey`) still matches between the seed and the provider. The helper reads the token through `TokenStorage.get()`, so a storage-blocked embed still sends the token sign-in kept in memory; `index.html` runs before the bundle and stays on `localStorage` (rework round 1, S5). - **field selector path**: the object name is now `encodeURIComponent`-encoded into `/api/v1/objects/NAME/fields` (rework round 1, N3; not separately pinned, since the helper is module-private). - **Ratchet widened** (`sameServerFetch.bearer.ratchet.test.ts`): it now scans every `ui/packages/*/src` plus the console, and names the nine renderer packages explicitly so a dropped root fails loudly. A new arm counts a global fetch on a written `/api/` literal with no init, or with an inline init without `credentials`, as bare. The allow list stays shrink-only: the LocalizationFetchProvider row is removed (now 0 found), and two rows are added for sites read and recorded: `auth/LoginForm.tsx` (SSO sign-in, before any session exists) and `permissions/MePermissionsProvider.tsx` (the `fetcher ?? fetch` fallback; the console passes the authenticated fetch). Sites recorded but not converted, because they already ride the host's authenticated fetch (`apiFetch ?? fetch`, with the reason in their header docs): useRecordCrudVerdicts, useRowApprovalLocks, useRecordEditable, stageChangeStarts, queueClaim, ObjectChart, DatasetWidget, ReportDateRange. Injection only, with no bare fallback: preferenceOptions, ShareableObjectRefField. ## Tests <details><summary>New pins (bearer-only server double, each with a cookie-only control)</summary> - `app-shell/src/console/rendererFetch.bearerSession-37225.test.tsx`: ShareDialog list, useAgents, useAiModels, usePendingActions (list + approve) and useHitlInChat (decide), each mounted in a `SchemaRendererProvider` that carries the console's composition. With a stored token, the request carries `Authorization: Bearer TOKEN` beside `credentials: 'include'`. CONTROL, with no token: cookie-only, the 401 is refused, and it reaches the session-ended event. - `FieldSelectorWidget.loadFailure.test.tsx`: a new describe for the bearer-only session, plus a cookie-only control. - `console/src/__tests__/sessionCheckBootDedup.test.tsx`: a cold load sends one me/localization request carrying the bearer; the share key of the slot equals `meLocalizationInit('zh-CN')` and contains the authorization header; on a later boot with a cached seed, the provider alone sends the bearer. CONTROL, no token: two requests, neither carrying Authorization. CONTROL, a token stored after parse: the second request carries it. - Doubles in three neighbouring field-selector suites gained `headers` (the authenticated fetch reads `set-auth-token` off every response), and two gained the module-top collection imports `check:test-source-alias` asks for. </details> <details><summary>Readings (head f66978d)</summary> - Ratchet: 4/4 passed. - Pins at the merged head: 5 files / 82 tests passed. - Rework round 1 (head b0a4db6): the localization and field-selector pins plus the boot-dedup and App boot suites: 11 files / 139 tests passed. - Narrowed affected suites (app-shell metadata-admin, components share, plugin-chatbot, console subset): 168 files / 1722 tests passed; console subset 26 files / 371 tests passed. - Type-check (turbo, the 4 touched packages and their deps): 83/83 tasks successful. - `pnpm --dir ui exec vitest run scripts/`: 172 passed, 2 skipped. </details> <details><summary>Ablations (restored through ablation-replace; blob equals HEAD; git diff HEAD empty)</summary> - ShareDialog list read reverted to the bare fetch: the ratchet goes red (unlisted site), and both ShareDialog pins go red, including the control's session-end half. 3 failed / 8 passed. - The Authorization line deleted from `meLocalizationInit`: the 4 bearer cases go red and the cookie control stays green. 4 failed / 49 passed. - Rework round 1: `storedToken()` reverted from `TokenStorage.get()` to the direct `localStorage` read: only the new memory-fallback pin goes red. 1 failed / 53 passed. </details> ## Acceptance notes - **Deviation from the card's Expected, ruled A by the seat.** The card's Expected names a per-call `createAuthenticatedFetch`. The renderer packages instead send through the host's `apiFetch`. In the console that host fetch *is* `createAuthenticatedFetch({ sameOriginOnly: true })`, so `sameOriginOnly` and the settle signal are applied once, at the host, and the renderer packages stay free of an auth dependency. The cost: a host that mounts no provider stays cookie-only. - Changesets name the scope this PR covers: same-origin requests. Split-origin layouts still go out without the token (see #37509). They also note that a stored token now takes precedence over an `Authorization` a caller passes, and that the host's tenant and language headers ride these calls (N1). - The field selector reads `/api/v1/objects/NAME/fields`. No server route registers that path, and no form in either tree declares the widget, so it is dormant. Read only, not filed. - A cross-origin `VITE_AI_BASE_URL` / server URL goes bare through the `sameOriginOnly` host fetch, as the card allows. - Out-of-card bare sites, read and not converted: auth/LoginForm (1), auth/createAuthClient (3, fenced to the auth lane), data-objectstack/index (2, via an injected fetchImpl), data-objectstack/metadata-client (1), react/useElementApiDataSource (1, host fallback), react/useDatasetDimensionLabels (1, host fallback). ## Follow-up cards (rework round 1) - S1 + S2 + S3b, ratchet completeness (aliased fallback, concatenated or const URLs, spread inits, `same-origin`) and the `react` host fallbacks: #37505 - S3a, `data-objectstack` uploads and `metadata-client` bypassing the injected fetch: #37506 - S3c, the three same-server requests in `createAuthClient` (auth lane): #37507 - S3d, the field-selector route that no server registers: register it or retire the widget: #37508 - S4, split-origin deployments, where the seven converted calls still go without the token: #37509 ## Verification Two minutes: `pnpm --dir ui exec vitest run --maxWorkers=2 packages/app-shell/src/console/rendererFetch.bearerSession-37225.test.tsx`. Expect 7 passed: each bearer case carries `Bearer stored-session-token`, and each control goes out cookie-only. Read first, by risk: 1. `ui/apps/console/src/languageSeed.ts`: `meLocalizationInit`. The share key between the seed and the provider depends on both legs building the same headers. 2. `ui/packages/app-shell/src/sameServerFetch.bearer.ratchet.test.ts`: the widened roots and the new bare-literal arm. 3. `ui/apps/console/index.html`: the early seed script reads the token in a try block. --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6Ca6EBDpTBZk8v46Jjv)_ <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6Ca6EBDpTBZk8v46Jjv --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 818615b commit 5f34d65

20 files changed

Lines changed: 737 additions & 74 deletions
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/plugin-chatbot': patch
3+
---
4+
5+
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
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`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.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
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
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/console': patch
3+
---
4+
5+
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
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`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.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/components': patch
3+
---
4+
5+
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
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`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.

‎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/__tests__/sessionCheckBootDedup.test.tsx‎

Lines changed: 145 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,16 @@ import indexHtml from '../../index.html?raw';
2121
import mainSource from '../main.tsx?raw';
2222
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2323
import { render, screen, act, cleanup } from '@testing-library/react';
24-
import { AuthGuard, AuthProvider, useAuth } from '@object-ui/auth';
24+
import { AuthGuard, AuthProvider, TokenStorage, useAuth } from '@object-ui/auth';
2525
import { preflightAuth } from '../lib/auth-preflight';
2626
import { readConsoleDiscovery } from '../lib/early-discovery';
2727
import { getSharedDiscovery } from '@object-ui/data-objectstack';
2828
import { clearSharedDiscoveryCache } from '../../../../packages/data-objectstack/src/sharedDiscovery';
2929
import { SessionUserScope } from '../../../../packages/auth/src/ActiveOrganizationStorage';
30-
import { resetInflightGetsForTesting } from '../../../../packages/types/src/http-inflight';
30+
import { inflightGetKey, resetInflightGetsForTesting } from '../../../../packages/types/src/http-inflight';
3131
import { readCachedLanguageSeed, useLocalization } from '@object-ui/i18n';
3232
import { PLATFORM_LOCALE_READ_ALIASES, PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system';
33-
import { __resetPreferredLocaleForTests, pickPreferredLocale, seedTenantLanguage } from '../languageSeed';
33+
import { __resetPreferredLocaleForTests, meLocalizationInit, pickPreferredLocale, seedTenantLanguage } from '../languageSeed';
3434
import { LocalizationFetchProvider } from '../LocalizationFetchProvider';
3535

3636
const TOKEN = 'tok_valid';
@@ -898,3 +898,145 @@ describe("the language seed's me/localization starts at parse time beside discov
898898
expect(localizationCalls()).toHaveLength(1);
899899
});
900900
});
901+
902+
describe('a bearer-only session: the stored Bearer rides me/localization on all three legs, and they still share one request (objectstack#37225)', () => {
903+
const DISCOVERY_SLOT = Symbol.for('objectui.earlyDiscovery');
904+
const SEED_SLOT = Symbol.for('objectui.earlyLanguageSeed');
905+
const ME = '/api/v1/auth/me/localization';
906+
const BEARER = 'tok_bearer_only';
907+
const SIGNED_IN = { authenticated: true, locale: 'zh-CN', currency: 'CNY', timezone: 'Asia/Shanghai' };
908+
const localizationCalls = () => fetchStub.mock.calls.filter(([input]) => urlOf(input).includes('/me/localization'));
909+
const authorizationOf = (call: unknown[] | undefined) =>
910+
new Headers((call?.[1] as RequestInit | undefined)?.headers).get('Authorization');
911+
const parse = () => {
912+
runScript('startEarlyDiscovery');
913+
runScript('startEarlyLanguageSeed');
914+
};
915+
const forget = () => {
916+
const holder = globalThis as unknown as Record<symbol, unknown>;
917+
delete holder[DISCOVERY_SLOT];
918+
delete holder[SEED_SLOT];
919+
clearSharedDiscoveryCache();
920+
resetInflightGetsForTesting();
921+
__resetPreferredLocaleForTests();
922+
};
923+
924+
function Value() {
925+
const { locale, currency } = useLocalization();
926+
return <span data-testid="localization">{`${locale ?? '-'}/${currency ?? '-'}`}</span>;
927+
}
928+
929+
beforeEach(() => {
930+
forget();
931+
discoveryAnswer = () => json({ locale: { default: 'en', supported: ['en', 'zh-CN'] } });
932+
vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('zh-CN');
933+
// A server that sees only the bearer: no cookie rides in a unit test, so a
934+
// read without it is a caller it cannot see.
935+
localizationAnswer = () =>
936+
authorizationOf(fetchStub.mock.lastCall) === `Bearer ${BEARER}` ? json(SIGNED_IN) : json({ authenticated: false });
937+
});
938+
afterEach(forget);
939+
940+
it('one cold load, one me/localization: parse time, seed and provider share it, and it carries the Bearer', async () => {
941+
localStorage.setItem('auth-session-token', BEARER);
942+
parse();
943+
await settle();
944+
945+
await seedTenantLanguage('', 1_000);
946+
expect(readCachedLanguageSeed()).toBe('zh-CN');
947+
render(
948+
<LocalizationFetchProvider endpoint={ME}>
949+
<Value />
950+
</LocalizationFetchProvider>,
951+
);
952+
expect(await screen.findByText('zh-CN/CNY')).toBeTruthy();
953+
954+
expect(localizationCalls()).toHaveLength(1);
955+
const [, init] = localizationCalls()[0]!;
956+
expect(init).toMatchObject({ credentials: 'include' });
957+
expect(authorizationOf(localizationCalls()[0])).toBe(`Bearer ${BEARER}`);
958+
expect(new Headers(init?.headers).get('Accept-Language')).toBe('zh-CN');
959+
});
960+
961+
it("the share key still matches: index.html's request is keyed as the seed's and the provider's init", async () => {
962+
localStorage.setItem('auth-session-token', BEARER);
963+
parse();
964+
await settle();
965+
const slot = (globalThis as unknown as Record<symbol, { url: string; init: RequestInit }>)[SEED_SLOT]!;
966+
expect(inflightGetKey(slot.url, slot.init)).toBe(inflightGetKey(ME, meLocalizationInit('zh-CN')));
967+
expect(inflightGetKey(ME, meLocalizationInit('zh-CN'))).toContain(`authorization=Bearer ${BEARER}`);
968+
});
969+
970+
it('every later boot (a cached seed): the provider reads alone, with the Bearer, and is answered as the user', async () => {
971+
localStorage.setItem('auth-session-token', BEARER);
972+
localStorage.setItem('objectui-locale-seed', 'zh-CN');
973+
render(
974+
<LocalizationFetchProvider endpoint={ME}>
975+
<Value />
976+
</LocalizationFetchProvider>,
977+
);
978+
expect(await screen.findByText('zh-CN/CNY')).toBeTruthy();
979+
expect(localizationCalls()).toHaveLength(1);
980+
expect(authorizationOf(localizationCalls()[0])).toBe(`Bearer ${BEARER}`);
981+
});
982+
983+
it('CONTROL: no stored token, the cookie session: no Authorization on any leg, as before', async () => {
984+
parse();
985+
await settle();
986+
await seedTenantLanguage('', 1_000);
987+
// The seed took the parse-time request: one so far.
988+
expect(localizationCalls()).toHaveLength(1);
989+
render(
990+
<LocalizationFetchProvider endpoint={ME}>
991+
<Value />
992+
</LocalizationFetchProvider>,
993+
);
994+
await settle();
995+
// A signed-out answer is never handed to the provider, which asks itself,
996+
// exactly as before this change.
997+
expect(localizationCalls()).toHaveLength(2);
998+
for (const call of localizationCalls()) {
999+
expect(call[1]).toMatchObject({ credentials: 'include' });
1000+
expect(authorizationOf(call)).toBeNull();
1001+
}
1002+
// The bearer-only server cannot see it: nothing of the user's is cached or shown.
1003+
expect(readCachedLanguageSeed()).toBeNull();
1004+
expect(screen.getByTestId('localization').textContent).toBe('-/-');
1005+
});
1006+
1007+
it('CONTROL: a token stored since parse time is not answered by the parse-time request; the seed asks once itself, with it', async () => {
1008+
parse();
1009+
await settle();
1010+
localStorage.setItem('auth-session-token', BEARER);
1011+
1012+
await seedTenantLanguage('', 1_000);
1013+
1014+
expect(localizationCalls()).toHaveLength(2);
1015+
expect(authorizationOf(localizationCalls()[0])).toBeNull();
1016+
expect(authorizationOf(localizationCalls()[1])).toBe(`Bearer ${BEARER}`);
1017+
expect(readCachedLanguageSeed()).toBe('zh-CN');
1018+
});
1019+
1020+
it('blocked storage (an embed whose localStorage throws): the token sign-in kept in memory still rides the provider read', async () => {
1021+
vi.spyOn(window, 'localStorage', 'get').mockImplementation(() => {
1022+
throw new DOMException('blocked', 'SecurityError');
1023+
});
1024+
expect(() => window.localStorage.getItem('auth-session-token')).toThrow();
1025+
try {
1026+
// Sign-in stores the token; with storage blocked, `TokenStorage` keeps it in memory.
1027+
TokenStorage.set(BEARER);
1028+
expect(TokenStorage.get()).toBe(BEARER);
1029+
expect(new Headers(meLocalizationInit('zh-CN').headers).get('Authorization')).toBe(`Bearer ${BEARER}`);
1030+
render(
1031+
<LocalizationFetchProvider endpoint={ME}>
1032+
<Value />
1033+
</LocalizationFetchProvider>,
1034+
);
1035+
expect(await screen.findByText('zh-CN/CNY')).toBeTruthy();
1036+
expect(localizationCalls()).toHaveLength(1);
1037+
expect(authorizationOf(localizationCalls()[0])).toBe(`Bearer ${BEARER}`);
1038+
} finally {
1039+
TokenStorage.clear();
1040+
}
1041+
});
1042+
});

0 commit comments

Comments
 (0)