@ruckc/truss-code 1.47.0 → 1.48.1

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/README.md CHANGED
@@ -27,6 +27,10 @@ npm install monaco-editor # only if you use the editors
27
27
 
28
28
  `CodeBlock` colours with the small built-in highlighter and only uses Monaco's tokenizers when something else (an editor on the page) has already loaded Monaco, so a read-only block never downloads it. Set `highlighter="monaco"` on a block, or `configureCodeEditor({ highlighter: 'monaco' })` for every read-only view, to always load Monaco for colouring, or `'lite'` to never use it. `copy` adds a Copy button; to render Markdown fences with it, pass `{#snippet code({ lang, text })}<CodeBlock code={text} language={lang} copy />{/snippet}` to `@ruckc/truss-markdown`'s `Markdown`. That package does not depend on this one.
29
29
 
30
+ ## Strict CSP
31
+
32
+ Under `style-src 'self' 'nonce-…'` (no `'unsafe-inline'`) the editors work once a nonce is configured: `setCspNonce(nonce)` from `@ruckc/truss-ui` in the root layout, `configureCsp({ nonce })`, or `<meta property="csp-nonce" nonce="…">`. Monaco 0.57 has no nonce support of its own, so with a nonce present the package wraps `document.createElement('style')` (the element gets the nonce), `setAttribute('style', …)` (becomes a CSSOM assignment) and `innerHTML` / `insertAdjacentHTML` strings that contain `style="…"` (parsed in a policy-free document, with each style attribute moved to the CSSOM). Without a nonce nothing is wrapped. Monaco's own CSS is a normal stylesheet in a production build; in Vite dev, Vite reads its nonce from the same meta tag (or `html.cspNonce`). The Truss documentation has a Content Security Policy page with the details.
33
+
30
34
  ## License
31
35
 
32
36
  MIT
@@ -1,6 +1,9 @@
1
1
  <script lang="ts">
2
2
  import { csstext } from './cssvars.js';
3
3
  import SsrStyle from './SsrStyle.svelte';
4
+ import { prepareMonacoCsp } from './monaco-csp.js';
5
+ // with a CSP nonce configured, Monaco's own styles get it too (a no-op without one)
6
+ prepareMonacoCsp();
4
7
  const uid = $props.id();
5
8
  import { onMount, onDestroy } from 'svelte';
6
9
  import { Button, Tooltip } from '@ruckc/truss-ui';
@@ -7,6 +7,9 @@
7
7
  <script lang="ts">
8
8
  import { csstext } from './cssvars.js';
9
9
  import SsrStyle from './SsrStyle.svelte';
10
+ import { prepareMonacoCsp } from './monaco-csp.js';
11
+ // with a CSP nonce configured, Monaco's own styles get it too (a no-op without one)
12
+ prepareMonacoCsp();
10
13
  import { onMount } from 'svelte';
11
14
  import type { HTMLAttributes } from 'svelte/elements';
12
15
  import { Skeleton, matches } from '@ruckc/truss-ui';
@@ -7,6 +7,9 @@
7
7
  <script lang="ts">
8
8
  import { cssvars } from './cssvars.js';
9
9
  import SsrStyle from './SsrStyle.svelte';
10
+ import { prepareMonacoCsp } from './monaco-csp.js';
11
+ // with a CSP nonce configured, Monaco's own styles get it too (a no-op without one)
12
+ prepareMonacoCsp();
10
13
  import { onMount } from 'svelte';
11
14
  import { Skeleton } from '@ruckc/truss-ui';
12
15
  import type * as Monaco from 'monaco-editor';
@@ -1,6 +1,9 @@
1
1
  <script lang="ts">
2
2
  import { csstext } from './cssvars.js';
3
3
  import SsrStyle from './SsrStyle.svelte';
4
+ import { prepareMonacoCsp } from './monaco-csp.js';
5
+ // with a CSP nonce configured, Monaco's own styles get it too (a no-op without one)
6
+ prepareMonacoCsp();
4
7
  import { onMount, tick, untrack } from 'svelte';
5
8
  import type { ClassValue } from 'svelte/elements';
6
9
  import { Button, SegmentedControl, Textarea } from '@ruckc/truss-ui';
package/dist/csp.d.ts CHANGED
@@ -1 +1,3 @@
1
+ /** @internal The nonce without the component context (`configureCsp` or the meta tag): usable outside component initialisation. */
2
+ export declare function ambientNonce(): string | undefined;
1
3
  export declare function cspNonce(): string | undefined;
package/dist/csp.js CHANGED
@@ -5,8 +5,12 @@ import { getContext } from 'svelte';
5
5
  */
6
6
  const KEY = Symbol.for('@ruckc/truss-ui:csp-nonce');
