fix(workshop): simplify GitHub identities
This commit is contained in:
19 files changed
+114
-362
No files matched your search
@@ -91,7 +91,10 @@ GITHUB_CLIENT_SECRET=...
|
||||
OAuth settings synchronize on every PocketBase startup. Restart after rotation. A production deployment must never
|
||||
supply only one credential. `PB_ALLOWED_ORIGINS=*` is appropriate for the central community because arbitrary
|
||||
self-hosted Homarr origins must open its OAuth popup; a restricted list must include every allowed browser origin.
|
||||
Workshop uses the OAuth provider username as the public display name instead of the profile's full name.
|
||||
Workshop stores only the OAuth provider username in `users.githubUsername`; users cannot rename it. PocketBase maps
|
||||
**OAuth2 username** to `githubUsername` and leaves the OAuth2 id, full name, and avatar mappings empty. GitHub profiles
|
||||
and avatars are derived from `https://github.com/<username>` and `https://github.com/<username>.png`, so no duplicate
|
||||
profile metadata or avatar file is stored.
|
||||
|
||||
## Promote a Workshop moderator
|
||||
|
||||
|
||||
@@ -1,48 +1,7 @@
|
||||
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 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;
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
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(githubUsername, rawUser.login, oauthUser && oauthUser.name, rawUser.name).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) =>
|
||||
String(value)
|
||||
.replaceAll("&", "&")
|
||||
@@ -70,7 +29,6 @@ const sendEmail = (app, recipientEmail, subject, text, html) => {
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
deriveGithubIdentity,
|
||||
emailTemplate,
|
||||
escapeHtml,
|
||||
rejectRequest,
|
||||
|
||||
@@ -11,54 +11,12 @@ onBootstrap((event) => {
|
||||
event.next();
|
||||
const users = event.app.findCollectionByNameOrId("users");
|
||||
users.oauth2.enabled = configured;
|
||||
users.oauth2.mappedFields = { id: "", name: "", username: "displayName", avatarURL: "avatarUrl" };
|
||||
users.oauth2.mappedFields = { id: "", name: "", username: "githubUsername", avatarURL: "" };
|
||||
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) => {
|
||||
event.record.set("revision", 1);
|
||||
event.record.set("expectedRevision", 0);
|
||||
@@ -137,7 +95,7 @@ onRecordAfterCreateSuccess((event) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const commenterName = commenter.getString("displayName") || "A community member";
|
||||
const commenterName = commenter.getString("githubUsername") || "A community member";
|
||||
const submissionTitle = submission.getString("title");
|
||||
const rawExcerpt = event.record.getString("content").slice(0, 280);
|
||||
const submissionUrl = `${publicWorkshopUrl}/${submission.id}/`;
|
||||
@@ -174,7 +132,7 @@ onRecordAfterCreateSuccess((event) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const reporterName = reporter.getString("displayName") || "A community member";
|
||||
const reporterName = reporter.getString("githubUsername") || "A community member";
|
||||
const submissionTitle = submission.getString("title");
|
||||
const category = event.record.getString("category");
|
||||
const explanation = event.record.getString("explanation");
|
||||
|
||||
@@ -5,10 +5,7 @@ const cloneRule = (value) => (value === null ? null : String(value));
|
||||
const adminRule = "@request.auth.isAdmin = true";
|
||||
const identityFieldsUnchanged = [
|
||||
"@request.body.email:changed = false",
|
||||
"@request.body.displayName:changed = false",
|
||||
"@request.body.avatarUrl:changed = false",
|
||||
"@request.body.githubUsername:changed = false",
|
||||
"@request.body.githubProfileUrl:changed = false",
|
||||
].join(" && ");
|
||||
const immutableSubmissionFields = [
|
||||
"@request.body.author:changed = false",
|
||||
@@ -67,18 +64,7 @@ migrate(
|
||||
};
|
||||
|
||||
users.passwordAuth = { enabled: false };
|
||||
addUserField(new TextField({ name: "displayName", required: true, min: 1, max: 100 }));
|
||||
addUserField(new URLField({ name: "avatarUrl" }));
|
||||
addUserField(
|
||||
new FileField({
|
||||
name: "avatar",
|
||||
maxSelect: 1,
|
||||
maxSize: 2_097_152,
|
||||
mimeTypes: ["image/png", "image/jpeg", "image/webp"],
|
||||
}),
|
||||
);
|
||||
addUserField(new TextField({ name: "githubUsername", max: 100 }));
|
||||
addUserField(new URLField({ name: "githubProfileUrl" }));
|
||||
addUserField(new TextField({ name: "githubUsername", required: true, min: 1, max: 39 }));
|
||||
addUserField(new BoolField({ name: "isAdmin" }));
|
||||
|
||||
users.listRule = "";
|
||||
@@ -250,8 +236,7 @@ migrate(
|
||||
viewRule: "",
|
||||
viewQuery: `
|
||||
SELECT s.id, s.type, s.title, s.description, s.widgetSchema, s.screenshots, s.author,
|
||||
u.displayName AS authorName, u.avatar AS authorAvatar, u.avatarUrl AS authorAvatarUrl,
|
||||
u.githubUsername AS authorGithubUsername, u.githubProfileUrl AS authorGithubProfileUrl,
|
||||
u.githubUsername AS authorGithubUsername,
|
||||
s.revision, s.changelog, s.outdated, s.created, s.updated,
|
||||
COALESCE((SELECT COUNT(*) FROM votes v WHERE v.submission = s.id AND v.value = 1), 0) AS upvotes,
|
||||
COALESCE((SELECT COUNT(*) FROM votes v WHERE v.submission = s.id AND v.value = -1), 0) AS downvotes,
|
||||
|
||||
@@ -6,7 +6,6 @@ WORKSHOP_TEST_PROJECT="homarr-workshop-test-$$"
|
||||
|
||||
node apps/workshop/tests/workshop-contracts.mjs
|
||||
node apps/workshop/tests/workshop-migration.mjs
|
||||
node apps/workshop/tests/workshop-identity.mjs
|
||||
|
||||
cleanup() {
|
||||
PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
|
||||
|
||||
@@ -24,9 +24,10 @@ if (!users.oauth2?.enabled || github?.clientId !== expectedClientId) {
|
||||
throw new Error(`GitHub OAuth was not synchronized for ${expectedClientId}`);
|
||||
}
|
||||
if (
|
||||
users.oauth2?.mappedFields?.username !== "displayName" ||
|
||||
users.oauth2?.mappedFields?.username !== "githubUsername" ||
|
||||
users.oauth2?.mappedFields?.id ||
|
||||
users.oauth2?.mappedFields?.name ||
|
||||
users.oauth2?.mappedFields?.avatarURL !== "avatarUrl"
|
||||
users.oauth2?.mappedFields?.avatarURL
|
||||
) {
|
||||
throw new Error(`GitHub OAuth field mapping was not synchronized: ${JSON.stringify(users.oauth2?.mappedFields)}`);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,9 @@ if (!hook.includes("require(`${__hooks}/workshop-utils.js`)")) {
|
||||
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('username: "githubUsername"') || hook.includes("onRecordAuthWithOAuth2Request")) {
|
||||
throw new Error("Workshop identity must use PocketBase's direct GitHub username mapping");
|
||||
}
|
||||
if (hook.includes("validateAndNormalizeSubmission")) {
|
||||
throw new Error("PocketBase must store Workshop submissions without interpreting their content");
|
||||
}
|
||||
@@ -38,6 +41,9 @@ if (hook.includes('findAllRecords("users")') || !hook.includes('findRecordsByFil
|
||||
}
|
||||
|
||||
const migration = await read("apps/workshop/pb_migrations/1784240000_workshop_widgets.js");
|
||||
for (const removedField of ["displayName", "avatarUrl", "githubProfileUrl"]) {
|
||||
if (migration.includes(removedField)) throw new Error(`Redundant Workshop user field remains: ${removedField}`);
|
||||
}
|
||||
for (const required of [
|
||||
"workshop_migration_state",
|
||||
"addedUserFields",
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
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 !== "octocat" ||
|
||||
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");
|
||||
@@ -46,7 +46,7 @@ await request("/api/collections/users", {
|
||||
body: JSON.stringify({ ...usersCollection, passwordAuth: { enabled: true, identityFields: ["email"] } }),
|
||||
});
|
||||
|
||||
const createUser = async (email, displayName, password, extra = {}) =>
|
||||
const createUser = async (email, githubUsername, password, extra = {}) =>
|
||||
request("/api/collections/users/records", {
|
||||
method: "POST",
|
||||
headers: rootHeaders,
|
||||
@@ -56,7 +56,7 @@ const createUser = async (email, displayName, password, extra = {}) =>
|
||||
verified: true,
|
||||
password,
|
||||
passwordConfirm: password,
|
||||
displayName,
|
||||
githubUsername,
|
||||
...extra,
|
||||
}),
|
||||
});
|
||||
@@ -70,65 +70,27 @@ const signIn = async (email, password) => {
|
||||
};
|
||||
|
||||
const authorPassword = "WorkshopAuthor123!";
|
||||
const author = await createUser("widget-author@example.invalid", "Widget Author", authorPassword);
|
||||
const author = await createUser("widget-author@example.invalid", "widget-author", authorPassword);
|
||||
const authorSession = await signIn(author.email, authorPassword);
|
||||
await expectStatus(
|
||||
`/api/collections/users/records/${author.id}`,
|
||||
{ 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",
|
||||
await expectStatus(
|
||||
`/api/collections/users/records/${author.id}`,
|
||||
{ method: "PATCH", headers: authorSession.headers, body: JSON.stringify({ githubUsername: "homarr-labs" }) },
|
||||
404,
|
||||
);
|
||||
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
|
||||
) {
|
||||
if (unchangedAuthor.githubUsername !== "widget-author") {
|
||||
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);
|
||||
const visitor = await createUser("widget-visitor@example.invalid", "widget-visitor", visitorPassword);
|
||||
const visitorSession = await signIn(visitor.email, visitorPassword);
|
||||
|
||||
const widget = {
|
||||
@@ -259,7 +221,7 @@ if (
|
||||
listing.score !== 2 ||
|
||||
listing.upvotes !== 2 ||
|
||||
listing.downvotes !== 0 ||
|
||||
listing.authorName !== "Widget Author" ||
|
||||
listing.authorGithubUsername !== "widget-author" ||
|
||||
listing.widgetSchema !== widget.$schema
|
||||
) {
|
||||
throw new Error("Workshop listing data is incorrect");
|
||||
@@ -270,7 +232,7 @@ const comment = await request("/api/collections/comments/records?expand=author",
|
||||
headers: visitorSession.headers,
|
||||
body: JSON.stringify({ submission: submission.id, author: visitor.id, content: "Useful widget" }),
|
||||
});
|
||||
if (comment.author !== visitor.id || comment.expand.author.displayName !== "Widget Visitor") {
|
||||
if (comment.author !== visitor.id || comment.expand.author.githubUsername !== "widget-visitor") {
|
||||
throw new Error("Comment author expansion is incorrect");
|
||||
}
|
||||
await expectStatus(
|
||||
|
||||
Reference in new issue
Block a user