harden v2 custom widgets and workshop

This commit is contained in:
ajnart committed 2026-07-28 14:12:14 +02:00
1 parent e8a2c87c2d
commit 723b46926a
194 files changed
+44862 -1265

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
import { spawnSync } from "node:child_process";
import { resolve } from "node:path";
const entrypoint = resolve("apps/workshop/entrypoint.sh");
const validator = resolve("apps/workshop/workshop-url.awk");
const validate = (value) =>
spawnSync("sh", [entrypoint, "--validate-url", "TEST_URL", value], {
encoding: "utf8",
env: { ...process.env, WORKSHOP_URL_VALIDATOR_PATH: validator },
});
for (const [value, expected] of [
["http://127.0.0.1:8090/", "http://127.0.0.1:8090"],
["https://example.com/docs/", "https://example.com/docs"],
["https://example.com:0/", "https://example.com:0"],
["https://[::1]:8090/workshop/", "https://[::1]:8090/workshop"],
]) {
const result = validate(value);
if (result.status !== 0 || result.stdout.trim() !== expected) {
throw new Error(`Expected valid runtime URL ${value}: ${result.stderr || result.stdout}`);
}
}
for (const value of [
"",
"http://",
"http:///docs",
"https://:",
"https://example.com:65536",
"https://::1",
"https://[:::1]",
"https://1.2.3.4.5",
"http://09.0.0.1",
"http://099.0.0.1",
"http://[::ffff:192.168.001.001]",
"http://[::ffff:192.168.1.01]",
"http://[fe80::1%25eth0]",
"https://user:password@example.com",
"https://example.com/workshop?token=secret",
"https://example.com/workshop#fragment",
"https://example.com/\tworkshop",
"https://example.com/\nworkshop",
]) {
const result = validate(value);
if (result.status === 0) throw new Error(`Expected invalid runtime URL to be rejected: ${JSON.stringify(value)}`);
}
console.log("Workshop runtime URL validation passed");
@@ -10,7 +10,13 @@ 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 widgetValidator = await read("apps/workshop/pb_hooks/widget-validator.js");
const canonicalWidgetValidator = await read("packages/workshop/src/pocketbase-validator.ts");
const dockerfile = await read("apps/workshop/Dockerfile");
const schema = await read("packages/workshop/src/schema.ts");
const workshopApp = await read("apps/docs/src/components/workshop/WorkshopApp.tsx");
const workshopAdmin = await read("apps/docs/src/components/workshop/WorkshopAdmin.tsx");
const workshopDetail = await read("apps/docs/src/components/workshop/DetailPage.tsx");
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`);
@@ -28,24 +34,113 @@ 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("WORKSHOP_REQUIRE_OAUTH") || !hook.includes("partial_credentials")) {
throw new Error("Workshop OAuth bootstrap must reject partial and required-but-disabled configurations");
}
if (
!hook.includes("onRecordAuthWithOAuth2Request") ||
!hook.includes("deriveGithubIdentity") ||
!hook.includes("event.oauth2User") ||
hook.includes("event.oAuth2User") ||
!hook.includes("event.createData.displayName = identity.displayName") ||
!hook.includes('event.record.set("displayName", identity.displayName)') ||
!hook.includes("workshop_oauth_identity_synchronized")
) {
throw new Error("Workshop GitHub identity must be synchronized for first and returning OAuth logins");
}
if (!hook.includes("workshop_report_reopened") || !hook.includes("status = 'dismissed'")) {
throw new Error("Workshop must permit a fresh report after a previous report was dismissed");
}
if (
!widgetValidator.includes("widget-validator.bundle.cjs") ||
!canonicalWidgetValidator.includes("customWidgetDefinitionSchema.safeParse")
) {
throw new Error("Workshop direct writes must use the bundled canonical Custom Widget validator");
}
await access(resolve("apps/workshop/pb_hooks/widget-validator.bundle.cjs"));
if (!dockerfile.includes("WORKSHOP_REQUIRE_PUBLIC_ORIGIN=true")) {
throw new Error("The production Workshop image must require an explicit public origin");
}
if (!dockerfile.includes("COPY --from=dependencies") || !dockerfile.includes("widget-validator.bundle.cjs")) {
throw new Error("The production Workshop image must copy the freshly generated canonical validator");
}
if (hook.includes('findAllRecords("users")') || !hook.includes('findRecordsByFilter("users"')) {
throw new Error("Workshop report notifications must use a filtered, bounded administrator query");
}
if (!hook.includes("WORKSHOP_WEB_URL")) {
throw new Error("PocketBase-generated Workshop links must use the configured public web URL");
}
for (const [name, source] of [
["Workshop listing", workshopApp],
["Workshop moderation", workshopAdmin],
["Workshop detail", workshopDetail],
]) {
if (/<a\b[^>]*\bhref=["']\/workshop/u.test(source)) {
throw new Error(`${name} must use base-path-aware Docusaurus links`);
}
if (/window\.location(?:\.href)?\s*=\s*["']\/workshop/u.test(source)) {
throw new Error(`${name} must use a base-path-aware redirect`);
}
}
const migration = await read("apps/workshop/pb_migrations/1784240000_workshop_widgets.js");
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}`);
}
const hardeningMigration = await read("apps/workshop/pb_migrations/1784240001_workshop_write_rate_limits.js");
for (const operation of ["create", "update", "delete"]) {
for (const collection of ["submissions", "votes", "comments", "reports"]) {
const label = `${collection}:${operation}`;
if (!hardeningMigration.includes(label)) throw new Error(`Workshop write rate limit is missing: ${label}`);
}
}
if (!hardeningMigration.includes("users:update")) throw new Error("Workshop user file updates must be rate limited");
const accessHardeningMigration = await read("apps/workshop/pb_migrations/1784240002_workshop_access_hardening.js");
for (const protectedField of [
"email:changed",
"displayName:changed",
"avatar:changed",
"avatarUrl:changed",
"githubUsername:changed",
"githubProfileUrl:changed",
]) {
if (!accessHardeningMigration.includes(protectedField)) {
throw new Error(`Workshop OAuth identity field remains caller-controlled: ${protectedField}`);
}
}
for (const protectedField of [
"title:changed",
"description:changed",
"content:changed",
"changelog:changed",
"screenshots:changed",
]) {
if (!accessHardeningMigration.includes(protectedField)) {
throw new Error(`Workshop moderators can still rewrite submissions: ${protectedField}`);
}
}
for (const protectedField of ["category:changed", "explanation:changed"]) {
if (!accessHardeningMigration.includes(protectedField)) {
throw new Error(`Workshop moderators can still rewrite reports: ${protectedField}`);
}
}
const workflow = await read(".github/workflows/workshop.yml");
if (/\n\s+paths:/u.test(workflow)) throw new Error("Workshop workflow must not filter out Docker build inputs");
if (!workflow.includes("DOCS_BASE_URL=/docs-site/") || !workflow.includes("workshop-base-path-smoke")) {
throw new Error("Workshop CI must exercise a non-root documentation deployment");
}
console.log("Workshop static contracts passed");
+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");
+11 -7
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",
@@ -157,13 +157,17 @@ 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)) {
+111
View File
@@ -0,0 +1,111 @@
import { createRequire } from "node:module";
import { readFile } from "node:fs/promises";
import vm from "node:vm";
const nodeRequire = createRequire(import.meta.url);
const workshopUtils = nodeRequire("../pb_hooks/workshop-utils.js");
const hookSource = await readFile("apps/workshop/pb_hooks/workshop.pb.js", "utf8");
let oauthHook;
const ignoreHook = () => {};
vm.runInNewContext(hookSource, {
__hooks: "/pb_hooks",
console: { log: () => {} },
onBootstrap: ignoreHook,
onRecordAfterCreateSuccess: ignoreHook,
onRecordCreateRequest: ignoreHook,
onRecordDeleteRequest: ignoreHook,
onRecordUpdateRequest: ignoreHook,
onRecordAuthWithOAuth2Request: (handler, collection) => {
if (collection !== "users") throw new Error(`OAuth hook targets unexpected collection: ${collection}`);
oauthHook = handler;
},
require: (specifier) => {
if (specifier !== "/pb_hooks/workshop-utils.js") {
throw new Error(`OAuth hook loaded unexpected dependency: ${specifier}`);
}
return workshopUtils;
},
});
if (typeof oauthHook !== "function") throw new Error("Workshop OAuth request hook was not registered");
const oauth2User = {
id: "provider-user-123",
name: "Octo Cat",
username: "octocat",
avatarURL: "https://avatars.githubusercontent.com/u/1?v=4",
rawUser: {},
};
const createData = {};
let createNextCalls = 0;
oauthHook({
app: { save: () => Promise.reject(new Error("New OAuth users must not be saved before PocketBase creates them")) },
createData,
next: () => {
createNextCalls += 1;
},
oauth2User,
providerName: "github",
record: null,
});
if (
createNextCalls !== 1 ||
createData.displayName !== "Octo Cat" ||
createData.avatarUrl !== "https://avatars.githubusercontent.com/u/1?v=4" ||
createData.githubUsername !== "octocat" ||
createData.githubProfileUrl !== "https://github.com/octocat"
) {
throw new Error(`First GitHub OAuth login did not synchronize trusted identity: ${JSON.stringify(createData)}`);
}
const returningValues = new Map();
const returningRecord = {
id: "returning-user-123",
set: (name, value) => returningValues.set(name, value),
};
let savedRecord;
let returningNextCalls = 0;
oauthHook({
app: {
save: (record) => {
savedRecord = record;
},
},
createData: {},
next: () => {
returningNextCalls += 1;
},
oauth2User,
providerName: "github",
record: returningRecord,
});
if (
savedRecord !== returningRecord ||
returningNextCalls !== 1 ||
returningValues.get("displayName") !== "Octo Cat" ||
returningValues.get("avatar") !== "" ||
returningValues.get("avatarUrl") !== "https://avatars.githubusercontent.com/u/1?v=4" ||
returningValues.get("githubUsername") !== "octocat" ||
returningValues.get("githubProfileUrl") !== "https://github.com/octocat"
) {
throw new Error("Returning GitHub OAuth login did not refresh trusted identity");
}
const ignoredCreateData = {};
let ignoredNextCalls = 0;
oauthHook({
app: {},
createData: ignoredCreateData,
next: () => {
ignoredNextCalls += 1;
},
oauth2User,
providerName: "oidc",
record: null,
});
if (ignoredNextCalls !== 1 || Object.keys(ignoredCreateData).length !== 0) {
throw new Error("Non-GitHub OAuth providers must pass through without GitHub identity synchronization");
}
console.log("Workshop OAuth hook contract passed");
@@ -0,0 +1,317 @@
import assert from "node:assert/strict";
import { readFile, writeFile } from "node:fs/promises";
const baseUrl = process.env.WORKSHOP_TEST_URL;
const snapshotPath = process.env.WORKSHOP_ROLLBACK_SNAPSHOT;
const phase = process.argv[2];
if (!baseUrl) throw new Error("WORKSHOP_TEST_URL is required");
if (!snapshotPath) throw new Error("WORKSHOP_ROLLBACK_SNAPSHOT is required");
if (!["fresh-prepare", "fresh-migrated", "fresh-restored", "prepare", "migrated", "restored"].includes(phase)) {
throw new Error("Unknown Workshop rollback test phase");
}
const superuser = {
email: "workshop-rollback@example.invalid",
password: "WorkshopRollback123!",
};
const baselineUser = {
email: "rollback-user@example.invalid",
password: "WorkshopRollbackUser123!",
note: "retained across the Workshop migration chain",
};
const baselineRateLimitLabel = "rollback_sentinel:create";
const workshopCollections = [
"workshop_migration_state",
"submissions",
"votes",
"comments",
"reports",
"workshop_listings",
];
const workshopUserFields = ["displayName", "avatarUrl", "avatar", "githubUsername", "githubProfileUrl", "isAdmin"];
const request = async (path, init = {}) => {
const response = await fetch(`${baseUrl}${path}`, {
...init,
headers: { "content-type": "application/json", ...init.headers },
});
const body = await response.json().catch(() => null);
if (!response.ok) throw new Error(`${response.status} ${path}: ${JSON.stringify(body)}`);
return body;
};
const auth = await request("/api/collections/_superusers/auth-with-password", {
method: "POST",
body: JSON.stringify({ identity: superuser.email, password: superuser.password }),
});
const rootHeaders = { authorization: `Bearer ${auth.token}` };
const collectionList = async () => {
const result = await request("/api/collections?perPage=200", { headers: rootHeaders });
return new Map(result.items.map((collection) => [collection.name, collection]));
};
const collection = (name) => request(`/api/collections/${name}`, { headers: rootHeaders });
const settings = () => request("/api/settings", { headers: rootHeaders });
const records = (name) =>
request(`/api/collections/${name}/records?perPage=200`, {
headers: rootHeaders,
});
const normalized = (value) => JSON.parse(JSON.stringify(value));
const publicOauthConfig = (oauth2) => {
const value = normalized(oauth2);
value.providers = value.providers?.map(({ clientSecret: _clientSecret, ...provider }) => provider);
return value;
};
const userConfig = (users) => ({
rules: {
listRule: users.listRule,
viewRule: users.viewRule,
createRule: users.createRule,
updateRule: users.updateRule,
deleteRule: users.deleteRule,
},
passwordAuth: normalized(users.passwordAuth),
oauth2: publicOauthConfig(users.oauth2),
fieldNames: users.fields.map((field) => field.name).toSorted(),
});
const readSnapshot = async () => JSON.parse(await readFile(snapshotPath, "utf8"));
const assertManagedRateLimits = (currentSettings) => {
assert.equal(currentSettings.rateLimits?.enabled, true, "Workshop migration did not enable rate limits");
const rateLimitLabels = new Set(currentSettings.rateLimits?.rules?.map((rule) => rule.label));
for (const operation of ["create", "update", "delete"]) {
for (const name of ["submissions", "votes", "comments", "reports"]) {
assert.ok(rateLimitLabels.has(`${name}:${operation}`), `Missing migrated rate limit ${name}:${operation}`);
}
}
assert.ok(rateLimitLabels.has("users:update"), "Missing migrated users:update rate limit");
return rateLimitLabels;
};
const assertBaselineData = async () => {
const userRecords = await records("users");
const retainedUser = userRecords.items.find((record) => record.email === baselineUser.email);
assert.equal(retainedUser?.baselineNote, baselineUser.note, "Baseline user data was not retained");
const sentinelRecords = await records("rollback_sentinel");
assert.equal(sentinelRecords.items.length, 1, "Unrelated baseline record count changed");
assert.equal(sentinelRecords.items[0]?.value, "keep-me", "Unrelated baseline data changed");
};
const assertMigrated = async () => {
const before = await readSnapshot();
const collections = await collectionList();
for (const name of [...workshopCollections, "users", "rollback_sentinel"]) {
assert.ok(collections.has(name), `Migrated database is missing collection ${name}`);
}
const users = await collection("users");
assert.equal(users.passwordAuth?.enabled, false, "Workshop migration must disable password authentication");
assert.deepEqual(
publicOauthConfig(users.oauth2),
before.users.oauth2,
"Workshop migration changed existing OAuth settings",
);
for (const name of workshopUserFields) {
assert.ok(
users.fields.some((field) => field.name === name),
`Workshop user field ${name} is missing`,
);
}
assert.match(
users.updateRule ?? "",
/githubProfileUrl:changed = false/u,
"OAuth identity update rule is not hardened",
);
const currentSettings = await settings();
const rateLimitLabels = assertManagedRateLimits(currentSettings);
assert.ok(rateLimitLabels.has(baselineRateLimitLabel), "Workshop migration removed an unrelated rate-limit rule");
const stateRecords = await records("workshop_migration_state");
assert.equal(stateRecords.items.length, 1, "Workshop migration state snapshot is missing");
const migrationState = JSON.parse(stateRecords.items[0].snapshot);
assert.equal(migrationState.usersExisted, true, "Workshop migration did not recognize the existing users collection");
assert.deepEqual(migrationState.users.passwordAuth, before.users.passwordAuth);
assert.deepEqual(publicOauthConfig(migrationState.users.oauth2), before.users.oauth2);
assert.deepEqual(
{
listRule: migrationState.users.listRule,
viewRule: migrationState.users.viewRule,
createRule: migrationState.users.createRule,
updateRule: migrationState.users.updateRule,
deleteRule: migrationState.users.deleteRule,
},
before.users.rules,
"Workshop migration state did not snapshot the original user rules",
);
assert.equal(
migrationState.users.oauth2.providers.find((provider) => provider.name === "github")?.clientSecret,
"rollback-baseline-secret",
"Workshop migration state did not retain the OAuth secret required for rollback",
);
assert.deepEqual(migrationState.rateLimits, before.rateLimits);
await assertBaselineData();
};
if (phase === "fresh-prepare") {
let collections = await collectionList();
if (collections.has("users")) {
await request("/api/collections/users", { method: "DELETE", headers: rootHeaders });
collections = await collectionList();
}
for (const name of [...workshopCollections, "users", "rollback_sentinel"]) {
assert.ok(!collections.has(name), `Fresh database unexpectedly contains collection ${name}`);
}
const currentSettings = await settings();
await writeFile(snapshotPath, JSON.stringify({ freshRateLimits: normalized(currentSettings.rateLimits) }), {
mode: 0o600,
});
console.log("Workshop fresh rollback baseline captured");
} else if (phase === "fresh-migrated") {
const collections = await collectionList();
for (const name of [...workshopCollections, "users"]) {
assert.ok(collections.has(name), `Fresh migration is missing collection ${name}`);
}
const users = await collection("users");
for (const name of workshopUserFields) {
assert.ok(
users.fields.some((field) => field.name === name),
`Fresh migration is missing user field ${name}`,
);
}
assertManagedRateLimits(await settings());
const stateRecords = await records("workshop_migration_state");
assert.equal(stateRecords.items.length, 1, "Fresh migration state snapshot is missing");
const migrationState = JSON.parse(stateRecords.items[0].snapshot);
assert.equal(migrationState.usersExisted, false, "Fresh migration incorrectly recorded an existing users collection");
assert.equal(migrationState.users, null, "Fresh migration retained nonexistent user settings");
console.log("Workshop fresh migration chain verified");
} else if (phase === "fresh-restored") {
const before = await readSnapshot();
const collections = await collectionList();
for (const name of [...workshopCollections, "users", "rollback_sentinel"]) {
assert.ok(!collections.has(name), `Fresh rollback left collection ${name}`);
}
assert.ok(collections.has("_superusers"), "Fresh rollback removed PocketBase superuser data");
const currentSettings = await settings();
assert.deepEqual(
normalized(currentSettings.rateLimits),
before.freshRateLimits,
"Fresh rollback did not restore the original rate-limit settings",
);
console.log("Workshop fresh rollback state verified");
} else if (phase === "prepare") {
const collections = await collectionList();
for (const name of [...workshopCollections, "users", "rollback_sentinel"]) {
assert.ok(!collections.has(name), `Fresh rollback fixture unexpectedly contains collection ${name}`);
}
await request("/api/collections", {
method: "POST",
headers: rootHeaders,
body: JSON.stringify({
type: "auth",
name: "users",
listRule: "@request.auth.id != ''",
viewRule: "id = @request.auth.id",
createRule: "@request.body.email != ''",
updateRule: "id = @request.auth.id",
deleteRule: "id = @request.auth.id",
passwordAuth: { enabled: true, identityFields: ["email"] },
oauth2: {
enabled: true,
providers: [
{
name: "github",
clientId: "rollback-baseline-client",
clientSecret: "rollback-baseline-secret",
},
],
},
fields: [{ type: "text", name: "baselineNote", max: 200 }],
}),
});
await request("/api/collections", {
method: "POST",
headers: rootHeaders,
body: JSON.stringify({
type: "base",
name: "rollback_sentinel",
listRule: null,
viewRule: null,
createRule: null,
updateRule: null,
deleteRule: null,
fields: [{ type: "text", name: "value", required: true, max: 100 }],
}),
});
await request("/api/settings", {
method: "PATCH",
headers: rootHeaders,
body: JSON.stringify({
rateLimits: {
enabled: false,
rules: [{ label: baselineRateLimitLabel, audience: "", duration: 17, maxRequests: 23 }],
},
}),
});
await request("/api/collections/users/records", {
method: "POST",
headers: rootHeaders,
body: JSON.stringify({
email: baselineUser.email,
emailVisibility: false,
verified: true,
password: baselineUser.password,
passwordConfirm: baselineUser.password,
baselineNote: baselineUser.note,
}),
});
await request("/api/collections/rollback_sentinel/records", {
method: "POST",
headers: rootHeaders,
body: JSON.stringify({ value: "keep-me" }),
});
const users = await collection("users");
const currentSettings = await settings();
assert.equal(users.passwordAuth?.enabled, true);
assert.equal(users.oauth2?.enabled, true);
assert.ok(users.oauth2?.providers?.some((provider) => provider.name === "github"));
assert.equal(currentSettings.rateLimits?.enabled, false);
assert.deepEqual(
currentSettings.rateLimits?.rules?.map((rule) => rule.label),
[baselineRateLimitLabel],
);
await assertBaselineData();
await writeFile(
snapshotPath,
JSON.stringify({ users: userConfig(users), rateLimits: normalized(currentSettings.rateLimits) }),
{ mode: 0o600 },
);
console.log("Workshop rollback baseline prepared");
} else if (phase === "migrated") {
await assertMigrated();
console.log("Workshop full migration chain verified");
} else {
const before = await readSnapshot();
const collections = await collectionList();
for (const name of workshopCollections) {
assert.ok(!collections.has(name), `Rollback left Workshop collection ${name}`);
}
for (const name of ["users", "rollback_sentinel"]) {
assert.ok(collections.has(name), `Rollback removed baseline collection ${name}`);
}
const users = await collection("users");
assert.deepEqual(userConfig(users), before.users, "Rollback did not restore user rules, fields, password, or OAuth");
const currentSettings = await settings();
assert.deepEqual(
normalized(currentSettings.rateLimits),
before.rateLimits,
"Rollback did not restore the original rate-limit settings",
);
await assertBaselineData();
console.log("Workshop full rollback state verified");
}
@@ -0,0 +1,332 @@
import { BUNDLED_CUSTOM_WIDGETS, customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
const baseUrl = process.env.WORKSHOP_TEST_URL ?? "http://127.0.0.1:18090";
const password = "WorkshopCorpus123!";
const shard = Number(process.env.WORKSHOP_CORPUS_SHARD ?? "0");
const shardCount = Number(process.env.WORKSHOP_CORPUS_SHARD_COUNT ?? "1");
if (!Number.isInteger(shard) || !Number.isInteger(shardCount) || shard < 0 || shardCount < 1 || shard >= shardCount) {
throw new Error("Validator corpus shard configuration is invalid");
}
const email = shardCount === 1 ? "workshop-corpus@example.invalid" : `workshop-corpus-${shard}@example.invalid`;
async function request(path: string, init: RequestInit = {}) {
const response = await fetch(`${baseUrl}${path}`, {
...init,
headers: { "content-type": "application/json", ...init.headers },
});
const body = (await response.json().catch(() => null)) as Record<string, unknown> | null;
return { response, body };
}
const root = await request("/api/collections/_superusers/auth-with-password", {
method: "POST",
body: JSON.stringify({ identity: "workshop-test@example.invalid", password: "WorkshopLocalTest123!" }),
});
if (!root.response.ok || typeof root.body?.token !== "string") throw new Error("Corpus superuser login failed");
const rootHeaders = { authorization: `Bearer ${root.body.token}` };
const createdUser = await request("/api/collections/users/records", {
method: "POST",
headers: rootHeaders,
body: JSON.stringify({
email,
emailVisibility: false,
verified: true,
password,
passwordConfirm: password,
displayName: "Validator Corpus",
}),
});
if (!createdUser.response.ok || typeof createdUser.body?.id !== "string") {
throw new Error(`Corpus user creation failed: ${JSON.stringify(createdUser.body)}`);
}
const userId = createdUser.body.id;
const signedIn = await request("/api/collections/users/auth-with-password", {
method: "POST",
body: JSON.stringify({ identity: email, password }),
});
if (!signedIn.response.ok || typeof signedIn.body?.token !== "string") throw new Error("Corpus user login failed");
const userHeaders = { authorization: `Bearer ${signedIn.body.token}` };
const bundled = BUNDLED_CUSTOM_WIDGETS.map(({ id, widget }) => ({
name: `bundled:${id}`,
widget: structuredClone(widget) as Record<string, unknown>,
}));
const base = structuredClone(bundled[0]?.widget);
if (!base) throw new Error("Bundled Custom Widget corpus is empty");
const asRecord = (value: unknown) => value as Record<string, unknown>;
const withMutation = (mutate: (widget: Record<string, unknown>) => void) => {
const widget = structuredClone(base) as Record<string, unknown>;
mutate(widget);
return widget;
};
bundled.push(
{
name: "source:valid-port-zero",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "http://example.com:0";
}),
},
{
name: "source:valid-trailing-dot",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "https://example.com.";
}),
},
{
name: "source:valid-idn",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "https://münich.example";
}),
},
{
name: "url:valid-ipv6-and-port",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "https://[2001:db8::1]:65535";
widget.iconUrl = "https://[2001:db8::1]:65535/icon.svg";
}),
},
{
name: "request:valid-harmless-key-metadata",
widget: withMutation((widget) => {
const requestDefinition = asRecord(Object.values(asRecord(widget.requests))[0]);
requestDefinition.path = "/api/status?key=status&auth=none";
requestDefinition.headers = {
Accept: "application/json",
"X-Api-Version": "2026-07",
"X-Feature-Key": "dashboard-layout",
};
}),
},
);
const adversarial = [
{
name: "manifest:unknown-secret-field",
widget: withMutation((widget) => {
widget.secrets = [{ value: "must-never-be-published" }];
}),
},
{
name: "source:embedded-credentials",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "https://user:password@example.com";
}),
},
{
name: "source:invalid-numeric-host",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "http://1.2.3.4.5";
}),
},
{
name: "source:invalid-numeric-leading-zero",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "http://09.0.0.1";
}),
},
{
name: "source:ambiguous-numeric-shorthand",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "http://127.1";
}),
},
{
name: "source:ambiguous-hexadecimal-ipv4",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "http://0x7f000001";
}),
},
{
name: "source:percent-encoded-host",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "https://%65xample.com";
}),
},
{
name: "source:backslash-normalization",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "https://example.com\\@attacker.invalid";
}),
},
{
name: "source:invalid-ipv6-zone",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "http://[fe80::1%25eth0]";
}),
},
{
name: "source:invalid-ipv6-embedded-ipv4",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "http://[::ffff:192.168.001.001]";
}),
},
{
name: "source:invalid-a-label",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "https://xn--a.example";
}),
},
{
name: "request:reserved-header",
widget: withMutation((widget) => {
const requestDefinition = asRecord(Object.values(asRecord(widget.requests))[0]);
requestDefinition.headers = { Authorization: "must-never-be-published" };
}),
},
{
name: "request:credential-in-body",
widget: withMutation((widget) => {
const requestDefinition = asRecord(Object.values(asRecord(widget.requests))[0]);
requestDefinition.body = { access_token: "must-never-be-published" };
}),
},
{
name: "request:credential-in-path-query",
widget: withMutation((widget) => {
const requestDefinition = asRecord(Object.values(asRecord(widget.requests))[0]);
requestDefinition.path = "/api/status?credential=Bearer-sk-secret-123456";
}),
},
{
name: "request:credential-in-custom-header",
widget: withMutation((widget) => {
const requestDefinition = asRecord(Object.values(asRecord(widget.requests))[0]);
requestDefinition.headers = { "X-Auth": "Bearer sk-secret-123456" };
}),
},
{
name: "request:common-token-in-header-value",
widget: withMutation((widget) => {
const requestDefinition = asRecord(Object.values(asRecord(widget.requests))[0]);
requestDefinition.headers = { "X-Service": "ghp_abcdefghijklmnopqrstuvwxyz123456" };
}),
},
{
name: "request:automatic-delete-query",
widget: withMutation((widget) => {
const requestDefinition = asRecord(Object.values(asRecord(widget.requests))[0]);
requestDefinition.kind = "query";
requestDefinition.trigger = "load";
requestDefinition.method = "DELETE";
}),
},
{
name: "icon:credential-query",
widget: withMutation((widget) => {
widget.iconUrl = "https://example.com/icon.png?clientSecret=must-never-be-published";
}),
},
{
name: "icon:unicode-mapped-numeric-host",
widget: withMutation((widget) => {
widget.iconUrl = "https://127.0.0.1/icon.png";
}),
},
{
name: "option:invalid-default",
widget: withMutation((widget) => {
asRecord(widget.options).invalid = { label: "Invalid", control: "number", default: "not-a-number" };
}),
},
{
name: "template:incompatible-request",
widget: withMutation((widget) => {
const requestId = Object.keys(asRecord(widget.requests))[0];
widget.template = `${String(widget.template)}<ActionButton requestId="${requestId}">Unsafe</ActionButton>`;
}),
},
{
name: "template:literal-credential",
widget: withMutation((widget) => {
widget.template = "<Text>Authorization: Bearer must-never-be-published</Text>";
}),
},
{
name: "template:blocked-script",
widget: withMutation((widget) => {
widget.template = "<script>unsafe()</script>";
}),
},
{
name: "template:unknown-component",
widget: withMutation((widget) => {
widget.template = "<DefinitelyNotAWidgetComponent />";
}),
},
{
name: "template:unknown-global",
widget: withMutation((widget) => {
widget.template = "<Text>{process.env.HOME}</Text>";
}),
},
];
let updateTargetId: string | undefined;
let updateTargetRevision = 0;
for (const [index, entry] of bundled.entries()) {
const canonicalAccepted = customWidgetDefinitionSchema.safeParse(entry.widget).success;
if (!canonicalAccepted) throw new Error(`Bundled widget failed canonical validation: ${entry.name}`);
const direct = updateTargetId
? await request(`/api/collections/submissions/records/${updateTargetId}`, {
method: "PATCH",
headers: userHeaders,
body: JSON.stringify({
title: `Corpus ${String(index + 1).padStart(2, "0")}`,
description: entry.name,
content: JSON.stringify(entry.widget),
expectedRevision: updateTargetRevision,
}),
})
: await request("/api/collections/submissions/records", {
method: "POST",
headers: userHeaders,
body: JSON.stringify({
type: "customWidget",
title: `Corpus ${String(index + 1).padStart(2, "0")}`,
description: entry.name,
widgetSchema: "caller-controlled",
content: JSON.stringify(entry.widget),
author: userId,
}),
});
if (!direct.response.ok || typeof direct.body?.id !== "string") {
throw new Error(
`PocketBase rejected bundled widget ${entry.name}: status=${direct.response.status}, body=${JSON.stringify(direct.body)}`,
);
}
updateTargetId ??= direct.body.id;
if (typeof direct.body.revision !== "number") throw new Error("Corpus response did not include a numeric revision");
updateTargetRevision = direct.body.revision;
}
if (!updateTargetId) throw new Error("Differential corpus did not create an update target");
const adversarialShard = adversarial.filter((_, index) => index % shardCount === shard);
for (const entry of adversarialShard) {
if (customWidgetDefinitionSchema.safeParse(entry.widget).success) {
throw new Error(`Adversarial corpus case passed canonical validation: ${entry.name}`);
}
const direct = await request(`/api/collections/submissions/records/${updateTargetId}`, {
method: "PATCH",
headers: userHeaders,
body: JSON.stringify({
content: JSON.stringify(entry.widget),
expectedRevision: updateTargetRevision,
}),
});
if (direct.response.status === 429) {
throw new Error(`Validator corpus was rate limited before checking ${entry.name}`);
}
if (direct.response.status !== 400) {
throw new Error(
`PocketBase accepted or mishandled invalid widget ${entry.name}: status=${direct.response.status}, body=${JSON.stringify(direct.body)}`,
);
}
}
console.log(
`Workshop validator differential corpus shard ${shard + 1}/${shardCount} passed (${bundled.length + adversarialShard.length} cases)`,
);
+87 -3
View File
@@ -34,6 +34,15 @@ for (const required of ["submissions", "votes", "comments", "reports", "workshop
for (const removed of ["workshop_admin_actions", "workshop_admins"]) {
if (collectionNames.has(removed)) throw new Error(`Removed Workshop collection still exists: ${removed}`);
}
const settings = await request("/api/settings", { headers: rootHeaders });
const rateLimitLabels = new Set(settings.rateLimits?.rules?.map((rule) => rule.label));
for (const operation of ["create", "update", "delete"]) {
for (const collection of ["submissions", "votes", "comments", "reports"]) {
const label = `${collection}:${operation}`;
if (!rateLimitLabels.has(label)) throw new Error(`Missing Workshop write rate limit: ${label}`);
}
}
if (!rateLimitLabels.has("users:update")) throw new Error("Workshop user/file updates are not rate limited");
// Production uses GitHub OAuth. Password auth is enabled only in this disposable database.
const usersCollection = await request("/api/collections/users", { headers: rootHeaders });
@@ -77,6 +86,29 @@ 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 unchangedAuthor = await request(`/api/collections/users/records/${author.id}`, {
headers: authorSession.headers,
});
if (
unchangedAuthor.displayName !== "Widget Author" ||
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);
@@ -295,7 +327,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 +349,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 +403,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 },