7
7
  const STATE = Symbol.for('@ruckc/truss-ui:csp');
8
- export function cspNonce() {
8
+ /** @internal The nonce without the component context (`configureCsp` or the meta tag): usable outside component initialisation. */
9
+ export function ambientNonce() {
9
10
  const state = globalThis[STATE];
10
11
  const m = typeof document === 'undefined' ? null : document.querySelector('meta[property="csp-nonce"], meta[name="csp-nonce"]');
11
- return getContext(KEY) || state?.nonce || m?.nonce || m?.content || undefined;
12
+ return state?.nonce || m?.nonce || m?.content || undefined;
13
+ }
14
+ export function cspNonce() {
15
+ return getContext(KEY) || ambientNonce();
12
16
  }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Strict-CSP support for Monaco (`style-src 'self' 'nonce-…'`, no `'unsafe-inline'`). Monaco 0.57 knows no nonce: it creates `<style>`
3
+ * elements with `document.createElement('style')`, sets `style` attributes with `setAttribute('style', …)`, and renders every text line
4
+ * through `innerHTML` / `insertAdjacentHTML` strings that carry `style="top:…"`. All three are blocked by such a policy.
5
+ *
6
+ * `installMonacoCsp(nonce)` wraps those entry points (only once a nonce is known; without one nothing is touched):
7
+ * - `document.createElement('style')` gives the element the nonce before Monaco fills or inserts it;
8
+ * - `Element.setAttribute('style', v)` becomes `el.style.cssText = v` (CSSOM, which CSP allows);
9
+ * - `innerHTML = …` and `insertAdjacentHTML(…)` strings holding `style="…"` are parsed in an policy-free document (`DOMParser`),
10
+ * each style attribute is moved to the CSSOM, and the finished nodes are inserted.
11
+ * A `<template>` (frameworks fill those through `innerHTML`) gets the converted nodes in its `content`. Everything else, including HTML without a style attribute, passes straight through.
12
+ */
13
+ /** Wraps Monaco's style creation so that it works under a nonce-only `style-src`. Idempotent; a later call replaces the nonce. Returns `uninstallMonacoCsp`. */
14
+ export declare function installMonacoCsp(nonce: string | undefined): () => void;
15
+ /** Restores the browser's own functions. Meant for tests; Monaco is global, so the editors leave the wrappers installed. */
16
+ export declare function uninstallMonacoCsp(): void;
17
+ /** Whether the wrappers are installed. */
18
+ export declare const monacoCspInstalled: () => boolean;
19
+ /** Called while a component initialises: installs the wrappers when the page has a CSP nonce (`setCspNonce`, `configureCsp` or the `csp-nonce` meta tag). A no-op without one. */
20
+ export declare function prepareMonacoCsp(): void;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Strict-CSP support for Monaco (`style-src 'self' 'nonce-…'`, no `'unsafe-inline'`). Monaco 0.57 knows no nonce: it creates `<style>`
3
+ * elements with `document.createElement('style')`, sets `style` attributes with `setAttribute('style', …)`, and renders every text line
4
+ * through `innerHTML` / `insertAdjacentHTML` strings that carry `style="top:…"`. All three are blocked by such a policy.
5
+ *
6
+ * `installMonacoCsp(nonce)` wraps those entry points (only once a nonce is known; without one nothing is touched):
7
+ * - `document.createElement('style')` gives the element the nonce before Monaco fills or inserts it;
8
+ * - `Element.setAttribute('style', v)` becomes `el.style.cssText = v` (CSSOM, which CSP allows);
9
+ * - `innerHTML = …` and `insertAdjacentHTML(…)` strings holding `style="…"` are parsed in an policy-free document (`DOMParser`),
10
+ * each style attribute is moved to the CSSOM, and the finished nodes are inserted.
11
+ * A `<template>` (frameworks fill those through `innerHTML`) gets the converted nodes in its `content`. Everything else, including HTML without a style attribute, passes straight through.
12
+ */
13
+ import { cspNonce } from './csp.js';
14
+ let current;
15
+ const HAS_STYLE = /\sstyle\s*=/i;
16
+ /** Parses `html` in a policy-free document and replaces every `style="…"` attribute with the equivalent CSSOM declarations. */
17
+ function toFragment(html) {
18
+ // DOMParser documents have no browsing context, so no CSP applies to the attributes while parsing (a <template> in the page is not exempt)
19
+ const body = new DOMParser().parseFromString(`<!doctype html><body>${html}`, 'text/html').body;
20
+ for (const el of body.querySelectorAll('[style]')) {
21
+ const css = el.getAttribute('style') ?? '';
22
+ el.removeAttribute('style');
23
+ el.style.cssText = css;
24
+ }
25
+ const frag = document.createDocumentFragment();
26
+ frag.append(...body.childNodes);
27
+ return frag;
28
+ }
29
+ /** Wraps Monaco's style creation so that it works under a nonce-only `style-src`. Idempotent; a later call replaces the nonce. Returns `uninstallMonacoCsp`. */
30
+ export function installMonacoCsp(nonce) {
31
+ if (!nonce || typeof document === 'undefined')
32
+ return uninstallMonacoCsp;
33
+ if (current) {
34
+ current.nonce = nonce;
35
+ return uninstallMonacoCsp;
36
+ }
37
+ const undo = {
38
+ setAttribute: Element.prototype.setAttribute,
39
+ innerHTML: Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML'),
40
+ insertAdjacentHTML: Element.prototype.insertAdjacentHTML
41
+ };
42
+ const state = (current = { nonce, undo });
43
+ const rawSet = undo.innerHTML.set;
44
+ const create = document.createElement;
45
+ document.createElement = function (...args) {
46
+ const el = create.apply(this, args);
47
+ if (String(args[0]).toLowerCase() === 'style')
48
+ el.nonce = state.nonce;
49
+ return el;
50
+ };
51
+ Element.prototype.setAttribute = function (name, value) {
52
+ if (String(name).toLowerCase() === 'style' && 'style' in this)
53
+ this.style.cssText = String(value);
54
+ else
55
+ undo.setAttribute.call(this, name, value);
56
+ };
57
+ Object.defineProperty(Element.prototype, 'innerHTML', {
58
+ ...undo.innerHTML,
59
+ set(v) {
60
+ const html = String(v);
61
+ if (!HAS_STYLE.test(html))
62
+ rawSet.call(this, v);
63
+ else
64
+ (this instanceof HTMLTemplateElement ? this.content : this).replaceChildren(toFragment(html));
65
+ }
66
+ });
67
+ Element.prototype.insertAdjacentHTML = function (where, v) {
68
+ const html = String(v);
69
+ if (!HAS_STYLE.test(html))
70
+ return undo.insertAdjacentHTML.call(this, where, v);
71
+ const frag = toFragment(html);
72
+ switch (String(where).toLowerCase()) {
73
+ case 'beforebegin':
74
+ this.before(frag);
75
+ break;
76
+ case 'afterbegin':
77
+ this.prepend(frag);
78
+ break;
79
+ case 'beforeend':
80
+ this.append(frag);
81
+ break;
82
+ default: this.after(frag);
83
+ }
84
+ };
85
+ return uninstallMonacoCsp;
86
+ }
87
+ /** Restores the browser's own functions. Meant for tests; Monaco is global, so the editors leave the wrappers installed. */
88
+ export function uninstallMonacoCsp() {
89
+ if (!current)
90
+ return;
91
+ const { undo } = current;
92
+ current = undefined;
93
+ delete document.createElement;
94
+ Element.prototype.setAttribute = undo.setAttribute;
95
+ Object.defineProperty(Element.prototype, 'innerHTML', undo.innerHTML);
96
+ Element.prototype.insertAdjacentHTML = undo.insertAdjacentHTML;
97
+ }
98
+ /** Whether the wrappers are installed. */
99
+ export const monacoCspInstalled = () => !!current;
100
+ /** Called while a component initialises: installs the wrappers when the page has a CSP nonce (`setCspNonce`, `configureCsp` or the `csp-nonce` meta tag). A no-op without one. */
101
+ export function prepareMonacoCsp() {
102
+ installMonacoCsp(cspNonce());
103
+ }
package/dist/monaco.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { ambientNonce } from './csp.js';
2
+ import { installMonacoCsp } from './monaco-csp.js';
1
3
  import { readTheme, monacoTheme } from './theme.js';
2
4
  let loader;
3
5
  let pending;
@@ -41,6 +43,7 @@ export function loadMonaco() {
41
43
  if (!loader)
42
44
  return Promise.reject(new Error('@ruckc/truss-code: Monaco is not configured. Call setMonacoLoader(() => import("monaco-editor")) or useMonaco() from "@ruckc/truss-code/monaco".'));
43
45
  if (!pending) {
46
+ installMonacoCsp(ambientNonce()); // under a strict style-src Monaco's styles need the nonce (no-op without one)
44
47
  const mine = (pending = loader());
45
48
  mine.then(() => {
46
49
  if (pending !== mine)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ruckc/truss-code",
3
- "version": "1.47.0",
3
+ "version": "1.48.1",
4
4
  "description": "Read-only code blocks, diff and merge views, plus an optional Monaco code editor, styled with Truss UI",
5
5
  "type": "module",
6
6
  "license": "MIT",