@bevel-software/platform-core-frontend 0.21.0 → 0.23.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.
Files changed (72) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +2 -0
  3. package/src/core/registry.ts +140 -0
  4. package/src/lib/api.ts +49 -0
  5. package/src/modules/access/__tests__/ManageAccessDialog.request.test.tsx +376 -0
  6. package/src/modules/access/api.ts +6 -4
  7. package/src/modules/access/components/AccessRequestControl.tsx +155 -0
  8. package/src/modules/{library → access}/components/AccessRequestsBanner.tsx +62 -24
  9. package/src/modules/access/components/ManageAccessDialog.tsx +81 -4
  10. package/src/modules/access/hooks/useAccessRequests.ts +183 -0
  11. package/src/modules/access/requests.api.ts +121 -0
  12. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +89 -1
  13. package/src/modules/admin/components/UserAccountsPage.tsx +93 -5
  14. package/src/modules/auth/components/LoginScreen.tsx +8 -0
  15. package/src/modules/auth/services/account.api.ts +26 -3
  16. package/src/modules/change-requests/__tests__/ChangeRequestDialog.brings-itself-up-to-date.test.tsx +171 -38
  17. package/src/modules/change-requests/__tests__/ChangeRequestDialog.fork-point.test.tsx +34 -19
  18. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +173 -6
  19. package/src/modules/change-requests/components/BranchFilePreview.tsx +7 -1
  20. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +155 -98
  21. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +89 -10
  22. package/src/modules/git/__tests__/HistoryVersionPreview.test.tsx +479 -0
  23. package/src/modules/git/components/FileHistoryPanel.tsx +52 -65
  24. package/src/modules/git/components/HistoryVersionPreview.tsx +410 -0
  25. package/src/modules/layout/__tests__/ReadOnlyBanner.test.tsx +157 -0
  26. package/src/modules/layout/components/ReadOnlyBanner.tsx +96 -0
  27. package/src/modules/library/__tests__/SkillPage.test.tsx +15 -0
  28. package/src/modules/library/__tests__/ToolPage.test.tsx +15 -1
  29. package/src/modules/library/__tests__/title-row-actions.ts +53 -1
  30. package/src/modules/library/components/PluginJoinRequests.tsx +2 -2
  31. package/src/modules/library/components/skill-page/SkillPage.tsx +2 -2
  32. package/src/modules/library/components/tool-page/ToolPage.tsx +11 -1
  33. package/src/modules/library/hooks/useJoinRequests.ts +26 -101
  34. package/src/modules/pr/services/pr-merge.api.ts +10 -2
  35. package/src/modules/settings/components/DeploymentPage.tsx +22 -0
  36. package/src/modules/settings/components/__tests__/DeploymentPage.test.tsx +72 -4
  37. package/src/modules/setup/__tests__/setup.first-run.test.tsx +276 -0
  38. package/src/modules/setup/__tests__/setup.github.test.tsx +416 -0
  39. package/src/modules/setup/__tests__/setup.kept-draft.test.tsx +275 -0
  40. package/src/modules/setup/__tests__/setup.repository-change.test.tsx +296 -0
  41. package/src/modules/setup/__tests__/setup.repository.test.tsx +463 -0
  42. package/src/modules/setup/__tests__/setup.test.tsx +13 -17
  43. package/src/modules/setup/components/GitHubRepositoryPanel.tsx +369 -0
  44. package/src/modules/setup/components/SetupGate.tsx +1 -0
  45. package/src/modules/setup/components/SetupScreen.tsx +608 -41
  46. package/src/modules/setup/services/setup.api.ts +171 -3
  47. package/src/modules/setup/utils/kept-draft.ts +86 -0
  48. package/src/modules/workspace/components/FileExplorer.tsx +140 -12
  49. package/src/modules/workspace/components/FileViewer.tsx +11 -1
  50. package/src/modules/workspace/components/TreeActionConfirm.tsx +5 -7
  51. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +603 -29
  52. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +23 -6
  53. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +41 -8
  54. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +20 -5
  55. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +39 -16
  56. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +27 -7
  57. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +20 -5
  58. package/src/modules/workspace/components/renderers/RetryReadButton.tsx +37 -0
  59. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +20 -5
  60. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +186 -7
  61. package/src/modules/workspace/components/renderers/__tests__/readPane.test.tsx +59 -0
  62. package/src/modules/workspace/components/renderers/htmlSandbox.ts +80 -20
  63. package/src/modules/workspace/components/renderers/index.ts +6 -1
  64. package/src/modules/workspace/components/renderers/readPane.ts +22 -0
  65. package/src/modules/workspace/components/renderers/rendererWorkspace.ts +50 -9
  66. package/src/modules/workspace/components/renderers/useReadRetry.ts +27 -0
  67. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +79 -0
  68. package/src/modules/workspace/routing/kb-routes.ts +25 -10
  69. package/src/modules/workspace/services/workspace.api.ts +22 -1
  70. package/src/shared/components/SlotBoundary.tsx +51 -0
  71. package/src/shared/markdown/__tests__/hrefs.test.ts +111 -0
  72. package/src/shared/markdown/hrefs.ts +80 -4
