refactor: trim v2 release hardening

This commit is contained in:
ajnart committed 2026-07-30 16:24:11 +02:00
1 parent 3cf1dc8341
commit 657704340c
79 files changed
+405 -3378

No files matched your search

-72
View File
@@ -1,72 +0,0 @@
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 },
});
const validateDocsBaseUrl = (value) =>
spawnSync("sh", [entrypoint, "--validate-docs-base-url", value], {
encoding: "utf8",
});
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]",
"http://[:1:2:3:4:5:6:7:8]",
"http://[1:2:3:4:5:6:7:8:]",
"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)}`);
}
for (const [value, expected] of [
["/", "/"],
["/docs/", "/docs"],
["/docs..preview", "/docs..preview"],
]) {
const result = validateDocsBaseUrl(value);
if (result.status !== 0 || result.stdout.trim() !== expected) {
throw new Error(`Expected valid DOCS_BASE_URL ${value}: ${result.stderr || result.stdout}`);
}
}
for (const value of ["docs", "/../docs", "/docs/../private", "/./docs", "/docs?preview=1"]) {
const result = validateDocsBaseUrl(value);
if (result.status === 0) throw new Error(`Expected invalid DOCS_BASE_URL to be rejected: ${JSON.stringify(value)}`);
}
console.log("Workshop runtime URL validation passed");
+10 -93
View File
@@ -9,78 +9,33 @@ 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 dockerfile = await read("apps/workshop/Dockerfile");
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");
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("WORKSHOP_REQUIRE_OAUTH") || !hook.includes("partial_credentials")) {
throw new Error("Workshop OAuth bootstrap must reject partial and required-but-disabled configurations");
if (hook.includes("validateAndNormalizeSubmission")) {
throw new Error("PocketBase must store Workshop submissions without interpreting their content");
}
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 (hook.includes("validateAndNormalizeSubmission") || hook.includes("workshop_submission_rejected")) {
throw new Error("PocketBase must not interpret or validate Workshop submission content");
}
for (const removedValidator of [
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",
]) {
let artifactExists = true;
try {
await access(resolve(removedValidator));
} catch (error) {
if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
artifactExists = false;
} else {
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 (artifactExists) throw new Error(`Workshop validator artifact must stay removed: ${removedValidator}`);
}
if (!dockerfile.includes("WORKSHOP_REQUIRE_PUBLIC_ORIGIN=true")) {
throw new Error("The production Workshop image must require an explicit public origin");
}
if (dockerfile.includes("widget-validator") || dockerfile.includes("build-workshop-validator")) {
throw new Error("The Workshop image must not build or copy a submission 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 [
@@ -96,44 +51,6 @@ for (const required of [
if (!migration.includes(required)) throw new Error(`Workshop rollback is missing state restoration: ${required}`);
}
for (const protectedField of [
"email:changed",
"displayName:changed",
"avatarUrl:changed",
"githubUsername:changed",
"githubProfileUrl:changed",
]) {
if (!migration.includes(protectedField)) {
throw new Error(`Workshop OAuth identity field remains caller-controlled: ${protectedField}`);
}
}
if (migration.includes("@request.body.avatar:changed")) {
throw new Error("Workshop access rules must not use the unsupported :changed modifier for file fields");
}
if (
!hook.includes('getUnsavedFiles("avatar")') ||
!hook.includes('original().getString("avatar")') ||
!hook.includes("Workshop avatars are managed by GitHub OAuth")
) {
throw new Error("Workshop avatar updates must be rejected by the user update request hook");
}
for (const protectedField of [
"title:changed",
"description:changed",
"content:changed",
"changelog:changed",
"screenshots:changed",
]) {
if (!migration.includes(protectedField)) {
throw new Error(`Workshop moderators can still rewrite submissions: ${protectedField}`);
}
}
for (const protectedField of ["category:changed", "explanation:changed"]) {
if (!migration.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");
-168
View File
@@ -1,168 +0,0 @@
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;
let userUpdateHook;
const ignoreHook = () => {};
vm.runInNewContext(hookSource, {
__hooks: "/pb_hooks",
console: { log: () => {} },
onBootstrap: ignoreHook,
onRecordAfterCreateSuccess: ignoreHook,
onRecordCreateRequest: ignoreHook,
onRecordDeleteRequest: ignoreHook,
onRecordUpdateRequest: (handler, collection) => {
if (collection === "users") userUpdateHook = handler;
},
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,
rejectRequest: (message) => {
throw new Error(message);
},
};
},
});
if (typeof oauthHook !== "function") throw new Error("Workshop OAuth request hook was not registered");
if (typeof userUpdateHook !== "function") throw new Error("Workshop user update 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");
}
let unchangedAvatarNextCalls = 0;
userUpdateHook({
next: () => {
unchangedAvatarNextCalls += 1;
},
record: {
getString: () => "provider-avatar.png",
getUnsavedFiles: () => [],
original: () => ({ getString: () => "provider-avatar.png" }),
},
});
if (unchangedAvatarNextCalls !== 1) {
throw new Error("User updates that leave the provider avatar unchanged must pass through");
}
for (const avatarChange of [
{
name: "upload",
current: "provider-avatar.png",
original: "provider-avatar.png",
unsavedFiles: [{ name: "forged-avatar.png" }],
},
{
name: "removal",
current: "",
original: "provider-avatar.png",
unsavedFiles: [],
},
]) {
let nextCalls = 0;
try {
userUpdateHook({
next: () => {
nextCalls += 1;
},
record: {
getString: () => avatarChange.current,
getUnsavedFiles: () => avatarChange.unsavedFiles,
original: () => ({ getString: () => avatarChange.original }),
},
});
throw new Error(`Workshop user avatar ${avatarChange.name} was accepted`);
} catch (error) {
if (!String(error).includes("managed by GitHub OAuth")) throw error;
}
if (nextCalls !== 0) throw new Error(`Rejected avatar ${avatarChange.name} continued the update request`);
}
console.log("Workshop OAuth hook contract passed");
@@ -1,261 +0,0 @@
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 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 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 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 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",
);
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}`);
}
await writeFile(snapshotPath, "{}", { 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}`,
);
}
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 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");
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/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");
assert.equal(users.passwordAuth?.enabled, true);
assert.equal(users.oauth2?.enabled, true);
assert.ok(users.oauth2?.providers?.some((provider) => provider.name === "github"));
await assertBaselineData();
await writeFile(snapshotPath, JSON.stringify({ users: userConfig(users) }), { 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");
await assertBaselineData();
console.log("Workshop full rollback state verified");
}