From 31f2f206dc9a40bbfd5c2c1691a284a3595cf658 Mon Sep 17 00:00:00 2001 From: Afolabi <35589781+Oba-One@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:46:05 -0800 Subject: [PATCH 1/5] Public projections: publish only allowlisted operational fields, proven with fast-check Plan item 20. An operational record used to carry every field its source held (`[key: string]: any`), guarded only by a denylist. Now: - PUBLIC_OPERATIONAL_RECORD_FIELDS lists each collection's top-level public fields, matching the content.public_* views and the committed snapshot - the snapshot keeps only those fields, after the quarantine check (so its alerts still fire) and in the record's own key order - the record types name their fields; an unlisted one does not type-check - scripts/public-projection-allowlist.test.ts proves with fast-check that extra and private fields (known names and random ones, at any depth) never reach operational records, map nodes, map state nodes or the impact payload, and that unapproved submissions are never published - fast-check 4.10.3 added as an exact devDependency (approved by afo) Co-Authored-By: Claude Opus 5.5 Agent-Model: claude-opus-5-5/high --- AGENTS.md | 2 +- bun.lock | 5 + package.json | 1 + packages/shared/src/public-content.ts | 108 +++++-- scripts/public-projection-allowlist.test.ts | 305 ++++++++++++++++++++ 5 files changed, 400 insertions(+), 21 deletions(-) create mode 100644 scripts/public-projection-allowlist.test.ts diff --git a/AGENTS.md b/AGENTS.md index f99521d..3aeece1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,7 +57,7 @@ Each rule names what enforces it. "Review only" means nothing fails automaticall | --- | --- | --- | | Packages and scripts type-check; the site builds inside the Pages size budget | CI `PR checks` | `.github/workflows/pr-checks.yml` | | Public agent routes use exported route constants and shared payload contracts | test, CI `PR checks` (`bun run test`) | `scripts/agent-contract.test.ts` | -| Public projections never expose emails, raw notes, IPs, user agents, spam metadata, steward notes, pending submissions or raw upstream feedback | tests, CI `PR checks` (`bun run test`); review for new fields | `scripts/public-content-contract.test.ts`, `scripts/map-node-contract.test.ts` | +| Public projections never expose emails, raw notes, IPs, user agents, spam metadata, steward notes, pending submissions or raw upstream feedback; an operational record publishes only its collection's allowlisted fields, so a new Directus column reaches the site only once added to `PUBLIC_OPERATIONAL_RECORD_FIELDS` | tests and fast-check properties, CI `PR checks` (`bun run test`); the payload types reject an unlisted field at type-check; review for new fields | `scripts/public-content-contract.test.ts`, `scripts/map-node-contract.test.ts`, `scripts/public-projection-allowlist.test.ts`, `packages/shared/src/public-content.ts` | | Plan hubs follow the hub contract | CI `PR checks` (`plans:validate`) | `scripts/plan-hub.ts` | | No em dashes in website copy | CI `Em dashes in website copy` | `.github/workflows/website-copy.yml` | | Installs stay on the frozen lockfile and the release-age gate; workflow and guidance changes are audited | CI `audit / Supply-chain guardrails` | `.github/workflows/supply-chain-guardrails.yml` | diff --git a/bun.lock b/bun.lock index 8b54374..6c817b5 100644 --- a/bun.lock +++ b/bun.lock @@ -11,6 +11,7 @@ "@types/node": "^22", "@typescript/native": "npm:typescript@7.0.2", "axe-core": "^4.11.4", + "fast-check": "4.10.3", "modern-web-guidance": "^0.0.169", "oxlint": "1.94.0", "typescript": "^6.0.3", @@ -903,6 +904,8 @@ "facepaint": ["facepaint@1.2.1", "", {}, "sha512-oNvBekbhsm/0PNSOWca5raHNAi6dG960Bx6LJgxDPNF59WpuspgQ17bN5MKwOr7JcFdQYc7StW3VZ28DBZLavQ=="], + "fast-check": ["fast-check@4.10.3", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-SBaU6nhh+sXxb05r2IHAKfxnR/1Pu6MqtHYaewM1BY6V5xzOxOk+4yoWO7WfeeyZG1iArFE6/DO/7iLYMUuOJg=="], + "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], "fast-string-truncated-width": ["fast-string-truncated-width@3.0.3", "", {}, "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g=="], @@ -1241,6 +1244,8 @@ "prosemirror-view": ["prosemirror-view@1.41.8", "", { "dependencies": { "prosemirror-model": "^1.20.0", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.1.0" } }, "sha512-TnKDdohEatgyZNGCDWIdccOHXhYloJwbwU+phw/a23KBvJIR9lWQWW7WHHK3vBdOLDNuF7TaX98GObUZOWkOnA=="], + "pure-rand": ["pure-rand@8.4.2", "", {}, "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng=="], + "radix3": ["radix3@1.1.2", "", {}, "sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA=="], "react": ["react@19.2.6", "", {}, "sha512-sfWGGfavi0xr8Pg0sVsyHMAOziVYKgPLNrS7ig+ivMNb3wbCBw3KxtflsGBAwD3gYQlE/AEZsTLgToRrSCjb0Q=="], diff --git a/package.json b/package.json index 188b149..3d57142 100644 --- a/package.json +++ b/package.json @@ -92,6 +92,7 @@ "@types/node": "^22", "@typescript/native": "npm:typescript@7.0.2", "axe-core": "^4.11.4", + "fast-check": "4.10.3", "modern-web-guidance": "^0.0.169", "oxlint": "1.94.0", "typescript": "^6.0.3" diff --git a/packages/shared/src/public-content.ts b/packages/shared/src/public-content.ts index 70c4d68..da22bd9 100644 --- a/packages/shared/src/public-content.ts +++ b/packages/shared/src/public-content.ts @@ -15,7 +15,55 @@ export type PublicOperationalContentCollection = | 'guilds' | 'projects'; -export interface PublicOperationalRecord { +// The top-level fields each collection publishes, and the only ones that reach the snapshot, +// whatever a database view or seed file adds. They match the `content.public_*` views (chapters +// also read imageAlt, imageCredit and imageFileId, which resolvePublicChapterImage consumes). +// Nested values stay guarded by containsPrivateOperationalContentField. +export const PUBLIC_OPERATIONAL_RECORD_FIELDS = Object.freeze({ + themes: Object.freeze(['id', 'name', 'slug', 'sortOrder', 'summary'] as const), + people: Object.freeze([ + 'avatar', 'bio', 'displayName', 'id', 'links', 'media', 'role', 'seo', 'slug', 'themeSlugs', + ] as const), + chapters: Object.freeze([ + 'authoredResourceSlugs', 'city', 'connectLinks', 'country', 'featuredStory', 'featuredStorySlugs', + 'featuredWeight', 'founded', 'id', 'image', 'impactSources', 'introQuote', 'introQuoteAttribution', + 'lat', 'link', 'links', 'long', 'media', 'name', 'proofSignals', 'region', 'relatedChapterSlugs', 'seo', + 'slug', 'status', 'stewardSlugs', 'stewards', 'summary', 'themeSlugs', + ] as const), + chapterInitiatives: Object.freeze([ + 'chapterSlug', 'description', 'featuredWeight', 'id', 'impactSources', 'links', 'proofSignals', + 'relatedResourceSlugs', 'relatedStorySlugs', 'slug', 'status', 'summary', 'themeSlugs', 'title', + ] as const), + guilds: Object.freeze([ + 'cadence', 'connectLinks', 'description', 'featuredWeight', 'foundedYear', 'id', 'image', 'links', + 'mandateParagraphs', 'media', 'memberSlugs', 'name', 'oneliner', 'outputs', 'principles', 'proofSignals', + 'publicMembers', 'seo', 'slug', 'status', 'stewardSlugs', 'stewards', 'summary', 'themeSlugs', 'type', + ] as const), + projects: Object.freeze([ + 'description', 'featuredWeight', 'guild', 'id', 'image', 'liveUrl', 'media', 'name', 'proofSignals', + 'repoUrl', 'seo', 'slug', 'status', 'stewardSlugs', 'summary', 'techStack', 'themeSlugs', + ] as const), +}); + +type PublicOperationalFieldOf = + (typeof PUBLIC_OPERATIONAL_RECORD_FIELDS)[C][number]; + +// A published record names only its collection's fields; a key outside the list does not type-check. +export type PublicOperationalRecordOf = { + slug: string; + id: string; +} & { [K in Exclude, 'slug' | 'id'>]?: any }; + +export type PublicThemeRecord = PublicOperationalRecordOf<'themes'>; +export type PublicPersonRecord = PublicOperationalRecordOf<'people'>; +export type PublicChapterRecord = PublicOperationalRecordOf<'chapters'>; +export type PublicChapterInitiativeRecord = PublicOperationalRecordOf<'chapterInitiatives'>; +export type PublicGuildRecord = PublicOperationalRecordOf<'guilds'>; +export type PublicProjectRecord = PublicOperationalRecordOf<'projects'>; +export type PublicOperationalRecord = PublicOperationalRecordOf; + +// A record on its way to publication: every field the source carried, until toPublicRecord. +interface OperationalRecordDraft { slug: string; id: string; [key: string]: any; @@ -41,12 +89,12 @@ export interface PublicOperationalImpactSourcePayload { export interface PublicOperationalContentSnapshot { version: 1; generatedAt: string; - themes: PublicOperationalRecord[]; - people: PublicOperationalRecord[]; - chapters: PublicOperationalRecord[]; - chapterInitiatives: PublicOperationalRecord[]; - guilds: PublicOperationalRecord[]; - projects: PublicOperationalRecord[]; + themes: PublicThemeRecord[]; + people: PublicPersonRecord[]; + chapters: PublicChapterRecord[]; + chapterInitiatives: PublicChapterInitiativeRecord[]; + guilds: PublicGuildRecord[]; + projects: PublicProjectRecord[]; locations: PublicOperationalLocation[]; impactSourceBindings: PublicOperationalImpactSourcePayload; } @@ -158,7 +206,7 @@ function stripWorkflowFields(record: UnknownRecord): UnknownRecord { return next; } -function normalizeRecord(record: UnknownRecord): PublicOperationalRecord | null { +function normalizeRecord(record: UnknownRecord): OperationalRecordDraft | null { const source = stripWorkflowFields(normalizeObject(record?.data ?? record)); const slug = normalizeSlug(record) || normalizeSlug(source); if (!slug) return null; @@ -240,7 +288,7 @@ function defaultsForCollection(collection: PublicOperationalContentCollection | function normalizeCollection( records: UnknownRecord[], collection: PublicOperationalContentCollection | '' = '' -): PublicOperationalRecord[] { +): OperationalRecordDraft[] { return asArray(records) .map(normalizeRecord) .filter(isPresent) @@ -342,8 +390,22 @@ export interface WithheldChapterImage { reason: 'unapproved_media'; } +// Keeps the collection's public fields, in the record's own order, so a regenerated snapshot +// diffs only where content changed. +function toPublicRecord( + record: OperationalRecordDraft, + collection: C +): PublicOperationalRecordOf { + const allowed = new Set(PUBLIC_OPERATIONAL_RECORD_FIELDS[collection]); + const published: UnknownRecord = {}; + for (const key of Object.keys(record)) { + if (allowed.has(key)) published[key] = record[key]; + } + return published as PublicOperationalRecordOf; +} + function quarantineUnsafeRecords( - records: ReturnType, + records: OperationalRecordDraft[], collection: string, quarantined: QuarantinedOperationalRecord[] ) { @@ -374,8 +436,8 @@ function quarantineUnsafeRecords( // describe the image the chapter shows. For a sourced image, media.imageAlt // and media.imageCredit remain the fallback. // - imageFileId: the upload's file id, which stays private. -function resolvePublicChapterImage(chapter: PublicOperationalRecord, uploadedImageUrl: string): { - chapter: PublicOperationalRecord; +function resolvePublicChapterImage(chapter: OperationalRecordDraft, uploadedImageUrl: string): { + chapter: OperationalRecordDraft; imageWithheld: boolean; } { const { @@ -430,7 +492,7 @@ function resolvePublicChapterImage(chapter: PublicOperationalRecord, uploadedIma } if (sourcedImages.length === 0 && socialImage === '') { - return { chapter: publicFields as PublicOperationalRecord, imageWithheld: false }; + return { chapter: publicFields as OperationalRecordDraft, imageWithheld: false }; } if (sourcedImageApproved) { @@ -508,35 +570,41 @@ export function toPublicOperationalContentSnapshot({ // A record cannot name its own upload; see resolvePublicChapterImage. const { uploadedImageUrl: _selfDeclaredUpload, ...record } = chapter; const resolved = resolvePublicChapterImage( - record as PublicOperationalRecord, + record as OperationalRecordDraft, toUploadedImageUrl(options.uploadedChapterImageUrls?.get(chapter.slug)) ); if (resolved.imageWithheld) chaptersWithWithheldImages.add(chapter.slug); return resolved.chapter; }); - const publicChapters = quarantineUnsafeRecords(chaptersWithPublicImages, 'chapters', quarantined); + const publicChapters = quarantineUnsafeRecords(chaptersWithPublicImages, 'chapters', quarantined) + .map((chapter) => toPublicRecord(chapter, 'chapters')); const withheldChapterImages: WithheldChapterImage[] = publicChapters .filter((chapter) => chaptersWithWithheldImages.has(chapter.slug)) .map((chapter) => ({ slug: chapter.slug, reason: 'unapproved_media' })); - const publicGuilds = quarantineUnsafeRecords(normalizeCollection(guilds, 'guilds'), 'guilds', quarantined); + const publicGuilds = quarantineUnsafeRecords(normalizeCollection(guilds, 'guilds'), 'guilds', quarantined) + .map((guild) => toPublicRecord(guild, 'guilds')); const publicGuildSlugs = new Set(publicGuilds.map((guild) => guild.slug).filter(Boolean)); const publicProjects = quarantineUnsafeRecords( normalizeCollection(projects, 'projects'), 'projects', quarantined - ).filter((project) => publicGuildSlugs.has(cleanString(project.guild ?? project.guildSlug))); + ) + .filter((project) => publicGuildSlugs.has(cleanString(project.guild ?? project.guildSlug))) + .map((project) => toPublicRecord(project, 'projects')); const snapshot: PublicOperationalContentSnapshot = { version: PUBLIC_OPERATIONAL_CONTENT_VERSION, generatedAt: toIso(generatedAt), - themes: quarantineUnsafeRecords(normalizeCollection(themes, 'themes'), 'themes', quarantined), - people: quarantineUnsafeRecords(normalizeCollection(people, 'people'), 'people', quarantined), + themes: quarantineUnsafeRecords(normalizeCollection(themes, 'themes'), 'themes', quarantined) + .map((theme) => toPublicRecord(theme, 'themes')), + people: quarantineUnsafeRecords(normalizeCollection(people, 'people'), 'people', quarantined) + .map((person) => toPublicRecord(person, 'people')), chapters: publicChapters, chapterInitiatives: quarantineUnsafeRecords( normalizeCollection(chapterInitiatives, 'chapterInitiatives'), 'chapterInitiatives', quarantined - ), + ).map((initiative) => toPublicRecord(initiative, 'chapterInitiatives')), guilds: publicGuilds, projects: publicProjects, locations: toPublicOperationalLocations(publicChapters), diff --git a/scripts/public-projection-allowlist.test.ts b/scripts/public-projection-allowlist.test.ts new file mode 100644 index 0000000..da20814 --- /dev/null +++ b/scripts/public-projection-allowlist.test.ts @@ -0,0 +1,305 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import fc from 'fast-check'; +import { + PUBLIC_OPERATIONAL_CONTENT_COLLECTIONS, + PUBLIC_OPERATIONAL_RECORD_FIELDS, + containsPrivateOperationalContentField, + toPublicOperationalContentSnapshot, + type PublicChapterRecord, + type PublicOperationalContentCollection, + type PublicPersonRecord, +} from '@greenpill-network/shared/public-content'; +import { + MAP_NODE_STATUSES, + PRIVATE_MAP_NODE_FIELDS, + PUBLIC_MAP_NODE_FIELDS, + containsPrivateMapNodeField, + toPublicMapNode, + type PublicMapNode, +} from '@greenpill-network/shared/map-nodes'; +import { + containsPrivateMapStateField, + toPublicMapStateChapterNode, + toPublicMapStateSubmittedNode, + type PublicMapStateNode, +} from '@greenpill-network/shared/map-state'; +import { + PRIVATE_CHAPTER_IMPACT_FIELDS, + containsPrivateChapterImpactField, + toPublicChapterImpactPayload, +} from '@greenpill-network/shared/chapter-impact'; +import { isPublicMapCoordinate } from '@greenpill-network/shared/map-locations'; + +// A value only ever placed in a field that must not be published. Finding it anywhere in a +// payload is a leak, whatever the key it travelled under. +const SECRET = 'SECRET-7f3a-never-public'; +const RUNS = { numRuns: 300 }; + +const committed = JSON.parse( + readFileSync(new URL('../packages/website/src/data/operational-content-snapshot.json', import.meta.url), 'utf8'), +); + +const leaks = (payload: unknown) => JSON.stringify(payload ?? null).includes(SECRET); + +const UNSAFE_OBJECT_KEYS = new Set(['__proto__', 'constructor', 'prototype']); + +// Field names drawn both from the known private lists and at random, so the properties cover +// names nobody has thought of yet. +const knownPrivateKey = fc.constantFrom( + ...PRIVATE_MAP_NODE_FIELDS, + ...PRIVATE_CHAPTER_IMPACT_FIELDS, + 'pendingSubmission', + 'pending_submission', + 'stewardNotes', + 'adminNotes', + 'ip', +); +const anyKey = fc.oneof(knownPrivateKey, fc.string({ minLength: 1, maxLength: 16 })); +const secretValue = fc.constantFrom(SECRET, { note: SECRET }, [SECRET], { nested: { deeper: SECRET } }); + +function extraFields(excluded: ReadonlySet) { + return fc.dictionary( + anyKey.filter((key) => !excluded.has(key) && !UNSAFE_OBJECT_KEYS.has(key)), + secretValue, + { maxKeys: 6 }, + ); +} + +// Inputs an operational record reads besides its published fields: the snapshot's own controls +// and the chapter image fields resolvePublicChapterImage turns into published alt text and credit. +const OPERATIONAL_CONTROL_KEYS = ['data', 'publicationStatus', 'publication_status', 'imageAlt', 'imageCredit']; + +function publish(collection: PublicOperationalContentCollection, records: Record[]) { + return toPublicOperationalContentSnapshot( + { + // Projects are published only under a published guild. + guilds: collection === 'guilds' ? records : committed.guilds, + [collection]: records, + generatedAt: committed.generatedAt, + }, + { onQuarantine: () => {}, onChapterImagesWithheld: () => {} }, + ); +} + +for (const collection of PUBLIC_OPERATIONAL_CONTENT_COLLECTIONS) { + const allowed = new Set(PUBLIC_OPERATIONAL_RECORD_FIELDS[collection]); + + test(`a ${collection} record publishes only its allowlisted fields, and extra fields change nothing`, () => { + fc.assert( + fc.property( + fc.constantFrom(...committed[collection]), + extraFields(new Set([...allowed, ...OPERATIONAL_CONTROL_KEYS])), + (base: Record, extras) => { + const baseline = publish(collection, [base])[collection]; + const snapshot = publish(collection, [{ ...base, ...extras }]); + assert.ok(!leaks(snapshot), 'a value from a field outside the allowlist was published'); + const published = snapshot[collection]; + if (containsPrivateOperationalContentField(extras)) { + // A private-looking field quarantines the record rather than publish around it. + assert.equal(published.length, 0); + return; + } + assert.deepEqual(published, baseline); + for (const record of published) { + for (const key of Object.keys(record)) assert.ok(allowed.has(key), `${collection} published ${key}`); + } + }, + ), + RUNS, + ); + }); + + test(`a private field nested inside a published ${collection} value is never published`, () => { + const objectFields = [...allowed].filter((field) => + committed[collection].some((record: Record) => { + const value = record[field]; + return value !== null && typeof value === 'object' && !Array.isArray(value); + }), + ); + if (objectFields.length === 0) return; + fc.assert( + fc.property( + fc.constantFrom(...committed[collection]), + fc.constantFrom(...objectFields), + knownPrivateKey, + (base: Record, field, key) => { + const record = { ...base, [field]: { ...(base[field] as object), [key]: SECRET } }; + const snapshot = publish(collection, [record]); + // The record is quarantined, or the field that held the value is withheld whole (an + // unreviewed chapter image's media); either way nothing private is published. + assert.ok(!leaks(snapshot)); + assert.ok(!containsPrivateOperationalContentField(snapshot[collection])); + }, + ), + RUNS, + ); + }); +} + +const publicText = fc.string({ maxLength: 24 }); +const publicCoordinate = fc + .record({ lat: fc.double({ min: -85, max: 85, noNaN: true }), long: fc.double({ min: -179, max: 179, noNaN: true }) }) + .filter(({ lat, long }) => isPublicMapCoordinate(lat, long)); + +// Every field toPublicMapNode and toPublicMapStateSubmittedNode read; nothing else can reach them. +const MAP_NODE_INPUT_KEYS = new Set([ + ...PUBLIC_MAP_NODE_FIELDS, + 'displayName', + 'placeName', + 'intent', + 'chapter_slug', + 'profile_url', + 'type', + 'nodeType', + 'href', +]); + +const submission = fc + .record({ + id: fc.uuid(), + name: publicText, + place: publicText, + city: publicText, + region: publicText, + country: publicText, + role: publicText, + publicNote: publicText, + themes: fc.array(publicText, { maxLength: 3 }), + coordinate: publicCoordinate, + privateFields: fc.subarray([...PRIVATE_MAP_NODE_FIELDS]), + extras: extraFields(MAP_NODE_INPUT_KEYS), + }) + .map(({ coordinate, privateFields, extras, ...fields }) => ({ + ...fields, + ...coordinate, + ...Object.fromEntries(privateFields.map((field) => [field, SECRET])), + ...extras, + })); + +test('an approved map node publishes only its public fields, never a private one', () => { + fc.assert( + fc.property(submission, (input) => { + const node = toPublicMapNode({ ...input, status: 'approved' }); + assert.ok(node, 'an approved node at a public coordinate is published'); + assert.ok(!leaks(node)); + assert.ok(!containsPrivateMapNodeField(node)); + for (const key of Object.keys(node)) assert.ok(PUBLIC_MAP_NODE_FIELDS.includes(key), key); + }), + RUNS, + ); +}); + +test('a pending, rejected or archived submission is never published', () => { + const unpublished = MAP_NODE_STATUSES.filter((status) => status !== 'approved'); + fc.assert( + fc.property(submission, fc.constantFrom(...unpublished, undefined, ''), (input, status) => { + assert.equal(toPublicMapNode({ ...input, status }), null); + assert.equal(toPublicMapStateSubmittedNode({ ...input, status }), null); + }), + RUNS, + ); +}); + +test('map state nodes carry no private field or value', () => { + const CHAPTER_INPUT_KEYS = new Set([ + 'lat', + 'latitude', + 'long', + 'lng', + 'longitude', + 'slug', + 'id', + 'name', + 'themes', + 'themeSlugs', + 'place', + 'city', + 'region', + 'country', + 'href', + 'link', + 'status', + ]); + const chapterLocation = fc + .record({ + slug: fc.stringMatching(/^[a-z][a-z0-9-]{0,15}$/), + name: publicText.filter((name) => name.trim() !== ''), + city: publicText, + country: publicText, + themeSlugs: fc.array(publicText, { maxLength: 3 }), + coordinate: publicCoordinate, + extras: extraFields(CHAPTER_INPUT_KEYS), + }) + .map(({ coordinate, extras, ...fields }) => ({ ...fields, ...coordinate, ...extras })); + fc.assert( + fc.property(submission, chapterLocation, (input, location) => { + for (const node of [ + toPublicMapStateSubmittedNode({ ...input, status: 'approved' }), + toPublicMapStateChapterNode(location), + ]) { + assert.ok(node); + assert.ok(!leaks(node)); + assert.ok(!containsPrivateMapStateField(node)); + } + }), + RUNS, + ); +}); + +test('raw upstream impact feedback, media and private notes never reach the impact payload', () => { + const withPrivate = (keys: string[]) => Object.fromEntries(keys.map((key) => [key, SECRET])); + const privateKeys = fc.subarray([...PRIVATE_CHAPTER_IMPACT_FIELDS], { minLength: 1 }); + fc.assert( + fc.property(privateKeys, privateKeys, privateKeys, privateKeys, (top, project, milestone, garden) => { + const payload = toPublicChapterImpactPayload({ + chapterSlug: 'test-chapter', + chapterName: 'Test chapter', + sources: { + impactEnabled: true, + karmaProjectUID: '0xproject', + greenGoodsGardenAddress: '0x0000000000000000000000000000000000000001', + ...withPrivate(top), + }, + karma: { + ...withPrivate(top), + project: { + uid: '0xproject', + slug: 'project', + title: 'Project', + url: 'https://gap.karmahq.xyz/project/project', + ...withPrivate(project), + }, + milestones: [{ uid: 'm1', title: 'Milestone', url: 'https://gap.karmahq.xyz/m1', ...withPrivate(milestone) }], + }, + greenGoods: { + ...withPrivate(top), + garden: { + address: '0x0000000000000000000000000000000000000001', + chainId: 42161, + name: 'Garden', + ...withPrivate(garden), + }, + }, + generatedAt: '2026-11-21T00:00:00.000Z', + }); + assert.ok(!leaks(payload)); + assert.ok(!containsPrivateChapterImpactField(payload)); + }), + RUNS, + ); +}); + +test('public payload types name their fields, so a private field does not type-check', () => { + const chapter: PublicChapterRecord = { slug: 'a', id: 'a', name: 'A' }; + // @ts-expect-error a published chapter has no email + const emailed: PublicChapterRecord = { slug: 'a', id: 'a', email: 'x@example.org' }; + // @ts-expect-error a published person has no raw note + const noted: PublicPersonRecord = { slug: 'a', id: 'a', rawNote: 'x' }; + // @ts-expect-error a public map node has no pending submission + const pending: Partial = { id: 'a', pendingRevision: {} }; + // @ts-expect-error a map state node has no review notes + const reviewed: Partial = { id: 'a', reviewNotes: 'x' }; + assert.ok(chapter && emailed && noted && pending && reviewed); +}); From 3112d448bba4d4808da28d64e3f84ed1c1a4cabd Mon Sep 17 00:00:00 2001 From: Afolabi <35589781+Oba-One@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:57:56 -0800 Subject: [PATCH 2/5] Public projections: catch known private names nested in operational records The fast-check properties found private values that the operational scan let through when nested inside a published object: media.request_metadata, featuredStory.request_ip, media.consumed_at, impactSources.mediaUrls, cadence.works. The scan now also matches, exactly, the private names the map node and impact contracts list (impact's media aside, a public operational field), plus a steward-note pattern. No key in the committed snapshot or the seed files matches the new names. The test model now expects workflow fields (reviewedBy and the like) to be stripped rather than quarantined, keeps media and media.reviewStatus as public operational names, and gives each property a 60 s limit so a loaded machine cannot fail it on time. Co-Authored-By: Claude Opus 5.5 Agent-Model: claude-opus-5-5/high --- packages/shared/src/public-content.ts | 15 +++++++++++ scripts/public-projection-allowlist.test.ts | 30 +++++++++++++++++---- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/packages/shared/src/public-content.ts b/packages/shared/src/public-content.ts index da22bd9..e80c97d 100644 --- a/packages/shared/src/public-content.ts +++ b/packages/shared/src/public-content.ts @@ -1,7 +1,9 @@ import { CHAPTER_IMPACT_SOURCES_VERSION, + PRIVATE_CHAPTER_IMPACT_FIELDS, normalizeImpactSources, } from './chapter-impact.js'; +import { PRIVATE_MAP_NODE_FIELDS } from './map-nodes.js'; import type { PublicImpactSourceBinding } from './chapter-impact.js'; import { isPublicMapCoordinate, parseMapCoordinate } from './map-locations.js'; @@ -133,6 +135,7 @@ const PRIVATE_OPERATIONAL_CONTENT_FIELD_PATTERNS = Object.freeze([ 'pending', 'admin', 'decodeddatajson', + 'stewardnote', ]); const PRIVATE_OPERATIONAL_CONTENT_EXACT_FIELD_KEYS = Object.freeze([ @@ -145,6 +148,17 @@ const PUBLIC_OPERATIONAL_CONTENT_EXACT_FIELD_KEY_ALLOWLIST = Object.freeze([ 'reviewstatus', ]); +const normalizeFieldKeyName = (key: string): string => key.trim().toLowerCase().replace(/[^a-z0-9]/g, ''); + +// The private names the map node and impact contracts already know (a request IP, an edit token, +// upstream work feedback), matched exactly so a nested value under one is caught here too. The +// impact list's `media` is left out: it is a public operational field. +const PRIVATE_OPERATIONAL_CONTENT_KNOWN_FIELD_KEYS: ReadonlySet = new Set( + [...PRIVATE_MAP_NODE_FIELDS, ...PRIVATE_CHAPTER_IMPACT_FIELDS.filter((field) => field !== 'media')].map( + normalizeFieldKeyName, + ), +); + const WORKFLOW_FIELDS = Object.freeze([ 'publicationStatus', 'publication_status', @@ -641,6 +655,7 @@ export function containsPrivateOperationalContentField(value: unknown, seen: Set !PUBLIC_OPERATIONAL_CONTENT_EXACT_FIELD_KEY_ALLOWLIST.includes(normalizedKey) && ( PRIVATE_OPERATIONAL_CONTENT_EXACT_FIELD_KEYS.includes(normalizedKey) || + PRIVATE_OPERATIONAL_CONTENT_KNOWN_FIELD_KEYS.has(normalizedKey) || PRIVATE_OPERATIONAL_CONTENT_FIELD_PATTERNS.some((pattern) => normalizedKey.includes(pattern)) ) ) { diff --git a/scripts/public-projection-allowlist.test.ts b/scripts/public-projection-allowlist.test.ts index da20814..a4239c5 100644 --- a/scripts/public-projection-allowlist.test.ts +++ b/scripts/public-projection-allowlist.test.ts @@ -36,6 +36,8 @@ import { isPublicMapCoordinate } from '@greenpill-network/shared/map-locations'; // payload is a leak, whatever the key it travelled under. const SECRET = 'SECRET-7f3a-never-public'; const RUNS = { numRuns: 300 }; +// Each run builds whole snapshots; a loaded machine must not fail a property on time alone. +const SLOW = { timeout: 60_000 }; const committed = JSON.parse( readFileSync(new URL('../packages/website/src/data/operational-content-snapshot.json', import.meta.url), 'utf8'), @@ -67,6 +69,19 @@ function extraFields(excluded: ReadonlySet) { ); } +// Workflow fields the snapshot strips before it checks a record for private fields: they are +// dropped, not quarantined. +const OPERATIONAL_WORKFLOW_KEYS = new Set([ + 'reviewedAt', + 'reviewed_at', + 'reviewedBy', + 'reviewed_by', + 'createdBy', + 'created_by', + 'updatedBy', + 'updated_by', +]); + // Inputs an operational record reads besides its published fields: the snapshot's own controls // and the chapter image fields resolvePublicChapterImage turns into published alt text and credit. const OPERATIONAL_CONTROL_KEYS = ['data', 'publicationStatus', 'publication_status', 'imageAlt', 'imageCredit']; @@ -86,7 +101,7 @@ function publish(collection: PublicOperationalContentCollection, records: Record for (const collection of PUBLIC_OPERATIONAL_CONTENT_COLLECTIONS) { const allowed = new Set(PUBLIC_OPERATIONAL_RECORD_FIELDS[collection]); - test(`a ${collection} record publishes only its allowlisted fields, and extra fields change nothing`, () => { + test(`a ${collection} record publishes only its allowlisted fields, and extra fields change nothing`, SLOW, () => { fc.assert( fc.property( fc.constantFrom(...committed[collection]), @@ -96,7 +111,10 @@ for (const collection of PUBLIC_OPERATIONAL_CONTENT_COLLECTIONS) { const snapshot = publish(collection, [{ ...base, ...extras }]); assert.ok(!leaks(snapshot), 'a value from a field outside the allowlist was published'); const published = snapshot[collection]; - if (containsPrivateOperationalContentField(extras)) { + const checked = Object.fromEntries( + Object.entries(extras).filter(([key]) => !OPERATIONAL_WORKFLOW_KEYS.has(key)), + ); + if (containsPrivateOperationalContentField(checked)) { // A private-looking field quarantines the record rather than publish around it. assert.equal(published.length, 0); return; @@ -111,7 +129,7 @@ for (const collection of PUBLIC_OPERATIONAL_CONTENT_COLLECTIONS) { ); }); - test(`a private field nested inside a published ${collection} value is never published`, () => { + test(`a private field nested inside a published ${collection} value is never published`, SLOW, () => { const objectFields = [...allowed].filter((field) => committed[collection].some((record: Record) => { const value = record[field]; @@ -123,7 +141,9 @@ for (const collection of PUBLIC_OPERATIONAL_CONTENT_COLLECTIONS) { fc.property( fc.constantFrom(...committed[collection]), fc.constantFrom(...objectFields), - knownPrivateKey, + // Private elsewhere but public here: an operational record's `media`, and its media's + // `reviewStatus`, which says whether the image may be shown. + knownPrivateKey.filter((key) => !['media', 'reviewStatus', 'review_status'].includes(key)), (base: Record, field, key) => { const record = { ...base, [field]: { ...(base[field] as object), [key]: SECRET } }; const snapshot = publish(collection, [record]); @@ -202,7 +222,7 @@ test('a pending, rejected or archived submission is never published', () => { ); }); -test('map state nodes carry no private field or value', () => { +test('map state nodes carry no private field or value', SLOW, () => { const CHAPTER_INPUT_KEYS = new Set([ 'lat', 'latitude', From 503620d1abc9bbe5cae03f03f3b6d815509e83a4 Mon Sep 17 00:00:00 2001 From: Afolabi <35589781+Oba-One@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:13:21 -0800 Subject: [PATCH 3/5] Public projections: fuzz arrays of objects too, check key order, one key normalizer From the adversarial review of PR 85 at 3112d44 (all non-blocking): - the nested property also plants private fields inside arrays of objects (links, stewards, proof signals, public members), and asserts that themes is the only collection with nothing nested rather than skipping silently - the extras property checks that published key order matches the record's - the duplicate key normalizer is gone; the comment on the known private names says generic ones fail closed and raise the quarantine alert Co-Authored-By: Claude Opus 5.5 Agent-Model: claude-opus-5-5/high --- packages/shared/src/public-content.ts | 11 ++++++----- scripts/public-projection-allowlist.test.ts | 19 ++++++++++++++++--- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/packages/shared/src/public-content.ts b/packages/shared/src/public-content.ts index e80c97d..e047e0d 100644 --- a/packages/shared/src/public-content.ts +++ b/packages/shared/src/public-content.ts @@ -148,14 +148,17 @@ const PUBLIC_OPERATIONAL_CONTENT_EXACT_FIELD_KEY_ALLOWLIST = Object.freeze([ 'reviewstatus', ]); -const normalizeFieldKeyName = (key: string): string => key.trim().toLowerCase().replace(/[^a-z0-9]/g, ''); +const cleanString = (value: unknown): string => (typeof value === 'string' ? value.trim() : ''); +const normalizeFieldKey = (key: unknown): string => cleanString(key).toLowerCase().replace(/[^a-z0-9]/g, ''); // The private names the map node and impact contracts already know (a request IP, an edit token, // upstream work feedback), matched exactly so a nested value under one is caught here too. The -// impact list's `media` is left out: it is a public operational field. +// impact list's `media` is left out: it is a public operational field. Some names are generic +// (`token`, `works`, `mediaUrls`): content that uses one is quarantined, which fails closed and +// raises the quarantine alert, so rename the field rather than drop the name from this list. const PRIVATE_OPERATIONAL_CONTENT_KNOWN_FIELD_KEYS: ReadonlySet = new Set( [...PRIVATE_MAP_NODE_FIELDS, ...PRIVATE_CHAPTER_IMPACT_FIELDS.filter((field) => field !== 'media')].map( - normalizeFieldKeyName, + normalizeFieldKey, ), ); @@ -172,8 +175,6 @@ const WORKFLOW_FIELDS = Object.freeze([ 'updated_by', ]); -const cleanString = (value: unknown): string => (typeof value === 'string' ? value.trim() : ''); -const normalizeFieldKey = (key: unknown): string => cleanString(key).toLowerCase().replace(/[^a-z0-9]/g, ''); const isPresent = (value: T | null | undefined): value is T => value !== null && value !== undefined; const toIso = (value: Date | string | null | undefined): string => { diff --git a/scripts/public-projection-allowlist.test.ts b/scripts/public-projection-allowlist.test.ts index a4239c5..99c12e3 100644 --- a/scripts/public-projection-allowlist.test.ts +++ b/scripts/public-projection-allowlist.test.ts @@ -120,6 +120,8 @@ for (const collection of PUBLIC_OPERATIONAL_CONTENT_COLLECTIONS) { return; } assert.deepEqual(published, baseline); + // The pick keeps the record's own key order, so a regenerated snapshot does not churn. + assert.deepEqual(published.map(Object.keys), baseline.map(Object.keys)); for (const record of published) { for (const key of Object.keys(record)) assert.ok(allowed.has(key), `${collection} published ${key}`); } @@ -130,13 +132,20 @@ for (const collection of PUBLIC_OPERATIONAL_CONTENT_COLLECTIONS) { }); test(`a private field nested inside a published ${collection} value is never published`, SLOW, () => { + // Object values and arrays of objects (links, stewards, proof signals, public members). + const isObject = (value: unknown) => value !== null && typeof value === 'object' && !Array.isArray(value); const objectFields = [...allowed].filter((field) => committed[collection].some((record: Record) => { const value = record[field]; - return value !== null && typeof value === 'object' && !Array.isArray(value); + return isObject(value) || (Array.isArray(value) && value.some(isObject)); }), ); - if (objectFields.length === 0) return; + // Themes hold no object values, so there is nothing nested to plant a field in. + if (collection === 'themes') { + assert.deepEqual(objectFields, []); + return; + } + assert.ok(objectFields.length > 0); fc.assert( fc.property( fc.constantFrom(...committed[collection]), @@ -145,7 +154,11 @@ for (const collection of PUBLIC_OPERATIONAL_CONTENT_COLLECTIONS) { // `reviewStatus`, which says whether the image may be shown. knownPrivateKey.filter((key) => !['media', 'reviewStatus', 'review_status'].includes(key)), (base: Record, field, key) => { - const record = { ...base, [field]: { ...(base[field] as object), [key]: SECRET } }; + const value = base[field]; + const planted = Array.isArray(value) + ? [{ ...(value.find(isObject) ?? {}), [key]: SECRET }, ...value] + : { ...(isObject(value) ? (value as object) : {}), [key]: SECRET }; + const record = { ...base, [field]: planted }; const snapshot = publish(collection, [record]); // The record is quarantined, or the field that held the value is withheld whole (an // unreviewed chapter image's media); either way nothing private is published. From b52f8c9373ee1b5dc8df2437253cc45722cf6efe Mon Sep 17 00:00:00 2001 From: Afolabi <35589781+Oba-One@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:27:32 -0800 Subject: [PATCH 4/5] Public projections: build map locations from the checked chapters, before the pick From Codex on PR 85: toPublicOperationalLocations accepts latitude and longitude aliases, but the pick removed them before the locations were built, so such a chapter would have left /locations.json. Locations and impact bindings build explicit payloads, so they now read the records that passed the quarantine check; the published chapter still carries only its listed fields. A test covers the alias case and fails without this change. Co-Authored-By: Claude Opus 5.5 Agent-Model: claude-opus-5-5/high --- packages/shared/src/public-content.ts | 10 ++++++---- scripts/public-projection-allowlist.test.ts | 9 +++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/packages/shared/src/public-content.ts b/packages/shared/src/public-content.ts index e047e0d..b2eba73 100644 --- a/packages/shared/src/public-content.ts +++ b/packages/shared/src/public-content.ts @@ -592,8 +592,10 @@ export function toPublicOperationalContentSnapshot({ return resolved.chapter; }); - const publicChapters = quarantineUnsafeRecords(chaptersWithPublicImages, 'chapters', quarantined) - .map((chapter) => toPublicRecord(chapter, 'chapters')); + // Locations and impact bindings build their own explicit payloads, so they read the checked + // records before the pick and keep accepting coordinate aliases such as latitude and longitude. + const checkedChapters = quarantineUnsafeRecords(chaptersWithPublicImages, 'chapters', quarantined); + const publicChapters = checkedChapters.map((chapter) => toPublicRecord(chapter, 'chapters')); const withheldChapterImages: WithheldChapterImage[] = publicChapters .filter((chapter) => chaptersWithWithheldImages.has(chapter.slug)) .map((chapter) => ({ slug: chapter.slug, reason: 'unapproved_media' })); @@ -622,8 +624,8 @@ export function toPublicOperationalContentSnapshot({ ).map((initiative) => toPublicRecord(initiative, 'chapterInitiatives')), guilds: publicGuilds, projects: publicProjects, - locations: toPublicOperationalLocations(publicChapters), - impactSourceBindings: toPublicOperationalImpactSourceBindings(publicChapters, generatedAt), + locations: toPublicOperationalLocations(checkedChapters), + impactSourceBindings: toPublicOperationalImpactSourceBindings(checkedChapters, generatedAt), }; if (quarantined.length > 0) { diff --git a/scripts/public-projection-allowlist.test.ts b/scripts/public-projection-allowlist.test.ts index 99c12e3..edb98c3 100644 --- a/scripts/public-projection-allowlist.test.ts +++ b/scripts/public-projection-allowlist.test.ts @@ -171,6 +171,15 @@ for (const collection of PUBLIC_OPERATIONAL_CONTENT_COLLECTIONS) { }); } +test('a chapter that gives its point as latitude and longitude still gets a map location', () => { + const base = committed.chapters.find((chapter: Record) => chapter.lat && !chapter.seo?.noindex); + const { lat, long, ...rest } = base; + const snapshot = publish('chapters', [{ ...rest, latitude: lat, longitude: long }]); + const location = snapshot.locations.find((entry) => entry.id === base.slug); + assert.deepEqual(location && { lat: location.lat, long: location.long }, { lat, long }); + assert.ok(!('latitude' in snapshot.chapters[0]), 'the alias itself is not a published field'); +}); + const publicText = fc.string({ maxLength: 24 }); const publicCoordinate = fc .record({ lat: fc.double({ min: -85, max: 85, noNaN: true }), long: fc.double({ min: -179, max: 179, noNaN: true }) }) From f7cc40d4cd4c8285f5056ebcab90a1069b37a35c Mon Sep 17 00:00:00 2001 From: Afolabi <35589781+Oba-One@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:36:04 -0800 Subject: [PATCH 5/5] Public projections: type the alias test's chapter lookup CI typecheck at b52f8c9: seo on a Record is unknown. Co-Authored-By: Claude Opus 5.5 Agent-Model: claude-opus-5-5/high --- scripts/public-projection-allowlist.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/public-projection-allowlist.test.ts b/scripts/public-projection-allowlist.test.ts index edb98c3..65c6027 100644 --- a/scripts/public-projection-allowlist.test.ts +++ b/scripts/public-projection-allowlist.test.ts @@ -172,7 +172,7 @@ for (const collection of PUBLIC_OPERATIONAL_CONTENT_COLLECTIONS) { } test('a chapter that gives its point as latitude and longitude still gets a map location', () => { - const base = committed.chapters.find((chapter: Record) => chapter.lat && !chapter.seo?.noindex); + const base = committed.chapters.find((chapter: Record) => chapter.lat && !chapter.seo?.noindex); const { lat, long, ...rest } = base; const snapshot = publish('chapters', [{ ...rest, latitude: lat, longitude: long }]); const location = snapshot.locations.find((entry) => entry.id === base.slug);