@bevel-software/platform-core-frontend 0.37.0 → 0.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/core/CoreAppShell.tsx +22 -10
- package/src/core/__tests__/AppChrome.test.tsx +27 -10
- package/src/core/__tests__/ShellRoutes.test.tsx +43 -2
- package/src/core/registry.ts +43 -2
- package/src/core/shell-paths.ts +30 -0
- package/src/lib/api.ts +7 -1
- package/src/modules/auth/__tests__/LoginScreen.test.tsx +9 -0
- package/src/modules/auth/__tests__/useAuthState.test.ts +92 -0
- package/src/modules/auth/components/LoginScreen.tsx +2 -0
- package/src/modules/auth/hooks/useAuthState.ts +4 -1
- package/src/modules/auth/index.ts +2 -0
- package/src/modules/auth/state/accountStorage.ts +32 -0
- package/src/modules/auth/state/tokenAccount.ts +53 -0
- package/src/modules/layout/index.ts +1 -1
- package/src/modules/settings/components/SettingsLayout.tsx +52 -9
- package/src/modules/settings/components/SettingsNav.tsx +24 -3
- package/src/modules/settings/components/__tests__/SettingsLayout.test.tsx +266 -5
- package/src/modules/settings/index.ts +1 -1
- package/src/modules/settings/settings-nav-items.tsx +130 -10
- package/src/modules/toolbar/commands/__tests__/actions.test.tsx +20 -5
- package/src/modules/toolbar/commands/actions.tsx +1 -0
- package/src/modules/toolbar/components/ProfileMenu.tsx +13 -1
- package/src/modules/toolbar/components/Toolbar.tsx +3 -2
- package/src/modules/toolbar/components/__tests__/ProfileMenu.app-sections.test.tsx +87 -0
- package/src/modules/toolbar/components/__tests__/ProfileMenu.test.tsx +1 -0
- package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +2 -1
- package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.tools.test.tsx +80 -32
- package/src/modules/workspace/components/renderers/__tests__/htmlToolBridge.test.ts +78 -8
- package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +10 -3
- package/src/modules/workspace/components/renderers/__tests__/pageConsentMemory.test.ts +177 -0
- package/src/modules/workspace/components/renderers/__tests__/useHtmlToolBridge.test.tsx +249 -23
- package/src/modules/workspace/components/renderers/htmlToolBridge.ts +52 -16
- package/src/modules/workspace/components/renderers/pageConsentMemory.ts +75 -0
- package/src/modules/workspace/components/renderers/useHtmlToolBridge.tsx +46 -11
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { useRef } from 'react';
|
|
2
|
-
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
3
3
|
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
|
4
4
|
import { MemoryRouter } from 'react-router-dom';
|
|
5
5
|
import {
|
|
@@ -9,8 +9,10 @@ import {
|
|
|
9
9
|
useHtmlToolBridge,
|
|
10
10
|
type RendererSurface,
|
|
11
11
|
} from '..';
|
|
12
|
+
import { AuthContext, type AuthContextValue } from '../../../../auth';
|
|
12
13
|
import { GitContext, type GitContextValue } from '../../../../git';
|
|
13
14
|
import { WorkspaceContext, type WorkspaceContextValue } from '../../../state/workspace.context';
|
|
15
|
+
import { sha256Hex } from '@bevel-software/platform-shared';
|
|
14
16
|
import { frameChannel, stubServer } from './pageToolsHarness';
|
|
15
17
|
|
|
16
18
|
/**
|
|
@@ -31,9 +33,9 @@ const workspace = { workspaceId: 'main', kbDirName: 'knowledge-base' } as unknow
|
|
|
31
33
|
const git = { status: { branch: 'main' } } as unknown as GitContextValue;
|
|
32
34
|
|
|
33
35
|
/** A downstream renderer: its own frame and document, the controller's bridge. */
|
|
34
|
-
function OtherHtmlRenderer({ viewKey }: { viewKey: number }) {
|
|
36
|
+
function OtherHtmlRenderer({ viewKey, path, source }: { viewKey: number; path: string; source: string }) {
|
|
35
37
|
const iframeRef = useRef<HTMLIFrameElement | null>(null);
|
|
36
|
-
const { toolBridge, cards } = useHtmlToolBridge({ iframeRef, filePath:
|
|
38
|
+
const { toolBridge, cards } = useHtmlToolBridge({ iframeRef, filePath: path, viewKey, source });
|
|
37
39
|
// The document carries the identity the controller minted for it, as the
|
|
38
40
|
// real runtime does (`buildSandboxedHtml` with this `toolBridge`).
|
|
39
41
|
const srcDoc = `${toolBridge.tools ? 'with tools' : 'without tools'} documentId="${toolBridge.documentId}"`;
|
|
@@ -47,7 +49,14 @@ function OtherHtmlRenderer({ viewKey }: { viewKey: number }) {
|
|
|
47
49
|
|
|
48
50
|
type Where = 'file page' | 'elsewhere' | 'embed';
|
|
49
51
|
|
|
50
|
-
function mount(
|
|
52
|
+
function mount(
|
|
53
|
+
where: Where,
|
|
54
|
+
opts: { openFilePage?: (path: string) => void; openInPlatform?: () => void; path?: string; page?: string; source?: string; account?: string | null } = {},
|
|
55
|
+
) {
|
|
56
|
+
const path = opts.path ?? PATH;
|
|
57
|
+
const page = opts.page ?? PAGE;
|
|
58
|
+
let source = opts.source ?? SOURCE;
|
|
59
|
+
const account = opts.account === undefined ? ACCOUNT : opts.account;
|
|
51
60
|
const surface: RendererSurface = {
|
|
52
61
|
kbDirName: 'knowledge-base',
|
|
53
62
|
openLink: () => undefined,
|
|
@@ -60,32 +69,39 @@ function mount(where: Where, opts: { openFilePage?: (path: string) => void; open
|
|
|
60
69
|
offersDownload: false,
|
|
61
70
|
};
|
|
62
71
|
const tree = (viewKey: number) => {
|
|
72
|
+
const view = <OtherHtmlRenderer viewKey={viewKey} path={path} source={source} />;
|
|
63
73
|
const renderer = opts.openInPlatform ? (
|
|
64
|
-
<OpenPageInPlatformContext.Provider value={opts.openInPlatform}>
|
|
65
|
-
<OtherHtmlRenderer viewKey={viewKey} />
|
|
66
|
-
</OpenPageInPlatformContext.Provider>
|
|
74
|
+
<OpenPageInPlatformContext.Provider value={opts.openInPlatform}>{view}</OpenPageInPlatformContext.Provider>
|
|
67
75
|
) : (
|
|
68
|
-
|
|
76
|
+
view
|
|
69
77
|
);
|
|
70
78
|
// A page-tools provider on the embed too: a surface never gets tools, whatever is above it.
|
|
71
79
|
const placed =
|
|
72
80
|
where === 'embed' ? (
|
|
73
|
-
<PageToolsContext.Provider value={{ pagePath:
|
|
81
|
+
<PageToolsContext.Provider value={{ pagePath: page }}>
|
|
74
82
|
<RendererSurfaceContext.Provider value={surface}>{renderer}</RendererSurfaceContext.Provider>
|
|
75
83
|
</PageToolsContext.Provider>
|
|
76
84
|
) : where === 'file page' ? (
|
|
77
|
-
<PageToolsContext.Provider value={{ pagePath:
|
|
85
|
+
<PageToolsContext.Provider value={{ pagePath: page }}>{renderer}</PageToolsContext.Provider>
|
|
78
86
|
) : (
|
|
79
87
|
renderer
|
|
80
88
|
);
|
|
81
|
-
|
|
89
|
+
const app = (
|
|
82
90
|
<MemoryRouter>
|
|
83
91
|
<WorkspaceContext.Provider value={workspace}>
|
|
84
92
|
<GitContext.Provider value={git}>{placed}</GitContext.Provider>
|
|
85
93
|
</WorkspaceContext.Provider>
|
|
86
94
|
</MemoryRouter>
|
|
87
95
|
);
|
|
96
|
+
return account === null ? (
|
|
97
|
+
app
|
|
98
|
+
) : (
|
|
99
|
+
<AuthContext.Provider value={{ user: { id: account } } as unknown as AuthContextValue}>{app}</AuthContext.Provider>
|
|
100
|
+
);
|
|
88
101
|
};
|
|
102
|
+
// Signed in as the account: its session token is the stored one, as after a
|
|
103
|
+
// sign-in in the app (a test of another tab's sign-in replaces it later).
|
|
104
|
+
if (account !== null) window.localStorage.setItem('bevel_token', sessionTokenFor(account));
|
|
89
105
|
let viewKey = 0;
|
|
90
106
|
const result = render(tree(viewKey));
|
|
91
107
|
const iframe = result.container.querySelector('iframe')!;
|
|
@@ -95,10 +111,12 @@ function mount(where: Where, opts: { openFilePage?: (path: string) => void; open
|
|
|
95
111
|
/**
|
|
96
112
|
* The renderer's view ends (a reload, a rebuilt document) while its
|
|
97
113
|
* frame stays. Answers a channel for the NEW document; the one taken
|
|
98
|
-
* before still posts as the old document.
|
|
114
|
+
* before still posts as the old document. A `nextSource` is the page's
|
|
115
|
+
* source after an edit; without one the new view shows the same source.
|
|
99
116
|
*/
|
|
100
|
-
nextView: () => {
|
|
117
|
+
nextView: (nextSource?: string) => {
|
|
101
118
|
viewKey += 1;
|
|
119
|
+
if (nextSource !== undefined) source = nextSource;
|
|
102
120
|
result.rerender(tree(viewKey));
|
|
103
121
|
return frameChannel(iframe);
|
|
104
122
|
},
|
|
@@ -106,7 +124,28 @@ function mount(where: Where, opts: { openFilePage?: (path: string) => void; open
|
|
|
106
124
|
}
|
|
107
125
|
|
|
108
126
|
const write = (requestId: string) => ({ type: 'bevel.tool.call', requestId, fn: 'callTool', args: ['edit_file', {}] });
|
|
109
|
-
const CARD = '
|
|
127
|
+
const CARD = "You're allowing changes using your account. Do you want to allow that?";
|
|
128
|
+
const SOURCE = '<button onclick="bevel.tools.callTool(\'edit_file\', {})">Edit</button>';
|
|
129
|
+
const ACCOUNT = 'user-a';
|
|
130
|
+
/** A session token as the server signs it: a JWT whose `userId` claim names the account (the signature is not checked here). */
|
|
131
|
+
const sessionTokenFor = (userId: string, nonce = 'n') => {
|
|
132
|
+
const part = (value: object) => btoa(JSON.stringify(value)).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
|
133
|
+
return `${part({ alg: 'HS256', typ: 'JWT' })}.${part({ userId, email: `${userId}@example.com`, nonce })}.signature`;
|
|
134
|
+
};
|
|
135
|
+
/** Where the browser keeps the account's Allow: one entry per digest, holding when it was allowed. */
|
|
136
|
+
const ALLOWED_PAGE_KEY_PREFIX = `bevel.account/${ACCOUNT}/htmlPage.allowedWrite.`;
|
|
137
|
+
|
|
138
|
+
/** The digests stored in localStorage, least recently allowed first: read through the storage API, as another tab would. */
|
|
139
|
+
const remembered = (): string[] =>
|
|
140
|
+
Array.from({ length: window.localStorage.length }, (_, i) => window.localStorage.key(i)!)
|
|
141
|
+
.filter((key) => key.startsWith(ALLOWED_PAGE_KEY_PREFIX) && Number.isFinite(Number(window.localStorage.getItem(key))))
|
|
142
|
+
.sort((a, b) => Number(window.localStorage.getItem(a)) - Number(window.localStorage.getItem(b)))
|
|
143
|
+
.map((key) => key.slice(ALLOWED_PAGE_KEY_PREFIX.length));
|
|
144
|
+
/** Every raw memory entry in storage, any account's, well-formed or not. */
|
|
145
|
+
const storedEntries = (): string[] =>
|
|
146
|
+
Array.from({ length: window.localStorage.length }, (_, i) => window.localStorage.key(i)!).filter((key) => key.includes('allowedWrite'));
|
|
147
|
+
|
|
148
|
+
beforeEach(() => window.localStorage.clear());
|
|
110
149
|
|
|
111
150
|
afterEach(() => {
|
|
112
151
|
cleanup();
|
|
@@ -173,37 +212,224 @@ describe('useHtmlToolBridge through a renderer of its own', () => {
|
|
|
173
212
|
expect(server.mcp).toEqual(['read_file']);
|
|
174
213
|
});
|
|
175
214
|
|
|
176
|
-
it('asks once for ten writes at once
|
|
215
|
+
it('asks once for ten writes at once, in the plain sentence with the path under it and two buttons', async () => {
|
|
177
216
|
const server = stubServer();
|
|
178
|
-
const { frame
|
|
217
|
+
const { frame } = mount('file page');
|
|
179
218
|
for (let i = 0; i < 10; i += 1) frame.post(write(`w${i}`));
|
|
180
219
|
expect(await screen.findByText(CARD)).toBeTruthy();
|
|
181
220
|
expect(screen.getByText(PAGE)).toBeTruthy();
|
|
182
|
-
|
|
221
|
+
const dialog = screen.getByRole('dialog');
|
|
222
|
+
const labels = [...dialog.querySelectorAll('button')].map((b) => b.textContent?.trim()).filter((t) => t === "Don't allow" || t === 'Allow');
|
|
223
|
+
expect(labels).toEqual(["Don't allow", 'Allow']);
|
|
224
|
+
expect(screen.getAllByRole('button', { name: 'Allow' })).toHaveLength(1);
|
|
183
225
|
expect(server.mcp).toEqual([]);
|
|
184
226
|
|
|
185
|
-
fireEvent.click(screen.getByRole('button', { name: 'Allow
|
|
227
|
+
fireEvent.click(screen.getByRole('button', { name: 'Allow' }));
|
|
186
228
|
await waitFor(() => expect(frame.replies).toHaveLength(10));
|
|
187
229
|
expect(frame.replies.every((r) => r.ok === true)).toBe(true);
|
|
188
230
|
|
|
189
231
|
frame.post(write('w10'));
|
|
190
232
|
await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w10', ok: true }));
|
|
191
233
|
expect(screen.queryByText(CARD)).toBeNull();
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
it('remembers an Allow by the digest of the page\'s source: a later view of the same source asks nothing', async () => {
|
|
237
|
+
const server = stubServer();
|
|
238
|
+
const { frame, nextView } = mount('file page');
|
|
239
|
+
frame.post(write('w1'));
|
|
240
|
+
fireEvent.click(await screen.findByRole('button', { name: 'Allow' }));
|
|
241
|
+
await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w1', ok: true }));
|
|
242
|
+
expect(remembered()).toEqual([sha256Hex(SOURCE)]);
|
|
192
243
|
|
|
193
244
|
const next = nextView();
|
|
194
|
-
next.post(write('
|
|
245
|
+
next.post(write('w2'));
|
|
246
|
+
await waitFor(() => expect(next.replies.at(-1)).toMatchObject({ requestId: 'w2', ok: true }));
|
|
247
|
+
expect(screen.queryByText(CARD)).toBeNull();
|
|
248
|
+
expect(server.mcp).toEqual(['edit_file', 'edit_file']);
|
|
249
|
+
|
|
250
|
+
// A new mount, as a reload or a navigation back is.
|
|
251
|
+
cleanup();
|
|
252
|
+
const reloaded = mount('file page');
|
|
253
|
+
reloaded.frame.post(write('w3'));
|
|
254
|
+
await waitFor(() => expect(reloaded.frame.replies.at(-1)).toMatchObject({ requestId: 'w3', ok: true }));
|
|
255
|
+
expect(screen.queryByText(CARD)).toBeNull();
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
it('asks again when one character of the source changed; Allow keeps both digests', async () => {
|
|
259
|
+
stubServer();
|
|
260
|
+
const { frame, nextView } = mount('file page');
|
|
261
|
+
frame.post(write('w1'));
|
|
262
|
+
fireEvent.click(await screen.findByRole('button', { name: 'Allow' }));
|
|
263
|
+
await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ ok: true }));
|
|
264
|
+
|
|
265
|
+
const edited = `${SOURCE} `;
|
|
266
|
+
const next = nextView(edited);
|
|
267
|
+
next.post(write('w2'));
|
|
195
268
|
expect(await screen.findByText(CARD)).toBeTruthy();
|
|
269
|
+
fireEvent.click(screen.getByRole('button', { name: 'Allow' }));
|
|
270
|
+
await waitFor(() => expect(next.replies.at(-1)).toMatchObject({ requestId: 'w2', ok: true }));
|
|
271
|
+
expect(remembered()).toEqual([sha256Hex(SOURCE), sha256Hex(edited)]);
|
|
272
|
+
|
|
273
|
+
// Changed back: that digest is still stored.
|
|
274
|
+
const reverted = nextView(SOURCE);
|
|
275
|
+
reverted.post(write('w3'));
|
|
276
|
+
await waitFor(() => expect(reverted.replies.at(-1)).toMatchObject({ requestId: 'w3', ok: true }));
|
|
277
|
+
expect(screen.queryByText(CARD)).toBeNull();
|
|
196
278
|
});
|
|
197
279
|
|
|
198
|
-
it('
|
|
280
|
+
it('remembers by content, not path: the same source at another path asks nothing', async () => {
|
|
281
|
+
stubServer();
|
|
282
|
+
const first = mount('file page');
|
|
283
|
+
first.frame.post(write('w1'));
|
|
284
|
+
fireEvent.click(await screen.findByRole('button', { name: 'Allow' }));
|
|
285
|
+
await waitFor(() => expect(first.frame.replies.at(-1)).toMatchObject({ ok: true }));
|
|
286
|
+
cleanup();
|
|
287
|
+
|
|
288
|
+
const copy = mount('file page', { path: 'knowledge-base/Dashboards/Copy.html', page: 'Dashboards/Copy.html' });
|
|
289
|
+
copy.frame.post(write('w2'));
|
|
290
|
+
await waitFor(() => expect(copy.frame.replies.at(-1)).toMatchObject({ requestId: 'w2', ok: true }));
|
|
291
|
+
expect(screen.queryByText(CARD)).toBeNull();
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
it('asks another account afresh for a source the first allowed; each account then keeps its own', async () => {
|
|
199
295
|
const server = stubServer();
|
|
200
|
-
const
|
|
296
|
+
const first = mount('file page', { account: 'user-a' });
|
|
297
|
+
first.frame.post(write('w1'));
|
|
298
|
+
fireEvent.click(await screen.findByRole('button', { name: 'Allow' }));
|
|
299
|
+
await waitFor(() => expect(first.frame.replies.at(-1)).toMatchObject({ requestId: 'w1', ok: true }));
|
|
300
|
+
cleanup();
|
|
301
|
+
|
|
302
|
+
const second = mount('file page', { account: 'user-b' });
|
|
303
|
+
second.frame.post(write('w2'));
|
|
304
|
+
expect(await screen.findByText(CARD)).toBeTruthy();
|
|
305
|
+
expect(server.mcp).toEqual(['edit_file']);
|
|
306
|
+
fireEvent.click(screen.getByRole('button', { name: 'Allow' }));
|
|
307
|
+
await waitFor(() => expect(second.frame.replies.at(-1)).toMatchObject({ requestId: 'w2', ok: true }));
|
|
308
|
+
const digest = sha256Hex(SOURCE);
|
|
309
|
+
expect(storedEntries().sort()).toEqual([
|
|
310
|
+
`bevel.account/user-a/htmlPage.allowedWrite.${digest}`,
|
|
311
|
+
`bevel.account/user-b/htmlPage.allowedWrite.${digest}`,
|
|
312
|
+
]);
|
|
313
|
+
cleanup();
|
|
314
|
+
|
|
315
|
+
const back = mount('file page', { account: 'user-a' });
|
|
316
|
+
back.frame.post(write('w3'));
|
|
317
|
+
await waitFor(() => expect(back.frame.replies.at(-1)).toMatchObject({ requestId: 'w3', ok: true }));
|
|
318
|
+
expect(screen.queryByText(CARD)).toBeNull();
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
it("sends nothing with another account's token: a sign-in in another tab refuses this view's calls, even an Allow it remembers", async () => {
|
|
322
|
+
const server = stubServer();
|
|
323
|
+
window.localStorage.setItem('bevel_token', sessionTokenFor('user-a'));
|
|
324
|
+
const first = mount('file page', { account: 'user-a' });
|
|
325
|
+
first.frame.post(write('w1'));
|
|
326
|
+
fireEvent.click(await screen.findByRole('button', { name: 'Allow' }));
|
|
327
|
+
await waitFor(() => expect(first.frame.replies.at(-1)).toMatchObject({ requestId: 'w1', ok: true }));
|
|
328
|
+
expect(server.mcp).toEqual(['edit_file']);
|
|
329
|
+
|
|
330
|
+
// Another tab signs in as user-b: the shared token is now theirs, while
|
|
331
|
+
// this tab still shows user-a's view with user-a's remembered Allow.
|
|
332
|
+
window.localStorage.setItem('bevel_token', sessionTokenFor('user-b'));
|
|
333
|
+
const next = first.nextView();
|
|
334
|
+
next.post(write('w2'));
|
|
335
|
+
next.post({ type: 'bevel.tool.call', requestId: 'r1', fn: 'callTool', args: ['read_file', {}] });
|
|
336
|
+
await waitFor(() => expect(next.replies.map((r) => (r as { requestId: string }).requestId).sort()).toEqual(['r1', 'w2']));
|
|
337
|
+
for (const reply of next.replies) {
|
|
338
|
+
expect(reply).toMatchObject({ ok: false, code: 'account_changed' });
|
|
339
|
+
expect((reply as { error: string }).error).toMatch(/signed in as another account in another tab/);
|
|
340
|
+
}
|
|
341
|
+
expect(screen.queryByText(CARD)).toBeNull();
|
|
342
|
+
expect(server.mcp).toEqual(['edit_file']);
|
|
343
|
+
// Not one request of the page's (manual lookup, call, refusal record)
|
|
344
|
+
// went out with user-b's token.
|
|
345
|
+
const sentWith = vi.mocked(fetch).mock.calls.map(([, init]) => new Headers(init?.headers).get('Authorization'));
|
|
346
|
+
expect(sentWith.length).toBeGreaterThan(0);
|
|
347
|
+
expect(new Set(sentWith)).toEqual(new Set([`Bearer ${sessionTokenFor('user-a')}`]));
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
it('sends nothing with no session token at all: the call is refused, not sent as nobody', async () => {
|
|
351
|
+
stubServer();
|
|
352
|
+
const { frame } = mount('file page', { account: 'user-a' });
|
|
353
|
+
window.localStorage.removeItem('bevel_token');
|
|
354
|
+
frame.post({ type: 'bevel.tool.call', requestId: 'r1', fn: 'callTool', args: ['read_file', {}] });
|
|
355
|
+
frame.post(write('w1'));
|
|
356
|
+
await waitFor(() => expect(frame.replies).toHaveLength(2));
|
|
357
|
+
for (const reply of frame.replies) expect(reply).toMatchObject({ ok: false, code: 'account_changed' });
|
|
358
|
+
expect(screen.queryByText(CARD)).toBeNull();
|
|
359
|
+
expect(vi.mocked(fetch)).not.toHaveBeenCalled();
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
it('keeps working on a token renewed for the same account', async () => {
|
|
363
|
+
const server = stubServer();
|
|
364
|
+
window.localStorage.setItem('bevel_token', sessionTokenFor('user-a', 'before'));
|
|
365
|
+
const { frame } = mount('file page', { account: 'user-a' });
|
|
366
|
+
frame.post(write('w1'));
|
|
367
|
+
fireEvent.click(await screen.findByRole('button', { name: 'Allow' }));
|
|
368
|
+
await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w1', ok: true }));
|
|
369
|
+
// A password change hands back a new token for the same account.
|
|
370
|
+
window.localStorage.setItem('bevel_token', sessionTokenFor('user-a', 'after'));
|
|
371
|
+
frame.post(write('w2'));
|
|
372
|
+
await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w2', ok: true }));
|
|
373
|
+
expect(server.mcp).toEqual(['edit_file', 'edit_file']);
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
it('keeps nothing with no account above the renderer: an Allow holds for its view, and every view asks', async () => {
|
|
377
|
+
stubServer();
|
|
378
|
+
const { frame, nextView } = mount('file page', { account: null });
|
|
201
379
|
frame.post(write('w1'));
|
|
202
|
-
fireEvent.click(await screen.findByRole('button', { name: '
|
|
380
|
+
fireEvent.click(await screen.findByRole('button', { name: 'Allow' }));
|
|
381
|
+
await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w1', ok: true }));
|
|
382
|
+
frame.post(write('w2'));
|
|
383
|
+
await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w2', ok: true }));
|
|
384
|
+
expect(storedEntries()).toEqual([]);
|
|
385
|
+
|
|
386
|
+
const next = nextView();
|
|
387
|
+
next.post(write('w3'));
|
|
388
|
+
expect(await screen.findByText(CARD)).toBeTruthy();
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
it('asks on every view in a browser that cannot store, with no error shown', async () => {
|
|
392
|
+
stubServer();
|
|
393
|
+
// A storage that throws on the memory's key (the app's own sign-in reads
|
|
394
|
+
// the same storage, so a storage refusing everything signs nobody in).
|
|
395
|
+
const real = window.localStorage;
|
|
396
|
+
const refuse = (key: string) => {
|
|
397
|
+
if (key.startsWith(ALLOWED_PAGE_KEY_PREFIX)) throw new DOMException('The quota has been exceeded.', 'QuotaExceededError');
|
|
398
|
+
};
|
|
399
|
+
vi.spyOn(window, 'localStorage', 'get').mockReturnValue({
|
|
400
|
+
getItem: (key: string) => (refuse(key), real.getItem(key)),
|
|
401
|
+
setItem: (key: string, value: string) => (refuse(key), real.setItem(key, value)),
|
|
402
|
+
removeItem: (key: string) => real.removeItem(key),
|
|
403
|
+
key: (i: number) => real.key(i),
|
|
404
|
+
get length() {
|
|
405
|
+
return real.length;
|
|
406
|
+
},
|
|
407
|
+
} as unknown as Storage);
|
|
408
|
+
const { frame, nextView } = mount('file page');
|
|
409
|
+
frame.post(write('w1'));
|
|
410
|
+
fireEvent.click(await screen.findByRole('button', { name: 'Allow' }));
|
|
411
|
+
await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w1', ok: true }));
|
|
412
|
+
const next = nextView();
|
|
413
|
+
next.post(write('w2'));
|
|
414
|
+
expect(await screen.findByText(CARD)).toBeTruthy();
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
it("Don't allow answers denied, runs nothing and stores nothing; the next write asks again, in this view and the next", async () => {
|
|
418
|
+
const server = stubServer();
|
|
419
|
+
const { frame, nextView } = mount('file page');
|
|
420
|
+
frame.post(write('w1'));
|
|
421
|
+
fireEvent.click(await screen.findByRole('button', { name: "Don't allow" }));
|
|
203
422
|
await waitFor(() => expect(frame.replies.at(-1)).toEqual({ type: 'bevel.tool.response', requestId: 'w1', ok: false, error: 'denied', code: 'denied' }));
|
|
204
423
|
expect(server.mcp).toEqual([]);
|
|
424
|
+
expect(window.localStorage.getItem(ALLOWED_PAGE_KEY_PREFIX + sha256Hex(SOURCE))).toBeNull();
|
|
425
|
+
expect(storedEntries()).toEqual([]);
|
|
205
426
|
frame.post(write('w2'));
|
|
206
427
|
expect(await screen.findByText(CARD)).toBeTruthy();
|
|
428
|
+
fireEvent.click(screen.getByRole('button', { name: "Don't allow" }));
|
|
429
|
+
await waitFor(() => expect(frame.replies.at(-1)).toMatchObject({ requestId: 'w2', code: 'denied' }));
|
|
430
|
+
const next = nextView();
|
|
431
|
+
next.post(write('w3'));
|
|
432
|
+
expect(await screen.findByText(CARD)).toBeTruthy();
|
|
207
433
|
});
|
|
208
434
|
|
|
209
435
|
// The frame keeps its window across `nextView` here, as a browser's does
|
|
@@ -243,7 +469,7 @@ describe('useHtmlToolBridge through a renderer of its own', () => {
|
|
|
243
469
|
const server = stubServer();
|
|
244
470
|
const { frame, nextView } = mount('file page');
|
|
245
471
|
frame.post({ type: 'bevel.tool.call', requestId: 'c1', fn: 'callToolChain', args: ['return 1'] });
|
|
246
|
-
fireEvent.click(await screen.findByRole('button', { name: 'Allow
|
|
472
|
+
fireEvent.click(await screen.findByRole('button', { name: 'Allow' }));
|
|
247
473
|
await waitFor(() => expect(frame.replies).toEqual([expect.objectContaining({ requestId: 'c1', ok: true })]));
|
|
248
474
|
|
|
249
475
|
frame.post(write('w1'));
|
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { createContext, useContext } from 'react';
|
|
2
2
|
import { authFetch } from '../../../../lib/api';
|
|
3
|
+
import { AccountChangedError } from '../../../auth';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* The app's half of `window.bevel.tools`: what answers an HTML page's tool
|
|
6
7
|
* calls, and what decides when the viewer is asked first.
|
|
7
8
|
*
|
|
8
9
|
* A page's call is answered over the hosted MCP server (`POST /api/mcp`) with
|
|
9
|
-
* the viewer's session
|
|
10
|
-
* viewer's own agent does — the same
|
|
11
|
-
* the
|
|
12
|
-
* Audit log under the page's path
|
|
13
|
-
* what an agent calls:
|
|
10
|
+
* the viewer's session and the page's path (`X-Bevel-Page`), so a page sees
|
|
11
|
+
* and reaches exactly the tools the viewer's own agent does — the same
|
|
12
|
+
* listing, the same refusals, nothing of the enterprise agent's internal
|
|
13
|
+
* tools — and the server records it in the Audit log under the page's path.
|
|
14
|
+
* The five members map to what an agent calls:
|
|
14
15
|
*
|
|
15
16
|
* searchTools(query) → `list_tools`, narrowed to the names that
|
|
16
17
|
* contain every word of `query` (all of them
|
|
@@ -25,7 +26,8 @@ import { authFetch } from '../../../../lib/api';
|
|
|
25
26
|
* deployment's UTCP manual tags `write`, a tool the manual does not list (a
|
|
26
27
|
* `.tool`'s, a plugin's MCP server's: nothing says they only read), every
|
|
27
28
|
* chain (a chain may call writers) and every upload — waits for the viewer's
|
|
28
|
-
* answer to one card per page view
|
|
29
|
+
* answer to one card per page view, unless this browser remembers an Allow
|
|
30
|
+
* for the page's exact source. See {@link PageConsent}.
|
|
29
31
|
*/
|
|
30
32
|
|
|
31
33
|
/** What a host that is the platform tells the HTML renderer: that tools are answered here, and for which page. */
|
|
@@ -104,7 +106,7 @@ const CHAIN_TOOL = 'call_tool_chain';
|
|
|
104
106
|
const UPLOAD_REQUEST_TOOL = 'request_file_upload';
|
|
105
107
|
const UPLOAD_APPLY_TOOL = 'apply_file_upload';
|
|
106
108
|
|
|
107
|
-
/** The answer a page gets when its viewer chose
|
|
109
|
+
/** The answer a page gets when its viewer chose Don't allow. */
|
|
108
110
|
export const DENIED = 'denied';
|
|
109
111
|
|
|
110
112
|
/** A tool call's failure, as the page receives it: the message, and a code for the cases a page may handle. */
|
|
@@ -310,7 +312,15 @@ export class PageToolsClient {
|
|
|
310
312
|
}
|
|
311
313
|
return map;
|
|
312
314
|
})
|
|
313
|
-
.catch(() =>
|
|
315
|
+
.catch((err: unknown) => {
|
|
316
|
+
// A session that is no longer this view's account's is not an
|
|
317
|
+
// unreadable manual: the call fails with it, and nothing is kept.
|
|
318
|
+
if (err instanceof AccountChangedError) {
|
|
319
|
+
this.writing = undefined;
|
|
320
|
+
throw err;
|
|
321
|
+
}
|
|
322
|
+
return null;
|
|
323
|
+
});
|
|
314
324
|
return this.writing;
|
|
315
325
|
}
|
|
316
326
|
|
|
@@ -398,13 +408,27 @@ function toPageResult(result: CallToolResult | undefined): unknown {
|
|
|
398
408
|
}
|
|
399
409
|
}
|
|
400
410
|
|
|
411
|
+
/**
|
|
412
|
+
* What the browser remembers of a page's earlier Allows, bound by the caller
|
|
413
|
+
* to the page view's source (see `pageConsentMemory.ts`).
|
|
414
|
+
*/
|
|
415
|
+
export interface PageConsentMemory {
|
|
416
|
+
/** Whether the viewer allowed this exact page before, in this browser. */
|
|
417
|
+
remembered(): boolean;
|
|
418
|
+
/** Keep this Allow for later views of the same page. */
|
|
419
|
+
remember(): void;
|
|
420
|
+
}
|
|
421
|
+
|
|
401
422
|
/**
|
|
402
423
|
* The viewer's answer about one page view's writes: asked once, on the first
|
|
403
|
-
* writing call, and held until the page is reloaded or left (a new instance)
|
|
424
|
+
* writing call, and held until the page is reloaded or left (a new instance)
|
|
425
|
+
* — unless the browser remembers an Allow for this exact page, in which case
|
|
426
|
+
* nothing asks at all.
|
|
404
427
|
*
|
|
405
|
-
* Allow holds: every later writing call runs without a card
|
|
406
|
-
* it
|
|
407
|
-
*
|
|
428
|
+
* Allow holds: every later writing call runs without a card, and the memory
|
|
429
|
+
* keeps it for later views. Don't allow does not: it answers the calls that
|
|
430
|
+
* were waiting on that card, remembers nothing, and the next writing call
|
|
431
|
+
* asks again. Calls that arrive while the card is open wait on that same
|
|
408
432
|
* card, so a page that fires ten writes at once sees one card, and every one
|
|
409
433
|
* of the ten gets the answer.
|
|
410
434
|
*
|
|
@@ -418,10 +442,12 @@ export class PageConsent {
|
|
|
418
442
|
private ended = false;
|
|
419
443
|
private asking: Promise<boolean | null> | null = null;
|
|
420
444
|
private readonly ask: () => Promise<boolean | null>;
|
|
445
|
+
private readonly memory: PageConsentMemory;
|
|
421
446
|
|
|
422
|
-
/** `ask` shows the card: true for Allow, false for
|
|
423
|
-
constructor(ask: () => Promise<boolean | null
|
|
447
|
+
/** `ask` shows the card: true for Allow, false for Don't allow, null when the view ended with the card still open. */
|
|
448
|
+
constructor(ask: () => Promise<boolean | null>, memory: PageConsentMemory) {
|
|
424
449
|
this.ask = ask;
|
|
450
|
+
this.memory = memory;
|
|
425
451
|
}
|
|
426
452
|
|
|
427
453
|
/** Whether a card is open right now — no call of the page runs while it is. */
|
|
@@ -443,11 +469,18 @@ export class PageConsent {
|
|
|
443
469
|
request(): Promise<boolean | null> {
|
|
444
470
|
if (this.ended) return Promise.resolve(null);
|
|
445
471
|
if (this.allowed) return Promise.resolve(true);
|
|
472
|
+
if (!this.asking && this.memory.remembered()) {
|
|
473
|
+
this.allowed = true;
|
|
474
|
+
return Promise.resolve(true);
|
|
475
|
+
}
|
|
446
476
|
this.asking ??= this.ask().then(
|
|
447
477
|
(ok) => {
|
|
448
478
|
this.asking = null;
|
|
449
479
|
if (this.ended) return null;
|
|
450
|
-
if (ok)
|
|
480
|
+
if (ok) {
|
|
481
|
+
this.allowed = true;
|
|
482
|
+
this.memory.remember();
|
|
483
|
+
}
|
|
451
484
|
return ok;
|
|
452
485
|
},
|
|
453
486
|
() => {
|
|
@@ -495,7 +528,9 @@ const CLOSED_MESSAGE = 'The page was closed before the viewer answered.';
|
|
|
495
528
|
* Answer one of a page's tool calls: wait out an open card, ask for consent
|
|
496
529
|
* when the call may write, run it, and say how it went. A call whose view
|
|
497
530
|
* ended (its `consent` closed) before it was decided runs nothing and is
|
|
498
|
-
* answered `closed`.
|
|
531
|
+
* answered `closed`. A call whose client refuses to send as another account
|
|
532
|
+
* (`AccountChangedError`, from the auth module's `accountFetch`) is answered
|
|
533
|
+
* `account_changed`. Never throws — every outcome is a response for the frame.
|
|
499
534
|
*/
|
|
500
535
|
export async function answerToolCall(
|
|
501
536
|
msg: ToolCallMessage,
|
|
@@ -539,6 +574,7 @@ export async function answerToolCall(
|
|
|
539
574
|
: await client.callTool(a, b);
|
|
540
575
|
return { type: 'bevel.tool.response', requestId: msg.requestId, ok: true, result };
|
|
541
576
|
} catch (err) {
|
|
577
|
+
if (err instanceof AccountChangedError) return fail(err.message, 'account_changed');
|
|
542
578
|
return fail(err instanceof Error ? err.message : String(err), err instanceof PageToolError ? err.code : undefined);
|
|
543
579
|
}
|
|
544
580
|
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { accountKeyPrefix } from '../../../auth';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Which pages the signed-in account allowed to write from this browser: the
|
|
5
|
+
* SHA-256 digests of the pages' sources. A page whose source hashes to one of
|
|
6
|
+
* them asks that account nothing; a source whose digest is not here, an edit
|
|
7
|
+
* included, asks once more. Kept per account, browser and deployment, and never
|
|
8
|
+
* a deny: Don't allow stores nothing. With no account (`null`) nothing is kept
|
|
9
|
+
* and every view asks.
|
|
10
|
+
*
|
|
11
|
+
* Each digest is its own `localStorage` entry under the account's prefix
|
|
12
|
+
* (the auth module's `accountKeyPrefix`), holding when it was last allowed. An Allow writes
|
|
13
|
+
* only its own entry, so two tabs allowing two pages at once cannot overwrite
|
|
14
|
+
* each other's; eviction past the cap removes only that account's oldest
|
|
15
|
+
* entries. Signing out clears the account's prefix.
|
|
16
|
+
*
|
|
17
|
+
* A browser that cannot store or read them is asked on every view, as it
|
|
18
|
+
* would be with nothing remembered, and is told nothing about it.
|
|
19
|
+
*/
|
|
20
|
+
const ENTRY_NAME = 'htmlPage.allowedWrite.';
|
|
21
|
+
|
|
22
|
+
/** How many digests one account keeps: past it, its least recently allowed is forgotten. */
|
|
23
|
+
const ALLOWED_PAGES_MAX = 500;
|
|
24
|
+
|
|
25
|
+
interface Entry {
|
|
26
|
+
digest: string;
|
|
27
|
+
at: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Every digest under this entry prefix with when it was allowed, least recent first. */
|
|
31
|
+
function entries(storage: Storage, prefix: string): Entry[] {
|
|
32
|
+
const found: Entry[] = [];
|
|
33
|
+
for (let i = 0; i < storage.length; i++) {
|
|
34
|
+
const key = storage.key(i);
|
|
35
|
+
if (key === null || !key.startsWith(prefix)) continue;
|
|
36
|
+
const at = Number(storage.getItem(key));
|
|
37
|
+
if (!Number.isFinite(at)) continue;
|
|
38
|
+
found.push({ digest: key.slice(prefix.length), at });
|
|
39
|
+
}
|
|
40
|
+
return found.sort((a, b) => a.at - b.at);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Whether this account allowed a page with this digest in this browser. */
|
|
44
|
+
export function isRemembered(account: string | null, digest: string): boolean {
|
|
45
|
+
if (account === null) return false;
|
|
46
|
+
try {
|
|
47
|
+
const at = window.localStorage.getItem(accountKeyPrefix(account) + ENTRY_NAME + digest);
|
|
48
|
+
return at !== null && Number.isFinite(Number(at));
|
|
49
|
+
} catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Remember this account's Allow for this digest, as its most recent one. */
|
|
55
|
+
export function remember(account: string | null, digest: string): void {
|
|
56
|
+
if (account === null) return;
|
|
57
|
+
try {
|
|
58
|
+
const storage = window.localStorage;
|
|
59
|
+
const prefix = accountKeyPrefix(account) + ENTRY_NAME;
|
|
60
|
+
const others = entries(storage, prefix).filter((e) => e.digest !== digest);
|
|
61
|
+
// Later than every other Allow, even several within one millisecond.
|
|
62
|
+
const at = Math.max(Date.now(), (others.at(-1)?.at ?? 0) + 1);
|
|
63
|
+
storage.setItem(prefix + digest, String(at));
|
|
64
|
+
// The cap is enforced on what storage holds AFTER this write, not on the
|
|
65
|
+
// snapshot above, so two tabs allowing at once still leave at most the
|
|
66
|
+
// cap. Each candidate is removed only while it still holds the time just
|
|
67
|
+
// read: one another tab has allowed again since is newer, and is kept.
|
|
68
|
+
const now = entries(storage, prefix).filter((e) => e.digest !== digest);
|
|
69
|
+
for (const old of now.slice(0, Math.max(0, now.length + 1 - ALLOWED_PAGES_MAX))) {
|
|
70
|
+
if (storage.getItem(prefix + old.digest) === String(old.at)) storage.removeItem(prefix + old.digest);
|
|
71
|
+
}
|
|
72
|
+
} catch {
|
|
73
|
+
// Not stored: the card shows on the next view, which is no worse than before.
|
|
74
|
+
}
|
|
75
|
+
}
|