@@ -335,6 +335,85 @@ describe('useFileNav.openLink', () => {
335
335
  open.mockRestore();
336
336
  });
337
337
 
338
+ // What a reader clicking a link WRITTEN IN AN HTML PAGE reaches: the
339
+ // sanitizer now keeps those hrefs, the nav bridge cancels the click the
340
+ // sandbox would not let the iframe make, and the address lands here.
341
+ it('opens a page linked by a relative path, resolved against the linking page', () => {
342
+ navigateMock.mockClear();
343
+ const { result } = renderNav('alice/draft');
344
+ result.current.openLink('Board.html', 'knowledge-base/Dashboards/a.html');
345
+ expect(navigateMock).toHaveBeenCalledWith(
346
+ '/workspace/alice%2Fdraft/knowledge-base/Dashboards/Board.html',
347
+ );
348
+ });
349
+
350
+ it('opens a page up a folder and keeps its fragment', () => {
351
+ navigateMock.mockClear();
352
+ const { result } = renderNav('alice/draft');
353
+ result.current.openLink('../Reports/Q3.html#totals', 'knowledge-base/Dashboards/a.html');
354
+ expect(navigateMock).toHaveBeenCalledWith(
355
+ '/workspace/alice%2Fdraft/knowledge-base/Reports/Q3.html#totals',
356
+ );
357
+ });
358
+
359
+ // A link to a page nobody wrote is still a navigation: the route goes to
360
+ // that path and `FileRoute` answers with its own "File not found" screen,
361
+ // exactly as it does for a mistyped URL. Resolution does not second-guess
362
+ // whether the file is there.
363
+ it('navigates to a page that does not exist, leaving not-found to the route', () => {
364
+ navigateMock.mockClear();
365
+ const { result } = renderNav('alice/draft');
366
+ result.current.openLink('Missing.html', 'knowledge-base/Dashboards/a.html');
367
+ expect(navigateMock).toHaveBeenCalledWith(
368
+ '/workspace/alice%2Fdraft/knowledge-base/Dashboards/Missing.html',
369
+ );
370
+ });
371
+
372
+ // Generated markup writes an href on its own line, and `sanitizeAgentHtml`
373
+ // keeps it by reading past the padding. The resolver has to read past the
374
+ // same padding or the kept link lands on a filename with spaces in it.
375
+ it('resolves a page link written on its own line, padding and all', () => {
376
+ navigateMock.mockClear();
377
+ const { result } = renderNav('alice/draft');
378
+ result.current.openLink('\n Board.html\n ', 'knowledge-base/Dashboards/a.html');
379
+ expect(navigateMock).toHaveBeenCalledWith(
380
+ '/workspace/alice%2Fdraft/knowledge-base/Dashboards/Board.html',
381
+ );
382
+ });
383
+
384
+ it('resolves a padded citation URL as a citation URL, not a relative path', () => {
385
+ navigateMock.mockClear();
386
+ const { result } = renderNav('alice/draft');
387
+ result.current.openLink(
388
+ ' /workspace/bob%2Fmain/knowledge-base/Reports/Q3.html#totals ',
389
+ 'knowledge-base/Dashboards/a.html',
390
+ );
391
+ expect(navigateMock).toHaveBeenCalledWith(
392
+ '/workspace/bob%2Fmain/knowledge-base/Reports/Q3.html#totals',
393
+ );
394
+ });
395
+
396
+ it('keeps a padded same-document anchor on the file it sits in', () => {
397
+ navigateMock.mockClear();
398
+ const { result } = renderNav('alice/draft');
399
+ result.current.openLink(' #goal ', 'knowledge-base/Dashboards/a.html');
400
+ expect(navigateMock).toHaveBeenCalledWith(
401
+ '/workspace/alice%2Fdraft/knowledge-base/Dashboards/a.html#goal',
402
+ );
403
+ });
404
+
405
+ // `window.open` would strip the padding itself, but the address handed over
406
+ // is the one the allowlist approved, so it goes over clean.
407
+ it('opens a padded external link at the address it names', () => {
408
+ navigateMock.mockClear();
409
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
410
+ const { result } = renderNav('alice/draft');
411
+ result.current.openLink('\n https://example.com/docs\n', 'knowledge-base/Dashboards/a.html');
412
+ expect(open).toHaveBeenCalledWith('https://example.com/docs', '_blank', 'noopener,noreferrer');
413
+ expect(navigateMock).not.toHaveBeenCalled();
414
+ open.mockRestore();
415
+ });
416
+
338
417
  // A section link is a scroll, not a navigation to somewhere else.
