Skip to content

Commit 06ce712

Browse files
fix(console): evaluate a setting's visible predicate with the expression interpreter, and hide it when it does not evaluate (#13432)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoFczGz9PyHzzvPyUf2P99fn)_ - [x] Adds no product-specific widget, dialog, hook or string (see AGENTS.md › Product-neutral renderer) ## What changes `SettingsView`'s `evalVisibility` compiled a manifest's `visible` string into a JavaScript function (`new Function` with a `with (data)` scope) and showed the setting whenever that failed. It now evaluates the string with `ExpressionEvaluator` from `@object-ui/core`, the CSP-safe interpreter (`SafeExpressionParser`) the renderer already uses for every other `visible` predicate, with the namespace's values bound as `data`. Called with `throwOnError: true`; a predicate that does not evaluate **hides** the setting. ## Why hide on error The server evaluates the same string with its own closed grammar (`evaluateVisibility` in `@objectstack/service-settings`) and refuses a save whose `visible` it cannot parse. Showing a field the server treats as broken was the console disagreeing with the server in the open direction. Every predicate the shipped manifests use (comparisons, `&&`, `||`, `!` over `data.<key>`, for example `${data.lockout_threshold > 0}`) evaluates as before. A bare identifier without the `data.` prefix no longer resolves, which matches the server grammar. ## Tests New `SettingsView.visibleExpression.test.tsx`, four cases: a predicate that holds and one that does not, the relational and logical operators, a predicate that does not parse (hidden), and an expression reaching outside the `data` scope (hidden, and it has no side effect). Red on `main`, green here: with the fix committed and `SettingsView.tsx` alone restored from `main` (`2958f17`), the file answers **2 failed / 2 passed** (the two failures are the hide-on-error cases); with the fix, **4 passed**. ## Local verification - `pnpm exec vitest run apps/console/src/pages/settings/`: **30 files, 243 passed** - `node scripts/check-changeset-presence.mjs`, `node scripts/check-changeset-no-major.mjs`, `pnpm check:new-line-citations`, `pnpm check:control-bytes`: exit 0 - `pnpm exec eslint` on the two touched files: exit 0 (3 pre-existing warnings in `SettingsView.tsx`, none on the changed lines) - NOT MEASURED locally: `@object-ui/console` `type-check`, which needs the whole workspace built; left to CI's type-check job. Changeset: `@object-ui/console` patch. No issue is linked: this work was dispatched directly. --- _Generated by [Claude Code](https://claude.ai/code/session_01SNJgKweepTFKCrYgaKeFZK)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2958f17 commit 06ce712

3 files changed

Lines changed: 125 additions & 10 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@object-ui/console': patch
3+
---
4+
5+
Settings: a setting's `visible` predicate is evaluated with the renderer's expression interpreter, and a predicate that does not evaluate hides the setting.
6+
7+
The settings page used to compile a manifest's `visible` string into a JavaScript function and show the setting whenever that failed. It now evaluates the string with `ExpressionEvaluator` from `@object-ui/core`, the CSP-safe interpreter every other `visible` predicate in the renderer uses, with the namespace's values bound as `data` (`${data.provider === 'cloudflare'}`). A predicate it cannot evaluate hides the setting, the same way the server refuses a save whose `visible` it cannot parse. Every predicate the shipped manifests declare (comparisons, `&&`, `||`, `!` over `data.<key>`) reads as before.

‎apps/console/src/pages/settings/SettingsView.tsx‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { toast } from 'sonner';
1313
import { ConsolePageHeader } from '@object-ui/app-shell';
1414
import { Loader2, ArrowLeft, ChevronRight, RotateCcw, ShieldAlert } from 'lucide-react';
1515
import { Button, Card, CardContent, Skeleton, Badge, getLazyIcon } from '@object-ui/components';
16+
import { ExpressionEvaluator } from '@object-ui/core';
1617
import { extractFieldErrors } from '@object-ui/react';
1718
import { useObjectTranslation } from '@object-ui/i18n';
1819
import { SettingsField } from './SettingsField';
@@ -27,21 +28,23 @@ import { useSettingsLabel, type SettingsLabelHelpers } from './useSettingsLabel'
2728
import { useUnsavedLeaveGuard } from './useUnsavedLeaveGuard';
2829

