@panomc/theme-core 1.0.0 → 1.1.0-dev.2

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.
@@ -226,6 +226,14 @@
226
226
  --bs-carousel-caption-color: #000;
227
227
  --bs-carousel-control-icon-filter: invert(1) grayscale(100);
228
228
  }
229
+ .card > .card-header {
230
+ border-bottom: 0;
231
+ background-color: transparent;
232
+ }
233
+ .card > .card-footer {
234
+ border-top: 0;
235
+ background-color: transparent;
236
+ }
229
237
  *,
230
238
  *::before,
231
239
  *::after {
@@ -226,6 +226,14 @@
226
226
  --bs-carousel-caption-color: #000;
227
227
  --bs-carousel-control-icon-filter: invert(1) grayscale(100);
228
228
  }
229
+ .card > .card-header {
230
+ border-bottom: 0;
231
+ background-color: transparent;
232
+ }
233
+ .card > .card-footer {
234
+ border-top: 0;
235
+ background-color: transparent;
236
+ }
229
237
  *,
230
238
  *::before,
231
239
  *::after {
@@ -185,3 +185,27 @@ describe.skipIf(!pluginMinDir)("contracts pull of the built test-fixtures/plugin
185
185
  expect(exists(theme, "plugin-contracts/min/src")).toBe(false);
186
186
  });
187
187
  });
188
+
189
+ describe("contracts pull: a package cannot reach outside plugin-contracts/", () => {
190
+ for (const ns of ["..", "../../outside", "a/b"]) {
191
+ test(`namespace '${ns}' is skipped, nothing is written or deleted outside`, () => {
192
+ const { theme, pkg } = themeWithMarket();
193
+ write(theme, "keep-me.txt", "owner file");
194
+ const views = JSON.parse(read(pkg, "contract/views.json"));
195
+ views.namespace = ns;
196
+ write(pkg, "contract/views.json", JSON.stringify(views));
197
+ installPackage(theme, pkg, "pano-plugin-market");
198
+
199
+ cli(theme, ["contracts", "pull"]);
200
+ expect(read(theme, "keep-me.txt")).toBe("owner file");
201
+ expect(exists(theme, "views.json")).toBe(false);
202
+ expect(exists(theme, "controllers.json")).toBe(false);
203
+ });
204
+ }
205
+
206
+ test("writeSnapshot refuses a namespace that is not a plain name", async () => {
207
+ const { writeSnapshot } = await import("../../contracts.js");
208
+ const { theme, pkg } = themeWithMarket();
209
+ expect(() => writeSnapshot(theme, { dir: pkg, pluginId: "x", namespace: ".." })).toThrow("not a plain name");
210
+ });
211
+ });
@@ -354,3 +354,19 @@ describe.skipIf(!pluginMinDir)("eject-view against the built test-fixtures/plugi
354
354
  expect(JSON.parse(read(theme, "plugin-contracts/min/views.json")).views["min:HelloPage"].page).toEqual({ path: "/hello" });
355
355
  });
356
356
  });
