Skip to content

fix(events): require a region on every event, drafts included - #1313

Merged
Ardnived merged 11 commits into
mainfrom
fix/region-always-set
Nov 28, 2026
Merged

Ardnived merged 11 commits into
mainfrom
fix/region-always-set

Conversation

@Ardnived

@Ardnived Ardnived commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Every event now needs a City / Venue on every save, drafts included, so no manager is locked out of an event they created.
  • Two related holes in region-subtree scoping are closed: Duplicate on events and regions, and clearing a region's parent.
  • A version restore or a proposal accept can no longer place an event outside the manager's area.

Change outline

Contract — what an event or region write is refused for

Three writes that went through are now refused. All three let a region manager make a row they could not reach afterwards, or move one out of another manager's area.

 POST /api/events, PATCH /api/events/:id                     src/collections/Events/Events.ts
   region (City / Venue)   required: true                    # Payload skips this on a draft save
+  region                  beforeValidate: requireRegion     # src/collections/Events/hooks/requireRegion.ts
+    create, no region                     → 400 ValidationError on `region`, draft or not, any caller
+    update naming `region: null`          → 400 ValidationError on `region`
+    update leaving `region` out           → passes (bookkeeping and job writes)
 POST /api/events/:id/duplicate, POST /api/regions/:id/duplicate   src/plugins/access/accessPlugin.ts