2930
/**
30-
* Evaluate the manifest's `visible: "${data.foo === 'bar'}"`
31-
* expression against the live value map. Intentionally minimal — a
32-
* full expression engine lives in `@object-ui/core` and can be wired
33-
* in later via plugin.
31+
* Evaluate the manifest's `visible: "${data.foo === 'bar'}"` expression
32+
* against the live value map, through `@object-ui/core`'s `ExpressionEvaluator`
33+
* — the CSP-safe interpreter (`SafeExpressionParser`) every other `visible`
34+
* predicate in the renderer is judged by, never a compiled JS function. The
35+
* manifest's values are bound as `data`, the one namespace the server's
36+
* settings grammar reads too.
37+
*
38+
* Fails CLOSED: a predicate that does not evaluate hides the setting, the way
39+
* the server refuses a save whose `visible` it cannot parse. Showing a field
40+
* the deployment never meant to expose is the worse of the two mistakes.
3441
*/
3542
function evalVisibility(expr: string | undefined, data: Record<string, unknown>): boolean {
3643
if (!expr) return true;
37-
const trimmed = expr.trim();
38-
const m = trimmed.match(/^\$\{(.+)\}$/);
39-
if (!m) return true;
4044
try {
41-
const fn = new Function('data', `with (data) { return (${m[1]}); }`);
42-
return Boolean(fn(data));
45+
return new ExpressionEvaluator({ data }).evaluateCondition(expr, { throwOnError: true });
4346
} catch {
44-
return true;
47+
return false;
4548
}
4649
}
4750

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* SettingsView — a setting's `visible` predicate is judged by the renderer's
11+
* expression interpreter (`ExpressionEvaluator` from `@object-ui/core`), with
12+
* the manifest values bound as `data`, and a predicate that does not evaluate
13+
* HIDES the setting.
14+
*
15+
* The server judges the same string with its own closed grammar and refuses a
16+
* save whose `visible` it cannot parse, so the console must not show a field
17+
* the server would treat as broken, and must never run the string as code.
18+
*/
19+
20+
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
21+
import { render, screen, cleanup } from '@testing-library/react';
22+
import { MemoryRouter, Route, Routes } from 'react-router-dom';
23+
import { I18nProvider } from '@object-ui/i18n';
24+
25+
const getSettingsNamespace = vi.fn();
26+
27+
vi.mock('../api', async () => {
28+
const actual = await vi.importActual<typeof import('../api')>('../api');
29+
return {
30+
...actual,
31+
getSettingsNamespace: (...a: unknown[]) => getSettingsNamespace(...a),
32+
saveSettingsNamespace: vi.fn(),
33+
runSettingsAction: vi.fn(),
34+
};
35+
});
36+
37+
vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
38+
39+
import { SettingsView } from '../SettingsView';
40+
41+
const PROBE = '__settingsVisibleProbe';
42+
43+
/** One always-visible anchor field, plus a field gated by `visible`. */
44+
function payload(visible: string, values: Record<string, unknown>) {
45+
return {
46+
manifest: {
47+
namespace: 'ai',
48+
label: 'AI',
49+
specifiers: [
50+
{ type: 'text', key: 'provider', label: 'Provider anchor' },
51+
{ type: 'text', key: 'gated', label: 'Gated field', visible },
52+
],
53+
},
54+
values: Object.fromEntries(
55+
Object.entries({ provider: '', gated: '', ...values }).map(([k, v]) => [k, { value: v, source: 'default' }]),
56+
),
57+
};
58+
}
59+
60+
async function gatedFieldShown(visible: string, values: Record<string, unknown> = {}): Promise<boolean> {
61+
getSettingsNamespace.mockResolvedValue(payload(visible, values));
62+
render(
63+
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }}>
64+
<MemoryRouter initialEntries={['/settings/ai']}>
65+
<Routes>
66+
<Route path="/settings/:namespace" element={<SettingsView />} />
67+
</Routes>
68+
</MemoryRouter>
69+
</I18nProvider>,
70+
);
71+
await screen.findByText('Provider anchor');
72+
return screen.queryByText('Gated field') !== null;
73+
}
74+
75+
beforeEach(() => {
76+
vi.clearAllMocks();
77+
delete (globalThis as Record<string, unknown>)[PROBE];
78+
});
79+
afterEach(() => {
80+
cleanup();
81+
delete (globalThis as Record<string, unknown>)[PROBE];
82+
});
83+
84+
describe('SettingsView — a setting\'s `visible` predicate', () => {
85+
it('shows the setting when the predicate holds and hides it when it does not', async () => {
86+
expect(await gatedFieldShown("${data.provider === 'cloudflare'}", { provider: 'cloudflare' })).toBe(true);
87+
cleanup();
88+
expect(await gatedFieldShown("${data.provider === 'cloudflare'}", { provider: 'openai' })).toBe(false);
89+
});
90+
91+
it('reads the relational and logical operators the shipped manifests use', async () => {
92+
expect(await gatedFieldShown('${data.provider > 0 && data.provider !== 3}', { provider: 5 })).toBe(true);
93+
cleanup();
94+
expect(await gatedFieldShown('${data.provider > 0}', { provider: 0 })).toBe(false);
95+
});
96+
97+
it('hides the setting when the predicate does not parse', async () => {
98+
expect(await gatedFieldShown('${data.provider ===}')).toBe(false);
99+
});
100+
101+
it('never runs the predicate as code, and hides a setting whose predicate it cannot evaluate', async () => {
102+
expect(await gatedFieldShown(`\${(globalThis.${PROBE} = 1) && true}`)).toBe(false);
103+
expect((globalThis as Record<string, unknown>)[PROBE]).toBeUndefined();
104+
});
105+
});

0 commit comments

Comments
 (0)