Repository navigation
feat(events): public event submissions, screening pipeline & write-guard plugin - #625
Merged
Merged
Conversation
…urced listings Events can now exist without a manager in two pre-adoption stages: 'unverified' (imported or user-submitted, published and badged client-side) and 'denied' (community-rejected via registrant votes, unpublished). Assigning a manager and saving adopts the event into the normal verification cycle; grooming edits without a manager change nothing (verifyOnSave skips). - manager is now conditionally required: every ladder stage implies one; unverified/denied/finished may be unmanaged (the stale sweep finishes run-out events that were never adopted) - new columns: confidenceScore (indexed Wilson lower bound for feed ranking) and systemMeta (namespaced JSON for system-managed metadata, starting with communityFeedback vote tallies); submitter relationship -> users - ExpireEvents gains two stage-independent sweeps: finish elapsed unverified/denied events (they carry nextCheckAt: null and are invisible to the due sweep), and trash finished events 6+ months past schedule end - Atlas sidebar surfaces managerless unverified/denied events from the manager's owned-region subtree so they can be found and adopted - admin: verification notice banners + off-ladder stage tracker steps for both new stages; quality checks run on published unverified events and report a dedicated 'denied' skip reason; events capped at 7 images Part 1 of the unverified-events plan (submissions collection and registrant voting follow in separate PRs). Co-Authored-By: Claude Fable 5 <[email protected]>
…project-wide write guard Community members can now submit new events and propose updates to existing ones through the Atlas widget, via the built-in create endpoint of a new event-submissions collection. Nothing anonymous mutates a live listing: submissions are screened asynchronously, then reviewed by a manager whose Accept creates the event (published + unverified) or applies the proposed patch, via admin buttons or a signed one-click email link. - writeGuard plugin: per-collection anti-spam policy on client-originated writes (x-turnstile-token header verification, URL-in-text scan, mailchecker disposable-email list); contactAdmin refactored onto the same helpers; registerForEvent inherits coverage through its internal writes - event-submissions collection: proposed-field subset (no title - accepted events keep or auto-fill theirs), controlled region targeting (existing country/state or city/venue anchor; only cities are auto-created, via the existing Mapbox geocoder), submitter upsert into users, status workflow screening | pending | spam | created | updated | rejected - ScreenEventSubmissions job (queued per submission + 15-min autoRun net): MX lookup (fail-open) + disposable re-check -> spam kept silently, else region resolution + review email to the responsible manager (event manager, nearest region manager, or the system contact) - accept/reject lifecycle op shared by the admin Accept/Reject buttons (replacing Save on open submissions) and the tokenized /submissions/review page (generic HMAC signed-token helper; mutation only on explicit POST) - access: new RESTRICTED_COLLECTIONS rule - users and event-submissions no longer ride the shared implicit-read path (closes a pre-existing hole where any published client key could read registrant names/emails); atlas-manager gains explicit read grants, sahaj-atlas-client gains create-only on event-submissions Co-Authored-By: Claude Fable 5 <[email protected]>
|
🚅 Deployed to the SahajCloud-pr-625 environment in sahajcloud
|
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-625
August 12, 2026 03:37
Destroyed
…nt spec mailchecker's disposable-domain list happens to include allowed.org, so the write-guard now (correctly) rejects the register fixture's email. The test is about origins, not email screening — switch to example.com. Co-Authored-By: Claude Fable 5 <[email protected]>
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-625
August 12, 2026 04:02
Destroyed
This was referenced Aug 12, 2026
…At watermark The two standalone sweeps added for the pre-adoption stages both led with `schedule.lastDate < now`, which matches every event that ever ended - permanently, and with no composite index on verification_stage. That degrades as the table grows, which country-batch imports will do quickly. nextCheckAt doesn't have that shape: it's a watermark, so only genuinely actionable rows ever sit in the past. Expressing the remaining transitions there returns the job to a single, permanently cheap due-query. - new resolveNextCheckAt() is the one place each stage's watermark is defined: schedule end for unverified/denied, min(stage deadline, schedule end) for the ladder, schedule end + 6 months for finished. Every writer routes through it (verify op, verifyOnSave, the job, the importer, the new hook) - stageMachine becomes a discriminated union (remind | trash | await-schedule) inside an exhaustive Record<VerificationStage, StageRule>, so a new stage can't be added without deciding what the job does with it. No FSM library: the state is one enum column transitioned by a nightly batch, and the graph projections we rely on (daysUntilUnpublish, the admin timeline) aren't something a library would cover - finished stops being a null-watermark dead end and becomes a dwell state with a retention deadline; finishesOnRunOut: false keeps a due finished event from re-finishing itself and deferring retention forever - new syncUnmanagedCheckAt hook arms the watermark on write for pre-adoption events (deliberately ignoring skipVerifyHook - it's derived data, and both paths that create unverified events set that flag) - a managed event whose schedule runs out is now finished the day after its last occurrence rather than up to a cadence later; the admin timeline gained a matching case so a capped watermark isn't mislabelled as a reminder date - scripts/backfill-finished-retention.ts arms pre-existing finished rows (dry-run clean against dev: 68 rows, 0 failures) Co-Authored-By: Claude Fable 5 <[email protected]>
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-625
August 12, 2026 19:08
Destroyed
… watermark module Three review follow-ups on the watermark refactor, all structural: - verifyOnSave + syncUnmanagedCheckAt collapse into syncVerificationOnSave. They were two branches of one question (what should this save do to the verification fields?), mutually exclusive by construction, and each carried its own copy of the schedule merge. The skipVerifyHook asymmetry between them — the verify branch honours it, the derived-watermark branch must not — is now a documented ordering inside one function rather than an invariant split across two files. - StageRule/finishesOnRunOut is gone; MACHINE is Record<VerificationStage, StageAction>. The flag encoded a tautology — finishing is a transition *into* `finished`, so it cannot apply to an event already there — which reads better as a guard at the one call site than as a field repeated across eight rows. The invariant it protected is covered end-to-end by the retention case in the int spec. - The watermark rule moves out of periods.ts into its own watermark.ts. periods.ts is cadence helpers; the watermark rule is the load-bearing contract behind the job's single query, and had turned its host into a grab bag. Also fixes a pre-existing flake in the listing-progress tests (1 of 4 runs): remindOnce took the first email sent to the manager address that every event in the spec shares, so a second reminder landing in the same job run could be asserted against by mistake. It now selects by event title — three consecutive clean runs after the change. src/lib/eventVerification stays in lib, deliberately: ten distinct owners import from it (the Events and Registrations collections, the job, three admin components, seeds, app routes, two lib folders), so co-locating it under Events would force cross-owner imports into a collection's internals — the arrangement .claude/rules/project-structure.md rule 4 prohibits. Co-Authored-By: Claude Fable 5 <[email protected]>
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-625
August 13, 2026 02:18
Destroyed
Admin-panel layout only — no schema change (tabs and collapsibles carry no `name`, so `migrate:create` generates nothing). - confidenceScore: was hidden, now a labelled read-only field in the Verification tab, shown only while `unverified` — the one stage where votes are still being collected, so anywhere else the number is a stale artefact - publicUrlFields now always wraps its fields in a collapsed 'Public Links' collapsible (Events, Regions, Pages), and takes hasAppUrl to omit appUrl entirely rather than emit a field that can only read null. Events opts out and moves the group into its Details tab - legacyMigrationFields collapsible starts collapsed - new collapsed 'System' collapsible gathers every machine-managed value that was previously hidden outright — nextCheckAt, registrationsFull, qualityOpenCount, qualityCheckVersion, systemMeta — so they're inspectable without a database query - systemMeta is admin-only in the UI (adminOnlyCondition) and carries access.update: () => false. Visibility and writability are decided separately on purpose: Payload deletes an access-denied key from the incoming patch rather than nulling the column, and system writers pass overrideAccess, so hiding the field can never let a manager's save wipe it. Pinned by two tests Co-Authored-By: Claude Fable 5 <[email protected]>
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-625
August 13, 2026 18:24
Destroyed
…icter contact rules Consolidation. stages.ts and stageMachine.ts each held part of the lifecycle, and some facts twice — an `unpublish` boolean on the transition AND a PUBLISHED_STAGES list, an UNMANAGED_STAGES list AND an 'await-schedule' action. Both files are now one exhaustive Record<VerificationStage, StageConfig> in lib/eventVerification/stages.ts, declaring published/managed/onDue once per stage; PUBLISHED_STAGES, UNMANAGED_STAGES, STAGE_DURATION_DAYS, LADDER and whether a transition unpublishes are all derived from it. stageMachine.ts is deleted (it had also outgrown the job folder — the collection, admin components, sidebar and importer all read it). Consolidating surfaced a real collision the tests caught: modelling `finished` as managed: false made isUnmanagedStage() true for it, so the watermark took the pre-adoption branch and skipped the retention window entirely. Those were two different questions wearing one name — isUnmanagedStage (may have no manager: unverified, denied, finished) is now distinct from isPreAdoptionStage (no clock but the schedule: unverified, denied). nextCheckAt stays nullable — null is the watermark's 'never', and inventing deadlines to avoid it would reintroduce exactly the churn the watermark removes. What was loose is now tight: `finished` falls back to retention-from- now when there's no schedule end (the importer maps a dump status straight to the stage, so dormant and open-ended rows could reach it with a null watermark and never be trashed), leaving exactly one nullable case — a pre-adoption stage with nothing scheduled. Pinned as an invariant over every stage. Also: the importer wasn't threading its injected clock into the watermark. Contact rules. A website no longer satisfies an inactive event's contact requirement — it's metadata, not a route to a person (1 of 16 inactive events in the dev DB relies on it and will need a real contact on next save). contactEmail gains a bounded validator composed with `email` from payload/shared (an email field takes no maxLength, and a custom validate replaces the built-in format check); contactPhone likewise via `text`. contactName now appears for a phone OR an email. Reverted: appUrl is emitted on Events again and the hasAppUrl opt-out is gone. Moved: submitter into the System collapsible. Co-Authored-By: Claude Fable 5 <[email protected]>
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-625
August 13, 2026 20:39
Destroyed
… drop dead weight Off-ladder is gone. The tracker had its own parallel vocabulary — OFF_LADDER, OffLadderStage, JOURNEY, STEP_ORDER — restating what STAGES already knew, and 'off ladder' only ever meant 'this stage isn't in my hardcoded list'. It now draws the journey the event is on: unverified -> denied -> verified for a pre-adoption listing (with copy saying what adoption actually takes), verified -> reminders -> expired once managed, finished as its own terminal. All six steps use the full STEP_COPY structure; the only thing this file still knows that the config doesn't is that three reminder stages collapse into one step. systemMeta is now a reusable field factory (src/fields/systemMetaField.ts) carrying a JSON Schema. That IS the built-in read helper: Payload generates the exact type into payload-types (so systemMeta?.communityFeedback?.denials is checked at compile time) and validates on write, so a malformed tally can't be stored. readCommunityFeedback is deleted — a defensive runtime parser could only report that bad data had already landed. collectIds walked pages of a table it was concurrently mutating; it's one pagination:false query, which is safe precisely because the watermark keeps the due set bounded by the day's work rather than the table. buildAtlasSidebarData is back to its original parallel shape. Pre-adoption events come out of the subtree query that already runs for the region counts — two extra fields in its select — instead of an OR branch that forced the region reads to complete first. Also: confidenceScore is visible for denied as well as unverified (on a denied event the score is the reason it came down), and backfillFinishedRetention is removed along with its script. Co-Authored-By: Claude Fable 5 <[email protected]>
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-625
August 13, 2026 21:03
Destroyed
Ardnived
added a commit
that referenced
this pull request
Aug 19, 2026
…on lifecycle (#638) * refactor(events): derive per-stage semantics from one attention level Five simplifications across the verification lifecycle, all removing a second encoding of a fact the stage table already knows: - `relationId` had two implementations; 7 of 10 call sites imported the one that can't parse a string id. Consolidated onto the complete one. - Every stage now declares an `attention` level. The sidebar bucket, the admin notice severity and the quality-check skip derive from it instead of each keeping their own per-stage table; `bucketForEvent`'s `default:` case (which silently labelled unfamiliar stages "verified") is gone, and the three tables that remain are exhaustive Records. - Deleted the `eventVerification` barrel (no importers) and the `UNMANAGED_STAGES` / `daysUntilUnpublish` exports nothing outside the module read. - `DAY_MS` is declared once in `lib/utilities/time` rather than inline in nine modules. - `addMonths` clamped: 31 Aug + 6 months was rolling into 3 March, so a finished event's retention ran a few days long. Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(tokens): sign every email link through one HMAC module There were three near-identical hand-rolled HMAC token modules — eventVerification/token, registrations/unsubscribeToken, and the generic utilities/signedToken written for #625 — with the same twenty lines of crypto and subtly different validity checks. The two older ones are now thin wrappers that supply their claims, TTL and `kind`. Beyond the duplication, this closes a real gap: all four link kinds are signed with the same Payload secret, and only the envelope's `kind` discriminator (which the two older modules lacked) stops a token issued for one link from being replayed against another. Pinned by a test. `signToken` gains `ttlMs: null` for never-expiring tokens, which is what the unsubscribe link needs — it may legitimately be clicked months into a course, and the action it authorizes is narrow and idempotent. Existing verify / unsubscribe links in already-sent emails stop validating, since the envelope shape changed. Accepted: the events being reminded about are re-notified on the job's next run. Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(events): validate notificationLog with a JSON Schema `notificationLog` was a bare JSON array with a hand-written narrower (`Array.isArray(value) ? value as Entry[] : []`) — a cast, not a check, so a malformed entry landed in the column and every reader had to hope. It now carries a JSON Schema, which Payload uses to generate `Event['notificationLog']` AND to reject a bad write with a ValidationError. The stored shape is unchanged (still a bare array), so no data migration is needed. Adopted from the approach in #618, which this supersedes. The schema's enums are derived from VERIFICATION_STAGES and, for the two unions declared in an email template, from a `completeList` helper that makes an incomplete restatement a compile error — the types are imported type-only, so no react-email code reaches the admin client bundle. A pair of assignments in the unit spec fails to compile if the schema and the hand-written entry types drift apart; both guards were verified by mutation, as was the validation itself (an int case asserts a missing key, an undeclared key and an out-of-enum value are all rejected). Registrations.reminderLog is the same pattern and has NOT followed — its comments now say so rather than claiming a mirror that no longer holds. Co-Authored-By: Claude Opus 5 <[email protected]> * chore(migrations): one payload entry point, and document why commands go quiet `db:migrate` and `db:migrations:create` were aliases for `payload migrate` and `payload migrate:create`, and `payload` was a passthrough to a binary pnpm already resolves from node_modules/.bin. Three names for two commands meant docs used them interchangeably, and whenever a command failed the wrapper looked like the suspect. All removed; everything is `pnpm payload <command>`. The wrappers were never the problem. Three real causes, each traced to library source and now written up in .claude/rules/migrations.md: - Dev email calls `nodemailer.createTestAccount()` — a live request to ethereal.email — on every config load, so on every CLI invocation. When it fails the adapter throws, and payload's `bin.js` runs the CLI under a bare `void start()` with no `.catch()`, so the process dies with exit 0 and NO output. This is the intermittent one: `pnpm payload migrate:status` alternates between a full table and zero lines on successive runs. Documented, not yet fixed — killing the network call costs the ethereal preview URL, so it needs a decision first. - `generate:types` logs "Compiling TS types…" then returns early and silently when the compiled output matches the file on disk. Silence means "no schema change", not a hang. - A `src/migrations/index.ts` referencing a missing migration file breaks EVERY payload command, because payload.config.ts imports the index for `prodMigrations` and the index statically imports all 44 files. The ERR_MODULE_NOT_FOUND sits at the top of a long stack trace, so it scrolls away — and vanishes entirely when piped through head/tail. Co-Authored-By: Claude Opus 5 <[email protected]> --------- Co-authored-by: Claude Opus 5 <[email protected]>
This was referenced Aug 19, 2026
# Conflicts: # src/collections/Events/Events.ts # src/migrations/index.ts # src/payload-types.ts
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-625
August 24, 2026 17:52
Destroyed
Ardnived
added a commit
that referenced
this pull request
Aug 24, 2026
Removes the ~25 columns and two child tables that mirrored Events, and adds `proposed` / `submitter_info` / `region_hint` jsonb. Pure drop + add: drizzle's rename-vs-create prompt was answered "create column" for each, which is correct — none of the new JSON columns is a renamed old one, and a rename would have carried a scalar into a jsonb column. The `down` path restores every column, both child tables and their FKs/indexes. A separate migration rather than a regeneration of 20260812_032435_add_event_submissions: that one is already applied to the #625 preview environment, and re-emitting it with a new timestamp would crash the boot migration on "column already exists". No data backfill: #625 is still open against main, so this collection has never existed outside dev and preview. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]>
Ardnived
added a commit
that referenced
this pull request
Aug 24, 2026
* refactor(submissions): collapse the mirrored schema into one Events patch EventSubmissions carried ~25 fields mirroring Events, plus a `mapSubmissionSchedule` translator converting the copy back into the real shape. Two sources of truth with a lossy layer between them. A submission now carries `proposed` — an Events data patch keyed by real Events field names, which Accept applies verbatim. `mapToEvent.ts` is deleted outright: with no simplified schedule vocabulary there is nothing to translate and no Temporal reconstruction to get wrong. `validateProposal` gates the patch at intake against the live Events config: every key must be a real Events field, and none may be system-managed (derived from `admin.readOnly`) or privileged. Without it an anonymous POST could set `verificationStage: 'verified'` and a `manager`, minting an adopted listing. Per-value validation stays where it already was — Events' own validation at Accept, which runs with full sibling context and surfaces to the reviewing manager. Submitter strings and region targeting fold into `submitterInfo` / `regionHint` JSON. The `submitter` relationship stays a real column: it is what `upsertUserByEmail` writes, and a Users join can only target a relationship (cf. `Users.submittedEvents`). The screening email's `buildDetails` now reuses the diff's own formatter and labeller, so email and review screen describe a submission the same way and a new Events field reaches both without either being edited. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * feat(submissions): review a proposal as a diff, with live preview The review view now shows what would change rather than a form of proposed values. Three components, each mounted on the field holding the data it renders (the pattern Events uses for notificationLog and qualityReport) rather than on `ui` fields reaching across form state: - ProposedChangesField on `proposedChanges` — a Payload `Table` of field / kind / current / proposed. The diff itself is microdiff, which was already a dependency and imported by nothing; it runs server-side because the browser has the proposal but not the event it would land on. Labels come from the Events config, so the wording cannot drift. - SubmitterPanel on `submitterInfo` — who sent it, read-only. - EventPreviewMount on `previewEvent` — opens live preview on mount and renders nothing. Keeping the arming and the data on one field means the panel can't be opened on a document with nothing to show. Live preview needs no access change and no preview endpoint: Payload posts the document's form state into the iframe, and `previewEvent` carries the merged event in that payload. The notice banner stops mapping `warning` onto Banner's `error` type — `.banner--type-error` applies color-svg(--theme-error-600) to every svg inside it, repainting WarningIcon's amber fill red and making a "needs a look" notice look like a failure. `.banner--has-icon` also sets only `display: flex`, so a 26px icon beside wrapping text stretched and drifted off the first line; three declarations in styles.css fix it. `emailVerdict` is now type-guarded — it 500'd the edit view when a malformed value reached `.replaceAll`. Accept no longer saves the form first; with nothing editable but `region` there is nothing to persist before deciding. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * chore(migrations): drop the mirrored submission columns Removes the ~25 columns and two child tables that mirrored Events, and adds `proposed` / `submitter_info` / `region_hint` jsonb. Pure drop + add: drizzle's rename-vs-create prompt was answered "create column" for each, which is correct — none of the new JSON columns is a renamed old one, and a rename would have carried a scalar into a jsonb column. The `down` path restores every column, both child tables and their FKs/indexes. A separate migration rather than a regeneration of 20260812_032435_add_event_submissions: that one is already applied to the #625 preview environment, and re-emitting it with a new timestamp would crash the boot migration on "column already exists". No data backfill: #625 is still open against main, so this collection has never existed outside dev and preview. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * fix(submissions): scan the nested patch, and keep the preview read out of the write Two defects the schema collapse exposed. The write guard's URL and email scans still named top-level fields, but the free text a spammer would use now sits inside `proposed` / `submitterInfo`. The scan silently found nothing — an integration case that had pinned `urls_not_allowed` started passing the spam through. The guard already walks paths, so the policy just needed repointing. The `previewEvent` / `proposedChanges` hooks loaded the target event with the caller's `req`. Those run in the `afterRead` of a create, so the request is mid-transaction, and joining it for a read-only projection aborted the write: `payload.create` returned a document with an id and left no row behind it, and only submissions naming a target event took the path. The projection needs the event's committed state, so it uses its own connection; `req` remains the memo key. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * test(submissions): cover the proposal contract and its projections Unit — mergeProposal (patch over target, group replaced wholesale not merged, new-event defaults), the diff's value formatting and Events-config labelling, and proposableEventFields. Integration — the forgery gate (verificationStage / manager / region / _status each rejected, posted as the literal wire body so the fixture helper can't hoist a key out of the patch and quietly test nothing), the diff and preview projections against a real target, and the findMany guard that keeps a list read from firing an event lookup per row. The privileged-field guard was mutation-checked: emptying PRIVILEGED_FIELDS makes the forgery test fail. Replaces the mapSubmissionSchedule / submissionEventPatch specs, whose subjects are deleted. The remaining schedule fixture moves to the real scheduleFields shape — with no translator, whatever the widget sends is what Events validates on Accept, and the old vocabulary is now correctly rejected. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * chore(test): drop the now-unused EventSubmission import Left behind when the mapSubmissionSchedule / submissionEventPatch specs moved out. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * docs(rules): record two Payload traps this branch hit Live preview pushes the document's form state into the iframe, so a frontend does not have to fetch it back. Every preview route in this repo re-fetches by collection+id, which reads like the only way — it isn't, and it costs you preview on a restricted collection or a document with no id, both of which describe an event submission. A virtual field's afterRead also runs on the response of a create, while that write's transaction is open. Forwarding `req` into a nested read there aborts the write: `payload.create` returns a document with an id and leaves no row behind it, and `disableErrors` does not help because the shared transaction is the problem, not the read's result. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(admin): share the Payload Table column builder ProposedChangesField and NotificationLogField each carried an identical `column()` helper — same signature, same `field: {} as never` stub for the property the Table type demands and never reads. Extracted to `components/admin/tableColumn.ts` so the next table doesn't copy it a third time. Found by the /simplify reuse pass. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * fix(submissions): close the registration-cluster escalation in proposed patches A `proposed` patch is applied to Events with manager authority on Accept. The gate excluded fields Events marks `admin.readOnly`, plus a short list of manager-editable-but-privileged ones — and the registration fields carry no `readOnly`, because a manager edits them freely. So an anonymous submitter could propose: - `registrationNotificationEmail` — every registrant's name, email and question answers forwarded to an inbox of their choosing, silently, from the moment a manager accepted; - `registrationMode: 'external'` + `externalRegistrationUrl` — every would-be registrant redirected off-site; - `images` — the listing dressed in another event's photographs; - `createdAt` / `updatedAt` — a forged history. The whole registration cluster is now privileged: registration is the event's data-collection surface, and a submitter is only ever describing an event, never configuring one. `join` fields are excluded by type — a join has no column for a patch to write. The security review found the notification-email hijack; the redirect via `registrationMode` came out of checking the same class of field, and the timestamps and the join came out of the new pin test. That test is the durable part: it asserts the exact proposable set against the real Events config, so adding a field to Events fails until someone decides explicitly whether the public may propose it. The three concrete exploits are pinned as their own cases. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * fix(submissions): merge groups the way Payload does Found reviewing the diff against real data. `mergeProposal` replaced a group wholesale, so a proposal correcting only `address.venueName` rendered as street, city, country, postcode and both coordinates being *removed* — and the live preview showed the same gutted event. Payload does not do that: verified against the running API, `payload.update` with `{ address: { venueName } }` changes the venue name and leaves its siblings intact. The diff was misrepresenting what Accept writes, which is the one thing it must never do. It now merges recursively through plain objects, while arrays and explicit nulls replace — matching Payload on both counts. That alone took a real update proposal from 27 rows to 10: the schedule group's derived values (`icalRule`, `upcomingDates`, `lastDate`) are inherited from the target now rather than read as deletions, so a one-line schedule edit no longer lists its own consequences as seven more. Also classify by what the reviewer sees rather than by microdiff's key-level verdict: a column that held `null` and now holds a value is a CHANGE to microdiff and plainly an addition to a human. `proposed.venueName` in the write-guard policy was scanning a path that never exists — the field nests inside the address group. Repointed, and `proposed.title` added. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * feat(submissions): unified diff, quoted note, status-appropriate actions Three things that only showed up once the review view had real data in it beside an open live-preview panel. **The diff is unified.** Four columns of current/proposed wrapped every value onto three lines in the ~third of the window this field gets with preview open. Now it is label, then the current value struck through in red above the proposed value in green, one column. An addition prints no struck-out `empty` line and a removal prints no green one — only the side that says something. No new dependency: `proposedChanges` already carries label/before/after, so a text-diff library would only re-derive what the server computed, and against raw JSON it would show quotes, commas and field names instead of "Contact Phone Number". **The submitter note reads as a quotation** — indented behind a rule, italic, attributed. It is a stranger's own words, and a reviewer weighing whether a submission is plausible needs to see that at a glance; as a plain line with quote marks it read as the CMS talking. The email is a mailto link, since replying is the obvious next move. **The actions match the status.** "Save" was the only offer on a resolved submission, which said nothing about what a manager could do next: - open — Accept / Reject, with Save alongside for the one editable field (`region`), since fixing an unresolved region gates Accept; - spam / rejected — **Reopen**, back to pending with the review stamp cleared. A screening false positive was otherwise unrecoverable from the admin; - created / updated — **Delete**, the record having served its purpose. The event it created is untouched, and the confirm says so. Reopen goes through `applyReview` rather than letting the form PATCH `status`, so every transition stays in one place, and it refuses `created`/`updated` (409 `not_reopenable`) — reopening one would invite a second Accept and a duplicate listing with it. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * feat(submissions): word-level diff, labelled transitions, Banner submitter card **Long values diff by word.** A rewritten description was previously two full paragraphs, leaving the reviewer to spot the edit themselves. Values over 60 characters now render once with only the changed words highlighted. Adds `diff` (jsdiff) for its `diffWords`. I tried `fast-diff` first — one file, no deps, exactly the "does one thing" library asked for — and rejected it on its output: being character-level it turned "main hall" → "annexe building" into `m`/`a`/`i`/`n`/`n`/`exe`, unreadable for prose, and it exports no semantic-cleanup pass to group those back into words. jsdiff is the larger package but runs **server-side only**, in the `proposedChanges` afterRead, so it never reaches the admin bundle. **The transition is named, not pilled.** The pill pushed the field name onto its own line at this width and drew the eye first, when the name is what a reviewer scans for. It is now a bold coloured suffix — "Contact Phone Number — Changed" — and the red/green lines carry the rest. **The submitter card is Payload's `Banner`** at its default neutral type, so background, padding and radius come from the theme rather than from hand-rolled CSS. `Card` was the obvious alternative and doesn't fit: it takes a `title` string and no children, leaving nowhere for the note. The note is a `<q>`, which supplies locale-correct quotation marks itself — the point being that a reviewer can tell the submitter's words from ours. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(submissions): name the components for their collection, label the fields **Renames.** `SubmitterPanel` → `EventSubmitterPanel`, `ProposedChangesField` → `EventSubmissionChanges`, `EventPreviewMount` → `EventSubmissionPreview`. Every component on this page now says which collection it belongs to; `src/components/admin/` is flat and shared, so a bare `SubmitterPanel` read as if any collection could mount it. **Field titles come from the collection.** `screeningResult` is labelled "Status" (the banner is the submission's status, whatever the column is called), plus "Submitted By" and "Proposed Changes". Removing `label: false` was not enough on its own, and the reason is worth recording: a custom `Field` component replaces Payload's **whole** field render, label included, so dropping `FieldLabel` deleted the headings rather than handing them back — only `event` and `region`, which use default components, still drew one. `FieldLabel` *is* the built-in title component, so it stays, now fed straight from `field.label` with no fallback string: the collection is the only place the wording lives. `previewEvent` keeps `label: false` — its component renders nothing, so a heading would sit above empty space. **The banner has its colour back.** Mapping `warning` onto Banner's `error` type was what repainted the amber WarningIcon red, so the last fix sent it to `default` — and left the entire pending state grey and inert. Banner ships no warning variant, so this adds one from Payload's own `--theme-warning-*` ramp (defined in its `colors.scss`, just unused by Banner) and leaves the icon alone. No `info` variant: Payload defines no info ramp, and screening/rejected are genuinely neutral. **Smaller:** only a *changed* field is suffixed now — an addition shows one green line and a removal one red line, so naming those was noise. The submitter's note is prefixed "Message:" (upright, so the italics mark only their words). Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * feat(submissions): name each submission, and title the status notice **A submission now has a title**, stamped on create: "New Event: <the title the event would be created with>" or "Update Event: <the target's title>". The list was a column of ids and the breadcrumb said "1", when the two things a reviewer sorts by are which event and whether it is new. For a new event the name is resolved through the **same composition the Events title hook runs**, so the label a reviewer approves is the title they end up with — a submission proposing a venue called Old Scout Hut is named "New Event: Meditation at Old Scout Hut", exactly as Events would. A submitter-supplied `proposed.title` wins, because Events only auto-fills a blank one. Getting that required lifting `resolveTitlePlace` / `resolveTitleTemplates` out of `Events/hooks/eventTitle.ts` into `lib/eventTitle/autoTitle.ts`, alongside the pure `compose.ts`. They were module-private, and a cross-owner import into another collection's folder is what `.claude/rules/project-structure.md` prohibits; the documented resolution is to generalize into `src/lib/`. Events now composes from there too, so the two cannot drift. Where nothing names the place — an online submission with no address and no anchor region, screening not yet having resolved one — the title degrades to the bare prefix rather than guessing. "New Event" is honest, and the diff under it carries the detail. **The status notice leads with the state.** Each status gains a 1–3 word title and a body trimmed of what the title, the buttons, or a field's own description already said: the region hint and the Event link each explain themselves where they sit, so the banner stopped repeating them. The screening detail notes stay — a verdict and its warnings are unique data, and they are what a spam call is triaged from. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(submissions): group diffs as YAML blocks, one component folder **A group now diffs as one block.** Seven separate "Address › …" rows told a reviewer which keys moved but never what the address ends up reading as. Any change inside a group or json field now collapses to a single entry rendering *every* subfield YAML-style, word-diffed, so the edit is shown in the context that makes it judgeable. The YAML is hand-rolled rather than handed to a serialiser, deliberately: keys are replaced with the Events field labels used elsewhere in the diff, and leaves go through `formatValue`, so a populated relationship reads as its title here exactly as it does on its own row. A serialiser would print the raw shape. Two things only real data revealed. Lexical rich text is a plain object too, so the description was being block-rendered as `Root: / Type: root / Children: [{…}]` — it stays on the scalar path, where `formatValue` already turns it into the words a reader sees. And a rendered group surfaced fields nobody proposes: `icalRule`, `upcomingDates`, `lastDate` (all derived from the dates beside them) and the opaque Mapbox id behind the address search box, now filtered. **One folder.** Every component for this collection lives in `components/admin/EventSubmissions/`, one file each, each named for what it is rather than what it renders: `EventSubmissionNotice` → `…Status`, `EventSubmitterPanel` → `…Submitter`, `EventSubmissionSaveButton` → `…Actions` (it draws Accept/Reject/Reopen/Delete, and hasn't been a save button for several commits). Class prefixes follow, and the three stylesheets merge into one. **Rejected is red.** It was neutral, which read as informational; it is a refusal, and should look like spam does at a glance. **The submitter card is actually grey.** Banner's default background reads from `--theme-elevation-*`, which `ProjectTheme` tints per project — under Sahaj Atlas the "neutral" card came out blue. Mixing the text colour into transparency gives a true grey that still inverts in dark mode. **The title field moves into the System drawer** — it is derived and read-only, and it already names the page via `useAsTitle`. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(submissions): bold group keys, fold Save into Accept **Group keys are bold**, so a rendered block scans as a table rather than a paragraph. Done by walking the diff segments rather than the finished string: a segment can begin mid-line, so only a key that genuinely starts a line counts, and "10:30" inside a value must not become one. Group entries carry a `block` flag for this rather than the renderer sniffing for newlines, which would mistake any multi-line description for a group. **Save is gone from the open state.** Saving a corrected region decides nothing on its own, so it was asking for two steps where there is one action; Accept now persists the form first when it is dirty. Nothing else on the page is editable, so a dirty form can only mean the region moved. The create view keeps a Save — a document that does not exist yet has nothing to accept. **The submitter card goes back to Banner's own background**, tinted with the project theme like every other banner. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * style(submissions): a submission awaiting review is not a warning "Needs Review" was amber, sitting beside red Spam, which made the collection's normal inbox read as a fault. It is the state every legitimate submission occupies until a manager decides — the point of the collection, not an exception. Now neutral, and worded "Awaiting Review": a queue rather than an alarm. That leaves no status using `warning`, so the severity comes out of the union along with its icon, its banner mapping and the custom `--theme-warning-*` variant added for it. Payload ships no warning banner style, which is why that variant existed; with nothing needing it, every severity maps onto a variant Banner actually has and the override is gone. The "— Changed" suffix in the diff keeps the warning ramp — that one is genuinely drawing attention to a difference. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * docs(rules): follow the renames and the eventTitle split `EventPreviewMount` is `EventSubmissionPreview` now, and `lib/eventTitle/` is no longer purely pure: `compose.ts` still is, but `autoTitle.ts` resolves a title against the templates global and the region name, and is shared by the Events title hook and EventSubmissions. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * fix(submissions): show the dormant listing, share the status vocabulary Findings from the simplify / code-review / security passes. **`inactive` was invisible to the reviewer.** `applyReview` derives it from the patch — no schedule proposed means a dormant listing, which never appears on the map until someone gives it one — but `mergeProposal` used a flat constant, so neither the diff nor the live preview mentioned it. A reviewer approved a complete-looking diff and got a hidden event. The defaults are now a function of the patch, composed by the preview, the diff and the write alike, so `applyReview` no longer restates `verificationStage` / `manager` either. The new integration case proves it: with no schedule the fixture had to grow a contact number, because Events requires a contact route on a dormant listing — exactly what the diff now surfaces up front. **Rich text was being merged as a group.** Lexical is a plain object, so the recursive merge walked into it and grafted the target's root attributes onto the proposal's tree. It is a value, not a group — the same reason `proposedChanges` keeps it off the block path — so it replaces whole now. **The URL scan covered one address subfield.** The policy named `proposed.address.venueName`, leaving street, room, city and the rest unscanned; a spammer could put a link in the street line. Naming the group lets `stringLeaves` walk all of it, which is what the comment above the policy already claimed. **The status union was written out three times** — collection, review op, two components — as string literals. Importing from `EventSubmissions.ts` would have pulled `serverEnv`, every hook and the review endpoint into the admin bundle, so a leaf `statuses.ts` that imports nothing carries it instead. The components now derive their button conditions from the same sets the review op enforces: a button offered for a status `applyReview` would refuse is a promise the UI can't keep. `STATUS_LABELS` stays distinct from the banner copy on purpose — the select names a stored value ("Pending Review"), the banner says what to do next ("Awaiting Review"). Also pins that an unknown key nested inside an allowed group never reaches the event, and moves the notes list's inline margin into a class. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * feat(submissions): order diff keys by the Events config and format dates Three things a reviewer noticed reading the diff side by side: - A YAML key was only bolded on a *changed* group. An added group carried no segments at all, so a wholly-new address rendered flat. Block entries now always carry segments, added or changed. - A patch and a stored event enumerate their keys in different orders, so the same group read one way on a new submission and another on an update — and the word diff called the reshuffle a change. Keys now follow the Events config's own field order on both sides. - Dates diffed as raw ISO strings, shredding `2026-07-18T16:00` into digit runs. They're formatted first (`18 Jul 2026, 16:00 UTC`), so the diff lands on the parts a human actually reads. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(submissions): let screening write its own notes, and type them The status bullets read like a debug dump — `Email verdict: disposable email`, `No responsible manager found` — leaving the reviewer to infer what followed from each. And the shape was declared in the job and re-declared, untyped, in the component, which is how the two drifted far enough that a malformed `emailVerdict` 500'd the edit view. Both fixed by the same move: a leaf `screening.ts` holds the typed `ScreeningResult` plus the note-writing functions, and the job composes complete sentences at the moment it decides, because it is the only party that knows *why*. `warnings` becomes `notes`; the enums stay stored for triage but are no longer what gets rendered. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * fix(submissions): read a diffed group the way the admin form shows it Three things a reviewer hit reading submission 14 side by side. **A schedule listed nine keys, most of them inert.** The recurrence controls all live in one row and keep whatever was last typed into them, so a weekly event still carried `Monthly Mode`, `On Day`, `Week`, `Day` and a stale `Occurrences` — state with no effect on the event, and no clue as to how any of it related. The admin form already hides them, and that rule is `admin.condition` on the field, so the diff now asks the same question rather than hard-coding which keys pair with which. Select values render as their option labels too (`Repeats: Weekly`, not `WEEKLY`; `On Days: Thu`, not `TH`). A condition is a hint for trimming noise, never a reason to show nothing: the address group's conditions mean "don't reveal these until a Mapbox place is picked", so honouring them literally filtered away every line of a hand-typed address. A block emptied by its own conditions falls back to the unfiltered one. **A list diffed by row number.** microdiff reports a hasMany per index, so adding a language surfaced as `Languages › #2`. Lists are now judged whole, like groups: `German` → `German, English`. **An added block was segmented** only so the renderer could bold its keys off the segments, which made a pure addition look like a partial edit. It's one plain `+` side again; the renderer bolds off `block`. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * fix(submissions): order the diff by the Events form's own field order Entries came out blocks-first, each set in whatever order microdiff walked them, so an update read Languages, Address, Schedule, then the contact row — an order matching neither the form a manager knows nor anything else. They now sort by where the collection declares each field. `flattenedFields` is depth-first in declaration order, with tabs, rows and collapsibles flattened away, so that *is* the order a manager reads down the Events form — and it's re-derived from the live config on every call, so moving a field in Events.ts moves it in the diff with nothing here to keep in step. A key the config doesn't declare sorts last rather than being dropped; an unrecognised key is exactly what a reviewer should see. Same rule the group renderer already applied to its own keys, so both now share one `declarationRank`. Mutation-checked: all three ordering tests fail with the sort removed. The first version of the "follows the collection" case passed without it — reversing the field list happened to coincide with blocks-then-scalars — so it now uses a permutation that interleaves a group and a list with the scalars. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * feat(submissions): assign a manager on accept, and write the banner for one Three changes to what a reviewer sees and can do. **`event` is hidden when empty.** A read-only relationship with nothing in it says only "no event" — which is already the message of the two fields shown in its place. `event` and `manager`/`region` are now complementary conditions, so the page always offers exactly one of the two. **A `manager` field, new events only.** Optional, and the whole of adoption: a created event with a manager is verified on the spot, without one it goes on the map marked unverified until somebody takes it on. An update proposal's target already has its own manager, so the field — and `region`, for the same reason — only show when there is no event yet. `newEventDefaults` takes the manager, so the diff, the preview and the write all agree about the stage. The create drops `skipVerifyHook` when a manager is assigned: that flag means "don't open a verification cycle", and skipping it would stamp `verified` with no `nextCheckAt`, leaving an event that never comes up for re-verification again. Pinned by an integration test that fails on exactly that. **The banner is written for a manager, not for us.** It said "assign a manager to adopt it into the verification cycle" — internal vocabulary for what a reviewer needs stated plainly: the public sees this event marked unverified until it has a manager. Spam said "Marked Spam / Kept for abuse tracking. Nobody was notified." and then a note repeating the classification; it now carries the reason alone. Screening no longer writes notes that ask nothing of anybody — a failed DNS lookup and which inbox the review request reached are ours to worry about, and are kept as an unrendered `diagnostic` rather than discarded. Notes stop showing once a submission is decided: "check the Region below" was still there on an accepted one, pointing at a field the page no longer shows. Two rendering defects surfaced by putting a relationship in the diff: a populated one was block-rendered, so a proposed manager came out as their whole row — id, roles, email, every notification preference — and `data.manager` is a bare id inside a field `afterRead`, so it read `Manager: 496`. References now format by name, resolved through the same per-request memo as the target event. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(submissions): one status vocabulary, and Payload's own openByDefault **The list and the banner now read from one place.** A row saying "Pending Review" opened onto a banner headed "Awaiting Review", which makes a reader stop and wonder whether they are two different things. `STATUS_LABELS` is now what each status is *called* everywhere a reviewer meets it — the list column, the `status` select, and the banner's heading — and the banner adds only the sentence saying what to do about it. (An earlier /simplify pass proposed merging these and I rejected it, on the grounds that a stored value and an instruction are different things. The instruction still is; the *name* never was.) **`EventSubmissionPreview` is deleted.** Payload 3.86 has `livePreview.openByDefault`, which does the same job better: it is applied server-side when building the document view, so the panel is open on first paint instead of after a mount effect, and it yields to the user's stored `editViewType` preference once they toggle the panel themselves — which the effect could not do, and so re-opened the panel every time a reviewer closed it and came back. That left the component doing nothing but render `null` to keep `previewEvent` off the page, which `admin.hidden` does natively: Payload renders a `HiddenField`, so the value still sits in form state — what `reduceFieldsToValues` posts to the iframe — with nothing taking up space. Verified in the served HTML: the hidden input's attribute reads `[object Object]`, i.e. `useField` handed it the real object. Both mechanics written up in `.claude/rules/admin-ui.md`, which recommended the effect. `FrameEditor` keeps it — it arms the preview on a tab, not on the document. Mutation-checked: with the stored preference cleared, removing `openByDefault` drops `collection-edit--is-live-previewing` from the server-rendered markup. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> * docs(collections): field hooks see bare relationship ids, not documents Cost a wrong implementation this branch: I assumed `data.manager` would be the populated doc at admin depth and passed it straight through, and the diff rendered `Manager: 496`. Population happens elsewhere in the read, so a field hook sees the raw id whatever depth the caller asked for. Documented beside the sibling rule it depends on — the resolution has to skip `req`, for the transaction reason directly above — with the `memoizeOnRequest` shape both review hooks share, and the neighbouring trap that a populated relationship is a plain object and will be expanded as a group by anything that assumes otherwise. Refs #641 Co-Authored-By: Claude Opus 5 <[email protected]> --------- Co-authored-by: Claude Opus 5 <[email protected]>
This was referenced Aug 26, 2026
sydevs-bot
added a commit
that referenced
this pull request
Sep 2, 2026
* feat(security): require Turnstile on event registration `POST /api/events/:id/register` was the last public write path without a captcha. Event submissions and user messages have required one since #625; this adds `turnstile: true` to the `registrations` create policy, so the write guard now demands a solved `x-turnstile-token` header on client-originated registration writes. The ordering mattered and is why this waited: the flip is breaking for any client not sending the header, so the Atlas widget had to send it first (sydevs/SahajAtlasWeb#182, merged). Turning this on before that would have refused every real registration. Two refusals, deliberately distinct, both now documented on the endpoint: 403 `captcha_failed` for a missing, forged, expired or replayed token, which a client retries with a freshly solved one; 500 `captcha_unavailable` when our secret is unset or Cloudflare is unreachable. The second is never a pass — a captcha gate that silently disables itself is worse than no gate, because nothing surfaces the misconfiguration. Adds a unit spec pinning the policy map, which nothing covered before. That map fails OPEN in one direction: an absent knob means "skip that check", so a dropped `turnstile: true` reopens a captcha-free public write path without breaking a build, a type-check or any other test. The spec goes red on exactly that removal. Closes #629 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01F2BczvDrd7opTwedpZHZ6L * fix(tests): make the registration captcha fixtures mirror Cloudflare Three CI failures, three different causes, only one of which was a bad test. 1. `client-origin-enforcement.int.spec.ts` calls the register endpoint directly and sent no token, so the new gate refused it with a 403 where it asserted 201. That spec is about origins, so it now mocks the verifier permanently valid and sends a token from `clientReq`. 2. My own "no `x-turnstile-token` header" case passed for the wrong reason and then failed for the right one. The mock returned success whatever it was handed, so the token's absence could not matter — the endpoint answered 201. The stub now mirrors siteverify: an empty token is `missing-input-response`, a rejection. This is the trap the repo's own rule warns about, arriving from the other direction — the assertion was sound and the fixture made it unfalsifiable. 3. "creates no registrant when the captcha is refused" was a wrong expectation about behaviour this PR does not own, and it found something worth keeping. `registerForEvent` upserts the `users` row and then creates the registration with no transaction around the pair, so a refused captcha stops the registration and leaves the user row. That is pre-existing — the `questions` validation 400 already did the same — and the fix is a transaction around both writes, which is a change to the endpoint's shape rather than a policy flip. Split in two: the captcha assertion now checks no REGISTRATION is created, and a second case documents the orphan row explicitly so the gap is recorded rather than asserted away. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01F2BczvDrd7opTwedpZHZ6L --------- Co-authored-by: Claude <[email protected]>
Closed
5 tasks
24 tasks
7 tasks
17 tasks
24 tasks
Ardnived
pushed a commit
that referenced
this pull request
Nov 5, 2026
`POST /api/events/:id/register` was the last public write path without a captcha. Event submissions and user messages have required one since #625; this adds `turnstile: true` to the `registrations` create policy, so the write guard now demands a solved `x-turnstile-token` header on client-originated registration writes. The ordering mattered and is why this waited: the flip is breaking for any client not sending the header, so the Atlas widget had to send it first (sydevs/SahajAtlasWeb#182, merged). Turning this on before that would have refused every real registration. Two refusals, deliberately distinct, both now documented on the endpoint: 403 `captcha_failed` for a missing, forged, expired or replayed token, which a client retries with a freshly solved one; 500 `captcha_unavailable` when our secret is unset or Cloudflare is unreachable. The second is never a pass — a captcha gate that silently disables itself is worse than no gate, because nothing surfaces the misconfiguration. Adds a unit spec pinning the policy map, which nothing covered before. That map fails OPEN in one direction: an absent knob means "skip that check", so a dropped `turnstile: true` reopens a captcha-free public write path without breaking a build, a type-check or any other test. The spec goes red on exactly that removal. Closes #629 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01F2BczvDrd7opTwedpZHZ6L
Ardnived
added a commit
that referenced
this pull request
Nov 5, 2026
There were three near-identical hand-rolled HMAC token modules — eventVerification/token, registrations/unsubscribeToken, and the generic utilities/signedToken written for #625 — with the same twenty lines of crypto and subtly different validity checks. The two older ones are now thin wrappers that supply their claims, TTL and `kind`. Beyond the duplication, this closes a real gap: all four link kinds are signed with the same Payload secret, and only the envelope's `kind` discriminator (which the two older modules lacked) stops a token issued for one link from being replayed against another. Pinned by a test. `signToken` gains `ttlMs: null` for never-expiring tokens, which is what the unsubscribe link needs — it may legitimately be clicked months into a course, and the action it authorizes is narrow and idempotent. Existing verify / unsubscribe links in already-sent emails stop validating, since the envelope shape changed. Accepted: the events being reminded about are re-notified on the job's next run. Co-Authored-By: Claude Opus 5 <[email protected]>
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Part 2 of the crowdsourced-listings plan (stacked on #624). Community members can submit new events and update proposals for existing events through the Atlas widget — via the built-in create endpoint of a new
event-submissionscollection (client public-key auth; no custom submit endpoint). Anonymous input never mutates a live listing: submissions are screened asynchronously, then a manager's Accept creates the event (published +unverified) or applies the proposed patch.How it fits together
POST /api/event-submissionswith the client key +x-turnstile-tokenheader.eventset ⇒ update proposal (target must be published); unset ⇒ new event (requires an existingcountryor a city/venueanchorRegion— level-checked in the hook, notfilterOptions, whose save-time validation forwards the clientreqand trips the select-required gate). Notitlefield — accepted events keep or auto-fill theirs.mailcheckerdisposable-email list.contactAdminrefactored onto the same helpers (contract pinned: 403captcha_failed, code-less 500);registerForEventinherits coverage through its internal user/registration writes. Machine codes:captcha_failed,urls_not_allowed,disposable_email,invalid_email.node:dns(fail-open) + disposable re-check →spamkept silently for abuse tracking, else region resolution (only cities are ever auto-created, canonicalized through the existing Mapbox geocoder under the chosen country/state) and a review email to the responsible manager — the event's manager, the nearest region manager up the chain (findManagerForRegion, extracted from the reminder escalation), or the system contact.applyReviewop behind (a) admin Accept/Reject buttons that replace Save on open submissions (Accept saves the form first, so manager corrections land), and (b) a tokenized/submissions/reviewpage on SahajCloud (mirrors/events/verify: generic HMAC signed-token helper with akinddiscriminator; mutation only on explicit POST — mail scanners can't auto-accept). Idempotent: a second review reports the terminal status.Security note — pre-existing hole closed
Collections in no project were "shared" ⇒ implicitly readable by every published API client, including
users(registrant names + emails, readable with the public Atlas widget key). NewRESTRICTED_COLLECTIONSrule (users,event-submissions) removes them from implicit read;atlas-managergets explicitreadgrants (+updateon submissions),sahaj-atlas-clientgets create-only onevent-submissions. Pinned by tests.New dependencies (signed off in planning)
mailchecker(server-side disposable-email list) ·microdiff(installed for the review diff panel; UI usage lands with the SahajAtlasWeb-facing iteration).Tests
tests/int/event-submissions.int.spec.ts(21 cases: guard rejections, forged-status forcing, submitter upsert, gate 400/404/409s, screening spam/pending/city-creation/recipient routing/system fallback, accept-new/accept-update/reject/idempotency/region-unresolved, restricted-access pins) ·tests/unit/anti-spam-guard.spec.ts(URL patterns, email checks, response mapping, signed tokens, schedule mapping, patch semantics) · regression:role-based-access(54),contact-admin(26),event-registration(38) all green. Migration validated (migration-validator).🤖 Generated with Claude Code