fix: harden v2 custom widgets and Workshop (#6480)
This commit is contained in:
1 parent
e8a2c87c2d
commit
557ebe0a2f
138 files changed
+5151
-1976
No files matched your search
@@ -26,7 +26,7 @@
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 36px; color: #18181b; font-size: 15px; line-height: 1.65">
|
||||
<p style="margin: 0 0 18px">A Workshop administrator removed your submission:</p>
|
||||
<p style="margin: 0 0 18px">A Workshop moderator removed your submission:</p>
|
||||
<div style="margin: 0 0 24px; padding: 16px 18px; border-left: 3px solid #dc2626; background: #fef2f2">
|
||||
<strong>{{submissionTitle}}</strong>
|
||||
</div>
|
||||
|
||||
@@ -1,56 +1,46 @@
|
||||
const CUSTOM_WIDGET_SCHEMA = "homarr-custom-widget-v2";
|
||||
const CUSTOM_CSS_SCHEMA = "homarr-custom-css-v1";
|
||||
const MAX_CSS_LENGTH = 16_384;
|
||||
const MAX_CONTENT_LENGTH = 1_000_000;
|
||||
const GITHUB_USERNAME_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/;
|
||||
|
||||
const rejectRequest = (message) => {
|
||||
throw new BadRequestError(message);
|
||||
};
|
||||
|
||||
const validateWidgetManifest = (content) => {
|
||||
let widget;
|
||||
try {
|
||||
widget = JSON.parse(content);
|
||||
} catch {
|
||||
rejectRequest("Widget content must be valid JSON");
|
||||
const normalizedIdentityText = (...values) => {
|
||||
for (const value of values) {
|
||||
if (typeof value !== "string") continue;
|
||||
const normalized = [...value]
|
||||
.filter((character) => {
|
||||
const code = character.codePointAt(0) || 0;
|
||||
return code > 31 && code !== 127;
|
||||
})
|
||||
.join("")
|
||||
.trim();
|
||||
if (normalized) return normalized;
|
||||
}
|
||||
if (!widget || Array.isArray(widget) || typeof widget !== "object") rejectRequest("Widget must be a JSON object");
|
||||
if (widget.$schema !== CUSTOM_WIDGET_SCHEMA) rejectRequest("Widget schema is not supported");
|
||||
if (typeof widget.name !== "string" || !widget.name.trim() || widget.name.length > 100)
|
||||
rejectRequest("Widget name is invalid");
|
||||
if (!widget.sources || Array.isArray(widget.sources) || typeof widget.sources !== "object" || !widget.sources.default)
|
||||
rejectRequest("Widget must define a default source");
|
||||
if (Object.keys(widget.sources).length > 8) rejectRequest("Widget has too many sources");
|
||||
for (const source of Object.values(widget.sources)) {
|
||||
if (!source || Array.isArray(source) || typeof source !== "object") rejectRequest("Widget source is invalid");
|
||||
if (typeof source.baseUrl !== "string" || !/^https?:\/\//.test(source.baseUrl))
|
||||
rejectRequest("Widget source URL is invalid");
|
||||
if (!["public", "private", "loopback"].includes(source.networkScope))
|
||||
rejectRequest("Widget source network scope is invalid");
|
||||
}
|
||||
if (!widget.requests || Array.isArray(widget.requests) || typeof widget.requests !== "object")
|
||||
rejectRequest("Widget requests are invalid");
|
||||
if (!widget.options || Array.isArray(widget.options) || typeof widget.options !== "object")
|
||||
rejectRequest("Widget options are invalid");
|
||||
if (typeof widget.template !== "string" || !widget.template.trim()) rejectRequest("Widget template is invalid");
|
||||
return JSON.stringify(widget);
|
||||
return "";
|
||||
};
|
||||
|
||||
const validateAndNormalizeSubmission = (record) => {
|
||||
const type = record.getString("type");
|
||||
const content = record.getString("content");
|
||||
if (!content || content.length > MAX_CONTENT_LENGTH) rejectRequest("Submission content is invalid");
|
||||
record.set("title", record.getString("title").trim());
|
||||
record.set("description", record.getString("description").trim());
|
||||
record.set("changelog", record.getString("changelog").trim());
|
||||
if (type === "customCss") {
|
||||
if (!content.trim() || content.length > MAX_CSS_LENGTH) rejectRequest("Custom CSS is empty or too large");
|
||||
record.set("widgetSchema", CUSTOM_CSS_SCHEMA);
|
||||
return;
|
||||
}
|
||||
if (type !== "customWidget") rejectRequest("Submission type is invalid");
|
||||
record.set("content", validateWidgetManifest(content));
|
||||
record.set("widgetSchema", CUSTOM_WIDGET_SCHEMA);
|
||||
const deriveGithubIdentity = (oauthUser, recordId) => {
|
||||
const rawUser = oauthUser && typeof oauthUser.rawUser === "object" ? oauthUser.rawUser : {};
|
||||
const candidateUsername = normalizedIdentityText(oauthUser && oauthUser.username, rawUser.login);
|
||||
const githubUsername =
|
||||
GITHUB_USERNAME_PATTERN.test(candidateUsername) && !candidateUsername.includes("--") ? candidateUsername : "";
|
||||
const displayName =
|
||||
normalizedIdentityText(oauthUser && oauthUser.name, rawUser.name, githubUsername, rawUser.login).slice(0, 100) ||
|
||||
`GitHub user ${String(recordId || "").slice(0, 8)}`;
|
||||
const candidateAvatarUrl = normalizedIdentityText(
|
||||
oauthUser && oauthUser.avatarURL,
|
||||
oauthUser && oauthUser.avatarUrl,
|
||||
rawUser.avatar_url,
|
||||
);
|
||||
const avatarUrl =
|
||||
candidateAvatarUrl.length <= 2_048 && /^https:\/\/[^"'\\\s]+$/i.test(candidateAvatarUrl) ? candidateAvatarUrl : "";
|
||||
|
||||
return {
|
||||
displayName,
|
||||
avatarUrl,
|
||||
githubUsername,
|
||||
githubProfileUrl: githubUsername ? `https://github.com/${githubUsername}` : "",
|
||||
};
|
||||
};
|
||||
|
||||
const escapeHtml = (value) =>
|
||||
@@ -80,9 +70,9 @@ const sendEmail = (app, recipientEmail, subject, text, html) => {
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
deriveGithubIdentity,
|
||||
emailTemplate,
|
||||
escapeHtml,
|
||||
rejectRequest,
|
||||
sendEmail,
|
||||
validateAndNormalizeSubmission,
|
||||
};
|
||||
@@ -1,19 +1,64 @@
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
onBootstrap((event) => {
|
||||
event.next();
|
||||
const users = event.app.findCollectionByNameOrId("users");
|
||||
const clientId = String($os.getenv("GITHUB_CLIENT_ID") || "").trim();
|
||||
const clientSecret = String($os.getenv("GITHUB_CLIENT_SECRET") || "").trim();
|
||||
if (Boolean(clientId) !== Boolean(clientSecret)) {
|
||||
console.log(JSON.stringify({ event: "workshop_oauth_configuration_rejected", reason: "partial_credentials" }));
|
||||
throw new Error("GitHub OAuth requires both GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET");
|
||||
}
|
||||
const configured = Boolean(clientId && clientSecret);
|
||||
event.next();
|
||||
const users = event.app.findCollectionByNameOrId("users");
|
||||
users.oauth2.enabled = configured;
|
||||
users.oauth2.providers = configured ? [{ name: "github", clientId, clientSecret }] : [];
|
||||
event.app.save(users);
|
||||
console.log(JSON.stringify({ event: "workshop_oauth_synchronized", enabled: configured }));
|
||||
});
|
||||
|
||||
onRecordAuthWithOAuth2Request((event) => {
|
||||
if (event.providerName !== "github" || !event.oauth2User) {
|
||||
event.next();
|
||||
return;
|
||||
}
|
||||
|
||||
const { deriveGithubIdentity } = require(`${__hooks}/workshop-utils.js`);
|
||||
const identity = deriveGithubIdentity(event.oauth2User, event.record ? event.record.id : event.oauth2User.id);
|
||||
if (event.record) {
|
||||
event.record.set("displayName", identity.displayName);
|
||||
event.record.set("avatar", "");
|
||||
event.record.set("avatarUrl", identity.avatarUrl);
|
||||
event.record.set("githubUsername", identity.githubUsername);
|
||||
event.record.set("githubProfileUrl", identity.githubProfileUrl);
|
||||
event.app.save(event.record);
|
||||
} else {
|
||||
event.createData.displayName = identity.displayName;
|
||||
event.createData.avatarUrl = identity.avatarUrl;
|
||||
event.createData.githubUsername = identity.githubUsername;
|
||||
event.createData.githubProfileUrl = identity.githubProfileUrl;
|
||||
}
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
event: "workshop_oauth_identity_synchronized",
|
||||
provider: "github",
|
||||
recordId: event.record ? event.record.id : null,
|
||||
newRecord: !event.record,
|
||||
}),
|
||||
);
|
||||
event.next();
|
||||
}, "users");
|
||||
|
||||
onRecordUpdateRequest((event) => {
|
||||
const { rejectRequest } = require(`${__hooks}/workshop-utils.js`);
|
||||
const originalAvatar = event.record.original().getString("avatar");
|
||||
const pendingAvatarFiles = event.record.getUnsavedFiles("avatar");
|
||||
if (event.record.getString("avatar") !== originalAvatar || pendingAvatarFiles.length > 0) {
|
||||
rejectRequest("Workshop avatars are managed by GitHub OAuth");
|
||||
}
|
||||
event.next();
|
||||
}, "users");
|
||||
|
||||
onRecordCreateRequest((event) => {
|
||||
const { validateAndNormalizeSubmission } = require(`${__hooks}/workshop-utils.js`);
|
||||
validateAndNormalizeSubmission(event.record);
|
||||
event.record.set("revision", 1);
|
||||
event.record.set("expectedRevision", 0);
|
||||
event.record.set("changelog", "");
|
||||
@@ -22,20 +67,42 @@ onRecordCreateRequest((event) => {
|
||||
}, "submissions");
|
||||
|
||||
onRecordUpdateRequest((event) => {
|
||||
const { rejectRequest, validateAndNormalizeSubmission } = require(`${__hooks}/workshop-utils.js`);
|
||||
const { rejectRequest } = require(`${__hooks}/workshop-utils.js`);
|
||||
const original = event.record.original();
|
||||
const currentRevision = original.getInt("revision");
|
||||
const expectedRevision = event.record.getInt("expectedRevision");
|
||||
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 1) {
|
||||
rejectRequest("Submission changed since it was read");
|
||||
}
|
||||
validateAndNormalizeSubmission(event.record);
|
||||
event.record.set("expectedRevision", expectedRevision);
|
||||
event.record.set("revision", currentRevision + 1);
|
||||
event.next();
|
||||
}, "submissions");
|
||||
|
||||
onRecordCreateRequest((event) => {
|
||||
const auth = event.requestInfo().auth;
|
||||
const reporter = event.record.getString("reporter");
|
||||
const submission = event.record.getString("submission");
|
||||
if (auth && auth.id === reporter) {
|
||||
const dismissed = event.app.findRecordsByFilter(
|
||||
"reports",
|
||||
"reporter = {:reporter} && submission = {:submission} && status = 'dismissed'",
|
||||
"",
|
||||
1,
|
||||
0,
|
||||
{ reporter, submission },
|
||||
);
|
||||
if (dismissed.length > 0) {
|
||||
event.app.delete(dismissed[0]);
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
event: "workshop_report_reopened",
|
||||
reporterId: reporter,
|
||||
submissionId: submission,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
event.record.set("status", "open");
|
||||
event.next();
|
||||
}, "reports");
|
||||
@@ -62,6 +129,7 @@ onRecordAfterCreateSuccess((event) => {
|
||||
const commenter = event.app.findRecordById("users", event.record.get("author"));
|
||||
const recipientEmail = recipient.email();
|
||||
const publicOrigin = $os.getenv("WORKSHOP_PUBLIC_ORIGIN").replace(/\/$/, "");
|
||||
const publicWorkshopUrl = ($os.getenv("WORKSHOP_WEB_URL") || `${publicOrigin}/workshop`).replace(/\/$/, "");
|
||||
|
||||
if (!recipientEmail || recipient.id === commenter.id || !publicOrigin) {
|
||||
event.next();
|
||||
@@ -71,7 +139,7 @@ onRecordAfterCreateSuccess((event) => {
|
||||
const commenterName = commenter.getString("displayName") || "A community member";
|
||||
const submissionTitle = submission.getString("title");
|
||||
const rawExcerpt = event.record.getString("content").slice(0, 280);
|
||||
const submissionUrl = `${publicOrigin}/workshop/${submission.id}/`;
|
||||
const submissionUrl = `${publicWorkshopUrl}/${submission.id}/`;
|
||||
const template = emailTemplate("comment-email.html")
|
||||
.replaceAll("{{commenterName}}", escapeHtml(commenterName))
|
||||
.replaceAll("{{submissionTitle}}", escapeHtml(submissionTitle))
|
||||
@@ -97,6 +165,7 @@ onRecordAfterCreateSuccess((event) => {
|
||||
const submission = event.app.findRecordById("submissions", event.record.get("submission"));
|
||||
const reporter = event.app.findRecordById("users", event.record.get("reporter"));
|
||||
const publicOrigin = $os.getenv("WORKSHOP_PUBLIC_ORIGIN").replace(/\/$/, "");
|
||||
const publicWorkshopUrl = ($os.getenv("WORKSHOP_WEB_URL") || `${publicOrigin}/workshop`).replace(/\/$/, "");
|
||||
const admins = event.app.findRecordsByFilter("users", "isAdmin = true && email != ''", "", 100, 0);
|
||||
|
||||
if (!publicOrigin || admins.length === 0) {
|
||||
@@ -108,8 +177,8 @@ onRecordAfterCreateSuccess((event) => {
|
||||
const submissionTitle = submission.getString("title");
|
||||
const category = event.record.getString("category");
|
||||
const explanation = event.record.getString("explanation");
|
||||
const adminUrl = `${publicOrigin}/workshop/admin`;
|
||||
const submissionUrl = `${publicOrigin}/workshop/${submission.id}/`;
|
||||
const adminUrl = `${publicWorkshopUrl}/admin`;
|
||||
const submissionUrl = `${publicWorkshopUrl}/${submission.id}/`;
|
||||
const template = emailTemplate("report-email.html")
|
||||
.replaceAll("{{reporterName}}", escapeHtml(reporterName))
|
||||
.replaceAll("{{submissionTitle}}", escapeHtml(submissionTitle))
|
||||
@@ -155,12 +224,15 @@ onRecordDeleteRequest((event) => {
|
||||
if (!recipientEmail) return;
|
||||
|
||||
const publicOrigin = $os.getenv("WORKSHOP_PUBLIC_ORIGIN").replace(/\/$/, "");
|
||||
const workshopUrl = publicOrigin ? `${publicOrigin}/workshop/` : "";
|
||||
const workshopUrl = ($os.getenv("WORKSHOP_WEB_URL") || (publicOrigin ? `${publicOrigin}/workshop` : "")).replace(
|
||||
/\/?$/,
|
||||
"/",
|
||||
);
|
||||
const template = emailTemplate("submission-deleted-email.html").replaceAll(
|
||||
"{{submissionTitle}}",
|
||||
escapeHtml(submissionTitle),
|
||||
);
|
||||
const text = `A Workshop administrator removed your submission “${submissionTitle}”.${
|
||||
const text = `A Workshop moderator removed your submission “${submissionTitle}”.${
|
||||
workshopUrl ? `\n\nReturn to Workshop: ${workshopUrl}` : ""
|
||||
}`;
|
||||
|
||||
|
||||
Reference in new issue
Block a user