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..b2eba73 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'; @@ -15,7 +17,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 +91,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; } @@ -85,6 +135,7 @@ const PRIVATE_OPERATIONAL_CONTENT_FIELD_PATTERNS = Object.freeze([ 'pending', 'admin', 'decodeddatajson', + 'stewardnote', ]); const PRIVATE_OPERATIONAL_CONTENT_EXACT_FIELD_KEYS = Object.freeze([ @@ -97,6 +148,20 @@ const PUBLIC_OPERATIONAL_CONTENT_EXACT_FIELD_KEY_ALLOWLIST = Object.freeze([ 'reviewstatus', ]); +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. 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( + normalizeFieldKey, + ), +); + const WORKFLOW_FIELDS = Object.freeze([ 'publicationStatus', 'publication_status', @@ -110,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 => { @@ -158,7 +221,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 +303,7 @@ function defaultsForCollection(collection: PublicOperationalContentCollection | function normalizeCollection( records: UnknownRecord[], collection: PublicOperationalContentCollection | '' = '' -): PublicOperationalRecord[] { +): OperationalRecordDraft[] { return asArray(records) .map(normalizeRecord) .filter(isPresent) @@ -342,8 +405,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 +451,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 +507,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,39 +585,47 @@ 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); + // 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' })); - 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), - impactSourceBindings: toPublicOperationalImpactSourceBindings(publicChapters, generatedAt), + locations: toPublicOperationalLocations(checkedChapters), + impactSourceBindings: toPublicOperationalImpactSourceBindings(checkedChapters, generatedAt), }; if (quarantined.length > 0) { @@ -573,6 +658,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 new file mode 100644 index 0000000..65c6027 --- /dev/null +++ b/scripts/public-projection-allowlist.test.ts @@ -0,0 +1,347 @@ +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 }; +// 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'), +); + +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 }, + ); +} + +// 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']; + +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`, SLOW, () => { + 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]; + 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; + } + 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}`); + } + }, + ), + RUNS, + ); + }); + + 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 isObject(value) || (Array.isArray(value) && value.some(isObject)); + }), + ); + // 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]), + fc.constantFrom(...objectFields), + // 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 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. + assert.ok(!leaks(snapshot)); + assert.ok(!containsPrivateOperationalContentField(snapshot[collection])); + }, + ), + RUNS, + ); + }); +} + +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 }) }) + .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', SLOW, () => { + 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); +});