fix: harden v2 custom widgets and Workshop (#6480)

This commit is contained in:
Thomas authored and GitHub committed 2026-07-31 13:28:53 +02:00
1 parent e8a2c87c2d
commit 557ebe0a2f
138 files changed
+5151 -1976

No files matched your search

+20 -14
View File
@@ -9,25 +9,30 @@ if (typeof clientExport !== "string") throw new Error("Workshop client export is
await access(resolve("packages/workshop", clientExport));
const hook = await read("apps/workshop/pb_hooks/workshop.pb.js");
const hookUtils = await read("apps/workshop/pb_hooks/workshop-utils.js");
const schema = await read("packages/workshop/src/schema.ts");
const constantValue = (source, name) => {
const match = source.match(new RegExp(`(?:export )?const ${name} = ([\\d_]+)`));
if (!match?.[1]) throw new Error(`Workshop limit ${name} is missing or is not a numeric literal`);
return Number(match[1].replaceAll("_", ""));
};
if (constantValue(hookUtils, "MAX_CSS_LENGTH") !== constantValue(schema, "MAX_WORKSHOP_CSS_LENGTH")) {
throw new Error("PocketBase and shared Workshop CSS limits must match");
}
if (constantValue(hookUtils, "MAX_CONTENT_LENGTH") !== constantValue(schema, "MAX_WORKSHOP_CONTENT_LENGTH")) {
throw new Error("PocketBase and shared Workshop content limits must match");
}
if (!hook.includes("require(`${__hooks}/workshop-utils.js`)")) {
throw new Error("Workshop handlers must load shared helpers inside their isolated PocketBase contexts");
}
if (!hook.includes("onBootstrap") || !hook.includes("users.oauth2.providers = configured")) {
throw new Error("Workshop OAuth settings must be synchronized at every bootstrap");
}
if (hook.includes("validateAndNormalizeSubmission")) {
throw new Error("PocketBase must store Workshop submissions without interpreting their content");
}
for (const artifact of [
"apps/workshop/pb_hooks/widget-validator.js",
"apps/workshop/pb_hooks/widget-validator.bundle.cjs",
"packages/workshop/src/pocketbase-validator.ts",
"scripts/build-workshop-validator.mjs",
]) {
await access(resolve(artifact))
.then(() => {
throw new Error(`Workshop validator artifact must stay removed: ${artifact}`);
})
.catch((error) => {
if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
throw error;
});
}
if (hook.includes('findAllRecords("users")') || !hook.includes('findRecordsByFilter("users"')) {
throw new Error("Workshop report notifications must use a filtered, bounded administrator query");
}
@@ -36,11 +41,12 @@ const migration = await read("apps/workshop/pb_migrations/1784240000_workshop_wi
for (const required of [
"workshop_migration_state",
"addedUserFields",
"cloneRule(users.listRule)",
"CREATE TRIGGER submissions_revision_cas",
"NEW.expectedRevision != OLD.revision",
"state.rateLimits.enabled",
"users.passwordAuth = state.users.passwordAuth",
"users.oauth2 = state.users.oauth2",
"app.delete(users)",
]) {
if (!migration.includes(required)) throw new Error(`Workshop rollback is missing state restoration: ${required}`);
}
+63
View File
@@ -0,0 +1,63 @@
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const { deriveGithubIdentity } = require("../pb_hooks/workshop-utils.js");
const identity = deriveGithubIdentity(
{
name: " Octo Cat ",
username: "octocat",
avatarURL: "https://avatars.githubusercontent.com/u/1?v=4",
rawUser: {},
},
"record123456",
);
if (
identity.displayName !== "Octo Cat" ||
identity.githubUsername !== "octocat" ||
identity.githubProfileUrl !== "https://github.com/octocat" ||
identity.avatarUrl !== "https://avatars.githubusercontent.com/u/1?v=4"
) {
throw new Error(`Trusted GitHub identity was not normalized: ${JSON.stringify(identity)}`);
}
const rawFallback = deriveGithubIdentity(
{
name: "",
username: "",
avatarURL: "",
rawUser: {
name: "\nRaw User\u0000",
login: "raw-user",
avatar_url: "https://avatars.githubusercontent.com/u/2",
},
},
"record123456",
);
if (
rawFallback.displayName !== "Raw User" ||
rawFallback.githubUsername !== "raw-user" ||
rawFallback.githubProfileUrl !== "https://github.com/raw-user"
) {
throw new Error(`Raw GitHub identity fallback was not normalized: ${JSON.stringify(rawFallback)}`);
}
const rejected = deriveGithubIdentity(
{
name: "\n",
username: "not/a/github-user",
avatarURL: "javascript:alert(1)",
rawUser: {},
},
"record123456",
);
if (
rejected.displayName !== "GitHub user record12" ||
rejected.githubUsername !== "" ||
rejected.githubProfileUrl !== "" ||
rejected.avatarUrl !== ""
) {
throw new Error(`Invalid provider identity fields were retained: ${JSON.stringify(rejected)}`);
}
console.log("Workshop OAuth identity normalization passed");
+12 -19
View File
@@ -50,7 +50,7 @@ class Record {
const original = {
passwordAuth: { enabled: true, identityFields: ["email"] },
oauth2: { enabled: true, providers: [{ name: "original", clientId: "before" }] },
oauth2: { enabled: true, providers: [{ name: "original", clientId: "before", clientSecret: "before-secret" }] },
rules: {
listRule: "original-list",
viewRule: "original-view",
@@ -58,13 +58,11 @@ const original = {
updateRule: "original-update",
deleteRule: "original-delete",
},
rateLimits: { enabled: false, rules: [{ label: "original", audience: "", duration: 1, maxRequests: 1 }] },
};
const users = new Collection({ type: "auth", name: "users", fields: [{ type: "text", name: "existing" }] });
users.passwordAuth = structuredClone(original.passwordAuth);
users.oauth2 = structuredClone(original.oauth2);
Object.assign(users, original.rules);
const settings = { rateLimits: structuredClone(original.rateLimits) };
const collections = new Map([[users.id, users]]);
const records = new Map();
const rawQueries = [];
@@ -99,9 +97,6 @@ const app = {
collections.delete(collection.id);
records.delete(collection.id);
},
settings() {
return settings;
},
};
let migration;
@@ -122,7 +117,7 @@ vm.runInNewContext(source, sandbox);
if (!migration) throw new Error("Workshop migration did not register");
migration.up(app);
if (!collections.has("workshop_migration_state") || settings.rateLimits.enabled !== true) {
if (!collections.has("workshop_migration_state")) {
throw new Error("Workshop migration did not capture state before applying changes");
}
if (
@@ -145,8 +140,6 @@ for (const [name, value] of Object.entries(original.rules)) {
}
if (users.fields.values.map((field) => field.name).join(",") !== "existing")
throw new Error("Workshop user fields were not removed on rollback");
if (JSON.stringify(settings.rateLimits) !== JSON.stringify(original.rateLimits))
throw new Error("Rate limits were not restored");
for (const name of ["workshop_migration_state", "workshop_listings", "reports", "comments", "votes", "submissions"]) {
if (collections.has(name)) throw new Error(`Rollback left collection ${name}`);
}
@@ -154,20 +147,20 @@ for (const name of ["workshop_migration_state", "workshop_listings", "reports",
collections.clear();
records.clear();
rawQueries.length = 0;
settings.rateLimits = structuredClone(original.rateLimits);
migration.up(app);
const bootstrappedUsers = collections.get("users");
if (!bootstrappedUsers) throw new Error("Fresh migration did not create the users collection");
if (!collections.has("users")) throw new Error("Fresh migration did not create the users collection");
migration.down(app);
if (collections.get("users") !== bootstrappedUsers) {
throw new Error("Fresh rollback removed the users collection required by the bootstrap hook");
}
for (const name of ["workshop_migration_state", "workshop_listings", "reports", "comments", "votes", "submissions"]) {
for (const name of [
"users",
"workshop_migration_state",
"workshop_listings",
"reports",
"comments",
"votes",
"submissions",
]) {
if (collections.has(name)) throw new Error(`Fresh rollback left collection ${name}`);
}
if (JSON.stringify(settings.rateLimits) !== JSON.stringify(original.rateLimits)) {
throw new Error("Fresh rollback did not restore rate limits");
}
console.log("Workshop migration up/down restoration passed");
+106 -35
View File
@@ -77,6 +77,55 @@ await expectStatus(
{ method: "PATCH", headers: authorSession.headers, body: JSON.stringify({ isAdmin: true }) },
404,
);
for (const [field, value] of [
["displayName", "Homarr Team"],
["avatarUrl", "https://example.invalid/forged-avatar.png"],
["githubUsername", "homarr-labs"],
["githubProfileUrl", "https://github.com/homarr-labs"],
]) {
await expectStatus(
`/api/collections/users/records/${author.id}`,
{ method: "PATCH", headers: authorSession.headers, body: JSON.stringify({ [field]: value }) },
404,
);
}
const forgedAvatar = new FormData();
forgedAvatar.set(
"avatar",
new Blob(
[
Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
"base64",
),
],
{ type: "image/png" },
),
"forged-avatar.png",
);
const avatarResponse = await fetch(`${baseUrl}/api/collections/users/records/${author.id}`, {
method: "PATCH",
headers: authorSession.headers,
body: forgedAvatar,
});
const avatarResponseBody = await avatarResponse.json().catch(() => null);
if (avatarResponse.status !== 400 || !JSON.stringify(avatarResponseBody).includes("managed by GitHub OAuth")) {
throw new Error(
`Workshop user avatar upload bypassed the OAuth identity hook: ${avatarResponse.status} ${JSON.stringify(avatarResponseBody)}`,
);
}
const unchangedAuthor = await request(`/api/collections/users/records/${author.id}`, {
headers: authorSession.headers,
});
if (
unchangedAuthor.displayName !== "Widget Author" ||
unchangedAuthor.avatar ||
unchangedAuthor.avatarUrl ||
unchangedAuthor.githubUsername ||
unchangedAuthor.githubProfileUrl
) {
throw new Error("Workshop users can forge OAuth provider identity fields");
}
const visitorPassword = "WorkshopVisitor123!";
const visitor = await createUser("widget-visitor@example.invalid", "Widget Visitor", visitorPassword);
@@ -105,7 +154,7 @@ const submission = await request("/api/collections/submissions/records", {
type: "customWidget",
title: "Workshop runtime probe",
description: "PocketBase integration test",
widgetSchema: "homarr-custom-css-v1",
widgetSchema: widget.$schema,
content: JSON.stringify(widget),
author: author.id,
revision: 999,
@@ -121,38 +170,8 @@ if (
submission.changelog !== "" ||
submission.outdated !== false
) {
throw new Error("Submission publication was not validated and normalized server-side");
throw new Error("Submission publication metadata was not initialized server-side");
}
await expectStatus(
"/api/collections/submissions/records",
{
method: "POST",
headers: visitorSession.headers,
body: JSON.stringify({
type: "customCss",
title: "Oversized stylesheet",
content: "x".repeat(16_385),
widgetSchema: "homarr-custom-widget-v2",
author: visitor.id,
}),
},
400,
);
await expectStatus(
"/api/collections/submissions/records",
{
method: "POST",
headers: visitorSession.headers,
body: JSON.stringify({
type: "customWidget",
title: "Invalid widget payload",
content: ".dashboard { color: red; }",
widgetSchema: "homarr-custom-widget-v2",
author: visitor.id,
}),
},
400,
);
const ownerVotes = await request("/api/collections/votes/records", { headers: authorSession.headers });
if (
ownerVotes.items.length !== 1 ||
@@ -295,7 +314,7 @@ const report = await request("/api/collections/reports/records", {
await expectStatus(`/api/collections/reports/records/${report.id}`, { headers: visitorSession.headers }, 404);
await expectStatus("/api/collections/reports/records", { headers: visitorSession.headers }, 200);
const publicReports = await request("/api/collections/reports/records", { headers: visitorSession.headers });
if (publicReports.items.length !== 0) throw new Error("Report details must remain private to Workshop administrators");
if (publicReports.items.length !== 0) throw new Error("Report details must remain private to Workshop moderators");
await expectStatus(
`/api/collections/reports/records/${report.id}`,
{ method: "DELETE", headers: visitorSession.headers },
@@ -317,14 +336,45 @@ await expectStatus(
const reports = await request("/api/collections/reports/records", { headers: authorSession.headers });
if (reports.items.length !== 1 || reports.items[0].reporter !== visitor.id || reports.items[0].status !== "open") {
throw new Error("Workshop administrators must be able to review reports");
throw new Error("Workshop moderators must be able to review reports");
}
await expectStatus(
`/api/collections/reports/records/${report.id}`,
{
method: "PATCH",
headers: authorSession.headers,
body: JSON.stringify({ category: "spam", explanation: "Moderator-authored replacement" }),
},
404,
);
const dismissedReport = await request(`/api/collections/reports/records/${report.id}`, {
method: "PATCH",
headers: authorSession.headers,
body: JSON.stringify({ status: "dismissed" }),
});
if (dismissedReport.status !== "dismissed") throw new Error("Workshop administrators must be able to dismiss reports");
if (dismissedReport.status !== "dismissed") throw new Error("Workshop moderators must be able to dismiss reports");
const reopenedReport = await request("/api/collections/reports/records", {
method: "POST",
headers: visitorSession.headers,
body: JSON.stringify({
submission: submission.id,
reporter: visitor.id,
category: "malicious",
explanation: "The later submission revision now needs another review",
status: "dismissed",
}),
});
if (reopenedReport.status !== "open" || reopenedReport.id === report.id) {
throw new Error("A dismissed Workshop report must be replaceable with a fresh open report");
}
const reopenedReports = await request("/api/collections/reports/records", { headers: authorSession.headers });
if (
reopenedReports.items.length !== 1 ||
reopenedReports.items[0].id !== reopenedReport.id ||
reopenedReports.items[0].status !== "open"
) {
throw new Error("Re-reporting must replace only the reporter's dismissed report");
}
const visitorSubmission = await request("/api/collections/submissions/records", {
method: "POST",
@@ -340,6 +390,27 @@ const visitorSubmission = await request("/api/collections/submissions/records",
outdated: false,
}),
});
await expectStatus(
`/api/collections/submissions/records/${visitorSubmission.id}`,
{
method: "PATCH",
headers: authorSession.headers,
body: JSON.stringify({
title: "Moderator-authored replacement",
content: JSON.stringify({ ...widget, name: "Moderator-authored replacement" }),
expectedRevision: 1,
}),
},
404,
);
const moderatedStatus = await request(`/api/collections/submissions/records/${visitorSubmission.id}`, {
method: "PATCH",
headers: authorSession.headers,
body: JSON.stringify({ outdated: true, expectedRevision: 1 }),
});
if (!moderatedStatus.outdated || moderatedStatus.revision !== 2) {
throw new Error("Workshop moderators must be limited to CAS-protected submission status changes");
}
await expectStatus(
`/api/collections/submissions/records/${visitorSubmission.id}`,
{ method: "DELETE", headers: authorSession.headers },