Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
5 changes: 5 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
"@types/node": "^22",
"@typescript/native": "npm:typescript@7.0.2",
"axe-core": "^4.11.4",
"fast-check": "4.10.3",
Comment thread
Oba-One marked this conversation as resolved.
Resolved
"modern-web-guidance": "^0.0.169",
"oxlint": "1.94.0",
"typescript": "^6.0.3"
Expand Down
134 changes: 110 additions & 24 deletions packages/shared/src/public-content.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -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<C extends PublicOperationalContentCollection> =
(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<C extends PublicOperationalContentCollection> = {
slug: string;
id: string;
} & { [K in Exclude<PublicOperationalFieldOf<C>, '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<PublicOperationalContentCollection>;

// A record on its way to publication: every field the source carried, until toPublicRecord.
interface OperationalRecordDraft {
slug: string;
id: string;
[key: string]: any;
Expand All @@ -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;
}
Expand Down Expand Up @@ -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([
Expand All @@ -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<string> = new Set(
[...PRIVATE_MAP_NODE_FIELDS, ...PRIVATE_CHAPTER_IMPACT_FIELDS.filter((field) => field !== 'media')].map(
normalizeFieldKey,
),
);

const WORKFLOW_FIELDS = Object.freeze([
'publicationStatus',
'publication_status',
Expand All @@ -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 = <T>(value: T | null | undefined): value is T => value !== null && value !== undefined;

const toIso = (value: Date | string | null | undefined): string => {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -240,7 +303,7 @@ function defaultsForCollection(collection: PublicOperationalContentCollection |
function normalizeCollection(
records: UnknownRecord[],
collection: PublicOperationalContentCollection | '' = ''
): PublicOperationalRecord[] {
): OperationalRecordDraft[] {
return asArray(records)
.map(normalizeRecord)
.filter(isPresent)
Expand Down Expand Up @@ -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<C extends PublicOperationalContentCollection>(
record: OperationalRecordDraft,
collection: C
): PublicOperationalRecordOf<C> {
const allowed = new Set<string>(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<C>;
}

function quarantineUnsafeRecords(
records: ReturnType<typeof normalizeCollection>,
records: OperationalRecordDraft[],
collection: string,
quarantined: QuarantinedOperationalRecord[]
) {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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))
)
) {
Expand Down
Loading
Loading