Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
fix: preserve CSS cascade and imports in CSP fallback
Tw9345afde308df3
diff --git a/AGENTS.md b/AGENTS.mdindex aa484e9a..87bafdd7 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -90,6 +90,8 @@ Proactive latent-bug sweeps use `.agents/skills/bugs/SKILL.md`. Pick one row and## Current Risk Areas+- Injected CSS uses `src-tauri/src/inject/styles.js`: preserve DOM stylesheet order on ordinary pages; use constructable sheets only when CSP blocks the style element. `replaceSync` silently drops `@import`, so keep import-bearing CSS on its original DOM path, including escaped/case-insensitive at-keywords. Strict CSP plus imports remains unsupported. Run `node tests/browser/style-injection.mjs` with an installed Playwright runtime; mock CSSStyleSheet tests do not validate CSP or cascade behavior.+- CLI options are user-facing and must stay synchronized across `bin/helpers/cli-program.ts`, `bin/types.ts`, `bin/defaults.ts`, `bin/helpers/merge.ts`, generated `dist/cli.js`, `schema/pake.schema.json`, and `docs/cli-usage*.md`. Schema-to-CLI sync is enforced by `tests/unit/config-file.test.ts`; the rest is manual discipline.- The `--json` machine contract is public API for agents: stdout carries exactly one JSON result (nothing else may write to stdout in machine mode), and the exit codes (0/2/3/4/1) plus error codes (`INVALID_INPUT`, `ENV_MISSING`, `BUILD_FAILED`, `UNEXPECTED`, plus `NETWORK` which is reserved and currently unused, since network failures report under the phase code) must stay stable. `logger.warn` feeds the JSON `warnings` array, so warn is for real warnings only, not status lines. Owners: `bin/utils/output.ts`, `bin/cli.ts`, `bin/utils/shell.ts`.- Local file/directory packaging stages user content into the package's own `dist/` (moving it to `dist_bak` and restoring only `cli.js`). A crashed local-input run can strand `dev.js` and test fixtures in `dist_bak`; `restoreLocalTree()` heals that at the top of every CLI action, so it needs no manual cleanup. Owners: `stageLocalTree` and `restoreLocalTree` in `bin/helpers/merge.ts`.diff --git a/src-tauri/src/inject/styles.js b/src-tauri/src/inject/styles.jsindex 477ea6d8..5a965e10 100644--- a/src-tauri/src/inject/styles.js+++ b/src-tauri/src/inject/styles.js@@ -6,12 +6,34 @@return;}+ function containsImport(css) {+ // Skip comments, strings and escaped delimiters; decode at-keyword escapes. Import+ // rules are case-insensitive and need not begin a line. replaceSync silently+ // drops them, so a blocked sheet containing imports must keep its DOM path.+ const tokens =+ /\/\*[\s\S]*?(?:\*\/|$)|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|\\(?:[0-9a-f]{1,6}[\t\n\f\r ]?|[^\n\r\f])|@((?:[-\w\u0080-\uffff]|\\(?:[0-9a-f]{1,6}[\t\n\f\r ]?|[^\n\r\f]))+)/gi;+ for (const token of css.matchAll(tokens)) {+ if (!token[1]) continue;+ const keyword = token[1].replace(+ /\\([0-9a-f]{1,6})[\t\n\f\r ]?|\\([^\n\r\f])/gi,+ (_escape, hex, character) => {+ const code = hex ? parseInt(hex, 16) : 0;+ return hex+ ? String.fromCodePoint(code > 0 && code <= 0x10ffff ? code : 0xfffd)+ : character;+ },+ );+ if (keyword.toLowerCase() === "import") return true;+ }+ return false;+ }+function injectWithAdoptedStyleSheet(css, id) {try {if (typeof window.CSSStyleSheet !== "function" ||!("adoptedStyleSheets" in document) ||- /^\s*@import\b/m.test(css)+ containsImport(css)) {return null;}@@ -54,11 +76,6 @@}}- const sheet = injectWithAdoptedStyleSheet(css, id);- if (sheet) {- return sheet;- }-const style = document.createElement("style");if (id) {style.id = id;@@ -67,6 +84,17 @@(document.head || document.body || document.documentElement)?.appendChild(style,);++ // Preserve normal DOM cascade order, including custom CSS with imports.+ // CSP-blocked style elements have no associated sheet. Only those need the+ // constructable-sheet fallback; imports remain subject to the page's CSP.+ if (!style.sheet) {+ const sheet = injectWithAdoptedStyleSheet(css, id);+ if (sheet) {+ style.remove();+ return sheet;+ }+ }return style;};})();diff --git a/tests/browser/style-injection.mjs b/tests/browser/style-injection.mjsnew file mode 100644index 00000000..c43cd49f--- /dev/null+++ b/tests/browser/style-injection.mjs@@ -0,0 +1,200 @@+// Run with Node and an installed Playwright: node tests/browser/style-injection.mjs+// PAKE_PLAYWRIGHT_MODULE / PAKE_BROWSER_EXECUTABLE can select an existing runtime.+// PAKE_STYLE_SOURCE selects a prior helper for regression red runs.+import assert from "node:assert/strict";+import fs from "node:fs/promises";+import path from "node:path";+import { pathToFileURL } from "node:url";+import { test, before, after } from "node:test";++const source = await fs.readFile(+ process.env.PAKE_STYLE_SOURCE || "src-tauri/src/inject/styles.js",+ "utf8",+);+const { chromium } = await import(+ process.env.PAKE_PLAYWRIGHT_MODULE+ ? pathToFileURL(path.resolve(process.env.PAKE_PLAYWRIGHT_MODULE)).href+ : "playwright"+);+let browser;++before(async () => {+ browser = await chromium.launch({+ headless: true,+ ...(process.env.PAKE_BROWSER_EXECUTABLE+ ? { executablePath: process.env.PAKE_BROWSER_EXECUTABLE }+ : {}),+ });+});+after(async () => browser?.close());++async function withPage(strict, run) {+ const page = await browser.newPage();+ try {+ // Every request is fulfilled locally. Fixtures never contact a real site.+ await page.route("**/*", (route) => {+ const isCss = route.request().url().endsWith("theme.css");+ return route.fulfill({+ status: 200,+ contentType: isCss ? "text/css" : "text/html",+ headers: strict+ ? { "Content-Security-Policy": "style-src 'none'" }+ : {},+ body: isCss+ ? "body { color: rgb(1, 2, 3); }"+ : "<!doctype html><html><head></head><body>Find this sample text</body></html>",+ });+ });+ await page.goto("https://pake-style.test/");+ await page.evaluate(source);+ await run(page);+ } finally {+ await page.close();+ }+}++for (const css of [+ '/* theme */@import "theme.css";',+ '@IMPORT "theme.css";',+ '@charset "UTF-8";@import "theme.css";',+ '@\\69mport "theme.css";',+]) {+ test(`preserves imported CSS: ${css}`, () =>+ withPage(false, async (page) => {+ await page.evaluate((text) => window.__PAKE_INJECT_STYLE__(text), css);+ await page.waitForFunction(+ () => getComputedStyle(document.body).color === "rgb(1, 2, 3)",+ null,+ { timeout: 2000 },+ );+ assert.equal(+ await page.evaluate(() => document.adoptedStyleSheets.length),+ 0,+ );+ }));+}++test("preserves file order across plain and imported custom CSS", () =>+ withPage(false, async (page) => {+ const color = await page.evaluate(() => {+ window.__PAKE_INJECT_STYLE__("body { color: red; }");+ window.__PAKE_INJECT_STYLE__(+ '@import "theme.css"; body { color: blue; }',+ );+ return getComputedStyle(document.body).color;+ });+ assert.equal(color, "rgb(0, 0, 255)");+ }));++test("proves CSP blocks DOM styles while the fallback applies", () =>+ withPage(true, async (page) => {+ const result = await page.evaluate(() => {+ const blocked = document.createElement("style");+ blocked.textContent = "body { color: blue; }";+ document.head.append(blocked);+ const before = getComputedStyle(document.body).color;+ const blockedSheet = blocked.sheet;+ blocked.remove();+ window.__PAKE_INJECT_STYLE__("body { color: red; }", "pake-test-style");+ return {+ before,+ blockedSheet,+ after: getComputedStyle(document.body).color,+ elements: document.querySelectorAll("style").length,+ };+ });+ assert.deepEqual(result, {+ before: "rgb(0, 0, 0)",+ blockedSheet: null,+ after: "rgb(255, 0, 0)",+ elements: 0,+ });+ }));++test("preserves existing adopted sheets and recreates removed cache entries", () =>+ withPage(true, async (page) => {+ const result = await page.evaluate(() => {+ const existing = new CSSStyleSheet();+ existing.replaceSync("body { font-size: 23px; }");+ document.adoptedStyleSheets = [existing];+ const first = window.__PAKE_INJECT_STYLE__(+ "body { color: red; }",+ "pake-test-style",+ );+ const repeated = window.__PAKE_INJECT_STYLE__(+ "body { color: red; }",+ "pake-test-style",+ );+ const preserved = document.adoptedStyleSheets.includes(existing);+ document.adoptedStyleSheets = [existing];+ const recreated = window.__PAKE_INJECT_STYLE__(+ "body { color: red; }",+ "pake-test-style",+ );+ return {+ preserved,+ same: first === repeated,+ recreated: first !== recreated,+ count: document.adoptedStyleSheets.length,+ color: getComputedStyle(document.body).color,+ };+ });+ assert.deepEqual(result, {+ preserved: true,+ same: true,+ recreated: true,+ count: 2,+ color: "rgb(255, 0, 0)",+ });+ }));++test("keeps strict-CSP imports visibly unsupported instead of dropping rules", () =>+ withPage(true, async (page) => {+ const result = await page.evaluate(() => {+ const css = '/* theme */@IMPORT "theme.css"; body { color: red; }';+ const style = window.__PAKE_INJECT_STYLE__(css);+ return {+ tag: style.tagName,+ text: style.textContent,+ sheet: style.sheet,+ adopted: document.adoptedStyleSheets.length,+ };+ });+ assert.deepEqual(result, {+ tag: "STYLE",+ text: '/* theme */@IMPORT "theme.css"; body { color: red; }',+ sheet: null,+ adopted: 0,+ });+ }));++test("renders the actual Find panel under strict CSP", () =>+ withPage(true, async (page) => {+ await page.evaluate(() => {+ window.pakeConfig = { enable_find: true };+ });+ await page.evaluate(+ await fs.readFile("src-tauri/src/inject/find.js", "utf8"),+ );+ const result = await page.evaluate(() => {+ window.pakeFind.open();+ const panel = document.querySelector("#pake-find-panel");+ return {+ exists: !!panel,+ position: panel && getComputedStyle(panel).position,+ };+ });+ assert.deepEqual(result, { exists: true, position: "fixed" });+ }));++test("does not treat strings, comments or escaped selectors as import rules", () =>+ withPage(true, async (page) => {+ const color = await page.evaluate(() => {+ document.body.className = "@import";+ window.__PAKE_INJECT_STYLE__(+ '/* @import */ .\\@import { color: red; } body::before { content: "@import"; }',+ );+ return getComputedStyle(document.body).color;+ });+ assert.equal(color, "rgb(255, 0, 0)");+ }));diff --git a/tests/unit/find-shortcuts.test.js b/tests/unit/find-shortcuts.test.jsindex 4231da8d..0b2ac2d7 100644--- a/tests/unit/find-shortcuts.test.js+++ b/tests/unit/find-shortcuts.test.js@@ -25,6 +25,12 @@ function createElement(tagName) {append(...children) {children.forEach((child) => element.appendChild(child));},+ remove() {+ const siblings = element.parentElement?.children;+ if (siblings) siblings.splice(siblings.indexOf(element), 1);+ element.parentElement = null;+ element.parentNode = null;+ },addEventListener(type, handler) {element.listeners = element.listeners || {};element.listeners[type] = element.listeners[type] || [];diff --git a/tests/unit/style-injection.test.js b/tests/unit/style-injection.test.jsindex 4c068de5..eff64d0b 100644--- a/tests/unit/style-injection.test.js+++ b/tests/unit/style-injection.test.js@@ -8,17 +8,28 @@ const source = fs.readFileSync("utf-8",);-function loadStyleHelper({ supportsAdoptedStyleSheets }) {+function loadStyleHelper({+ supportsAdoptedStyleSheets,+ blocksStyleElements = true,+}) {const appendedStyles = [];const document = {head: {appendChild(style) {appendedStyles.push(style);+ style.sheet = blocksStyleElements ? null : {};return style;},},createElement(tagName) {- return { tagName, id: "", textContent: "" };+ return {+ tagName,+ id: "",+ textContent: "",+ remove() {+ appendedStyles.splice(appendedStyles.indexOf(this), 1);+ },+ };},getElementById() {return null;@@ -45,6 +56,22 @@ function loadStyleHelper({ supportsAdoptedStyleSheets }) {}describe("Pake style injection", () => {+ it("preserves DOM stylesheet order when inline styles are allowed", () => {+ const { appendedStyles, context } = loadStyleHelper({+ supportsAdoptedStyleSheets: true,+ blocksStyleElements: false,+ });+ context.window.__PAKE_INJECT_STYLE__("body { color: red; }");+ context.window.__PAKE_INJECT_STYLE__(+ '@import "theme.css"; body { color: blue; }',+ );+ expect(context.document.adoptedStyleSheets).toHaveLength(0);+ expect(appendedStyles.map((style) => style.textContent)).toEqual([+ "body { color: red; }",+ '@import "theme.css"; body { color: blue; }',+ ]);+ });+it("uses adopted style sheets when the page blocks style elements", () => {const { appendedStyles, context } = loadStyleHelper({supportsAdoptedStyleSheets: true,@@ -89,6 +116,30 @@ describe("Pake style injection", () => {expect(appendedStyles[0].textContent).toContain("@import");});+ it.each([+ '/* theme */@import "theme.css";',+ '@IMPORT "theme.css";',+ '@charset "UTF-8";@import "theme.css";',+ '@\\69mport "theme.css";',+ ])("does not silently discard imports under CSP: %s", (css) => {+ const { appendedStyles, context } = loadStyleHelper({+ supportsAdoptedStyleSheets: true,+ });+ context.window.__PAKE_INJECT_STYLE__(css);+ expect(context.document.adoptedStyleSheets).toHaveLength(0);+ expect(appendedStyles[0].textContent).toBe(css);+ });++ it.each([+ '/* @import */ body::before { content: "@import"; }',+ ".\\@import { color: red; }",+ "@import-theme; body { color: red; }",+ ])("does not mistake other CSS tokens for import rules: %s", (css) => {+ const { context } = loadStyleHelper({ supportsAdoptedStyleSheets: true });+ context.window.__PAKE_INJECT_STYLE__(css);+ expect(context.document.adoptedStyleSheets).toHaveLength(1);+ });+it("falls back to a style element when adopted style sheets are unavailable", () => {const { appendedStyles, context } = loadStyleHelper({supportsAdoptedStyleSheets: false,