357
+
358
+ describe("eject-view: a package cannot copy files from outside its contract/src", () => {
359
+ test("a view source that leaves contract/src is refused", () => {
360
+ const { theme, pkg } = themeWithMarket();
361
+ write(pkg, "secret.txt", "private key");
362
+ const views = JSON.parse(read(pkg, "contract/views.json"));
363
+ views.views["market:ProductCard"].source = "src/../../secret.txt";
364
+ write(pkg, "contract/views.json", JSON.stringify(views));
365
+ installPackage(theme, pkg, "pano-plugin-market");
366
+
367
+ const run = cli(theme, ["eject-view", "market:ProductCard"]);
368
+ expect(run.code).not.toBe(0);
369
+ expect(run.out).toContain("is not inside the package's contract/src");
370
+ expect(exists(theme, "src/views/market/ProductCard.svelte")).toBe(false);
371
+ });
372
+ });
package/bin/contracts.js CHANGED
@@ -79,6 +79,43 @@ function sameBytes(file, buffer) {
79
79
  /** Posix path relative to a root, for messages and stored paths. */
80
80
  const posix = (p) => p.split(path.sep).join("/");
81
81
 
82
+ // A plugin package names its namespace, id and view files itself; they become paths in the theme, so they must stay
83
+ // plain names (no `..`, no separators) and the files must stay inside the package's `contract/`.
84
+ const SAFE_NAMESPACE = /^[a-z0-9][a-z0-9_-]*$/i;
85
+ const SAFE_PLUGIN_ID = /^[A-Za-z0-9._-]+$/;
86
+ const SAFE_VIEW_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
87
+
88
+ /** @param {unknown} namespace */
89
+ export const isSafeNamespace = (namespace) => typeof namespace === "string" && SAFE_NAMESPACE.test(namespace);
90
+
91
+ /** @param {unknown} pluginId */
92
+ export const isSafePluginId = (pluginId) =>
93
+ typeof pluginId === "string" && SAFE_PLUGIN_ID.test(pluginId) && pluginId !== "." && pluginId !== "..";
94
+
95
+ /**
96
+ * `rel` joined to `base`, or null when the result leaves `base` or passes through a symbolic link.
97
+ * @param {string} base
98
+ * @param {string} rel
99
+ * @returns {string | null}
100
+ */
101
+ export function insideDir(base, rel) {
102
+ if (typeof rel !== "string" || rel === "" || path.isAbsolute(rel)) return null;
103
+ const root = path.resolve(base);
104
+ const file = path.resolve(root, rel);
105
+ if (!file.startsWith(root + path.sep)) return null;
106
+
107
+ let at = root;
108
+ for (const part of path.relative(root, file).split(path.sep)) {
109
+ at = path.join(at, part);
110
+ try {
111
+ if (fs.lstatSync(at).isSymbolicLink()) return null;
112
+ } catch {
113
+ break; // the rest does not exist yet
114
+ }
115
+ }
116
+ return file;
117
+ }
118
+
82
119
  /** `pano-plugin-market` -> `market` (doc 01 section 1: only a leading `pano-plugin-` is stripped). */
83
120
  export function defaultNamespace(pluginId) {
84
121
  return String(pluginId).replace(/^pano-plugin-/, "");
@@ -108,11 +145,16 @@ export function readPackage(dir) {
108
145
  if (!viewsJson || typeof viewsJson !== "object") return null;
109
146
  const index = readJson(path.join(dir, "pano-plugin.json"));
110
147
  const pluginId = viewsJson.pluginId ?? index?.pluginId ?? path.basename(dir);
148
+ const namespace = viewsJson.namespace ?? index?.namespace ?? defaultNamespace(pluginId);
149
+ if (!isSafePluginId(pluginId) || !isSafeNamespace(namespace)) {
150
+ process.stderr.write(`theme-core: skipped ${dir}: its plugin id or namespace is not a plain name\n`);
151
+ return null;
152
+ }
111
153
 
112
154
  return {
113
155
  dir,
114
156
  pluginId,
115
- namespace: viewsJson.namespace ?? index?.namespace ?? defaultNamespace(pluginId),
157
+ namespace,
116
158
  viewsJson,
117
159
  controllersJson: readJson(path.join(dir, "contract", "controllers.json")),
118
160
  index,
@@ -200,9 +242,12 @@ export function readSnapshots(themeDir) {
200
242
  const dir = path.join(root, entry);
201
243
  const viewsJson = readJson(path.join(dir, "views.json"));
202
244
  if (!viewsJson) continue;
245
+ const namespace = viewsJson.namespace ?? entry;
246
+ const pluginId = viewsJson.pluginId ?? `pano-plugin-${entry}`;
247
+ if (!isSafeNamespace(namespace) || !isSafePluginId(pluginId)) continue;
203
248
  snapshots.push({
204
- namespace: viewsJson.namespace ?? entry,
205
- pluginId: viewsJson.pluginId ?? `pano-plugin-${entry}`,
249
+ namespace,
250
+ pluginId,
206
251
  dir,
207
252
  viewsJson,
208
253
  controllersJson: readJson(path.join(dir, "controllers.json")),
@@ -260,7 +305,8 @@ export function diffViews(before, after) {
260
305
  * @returns {{ namespace: string, pluginId: string, first: boolean, written: string[], removed: string[], viewsChanged: boolean, diff: ReturnType<typeof diffViews> }}
261
306
  */
262
307
  export function writeSnapshot(themeDir, pkg) {
263
- const target = path.join(themeDir, SNAPSHOT_DIR, pkg.namespace);
308
+ const target = isSafeNamespace(pkg.namespace) ? insideDir(path.join(themeDir, SNAPSHOT_DIR), pkg.namespace) : null;
309
+ if (!target) throw new CliError(`${pkg.pluginId}: namespace '${pkg.namespace}' is not a plain name`);
264
310
  const first = !isFile(path.join(target, "views.json"));
265
311
  const before = first ? null : readJson(path.join(target, "views.json"));
266
312
  const contractDir = path.join(pkg.dir, "contract");
@@ -1064,8 +1110,8 @@ function helperClosure(contractSrcDir, sourcePath, direct) {
1064
1110
  while (queue.length && seen.size < limit) {
1065
1111
  const rel = queue.shift();
1066
1112
  if (seen.has(rel)) continue;
1067
- const file = path.join(contractSrcDir, rel);
1068
- if (!isFile(file)) continue;
1113
+ const file = insideDir(contractSrcDir, rel);
1114
+ if (!file || !isFile(file)) continue;
1069
1115
  seen.add(rel);
1070
1116
 
1071
1117
  const text = fs.readFileSync(file, "utf8");
@@ -1191,7 +1237,11 @@ function ejectFromPackage({ themeDir, pkg, name, pages, log }) {
1191
1237
  for (const viewId of ids) {
1192
1238
  const view = allViews[viewId];
1193
1239
  const viewName = viewId.slice(ns.length + 1);
1194
- const sourceFile = path.join(contractDir, view.source);
1240
+ if (!SAFE_VIEW_NAME.test(viewName)) throw new CliError(`${viewId}: the view name is not a plain name`);
1241
+ const sourceFile = insideDir(contractDir, view.source);
1242
+ if (!sourceFile || !sourceFile.startsWith(path.resolve(contractSrc) + path.sep)) {
1243
+ throw new CliError(`${viewId}: source ${view.source} is not inside the package's contract/src`);
1244
+ }
1195
1245
  if (!isFile(sourceFile)) {
1196
1246
  throw new CliError(`${viewId}: readable source ${posix(path.join("contract", view.source))} is missing in the package (rebuild the plugin)`);
1197
1247
  }
@@ -1207,7 +1257,7 @@ function ejectFromPackage({ themeDir, pkg, name, pages, log }) {
1207
1257
  const viewResult = writeOwned(target, transformed.code, themeDir);
1208
1258
 
1209
1259
  const helperResults = helpers.map((helper) =>
1210
- writeOwned(path.join(themeDir, "src", "views", ns, helper), fs.readFileSync(path.join(contractSrc, helper)), themeDir),
1260
+ writeOwned(path.join(themeDir, "src", "views", ns, helper), fs.readFileSync(insideDir(contractSrc, helper)), themeDir),
1211
1261
  );
1212
1262
 
1213
1263
  // controllers: those the package index lists for the view, plus the literal calls in its source
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@panomc/theme-core",
3
- "version": "1.0.0",
3
+ "version": "1.1.0-dev.2",
4
4
  "description": "The Pano theme engine: hooks factories, plugin engine, headless page controllers, default views and the theme CLI. Themes depend on this package instead of forking vanilla-theme.",
5
5
  "author": "PanoMC",
6
6
  "pano": {
@@ -61,7 +61,7 @@
61
61
  "@fortawesome/fontawesome-free": "^6.7.2"
62
62
  },
63
63
  "peerDependencies": {
64
- "@panomc/sdk": "^2.0.0",
64
+ "@panomc/sdk": "^2.0.0-dev.2",
65
65
  "@sveltejs/adapter-node": "^6.0.0",
66
66
  "@sveltejs/kit": "^3.1.0",
67
67
  "@sveltejs/vite-plugin-svelte": "^7.3.1",
@@ -71,7 +71,7 @@
71
71
  "vite": "^8.3.4"
72
72
  },
73
73
  "devDependencies": {
74
- "@panomc/sdk": "2.0.0",
74
+ "@panomc/sdk": "2.0.0-dev.2",
75
75
  "@sveltejs/adapter-node": "^6.0.0",
76
76
  "@sveltejs/kit": "^3.1.0",
77
77
  "@sveltejs/vite-plugin-svelte": "^7.3.1",
@@ -198,8 +198,12 @@ export function createLicenseRuntime(licenseConstants) {
198
198
  //
199
199
  // The check is wrapped in a try-catch so a malformed/missing manifest is reported as
200
200
  // FILE_TAMPERED instead of bubbling a generic FS error (those are noisy and unhelpful).
201
+ //
202
+ // The expected fingerprint comes from the signed token (`fp`, computed by panomc.com when the
203
+ // theme was uploaded) when the token carries one. manifest.json sits next to the files and is
204
+ // not signed, so without `fp` the check only catches accidental corruption, not deliberate edits.
201
205
  try {
202
- verifyFileFingerprint();
206
+ verifyFileFingerprint(payload.fp);
203
207
  } catch (e) {
204
208
  if (e instanceof LicenseError) throw e;
205
209
  throw new LicenseError(LICENSE_REASONS.FILE_TAMPERED, e?.message || String(e));
@@ -314,7 +318,8 @@ export function createLicenseRuntime(licenseConstants) {
314
318
  return null;
315
319
  }
316
320
 
317
- function verifyFileFingerprint() {
321
+ /** @param {unknown} signedFingerprint the `fp` claim of the verified token, when it has one */
322
+ function verifyFileFingerprint(signedFingerprint) {
318
323
  const themeRoot = locateThemeRoot();
319
324
  if (!themeRoot) {
320
325
  throw new LicenseError(
@@ -323,7 +328,10 @@ export function createLicenseRuntime(licenseConstants) {
323
328
  );
324
329
  }
325
330
  const manifest = JSON.parse(readFileSync(path.join(themeRoot, "manifest.json"), "utf-8"));
326
- const expected = manifest.fileFingerprint;
331
+ if (signedFingerprint !== undefined && !/^[0-9a-f]{64}$/i.test(String(signedFingerprint))) {
332
+ throw new LicenseError(LICENSE_REASONS.FILE_TAMPERED, "the license's fp claim is malformed");
333
+ }
334
+ const expected = signedFingerprint !== undefined ? String(signedFingerprint).toLowerCase() : manifest.fileFingerprint;
327
335
  if (typeof expected !== "string" || expected.length !== 64) {
328
336
  throw new LicenseError(
329
337
  LICENSE_REASONS.FILE_TAMPERED,
@@ -57,6 +57,8 @@ export const logout = async () => {};`,
57
57
  "$pano/lib/api.util.js": `export const responses = {};
58
58
  export default { get: async ({ path }) => responses[path] ?? {} };`,
59
59
  "$pano/lib/auth.util.js": `export const hasPermission = () => true;`,
60
+ // the i18n stub prints its values as JSON, which a real sanitizer would rewrite; html.util has its own test
61
+ "$pano/lib/html.util.js": `export const sanitizeRichHtml = (html) => (typeof html === "string" ? html : "");`,
60
62
  };
61
63
 
62
64
  /** Components that need the network, the browser or packages the temp folder cannot resolve. */
@@ -0,0 +1,67 @@
1
+ import { describe, expect, test } from "bun:test";
2
+
3
+ import { filterStyle, sanitizeRichHtml, styleTag } from "../html.util.js";
4
+
5
+ describe("sanitizeRichHtml", () => {
6
+ test("keeps what the panel editor writes", () => {
7
+ const html =
8
+ '<h2>Title</h2><p>Hi <strong>all</strong> <em>x</em> <a href="https://panomc.com" target="_blank" rel="noopener">link</a></p>' +
9
+ '<p><span style="color: #ff0000; font-size: 18px">red</span></p><ul><li>one</li></ul><img src="https://x.test/a.png" alt="a">';
10
+ const out = sanitizeRichHtml(html);
11
+ expect(out).toContain("<h2>Title</h2>");
12
+ expect(out).toContain('<a href="https://panomc.com" target="_blank" rel="noopener">link</a>');
13
+ expect(out).toContain('style="color:#ff0000;font-size:18px"');
14
+ expect(out).toContain('<img src="https://x.test/a.png" alt="a" />');
15
+ });
16
+
17
+ test("removes script, event handlers and javascript: links", () => {
18
+ const out = sanitizeRichHtml(
19
+ '<p>ok</p><script>alert(1)</script><img src="x" onerror="alert(1)"><a href="javascript:alert(1)">x</a><iframe src="https://e.test"></iframe><svg onload="alert(1)"></svg>',
20
+ );
21
+ expect(out).not.toContain("<script");
22
+ expect(out).not.toContain("onerror");
23
+ expect(out).not.toContain("javascript:");
24
+ expect(out).not.toContain("<iframe");
25
+ expect(out).not.toContain("onload");
26
+ expect(out).toContain("<p>ok</p>");
27
+ });
28
+
29
+ test("a style value cannot carry markup", () => {
30
+ expect(sanitizeRichHtml('<span style="color: red;}</style><script>">x</span>')).not.toContain("<script");
31
+ });
32
+
33
+ test("a style value cannot load a url", () => {
34
+ const out = sanitizeRichHtml('<span style="background-color: url(https://e.test/x.png); color: red">x</span>');
35
+ expect(out).not.toContain("url(");
36
+ expect(out).toContain("color:red");
37
+ });
38
+
39
+ test("filterStyle keeps the allowed declarations only", () => {
40
+ expect(filterStyle("color: red; position: fixed; background-color: url(https://e.test); font-size: 12px")).toBe(
41
+ "color:red;font-size:12px",
42
+ );
43
+ expect(filterStyle("behavior: url(x.htc)")).toBe("");
44
+ });
45
+
46
+ test("not a string yields an empty string", () => {
47
+ expect(sanitizeRichHtml(null)).toBe("");
48
+ expect(sanitizeRichHtml(undefined)).toBe("");
49
+ expect(sanitizeRichHtml(5)).toBe("");
50
+ });
51
+ });
52
+
53
+
54
+ describe("styleTag", () => {
55
+ test("keeps $ patterns literal", () => {
56
+ expect(styleTag("a::after { content: \"$' $& $` $$\" }")).toBe("<style>a::after { content: \"$' $& $` $$\" }</style>");
57
+ });
58
+
59
+ test("a </style inside cannot close the element", () => {
60
+ const out = styleTag("body{} </STYLE><script>alert(1)</script>");
61
+ expect(out.toLowerCase().indexOf("</style")).toBe(out.length - "</style>".length);
62
+ });
63
+
64
+ test("not a string yields an empty element", () => {
65
+ expect(styleTag(undefined)).toBe("<style></style>");
66
+ });
67
+ });
@@ -167,7 +167,9 @@ function makeTheme(files = {}, { workspace = false } = {}) {
167
167
  }
168
168
 
169
169
  function run(script, cwd) {
170
- const proc = Bun.spawnSync([process.execPath, script], { cwd, stdout: "pipe", stderr: "pipe" });
170
+ // --no-install: with no node_modules in sight Bun would auto-install, resolving "@panomc/sdk" from its global
171
+ // cache, and the "sdk missing" fixtures would find one wherever the machine happened to cache it.
172
+ const proc = Bun.spawnSync([process.execPath, "--no-install", script], { cwd, stdout: "pipe", stderr: "pipe" });
171
173
 
172
174
  return { code: proc.exitCode, out: proc.stdout.toString() + proc.stderr.toString() };
173
175
  }
@@ -0,0 +1,92 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { createSign, generateKeyPairSync } from "node:crypto";
3
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+
7
+ import { createLicenseRuntime } from "../../kit/license-runtime.js";
8
+ import { computeStableFileFingerprint } from "../../../bin/license/file-fingerprint.js";
9
+
10
+ // The file-integrity check of a premium theme: when the signed token carries `fp`, that is the expected
11
+ // fingerprint, so editing a file and re-stamping the unsigned manifest.json no longer passes.
12
+
13
+ const THEME_ID = "test-theme";
14
+ const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
15
+ const keyBase64 = publicKey.export({ type: "spki", format: "der" }).toString("base64");
16
+ const b64url = (value) => Buffer.from(value).toString("base64url");
17
+
18
+ function sign(payload) {
19
+ const head = b64url(JSON.stringify({ alg: "RS256", typ: "JWT" }));
20
+ const body = b64url(JSON.stringify(payload));
21
+ const signature = createSign("RSA-SHA256").update(`${head}.${body}`).sign(privateKey);
22
+ return `${head}.${body}.${signature.toString("base64url")}`;
23
+ }
24
+
25
+ const claims = (extra = {}) => ({
26
+ iss: "panomc.com",
27
+ aud: THEME_ID,
28
+ ver: "1.0.0",
29
+ exp: Math.floor(Date.now() / 1000) + 3600,
30
+ ...extra,
31
+ });
32
+
33
+ let root;
34
+ let cwd;
35
+
36
+ const verify = () =>
37
+ createLicenseRuntime({
38
+ PANO_LICENSE_PUBLIC_KEY_BASE64: keyBase64,
39
+ PANO_LICENSE_THEME_ID: THEME_ID,
40
+ PANO_LICENSE_THEME_VERSION: "1.0.0",
41
+ PANO_LICENSE_REQUIRED: true,
42
+ }).verifyLicenseFromEnv();
43
+
44
+ function setUp({ file, manifestFp, token }) {
45
+ writeFileSync(join(root, "client", "app.js"), file);
46
+ writeFileSync(join(root, ".pano-license.jwt"), token);
47
+ writeFileSync(join(root, "manifest.json"), JSON.stringify({ id: THEME_ID, fileFingerprint: manifestFp }));
48
+ }
49
+
50
+ const fingerprintWith = (file) => {
51
+ writeFileSync(join(root, "client", "app.js"), file);
52
+ return computeStableFileFingerprint(root, ["manifest.json", ".pano-license.jwt"]);
53
+ };
54
+
55
+ beforeAll(() => {
56
+ root = mkdtempSync(join(tmpdir(), "tc-license-"));
57
+ mkdirSync(join(root, "client"));
58
+ cwd = process.cwd();
59
+ process.chdir(root);
60
+ });
61
+
62
+ afterAll(() => {
63
+ process.chdir(cwd);
64
+ rmSync(root, { recursive: true, force: true });
65
+ });
66
+
67
+ describe("premium theme file fingerprint", () => {
68
+ test("without an fp claim the manifest value is compared (corruption check)", () => {
69
+ const fp = fingerprintWith("one");
70
+ setUp({ file: "one", manifestFp: fp, token: sign(claims()) });
71
+ expect(verify()).not.toBeNull();
72
+ });
73
+
74
+ test("the signed fp wins over the manifest", () => {
75
+ const fp = fingerprintWith("one");
76
+ setUp({ file: "one", manifestFp: "0".repeat(64), token: sign(claims({ fp })) });
77
+ expect(verify()).not.toBeNull();
78
+ });
79
+
80
+ test("an edited file with a re-stamped manifest fails against the signed fp", () => {
81
+ const fp = fingerprintWith("one");
82
+ const restamped = fingerprintWith("edited");
83
+ setUp({ file: "edited", manifestFp: restamped, token: sign(claims({ fp })) });
84
+ expect(() => verify()).toThrow("theme files have been modified");
85
+ });
86
+
87
+ test("a malformed fp claim fails", () => {
88
+ const fp = fingerprintWith("one");
89
+ setUp({ file: "one", manifestFp: fp, token: sign(claims({ fp: "nope" })) });
90
+ expect(() => verify()).toThrow("fp claim is malformed");
91
+ });
92
+ });
@@ -0,0 +1,65 @@
1
+ import { afterAll, beforeAll, describe, expect, mock, test } from "bun:test";
2
+ import { Window } from "happy-dom";
3
+
4
+ // The theme-settings iframe takes messages only from its parent window on its own origin, posts only to that
5
+ // origin, gives confirmations unguessable ids and injects only same-origin stylesheets.
6
+
7
+ const win = new Window({ url: "https://site.test/theme-settings" });
8
+ const saved = {};
9
+ const posted = [];
10
+
11
+ mock.module("svelte", () => ({ onMount: (fn) => fn(), onDestroy: () => {} }));
12
+ mock.module("@sveltejs/kit", () => ({ redirect: () => new Error("redirect") }));
13
+ mock.module("$app/env", () => ({ browser: true, dev: false }));
14
+ mock.module("$pano/lib/auth.util", () => ({ hasPermission: () => true, Permissions: {} }));
15
+
16
+ let logic;
17
+
18
+ beforeAll(async () => {
19
+ for (const key of ["window", "document", "ResizeObserver", "MessageEvent"]) saved[key] = globalThis[key];
20
+ globalThis.window = win;
21
+ globalThis.document = win.document;
22
+ globalThis.ResizeObserver = class { observe() {} disconnect() {} };
23
+ globalThis.MessageEvent = win.MessageEvent;
24
+ win.parent.postMessage = (data, target) => posted.push({ data, target });
25
+ logic = await import("../ui-logics/layout-logics/ThemeSettingsLayoutLogics.js");
26
+ logic.init();
27
+ });
28
+
29
+ afterAll(() => {
30
+ for (const [key, value] of Object.entries(saved)) globalThis[key] = value;
31
+ });
32
+
33
+ const send = (data, { origin = "https://site.test", source = win.parent } = {}) =>
34
+ win.dispatchEvent(new win.MessageEvent("message", { data, origin, source }));
35
+
36
+ describe("theme-settings iframe messages", () => {
37
+ test("posts go to the own origin, never '*'", () => {
38
+ logic.showSuccessToast("x");
39
+ expect(posted.length).toBeGreaterThan(0);
40
+ expect(posted.every((p) => p.target === "https://site.test")).toBe(true);
41
+ });
42
+
43
+ test("a confirm callback fires only for the parent on the own origin, with the unguessable id", () => {
44
+ let fired = 0;
45
+ posted.length = 0;
46
+ logic.showConfirm("reset?", () => fired++);
47
+ const id = posted.find((p) => p.data.type === "show-confirm").data.id;
48
+ expect(typeof id).toBe("string");
49
+ expect(id.length).toBeGreaterThanOrEqual(32);
50
+
51
+ send({ type: "confirm-callback", id }, { origin: "https://evil.test" });
52
+ send({ type: "confirm-callback", id }, { source: null });
53
+ send({ type: "confirm-callback", id: 1 });
54
+ expect(fired).toBe(0);
55
+
56
+ send({ type: "confirm-callback", id });
57
+ expect(fired).toBe(1);
58
+ });
59
+
60
+ test("only same-origin stylesheet links are injected", () => {
61
+ send({ type: "inject-css-all", css: "", links: ["https://evil.test/x.css", "/panel/_app/a.css", "javascript:alert(1)"] });
62
+ const hrefs = [...win.document.querySelectorAll('link[data-panel-injected="true"]')].map((l) => l.getAttribute("href"));
63
+ expect(hrefs).toEqual(["/panel/_app/a.css"]);
64
+ });
65
+ });
@@ -106,11 +106,11 @@
106
106
  <img src="/assets/img/logo.svg" width="20" height="20" alt="Pano" />
107
107
  </a>
108
108
  <small>
109
- {@html $_("footer.been-created-with", {
109
+ {@html sanitizeRichHtml($_("footer.been-created-with", {
110
110
  values: {
111
111
  pano: `<a href="${PANO_WEBSITE_URL}" class="rounded focus-ring" target="_blank" rel="noreferrer">Pano</a>`,
112
112
  },
113
- })}
113
+ }))}
114
114
  </small>
115
115
  </div>
116
116
  </div>
@@ -122,6 +122,7 @@
122
122
  <script>
123
123
  import { getContext } from "svelte";
124
124
  import { _ } from "svelte-i18n";
125
+ import { sanitizeRichHtml } from "$pano/lib/html.util.js";
125
126
  import copy from "copy-to-clipboard";
126
127
  import tooltip from "$pano/lib/tooltip.util";
127
128
  import { PANO_WEBSITE_URL } from "$pano/lib/variables";
@@ -1,5 +1,5 @@
1
1
  <svelte:head>
2
- {@html `<style>;</style>`.replace(";", styles)}
2
+ {@html styleTag(styles)}
3
3
  </svelte:head>
4
4
 
5
5
  <!-- Header -->
@@ -30,6 +30,7 @@
30
30
  <script>
31
31
  import { getContext } from "svelte";
32
32
  import { _ } from "svelte-i18n";
33
+ import { styleTag } from "$pano/lib/html.util.js";
33
34
 
34
35
  const session = getContext("session");
35
36
  const themeSettings = getContext("themeSettings");
@@ -15,6 +15,7 @@
15
15
  <script>
16
16
  import { getContext } from "svelte";
17
17
  import { _ } from "svelte-i18n";
18
+ import { sanitizeRichHtml } from "$pano/lib/html.util.js";
18
19
  import { route } from "$pano/registry/routes.js";
19
20
 
20
21
  import { stripIdentifierWhitespace } from "$pano/lib/loginInput.util.js";
@@ -97,11 +98,11 @@
97
98
  id="registerAcceptTerms"
98
99
  type="checkbox" />
99
100
  <label class="form-check-label" for="registerAcceptTerms">
100
- {@html $_("components.modals.register.inputs.agreement-text", {
101
+ {@html sanitizeRichHtml($_("components.modals.register.inputs.agreement-text", {
101
102
  values: {
102
103
  link: `<a class="rounded focus-ring" href="${route("/rules")}">${$_("components.modals.register.inputs.server-rules")}</a>`,
103
104
  },
104
- })}
105
+ }))}
105
106
  </label>
106
107
  </div>
107
108
  {/if}
@@ -0,0 +1,125 @@
1
+ import { sanitize } from "@jill64/universal-sanitizer";
2
+
3
+ /*
4
+ * Rich HTML that panel users write (post bodies, staff ticket replies, the register agreement, translation
5
+ * overrides) goes through sanitizeRichHtml before any {@html}. The allow-list covers what the panel editor
6
+ * (TipTap StarterKit + Image + TextStyleKit) writes, plus common formatting tags older content may hold.
7
+ * Scripts, event handlers, iframes, forms and javascript: links are removed.
8
+ *
9
+ * The server side (SSR) runs sanitize-html, the browser DOMPurify; both get the same lists.
10
+ */
11
+
12
+ // One comma-joined string, not an array of words: the engine's class scanner (scripts/build-tokens.js) would read
13
+ // "h1", "mark", "small" ... as Bootstrap class names and grow the fallback sheet.
14
+ const TAGS = (
15
+ "a,abbr,b,blockquote,br,caption,code,col,colgroup,del,div,em,figcaption,figure,h1,h2,h3,h4,h5,h6,hr,i,img,ins," +
16
+ "kbd,li,mark,ol,p,pre,s,small,span,strike,strong,sub,sup,table,tbody,td,tfoot,th,thead,tr,u,ul"
17
+ ).split(",");
18
+
19
+ const GLOBAL_ATTRS = ["class", "style", "title"];
20
+ const TAG_ATTRS = {
21
+ a: ["href", "target", "rel"],
22
+ img: ["src", "alt", "width", "height"],
23
+ td: ["colspan", "rowspan"],
24
+ th: ["colspan", "rowspan"],
25
+ ol: ["start"],
26
+ };
27
+
28
+ // Only plain values (no url(), no expressions); the same rules as panel-ui's html-sanitize.util.js.
29
+ const STYLE_VALUE = [/^[#a-z0-9\s.,%()-]+$/i];
30
+ const FONT_FAMILY = [/^[a-z0-9\s,'"-]+$/i];
31
+ const STYLES = {
32
+ ...Object.fromEntries(
33
+ ["color", "background-color", "font-size", "font-weight", "font-style", "line-height", "width", "height"].map(
34
+ (name) => [name, STYLE_VALUE],
35
+ ),
36
+ ),
37
+ "font-family": FONT_FAMILY,
38
+ "text-align": [/^(left|right|center|justify)$/],
39
+ "text-decoration": [/^[a-z\s-]+$/i],
40
+ };
41
+
42
+ const SANITIZE_HTML = {
43
+ allowedTags: TAGS,
44
+ allowedAttributes: {
45
+ "*": GLOBAL_ATTRS,
46
+ ...TAG_ATTRS,
47
+ },
48
+ allowedStyles: { "*": STYLES },
49
+ allowedSchemes: ["http", "https", "mailto"],
50
+ allowedSchemesByTag: { img: ["http", "https", "data"] },
51
+ allowProtocolRelative: true,
52
+ disallowedTagsMode: "discard",
53
+ };
54
+
55
+ const DOMPURIFY = {
56
+ ALLOWED_TAGS: TAGS,
57
+ ALLOWED_ATTR: [...new Set([...GLOBAL_ATTRS, ...Object.values(TAG_ATTRS).flat()])],
58
+ ALLOW_DATA_ATTR: false,
59
+ };
60
+
61
+ /**
62
+ * The style attribute with only the declarations STYLES allows (DOMPurify keeps style as is; sanitize-html filters
63
+ * it through allowedStyles). Exported for the test.
64
+ *
65
+ * @param {string} style
66
+ * @returns {string}
67
+ */
68
+ export function filterStyle(style) {
69
+ return String(style)
70
+ .split(";")
71
+ .map((part) => {
72
+ const at = part.indexOf(":");
73
+ if (at < 0) return null;
74
+ const name = part.slice(0, at).trim().toLowerCase();
75
+ const value = part.slice(at + 1).trim();
76
+ return STYLES[name]?.some((rule) => rule.test(value)) ? `${name}:${value}` : null;
77
+ })
78
+ .filter(Boolean)
79
+ .join(";");
80
+ }
81
+
82
+ // The hook only acts while sanitizeRichHtml runs, so other DOMPurify users of the same instance are not changed.
83
+ let active = false;
84
+ let hooked = false;
85
+
86
+ /** @param {any} purify */
87
+ function hook(purify) {
88
+ if (hooked || typeof purify?.addHook !== "function") return;
89
+ hooked = true;
90
+ purify.addHook("uponSanitizeAttribute", (_node, data) => {
91
+ if (!active || data.attrName !== "style") return;
92
+ data.attrValue = filterStyle(data.attrValue);
93
+ if (!data.attrValue) data.keepAttr = false;
94
+ });
95
+ }
96
+
97
+ /**
98
+ * Removes everything from panel-written HTML that could run script; keeps formatting, links and images.
99
+ * Not a string (null, undefined, a number) yields "" so a missing value renders as nothing.
100
+ *
101
+ * @param {unknown} html
102
+ * @returns {string}
103
+ */
104
+ export function sanitizeRichHtml(html) {
105
+ if (typeof html !== "string" || html === "") return "";
106
+
107
+ active = true;
108
+ try {
109
+ return sanitize(html, { sanitizeHtml: SANITIZE_HTML, dompurify: DOMPURIFY, hook });
110
+ } finally {
111
+ active = false;
112
+ }
113
+ }
114
+
115
+ /**
116
+ * A `<style>` element for {@html} holding [css] as is: a `</style` inside it cannot end the element early, and `$`
117
+ * patterns stay literal (no String.replace with a string argument).
118
+ *
119
+ * @param {unknown} css
120
+ * @returns {string}
121
+ */
122
+ export function styleTag(css) {
123
+ const text = typeof css === "string" ? css : "";
124
+ return "<style>" + text.replace(/<\/(style)/gi, "<\\/$1") + "</style>";
125
+ }
@@ -5,20 +5,24 @@ import { writable } from "svelte/store";
5
5
  import { hasPermission, Permissions } from "$pano/lib/auth.util";
6
6
  import { browser } from "$app/env";
7
7
 
8
+ // The settings page runs in an iframe of the panel, which Pano serves from the same origin. Messages go only to
9
+ // that origin and are taken only from the parent window on it.
10
+ const panelOrigin = () => window.location.origin;
11
+
8
12
  function postHeight() {
9
13
  const h = Math.max(
10
14
  document.documentElement.scrollHeight,
11
15
  document.body.scrollHeight
12
16
  );
13
- window.parent.postMessage({ type: "theme-iframe-height", height: h }, "*");
17
+ window.parent.postMessage({ type: "theme-iframe-height", height: h }, panelOrigin());
14
18
  }
15
19
 
16
20
  function postLoaded() {
17
- window.parent.postMessage({ type: "theme-settings-loaded" }, "*");
21
+ window.parent.postMessage({ type: "theme-settings-loaded" }, panelOrigin());
18
22
  }
19
23
 
20
24
  function postReady() {
21
- window.parent.postMessage({ type: "theme-settings-ready" }, "*");
25
+ window.parent.postMessage({ type: "theme-settings-ready" }, panelOrigin());
22
26
  }
23
27
 
24
28
  // The theme settings UI runs inside an iframe in the panel, so its toasts are posted to
@@ -27,7 +31,7 @@ function postReady() {
27
31
  // failure and has to fall back to a neutral toast. A panel build that predates the field
28
32
  // simply ignores it.
29
33
  export function showToast(text, params = {}, toastComponent, variant = null) {
30
- window.parent.postMessage({ type: "show-toast", text, params, toastComponent, variant }, "*");
34
+ window.parent.postMessage({ type: "show-toast", text, params, toastComponent, variant }, panelOrigin());
31
35
  }
32
36
 
33
37
  export function showSuccessToast(text, params = {}) {
@@ -39,12 +43,28 @@ export function showErrorToast(text, params = {}) {
39
43
  }
40
44
 
41
45
  const confirmCallbacks = new Map();
42
- let confirmIdCounter = 0;
46
+
47
+ /** A confirm id nobody can guess, so a message cannot fire a pending confirmation. */
48
+ function confirmId() {
49
+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();
50
+ const bytes = new Uint8Array(16);
51
+ globalThis.crypto.getRandomValues(bytes);
52
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
53
+ }
54
+
55
+ /** Only stylesheets of this origin are injected. */
56
+ function sameOriginHref(href) {
57
+ try {
58
+ return typeof href === "string" && new URL(href, window.location.href).origin === window.location.origin;
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
43
63
 
44
64
  export function showConfirm(title, onConfirm) {
45
- const id = ++confirmIdCounter;
65
+ const id = confirmId();
46
66
  confirmCallbacks.set(id, onConfirm);
47
- window.parent.postMessage({ type: "show-confirm", title, id }, "*");
67
+ window.parent.postMessage({ type: "show-confirm", title, id }, panelOrigin());
48
68
  }
49
69
 
50
70
  export async function processLoadServer(event) {
@@ -104,6 +124,8 @@ export function init() {
104
124
  const hidden = writable(true);
105
125
 
106
126
  const handleMessage = function (e) {
127
+ if (e.source !== window.parent || e.origin !== window.location.origin) return;
128
+
107
129
  if (e.data)
108
130
  console.log("Theme received message", e.data.type);
109
131
 
@@ -127,7 +149,8 @@ export function init() {
127
149
 
128
150
  // CSS inject-all message (both inline and links)
129
151
  if (e.data && e.data.type === "inject-css-all") {
130
- const { css, links } = e.data;
152
+ const { css } = e.data;
153
+ const links = Array.isArray(e.data.links) ? e.data.links.filter(sameOriginHref) : [];
131
154
  console.log("Received combined CSS. Links:", links?.length, "Inline CSS length:", css?.length);
132
155
 
133
156
  removeExistingStyles();
@@ -61,6 +61,7 @@
61
61
 
62
62
  <script>
63
63
  import { _ } from "svelte-i18n";
64
+ import { sanitizeRichHtml } from "$pano/lib/html.util.js";
64
65
 
65
66
  import { route } from "$pano/registry/routes.js";
66
67
 
@@ -215,7 +216,7 @@
215
216
  <form class="pano-login-view" on:submit|preventDefault={onVerifyLink}>
216
217
  <div class="vstack gap-3">
217
218
  <p class="text-center text-muted mb-0">
218
- {@html $_("components.modals.login.link-code.description")}
219
+ {@html sanitizeRichHtml($_("components.modals.login.link-code.description"))}
219
220
  </p>
220
221
 
221
222
  <ErrorAlert error={$error} />
@@ -14,7 +14,7 @@
14
14
 
15
15
  <meta content={themeSettings.themeColor || "dark"} name="x-theme" />
16
16
 
17
- {@html `<style>;</style>`.replace(";", styles)}
17
+ {@html styleTag(styles)}
18
18
  </svelte:head>
19
19
 
20
20
  <Hook name="theme:top" />
@@ -47,6 +47,7 @@
47
47
  <!-- Modals End -->
48
48
 
49
49
  <script>
50
+ import { styleTag } from "$pano/lib/html.util.js";
50
51
  import Main from "$pano/lib/components/Main.svelte";
51
52
  import NotificationContainer from "$pano/lib/components/NotificationContainer.svelte";
52
53
  import Hook from "$pano/lib/components/Hook.svelte";
@@ -112,7 +112,7 @@
112
112
  <div class="card">
113
113
  <div class="pano-post-detail-view__body card-body">
114
114
  <div class="card-text text-break word-break">
115
- {@html data.post.text}
115
+ {@html sanitizeRichHtml(data.post.text)}
116
116
  </div>
117
117
  </div>
118
118
  {#if !(data.post.thumbnailUrl && (typeof themeSettings.postCoverImageEnabled === "undefined" ? true : themeSettings.postCoverImageEnabled))}
@@ -192,6 +192,7 @@
192
192
  import { route } from "$pano/registry/routes.js";
193
193
  import { postsPath } from "$pano/lib/home.js";
194
194
  import tooltip from "$pano/lib/tooltip.util";
195
+ import { sanitizeRichHtml } from "$pano/lib/html.util.js";
195
196
 
196
197
  import Date from "$pano/lib/components/Date.svelte";
197
198
  import Hook from "$pano/lib/components/Hook.svelte";
@@ -103,7 +103,7 @@
103
103
  <div class="card">
104
104
  <div class="pano-preview-post-view__body card-body">
105
105
  <div class="card-text text-break word-break">
106
- {@html post.text}
106
+ {@html sanitizeRichHtml(post.text)}
107
107
  </div>
108
108
  </div>
109
109
  {#if !(post.thumbnailUrl && (typeof themeSettings.postCoverImageEnabled === "undefined" ? true : themeSettings.postCoverImageEnabled))}
@@ -141,6 +141,7 @@
141
141
  <script>
142
142
  import { _ } from "svelte-i18n";
143
143
  import tooltip from "$pano/lib/tooltip.util";
144
+ import { sanitizeRichHtml } from "$pano/lib/html.util.js";
144
145
 
145
146
  import Date from "$pano/lib/components/Date.svelte";
146
147
 
@@ -14,13 +14,14 @@
14
14
 
15
15
  <div class="card">
16
16
  <div class="pano-rules-view__body card-body">
17
- {@html data.registerAgreement}
17
+ {@html sanitizeRichHtml(data.registerAgreement)}
18
18
  </div>
19
19
  </div>
20
20
  </div>
21
21
 
22
22
  <script>
23
23
  import { _ } from "svelte-i18n";
24
+ import { sanitizeRichHtml } from "$pano/lib/html.util.js";
24
25
 
25
26
  export let data;
26
27
  </script>
@@ -73,7 +73,7 @@
73
73
  <div class="col vstack align-items-start">
74
74
  <div class="card rounded-5 text-bg-primary border-0 shadow-sm">
75
75
  <div class="pano-ticket-detail-view__body-2 card-body answer px-3 py-2">
76
- {@html message.message}
76
+ {@html sanitizeRichHtml(message.message)}
77
77
  </div>
78
78
  </div>
79
79
  <small class="text-body-secondary mt-1">
@@ -146,6 +146,7 @@
146
146
 
147
147
  import Date from "$pano/lib/components/Date.svelte";
148
148
  import tooltip from "$pano/lib/tooltip.util";
149
+ import { sanitizeRichHtml } from "$pano/lib/html.util.js";
149
150
 
150
151
  import TicketStatus, {
151
152
  TicketStatuses,
@@ -17,17 +17,17 @@
17
17
  <div class="card mt-3 mt-lg-0">
18
18
  <CardHeader>
19
19
  <div slot="left">
20
- {@html data.categoryUrl
20
+ {@html sanitizeRichHtml(data.categoryUrl
21
21
  ? $_("pages.category-tickets.title", {
22
22
  values: {
23
23
  categoryName: `<strong>"${
24
24
  data.category.title === "-"
25
25
  ? $_("pages.category-tickets.no-category")
26
- : data.category.title
26
+ : escapeHtml(data.category.title)
27
27
  }"</strong>`,
28
28
  },
29
29
  })
30
- : $_("pages.tickets.title")}
30
+ : $_("pages.tickets.title"))}
31
31
  </div>
32
32
  <div slot="right" class="btn-group">
33
33
  <a
@@ -72,6 +72,8 @@
72
72
 
73
73
  <script>
74
74
  import { _ } from "svelte-i18n";
75
+ import { escapeHtml } from "@panomc/sdk/core/js/html.util.js";
76
+ import { sanitizeRichHtml } from "$pano/lib/html.util.js";
75
77
 
76
78
  import { route } from "$pano/registry/routes.js";
77
79
 
@@ -162,7 +162,7 @@
162
162
  class:text-muted={detail || !post.thumbnailUrl}
163
163
  class:clamp-text={!detail}>
164
164
  {#if detail}
165
- {@html post.text}
165
+ {@html sanitizeRichHtml(post.text)}
166
166
  {:else}
167
167
  {truncate(post.text.replace(/<[^>]*>?/gm, ""), 80)}...
168
168
  {/if}
@@ -240,6 +240,7 @@
240
240
  import { postsPath } from "$pano/lib/home.js";
241
241
  import { truncate } from "$pano/lib/string.util";
242
242
  import tooltip from "$pano/lib/tooltip.util";
243
+ import { sanitizeRichHtml } from "$pano/lib/html.util.js";
243
244
 
244
245
  import Date from "$pano/lib/components/Date.svelte";
245
246