339
418
  it('keeps a same-document anchor on the file it sits in', () => {
340
419
  navigateMock.mockClear();
@@ -3,7 +3,11 @@ import { useLocation, useNavigate } from 'react-router-dom';
3
3
  import { useGit } from '../../git/state/git.context';
4
4
  import { useWorkspace } from '../state/workspace.context';
5
5
  import { authFetch } from '../../../lib/api';
6
- import { isExternalHref, isOpenableExternalHref } from '../../../shared/markdown/hrefs';
6
+ import {
7
+ isExternalHref,
8
+ isOpenableExternalHref,
9
+ normalizeHref,
10
+ } from '../../../shared/markdown/hrefs';
7
11
 
8
12
  export const KB_ROUTE_PREFIX = '/workspace';
9
13
 
@@ -233,13 +237,21 @@ export type KbHref =
233
237
  * Serving bytes at another branch is the `?ref=` item in TODOS.md.
234
238
  */
235
239
  export function resolveKbHref(
236
- href: string,
240
+ rawHref: string,
237
241
  {
238
242
  basePath,
239
243
  kbDirName,
240
244
  repairMangledPath = true,
241
245
  }: { basePath: string; kbDirName: string | null; repairMangledPath?: boolean },
242
246
  ): KbHref | null {
247
+ // Read the href the way a browser reads it BEFORE anything is parsed out of
248
+ // it, not just before the scheme check. An href written on its own line in
249
+ // generated markup arrives padded, and `sanitizeAgentHtml` keeps it on that
250
+ // reading — so every row of the table above has to see the same string, or a
251
+ // padded `' Board.html '` resolves to a filename with spaces nobody wrote,
252
+ // a padded `' /workspace/…'` misses the prefix and resolves as a relative
253
+ // path, and a padded `' #goal'` loses its same-document row.
254
+ const href = normalizeHref(rawHref);
243
255
  if (!href) return null;
244
256
  if (isExternalHref(href)) return { kind: 'external' };
245
257
  const hashIdx = href.indexOf('#');
@@ -285,7 +297,9 @@ export function openExternalHref(href: string): boolean {
285
297
  // branch name and a file path — to the destination. The markdown pipeline's
286
298
  // body links already ship `rel="noopener noreferrer"`; this is the same
287
299
  // policy on the scripted path.
288
- window.open(href, '_blank', 'noopener,noreferrer');
300
+ // The NORMALIZED string, so the address opened is the one the allowlist
301
+ // approved rather than whatever padding the author left around it.
302
+ window.open(normalizeHref(href), '_blank', 'noopener,noreferrer');
289
303
  return true;
290
304
  }
291
305
 
@@ -363,13 +377,14 @@ export function useFileNav() {
363
377
  * is a dead click. Two surfaces do that:
364
378
  *
365
379
  * - The frontmatter panel, for a link-valued field.
366
- * - Agent HTML, via `bevel.navigate(href)` from its own inline script.
367
- * NOT via an anchor: `sanitizeAgentHtml` strips an `href` that
368
- * `isInternalNodeLink` rejects, which is every scheme-bearing URL, so
369
- * an external anchor loses its href before the nav bridge ever sees
370
- * it. The scripted call is the reachable path, and it is why the
371
- * allowlist below is load-bearing rather than belt-and-braces: that
372
- * argument is an arbitrary string no sanitizer inspected.
380
+ * - Agent HTML, two ways. A WRITTEN anchor whose address
381
+ * `sanitizeAgentHtml` kept — a document of the knowledge base, or an
382
+ * `http:`, `https:` or `mailto:` address — reaches here through the
383
+ * nav bridge, which cancels the click the sandbox would not let the
384
+ * iframe make. And `bevel.navigate(href)` from the page's own inline
385
+ * script, which is why the allowlist below is load-bearing rather than
386
+ * belt-and-braces: that argument is an arbitrary string no sanitizer
387
+ * ever inspected.
373
388
  *
374
389
  * (A markdown BODY link never arrives here: the pipeline renders an
375
390
  * external destination as a plain `target="_blank"` anchor and the browser
@@ -62,15 +62,36 @@ export async function listFiles(workspaceId: string): Promise<FileTreeEntry> {
62
62
  * - `version` is a cache key appended as `&v=`; `0` or undefined adds nothing,
63
63
  * so the URL stays stable (and browser-cacheable) until the file is known to
64
64
  * have changed. See `useImageRevision`.
65
+ * - `ref` asks for the file AS IT WAS at that save (a commit sha) instead of
66
+ * the working tree, and `side: 'before'` for the version just before it —
67
+ * what Version history's preview pane and its "Download this version" read,
68
+ * and the only thing the save that deleted a file can show. The backend
69
+ * refuses a save outside the viewed branch's history and never falls back to
70
+ * today's bytes, so a `ref` that goes wrong is an error, not a stale answer.
65
71
  */
66
72
  export function rawFileUrl(
67
73
  workspaceId: string,
68
74
  relativePath: string,
69
- options: { download?: boolean; version?: number } = {},
75
+ options: {
76
+ download?: boolean;
77
+ version?: number;
78
+ ref?: string | null;
79
+ side?: 'after' | 'before';
80
+ } = {},
70
81
  ): string {
71
82
  let url = `/api/workspace/${workspaceId}/file/raw?path=${encodeURIComponent(relativePath)}`;
72
83
  if (options.download) url += '&download=1';
73
84
  if (options.version) url += `&v=${options.version}`;
85
+ // Absence, not falsiness: `ref: ''` is a BUG at the call site, and omitting
86
+ // it would quietly answer with today's working-tree bytes under a caller
87
+ // that asked for a past version. Sent as it is, the backend's own 400 says
88
+ // so.
89
+ if (options.ref != null) {
90
+ url += `&ref=${encodeURIComponent(options.ref)}`;
91
+ // `side` only means anything next to a ref — the backend refuses it on its
92
+ // own — so it is appended only here, and only when it is not the default.
93
+ if (options.side === 'before') url += '&side=before';
94
+ }
74
95
  return url;
75
96
  }
76
97
 
@@ -0,0 +1,51 @@
1
+ import { Component, type ErrorInfo, type ReactNode } from 'react';
2
+ import { Banner } from './Banner';
3
+
4
+ interface SlotBoundaryProps {
5
+ children: ReactNode;
6
+ /**
7
+ * What the slot holds, as the page would name it to the person reading:
8
+ * "workspace panel". It completes the sentence shown in its place.
9
+ */
10
+ label: string;
11
+ }
12
+
13
+ interface SlotBoundaryState {
14
+ failed: boolean;
15
+ }
16
+
17
+ /**
18
+ * A fence around a component core did not write.
19
+ *
20
+ * A registry slot hands part of a core page to the distribution that runs
21
+ * it. Without a boundary, a throw while that component renders unmounts the
22
+ * whole page around it, because React takes down the nearest tree that has
23
+ * one — so a fault in the part core knows nothing about would cost the
24
+ * person the part core does own. The slot's failure stays the slot's: its
25
+ * place says it could not be shown, and everything else on the page stands.
26
+ *
27
+ * It does not retry. What failed is the distribution's code on this render;
28
+ * rendering it again gets the same throw, and the page has a reload for the
29
+ * day the cause was something that passes.
30
+ */
31
+ export class SlotBoundary extends Component<SlotBoundaryProps, SlotBoundaryState> {
32
+ state: SlotBoundaryState = { failed: false };
33
+
34
+ static getDerivedStateFromError(): SlotBoundaryState {
35
+ return { failed: true };
36
+ }
37
+
38
+ componentDidCatch(error: Error, info: ErrorInfo) {
39
+ console.error(`[slot] the ${this.props.label} failed to render`, error, info.componentStack);
40
+ }
41
+
42
+ render() {
43
+ if (!this.state.failed) return this.props.children;
44
+ return (
45
+ <Banner tone="danger" role="alert">
46
+ The {this.props.label} couldn&rsquo;t be shown. The rest of this page is unaffected; reload to try
47
+ again.
48
+ </Banner>
49
+ );
50
+ }
51
+ }
@@ -0,0 +1,111 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import {
3
+ isExternalHref,
4
+ isOpenableExternalHref,
5
+ isPageLinkExternalHref,
6
+ normalizeHref,
7
+ } from '../hrefs';
8
+
9
+ // Generated markup puts an href on its own line often enough that the padding
10
+ // has to be invisible to the scheme check — otherwise a perfectly ordinary
11
+ // external link reads as a workspace path and the app tries to open it as a
12
+ // file. A browser ignores the same characters, and because every list here is
13
+ // an ALLOWLIST, ignoring them can never let a new scheme through.
14
+ describe('leading whitespace before a scheme', () => {
15
+ const padded = '\n https://example.com/docs\n ';
16
+
17
+ it('does not hide a scheme from any of the three questions', () => {
18
+ expect(isExternalHref(padded)).toBe(true);
19
+ expect(isOpenableExternalHref(padded)).toBe(true);
20
+ expect(isPageLinkExternalHref(padded)).toBe(true);
21
+ });
22
+
23
+ it('does not let a padded javascript: address through either', () => {
24
+ expect(isOpenableExternalHref(' javascript:alert(1)')).toBe(false);
25
+ expect(isPageLinkExternalHref(' javascript:alert(1)')).toBe(false);
26
+ // …and it is still recognised as leaving the workspace, so nothing tries
27
+ // to open it as a file.
28
+ expect(isExternalHref(' javascript:alert(1)')).toBe(true);
29
+ });
30
+
31
+ it('leaves a padded workspace path a workspace path', () => {
32
+ expect(isExternalHref(' Dashboards/Board.html')).toBe(false);
33
+ expect(isPageLinkExternalHref(' Dashboards/Board.html')).toBe(false);
34
+ });
35
+ });
36
+
37
+ describe('isPageLinkExternalHref', () => {
38
+ it.each([
39
+ 'http://example.com/docs',
40
+ 'https://example.com/docs',
41
+ 'HTTPS://Example.com/Docs',
42
+ 'MailTo:team@example.com',
43
+ 'mailto:team@example.com',
44
+ ])('accepts %s', (href) => {
45
+ expect(isPageLinkExternalHref(href)).toBe(true);
46
+ });
47
+
48
+ it.each([
49
+ // Openable when the app itself decided to follow one, but not an address
50
+ // a generated page may put in front of a reader.
51
+ 'tel:+15551234',
52
+ 'sms:+15551234',
53
+ 'geo:51.5,-0.1',
54
+ // Never openable anywhere.
55
+ 'javascript:alert(1)',
56
+ 'data:text/html,evil',
57
+ 'file:///etc/passwd',
58
+ 'vbscript:msgbox(1)',
59
+ 'x-devonthink-item:4F2A',
60
+ // No scheme written down at all.
61
+ '//cdn.example.com/x.js',
62
+ 'Dashboards/Board.html',
63
+ '',
64
+ ])('rejects %s', (href) => {
65
+ expect(isPageLinkExternalHref(href)).toBe(false);
66
+ });
67
+
68
+ // A kept scheme the opener refuses would be a link that survives
69
+ // sanitization and then does nothing when clicked. Containment, pinned.
70
+ it('accepts nothing the external opener would refuse', () => {
71
+ for (const href of ['http://example.com', 'https://example.com', 'mailto:a@b.com']) {
72
+ expect(isPageLinkExternalHref(href)).toBe(true);
73
+ expect(isOpenableExternalHref(href)).toBe(true);
74
+ expect(isExternalHref(href)).toBe(true);
75
+ }
76
+ });
77
+
78
+ // The asymmetry the two lists are written around, pinned from BOTH sides.
79
+ // A protocol-relative address resolves against the page's own scheme: for
80
+ // the app, always http(s), so the opener takes it; for a sandboxed page,
81
+ // `about:srcdoc`, where there is nothing sensible to inherit, so the
82
+ // sanitizer drops it. Rejecting it in one place only is the point.
83
+ it('lets the opener follow a protocol-relative address the markup may not keep', () => {
84
+ expect(isOpenableExternalHref('//cdn.example.com/x.js')).toBe(true);
85
+ expect(isOpenableExternalHref(' //cdn.example.com/x.js')).toBe(true);
86
+ expect(isPageLinkExternalHref('//cdn.example.com/x.js')).toBe(false);
87
+ });
88
+ });
89
+
90
+ // Every reader of an href runs the same rule, so the string a check judges is
91
+ // the string the app then follows.
92
+ describe('normalizeHref', () => {
93
+ it('drops the padding a browser drops', () => {
94
+ expect(normalizeHref('\n https://example.com/docs\n ')).toBe(
95
+ 'https://example.com/docs',
96
+ );
97
+ expect(normalizeHref(' Board.html ')).toBe('Board.html');
98
+ expect(normalizeHref(' #goal ')).toBe('#goal');
99
+ });
100
+
101
+ it('removes a tab, line feed or carriage return from inside', () => {
102
+ expect(normalizeHref('java\tscript:alert(1)')).toBe('javascript:alert(1)');
103
+ expect(normalizeHref('java\nscript:alert(1)')).toBe('javascript:alert(1)');
104
+ expect(normalizeHref('java\rscript:alert(1)')).toBe('javascript:alert(1)');
105
+ });
106
+
107
+ it('leaves an ordinary href alone, spaces inside a name included', () => {
108
+ expect(normalizeHref('Knowledge/Notes today.md#goal')).toBe('Knowledge/Notes today.md#goal');
109
+ expect(normalizeHref('')).toBe('');
110
+ });
111
+ });
@@ -18,7 +18,48 @@
18
18
  * into the enterprise embed, which has no router.
19
19
  */
20
20
  export function isExternalHref(href: string): boolean {
21
- return /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith('//');
21
+ const url = normalizeHref(href);
22
+ return /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//');
23
+ }
24
+
25
+ /**
26
+ * An href as a browser reads it: the C0 controls and spaces at either end
27
+ * dropped, and every ASCII tab, line feed and carriage return removed from
28
+ * inside. An href written on its own line — which generated markup does all
29
+ * the time —
30
+ *
31
+ * <a href="
32
+ * https://example.com/docs
33
+ * ">docs</a>
34
+ *
35
+ * arrives here with that padding, and without this it reads as a path with no
36
+ * scheme: the app would try to open `https://example.com/docs` as a file in
37
+ * the workspace instead of opening a tab. By the same rule
38
+ * ` JaVaScRiPt:alert(1)` and `java&#9;script:alert(1)` are `javascript:` to
39
+ * the checks below, because they are `javascript:` to a browser that
40
+ * navigates them.
41
+ *
42
+ * THE ONE RULE, FOR EVERY READER OF AN HREF. The scheme checks here, the
43
+ * sanitizer's keep-decision and the resolver that turns a kept href into a
44
+ * path all run it, so the string judged is the string followed. A padded
45
+ * `' Board.html '` that the sanitizer keeps must not reach
46
+ * `resolveRelativePath` with the spaces still on it — they would become part
47
+ * of a filename nobody wrote.
48
+ *
49
+ * It takes an inner tab out of a workspace path too (`'No\ttes.md'` resolves
50
+ * as `'Notes.md'`), which is what a browser does with the same href; a file
51
+ * whose name contains a literal tab is not reachable by a written link
52
+ * either way.
53
+ */
54
+ export function normalizeHref(href: string): string {
55
+ const inner = href.replace(/[\t\n\r]/g, '');
56
+ let start = 0;
57
+ let end = inner.length;
58
+ // Written as a scan rather than a regex character class, which would be a
59
+ // pattern full of literal control characters.
60
+ while (start < end && inner.charCodeAt(start) <= 0x20) start += 1;
61
+ while (end > start && inner.charCodeAt(end - 1) <= 0x20) end -= 1;
62
+ return start === 0 && end === inner.length ? inner : inner.slice(start, end);
22
63
  }
23
64
 
24
65
  /**
@@ -26,6 +67,10 @@ export function isExternalHref(href: string): boolean {
26
67
  * answers "does this leave the workspace"; this answers "may we hand it to
27
68
  * `window.open`", and the two are not the same question.
28
69
  *
70
+ * The href is read through {@link normalizeHref}, so padding and inner
71
+ * controls disguise nothing: ` javascript:…` is still `javascript:` and still
72
+ * absent from the list.
73
+ *
29
74
  * `window.open('javascript:…')` runs the script in a document that inherits
30
75
  * the OPENER's origin — so an allowlist here is what keeps the HTML sandbox a
31
76
  * sandbox. Agent HTML gets `globalThis.bevel.navigate(anyString)`, which posts
@@ -43,8 +88,39 @@ export function isExternalHref(href: string): boolean {
43
88
  const OPENABLE_SCHEMES = new Set(['http:', 'https:', 'mailto:', 'tel:', 'sms:', 'geo:']);
44
89
 
45
90
  export function isOpenableExternalHref(href: string): boolean {
46
- if (href.startsWith('//')) return true;
47
- const colon = href.indexOf(':');
91
+ const url = normalizeHref(href);
92
+ if (url.startsWith('//')) return true;
93
+ const colon = url.indexOf(':');
94
+ if (colon < 0) return false;
95
+ return OPENABLE_SCHEMES.has(url.slice(0, colon + 1).toLowerCase());
96
+ }
97
+
98
+ /**
99
+ * The external schemes a link WRITTEN IN A PAGE'S MARKUP may keep — a strict
100
+ * subset of {@link OPENABLE_SCHEMES}.
101
+ *
102
+ * `isOpenableExternalHref` answers "may we hand this to `window.open`" about a
103
+ * destination the app has already decided to follow. This answers a narrower
104
+ * question: which addresses an UNTRUSTED agent-authored page may put in front
105
+ * of a reader as a clickable link. Only the three a document normally carries
106
+ * — `http:`, `https:` and `mailto:`. A `tel:`, `sms:` or `geo:` address hands
107
+ * the reader's device to another app; that is a thing a person writes in a
108
+ * markdown document, not one a generated page gets to mint.
109
+ *
110
+ * Protocol-relative (`//cdn.example.com/…`) is NOT kept here, though
111
+ * `isOpenableExternalHref` allows it: that one resolves against the page's own
112
+ * scheme, and a sandboxed page's own origin is `about:srcdoc`, where there is
113
+ * nothing sensible to inherit.
114
+ *
115
+ * A subset, deliberately. A scheme kept here that `isOpenableExternalHref`
116
+ * rejected would survive sanitization and then do nothing when clicked; the
117
+ * tests pin the containment so the two lists cannot drift into that state.
118
+ */
119
+ const PAGE_LINK_SCHEMES = new Set(['http:', 'https:', 'mailto:']);
120
+
121
+ export function isPageLinkExternalHref(href: string): boolean {
122
+ const url = normalizeHref(href);
123
+ const colon = url.indexOf(':');
48
124
  if (colon < 0) return false;
49
- return OPENABLE_SCHEMES.has(href.slice(0, colon + 1).toLowerCase());
125
+ return PAGE_LINK_SCHEMES.has(url.slice(0, colon + 1).toLowerCase());
50
126
  }