-  create access with empty data, then copy the source's region / parent
+  disableDuplicate: true  → 400 "cannot be duplicated", and no Duplicate in the admin menu
+    set for every region-scoped collection, so a new slug needs no second edit
+    written only as `true` — sanitize gives an auth collection `?? true` AFTER every plugin
 PATCH /api/regions/:id (and bulk), as a region manager       src/plugins/access/regionSubtreeAccess.ts
   parent inside the subtree                       → allowed
   parent outside, equal to the stored one         → allowed (a subtree root's own parent)
-  parent: null / '' / 'none' / 'null'            → allowed
+  any posted parent that is not an owned id       → allowed only if it equals the stored one
+                                                  # so an empty parent on a non-root → 403
+  the same in a bulk update                       → 403
   parent omitted                                  → allowed

Flow — writes that show access no region

Restoring a version and accepting a proposal both write a region that access never saw. A collection hook now judges the region the write will store.

 POST /api/events/versions/:id (restoreVersion)
   update access with { _status } only              # the old version's region is not in it
+  Events.hooks.beforeValidate: keepRegionInSubtree  src/collections/Events/hooks/keepRegionInSubtree.ts
+    non-admin manager on req, region ≠ stored, not in owned subtree → 403
 PATCH /api/user-submissions/:id { status: 'accepted' }   src/collections/UserSubmissions/lifecycle/review.ts
   payload.create(events, overrideAccess: true, req = reviewer)
+    keepRegionInSubtree: a create always counts as a move → region must be in the reviewer's subtree
   update proposals: patch carries no region → equal to stored → passes

Behaviour — why a draft could orphan an event

How the lockout worked: create access lets a missing region through, because the admin asks the same question with no data to decide whether to show the Create button. Update access then reads the stored region.

 scopeRegionSubtreeWrite(events)                              src/plugins/access/regionSubtreeAccess.ts
   create: region posted → must be in the owned subtree
           no region     → allowed if the manager owns any region
-                          (draft save skips `required` → row stored with region = null)
+                          (requireRegion then refuses the save, so no row is stored)
   update: stored region in subtree, or manager == user → allowed
-          stored region null, manager unset            → 403 for the manager who created it

Preview

Sign in as Rafael Quintero, who manages Fixture Harbourton, the city above Fixture Lantern Hall.

Test results

  • Lean gate: ✓ lint, format, typecheck (src and tests), unit lane (3924 tests)
  • Targeted specs: after this round, role-based-access, user-submissions-review-lifecycle, atlas-collections and events-geojson (192 tests), plus every int spec that creates events or regions or touches submissions (47 files, 1077 tests) before the merge of the loop's commits
  • Build: N/A (Railway builds the preview)

Manual verification

  1. As Rafael Quintero, click New Event in the sidebar, give it a title and no City / Venue, then Save Draft. Expect the field error, and no new row in the events list.
  2. As an admin, do the same. Expect the same refusal (the owner chose to bind everyone).
  3. As an admin, after merge, give each regionless production row below a region or parent. Until then, any save that sends their empty City / Venue is refused.

Notes for reviewer

  • Existing production rows. A read-only query on 2026-11-27 found four non-trashed draft events with no region and one non-country region with no parent. This PR changes no data. An admin has to assign them:
    • Events 2027, 2029, 2002 and 1932, all drafts created 2026-11-13 to 2026-11-27. Only 1932 still has a manager (401), so only that one is reachable by a non-admin.
    • Region 1728, a city named "Kazan" with no parent.
  • Owner decisions: region required for everyone, admins and the class import included; Duplicate disabled rather than checked after the copy.
  • Disproved before filing: a string-typed region or parent id does not bypass subtree access. The access layer's relationId parses numeric strings, and a probe refused all four create and update cases.
  • Review fixes on this branch: parent: 'none' and 'null' still detached a region, because access reads the raw body and Payload empties those spellings afterwards. The test is now "not an owned id". requireRegion also refused a region posted as a numeric string, so it now uses the access layer's relationId.
  • Second review round: disableDuplicate moved into accessPlugin, keyed on isRegionSubtreeCollection. The first form wrote ?? isRegionSubtreeCollection(slug), an explicit false everywhere else, which defeated the disableDuplicate ?? true that sanitizeConfig gives an auth collection after every plugin — so managers and clients gained a registered duplicate route and an admin Duplicate action. No role grants create on either, so only an admin could reach it. The key is now written only as true, and the int case pins both auth collections' flag.
  • Rebutted: unifying requireRegion with requireOwnedParentOnCreate behind one generic field hook. An event has no legitimate regionless state; a root region legitimately has no parent, which is why that hook is create-only, and a hook bound on update would refuse the root-region save this branch added a case for.
  • Dismissed findings:
    • A numeric-string parent bypassing access: false, because the access layer's relationId parses numeric strings, and a probe confirmed it.
    • Saves of a legacy regionless row being refused: intended, because the owner chose to bind everyone. Writes that leave region out still pass, and there is a test for that.
    • Admins losing Duplicate: this was the owner's decision.
    • A bare 403 on a refused parent clear: every subtree refusal answers that way.
    • An extra stored-parent read on a country manager's save: about four primary-key reads per save, and only for managers listed on a country.
  • Restore and proposal accept (owner asked to fix in this PR): both were pre-existing. Both are now refused by keepRegionInSubtree, and each has a case that fails without the hook. Dismissed in that review round: a claim that a partial manager update is refused, which is false because Payload refills an omitted region before collection hooks run, as the existing in-subtree and assignee update cases show. Also a claim that region: '' slips past requireRegion, which is false because Payload empties it before the hook, now pinned by a case.
Detail

Why a field hook, not required or a collection hook. Payload skips every field validator on a draft save (skipValidation: isSavingDraft && !hasDraftValidationEnabled(...) in collections/operations/create.js and utilities/update.js), and versions.drafts.validate would validate every field of every draft. A collection beforeValidate hook cannot tell an omitted region from an empty one: Payload refills an omitted field from the stored row right after that field's own hooks. So the hook reads the omission off siblingData, never value, which already carries the refill.

Why Duplicate was a hole. duplicateOperation calls createOperation with data: {}. Create access runs on that empty data, before getDuplicateDocumentData's copy reaches the field hooks. Reads are project-wide, so a region manager could open any event or region and duplicate it into an area they do not own. A probe confirmed it for both collections, with and without a data override.

Why parent: null was a hole. relationId(null) is null, which the update branch read as "no parent posted" and allowed. On a sub-region that detached the region from the tree. On the manager's own top region it took the region out of the country manager's area. Admins still clear a parent freely: the admin bypass answers before this scoping runs.

🤖 Generated with Claude Code

Ardnived and others added 3 commits November 27, 2026 22:32
A region manager's write access to an event is its region, and Payload
skips `required` on a draft save, so a first draft saved without a region
locked out the manager who created it. `requireRegion` refuses a create
with no region, and any update that names an empty one, for everyone.

Two related holes in the same region-subtree scoping:

- Duplicate ran create access with empty data, then copied the source's
  region or parent, so a region manager could copy any readable class or
  region into an area they do not own. Events and Regions now set
  `disableDuplicate`.
- A posted `parent: null` was not treated as a move, so a region manager
  could detach a sub-region, or their own top region, from the tree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…on id

Access reads the raw body, and Payload turns `''`, `'none'` and `'null'`
into an empty parent only after it, so `parent: 'none'` still detached a
region. The test is now "not an owned id". `requireRegion` takes the
access layer's `relationId`, so a region posted as a numeric string is
no longer refused. Adds the allowed root-region save, the legacy-row
carve-out, and a config guard tying `disableDuplicate` to the scoped
collections.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@railway-app

railway-app Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-1313 environment in sahajcloud

Service Status Web Updated
SahajCloud 😴 Sleeping (View Logs) Web Nov 28, 2026 at 4:15 pm UTC
1 service not affected by this PR
  • mailpit

@sydevs-dispatcher

sydevs-dispatcher Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

🤖 no session running

recent dispatches
  • 06:42Z address-review · attempt 1 · session · done
  • 06:42Z address-review · attempt 1 · session
  • 06:31Z review-pr · attempt 1 · session · done
  • 06:31Z review-pr · attempt 1 · session

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-dispatcher sydevs-dispatcher Bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 28, 2026
@sydevs-dispatcher sydevs-dispatcher Bot moved this from Pending to Working in SYDevelopers Technical Roadmap Nov 28, 2026

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧐 Adversarial review

The diff is the size of its problem. Three gates for one invariant are forced rather than chosen: access cannot bind admins, and required is skipped on a draft. What is chosen is where two of them live — disableDuplicate is hand-set per collection although accessPlugin already rewrites every collection this scoping covers, and the new events guard is a near-copy of the regions one that agrees with it on nothing. No contract moves: no contractSync source changed, and the one consumer path that creates an event already supplies a region.

Findings

  • should-fix — disableDuplicate belongs in accessPlugin, keyed on isRegionSubtreeCollection — Events.ts:134
  • should-fix — requireRegion and requireOwnedParentOnCreate are one invariant in two shapes — requireRegion.ts:18
  • should-fix — Streamline: the new Events/AGENTS.md section restates requireRegion's JSDoc — Events/AGENTS.md:36
  • should-fix — the new access.md bullet gives two facts a second home — access.md:127
  • consider — the === null emptiness test reads as the bug its own sibling ⚠ forbids — requireRegion.ts:20

What was checked

Diff whole (9 files), plus regionSubtreeAccess.ts, requireOwnedParentOnCreate.ts, relationId, eventTitle.ts and accessPlugin.ts on the branch. Every row of the change outline traced to code; all hold. Confirmed relationId('') === 0, and that Payload's ''/'none'/'null' → null coercion runs ahead of field hooks, which is what makes both gates right. Preview: 3 links ON_HOST, ids 1025001/1025008/1002002 all in src/fixture/, each showing its claim. The one deleted test is rightly deleted: resolveTitlePlace reads a region. Streamliner: 1 piece listed, 1 kept, 1 finding posted; its second reverses a stated owner decision, so it was dropped.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Comment thread src/collections/Events/Events.ts Resolved
Comment thread docs/rules/access.md Resolved
Comment thread src/collections/Events/AGENTS.md Resolved
@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 28, 2026
@sydevs-dispatcher sydevs-dispatcher Bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 28, 2026
Being region-scoped is what forces the flag, so the plugin that already
rewrites every such collection's hooks, access and admin sets it too. A
slug added to REGION_SUBTREE_COLLECTIONS now carries the guard with no
second edit, and the two per-collection lines and their duplicated
rationale go.

`?? isRegionSubtreeCollection(slug)` leaves a collection free to set the
flag for its own reasons, as Albums, AppCards, Files, Images and imports
do. role-based-access.int.spec.ts already reads the flag off the booted
config, so it covers the new wiring unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYUbi9DHrWsxwPCzz2
relationId('') is 0, so `relationId(value) !== null` reads as the bug the
⚠ in regionSubtreeAccess.ts forbids. It is correct only because Payload
normalises every empty relationship spelling to null in the field pass
before field hooks run. Without the clause the next edit copies the shape
to a layer that runs earlier, where it is the hole.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYUbi9DHrWsxwPCzz2
The section retold the hook's own JSDoc and its condition list, and code
outranks prose. Its two whys with no other home move into that JSDoc, a
clause each: a regionless first draft locked out its own creator, and an
omitted `region` passes so a job touching an older regionless row is not
refused.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYUbi9DHrWsxwPCzz2
The bullet gave three facts a second home: the duplicate rationale, which
lives in accessPlugin's ⚠; the draft/`required` rationale, which lives in
requireRegion's JSDoc; and an inventory of what requireOwnedParentOnCreate
refuses, which the symbol already says. The invariant above them has no
other home, so it stays.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYUbi9DHrWsxwPCzz2
`sanitizeConfig` runs after every plugin and gives an auth collection
`disableDuplicate ?? true`, so the `??` form wrote an explicit `false`
for every other collection and defeated that default: `managers` and
`clients` gained a registered `POST /api/:collection/:id/duplicate`, a
local `duplicate()` that no longer threw, and a Duplicate action in the
admin. No role grants `create` on either, so only an admin could reach
it, but the route should not exist.

A conditional spread writes the key only where being region-scoped
forces it, and leaves every other collection exactly as its own config
had it. The int case now pins both auth collections' flag; it fails
against the `??` form.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYUbi9DHrWsxwPCzz2
@sydevs-bot

Copy link
Copy Markdown
Contributor

Four of five critic threads adopted, one rebutted.

Adopted — into accessPlugin 8e8d09b · the emptiness test 283b5f9 · the AGENTS.md section a6fe4c2 · the access.md bullet 9d5ef3e

Rebutted — one invariant, two shapes. A root region legitimately has no parent, so a hook bound on update would refuse the root-region save this branch covers.

The security sweep caught a regression in the first fix (a78e4b4). The ?? form wrote false everywhere else, defeating the disableDuplicate ?? true sanitize gives an auth collection after every plugin: managers and clients gained a duplicate route, admin-only. Written only as true now, both pinned.

Lean gate ✓; role-based-access ✓ 103, and the new assertion fails against the ?? form.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 28, 2026
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1313 November 28, 2026 07:05 Destroyed
@sydevs-dispatcher sydevs-dispatcher Bot moved this from Working to Pending in SYDevelopers Technical Roadmap Nov 28, 2026

@sydevs-dispatcher sydevs-dispatcher Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved for Ardnived, who wrote it: GitHub refuses an author's own approval. CI is green and the automated review has run. Enable auto-merge when you want it merged: the queue tests it against its base. 🤖 Written by the sydevs autonomous loop — see what this is

@sydevs-dispatcher sydevs-dispatcher Bot moved this from Pending to Awaiting in SYDevelopers Technical Roadmap Nov 28, 2026
Ardnived and others added 3 commits November 28, 2026 08:44
Two writers showed access no region: `restoreVersion` runs update access
with `{ _status }` alone and then writes the old version's region, and a
proposal accept creates the event with `overrideAccess: true` at the
region the reviewer left on the submission. So a region manager could
restore an event out of their area, or accept a new class into any city.
`keepRegionInSubtree` refuses either, after the field pass, for any
non-admin manager on `req`. A region equal to the stored one is no move,
so an event assignee still saves their own event.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…region-always-set

# Conflicts:
#	docs/rules/access.md
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1313 November 28, 2026 15:48 Destroyed
@Ardnived
Ardnived added this pull request to the merge queue Nov 28, 2026
Merged via the queue into main with commit 1973c62 Nov 28, 2026
10 checks passed
@Ardnived
Ardnived deleted the fix/region-always-set branch November 28, 2026 17:22
@sydevs-dispatcher sydevs-dispatcher Bot moved this from Awaiting to Done in SYDevelopers Technical Roadmap Nov 28, 2026

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-1313 — 41b19527 Deployed Nov 28, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

3 participants