Skip to content

Technical reference

The architecture, the concepts and the decisions behind them — including the ones that were wrong first. Written in English only: it describes identifiers, SQL and HTTP codes, and a half-translated engineering reference is harder to trust than an untranslated one.

What this is

CampingManager is one transactional core serving three products. They share a database and an API, and differ in audience, security posture and performance profile.

ProductAudienceOptimised for
MarketplaceTravellersDiscovery and conversion. Public and indexable.
Operator consoleCamping owners and staffDaily operations at reception, low friction.
Authority consolePublic administrationAggregation, drill-down, export, evidence.

The order matters. Statistics are only trustworthy if they derive from transactions an operator actually recorded, which is why the operator console is built first.

Scope, as of the TBS proposal. The product being delivered is a PMS for camping and glamping operators in Saudi Arabia. There is no authority console — the proposal is explicit that public bodies are not the audience — and no traveller marketplace; for camping the operator takes the booking by telephone, WhatsApp or at the gate, and for glamping the traveller books through the OTAs the operator already uses, which the platform keeps in sync. The authority scope model below is still described because it is built and inert, not because a regulator portal is planned.

Six principles shape everything below. Authority-facing numbers derive from immutable transactional facts. Tenant isolation is enforced in the database, not only in the application. Money is never a float. Prices and policies are versioned, never overwritten. Personal data is separated from statistical data at the table level. Every sensitive read is logged, not just every write.

Architecture at a glance

LayerChoice
FrontendNext.js 15 App Router, React 19, TypeScript, Tailwind v4
BackendNestJS 11 on Fastify, TypeScript
ValidationZod, strict schemas — unknown keys are rejected, not stripped
DatabasePostgreSQL 17 with PostGIS, pgcrypto, citext, btree_gist, pg_trgm
ORMPrisma 6, with hand-written SQL for everything it cannot model
Cache, rate limitsRedis 8
EmailBrevo over SMTP, behind a provider-agnostic port

NestJS was chosen because the hard problems here are cross-cutting, and its guard/interceptor/module model maps onto them almost one to one: tenant resolution is an interceptor, authorisation is a guard, audit is a database trigger plus a service, compliance packs are dynamic modules. Throughput is not the constraint — a national camping dataset is small — correctness and auditability are.

Prisma cannot express EXCLUDE constraints, Row Level Security, triggers, partial indexes or expression indexes. Each migration therefore carries a hand-written post.sql alongside the generated migration.sql, applied by a small runner and tracked by checksum. The drift check compares migrations to datamodel on a shadow database — never the live database to the datamodel, which would report permanent false drift from those extra objects and get switched off within a week.

Multi-tenancy: three barriers

One database, one schema, a tenant discriminator column. Schema-per-tenant was rejected: authority analytics are inherently cross-tenant and migrating N schemas is operationally hostile. Isolation is bought with defence in depth instead.

BarrierWhat it catches
1. Route scope resolutionA tampered or fabricated id in the URL. :orgId and :campingId are resolved against the actor’s assignments before any query runs. 403 and 404 are deliberately indistinguishable, so the API is not an existence oracle.
2. Prisma query guardA repository method that forgets its tenant filter. A client extension either injects camping_id IN (…) or throws — omitting it is not possible.
3. Row Level SecurityEverything else, including raw SQL. Policies are generated from one function, so a new table cannot get a subtly different predicate.

The application connects as app_rw: DML only, no DDL, no UPDATE or DELETE on audit_logs. Migrations use a separate owner connection. That split is what makes RLS meaningful — an application connecting as the table owner bypasses every policy unless FORCE ROW LEVEL SECURITY is set, which is why the helper always sets it.

The request scope is published to PostgreSQL with set_config(…, is_local => true) inside an explicit transaction. That is SET LOCAL in function form: it takes bound parameters, and the value dies with the transaction. A session-level SET would outlive the request and be visible to whichever request picked up that pooled connection next — the exact failure this layer exists to prevent.

No scope means no rows, never all rows. A query that forgot to publish its scope returns nothing, so the failure is a visible bug rather than a silent breach.

A boot-time assertion compares three independent facts: which models carry a tenant column, which the query guard filters, and which tables the database actually protects. Any disagreement names the table and stops the deploy.

Authorisation: permission plus scope

A permission alone is meaningless here. booking.read is always “booking.read on what”, so every check is a pair and every role assignment is bound to a scope.

platform                 the whole system
organization:<uuid>      a company and all its campings
camping:<uuid>           one site
jurisdiction:<uuid>      a geographic area, expanded by geography

A permission held at any level of the chain authorises the action: a platform administrator on any camping, an organisation owner on any of its sites, a regional authority on any camping in its region. Because a jurisdiction expands by geography, a new camping becomes visible to the right authority with no manual grant.

The authority level is the scope, not the role. authority_analyst @ jurisdiction:Asir and @ jurisdiction:Riyadh are one role with different reach, so promoting an analyst is a one-row change and the role matrix stays small.

There is no customer role and there are no customer permissions. A traveller is an authenticated user with no assignment at all; their endpoints are marked @SelfScoped() and operate only on their own rows. own_booking.read would be a catalogue row nobody ever checks.

Two rules close the obvious holes. A role may only be created from permissions its creator already holds, or anyone with platform.role.manage could mint a role containing the whole catalogue and grant it to themselves. And super_admin deliberately holds no guest-identity permission: a platform role has no lawful basis to read a traveller’s passport number, and granting it by default would make the access log meaningless.

The application refuses to start if any route lacks @Public(), @SelfScoped() or @RequirePermission(), or asks for a permission that is not in the catalogue. The most common access-control bug is not a wrong rule — it is a forgotten one on a new endpoint, in a hurry. This turns that into a failing deploy rather than a 403 discovered by a user.

Access tokens carry no permission list. They carry a scope_version, which every grant and revoke increments; the guard compares it and rejects a stale token with TOKEN_STALE, the client refreshes, and the change takes effect on the very next request instead of whenever the token happened to expire.

Identity and sessions

  • Passwords use Argon2id (64 MiB, t=3, p=4) plus a server-side pepper held in the environment, so a stolen database alone cannot be cracked offline.
  • New passwords are checked against Have I Been Pwned using k-anonymity — only the first five characters of the SHA-1 hash leave the process. The check fails open: a breached password is a real risk, but an auth system that stops working when a third party does is a bigger one.
  • A session is a family of refresh tokens. Each refresh issues a new one and marks the old used; presenting an already-used token means a replay or a stolen token used first, and both get the same answer — kill the whole family. Token theft becomes one detected unauthorised refresh rather than open-ended access.
  • Web clients get HttpOnly; Secure; SameSite=Lax cookies, so no token reaches JavaScript; mobile clients get the same tokens in the body. One mechanism, two transports.
  • CSRF uses double-submit on top of SameSite=Lax, and only for cookie-authenticated requests — a Bearer token is not sent automatically by the browser, so requiring the header there would only break mobile clients.
  • Unknown email and wrong password return byte-identical responses, and a missing account still costs an Argon2 verification so timing does not distinguish them.
  • TOTP with ten single-use backup codes. Secrets are sealed with AES-256-GCM under a versioned key, bound to the user so a ciphertext cannot be moved between rows.

Inventory: products and pitches

This is the modelling decision that would be most expensive to get wrong: retrofitting it later means migrating every booking.

Travellers buy a product — “a motorhome pitch with electricity”. Operators think in physical pitches — “A14 is flooded”. Hotels solve this with room-type plus room; campings need the same split, plus the option to sell a specific pitch, which is common for seasonal or premium ones.

TableRole
unit_groupsThe sellable product. Search and pricing run here: few rows, fast.
unitsThe physical pitch. Availability and the double-booking guard run here: physically true.

A booking made against a group is assigned to a unit, immediately or at check-in, and the assignment can be moved without touching the booking’s commercial terms. Occupancy is computed per unit, which is what an authority actually means by capacity.

A tiny camping with twenty undifferentiated tent pitches still creates twenty units in one group. The model does not get heavier, and the exclusion constraint does the work for free. Retiring is not deleting: a retired pitch keeps its row, because historical occupancy has to know it existed, and stops counting as capacity.

Everything that can occupy a pitch — a provisional hold, a confirmed booking, a manual block, maintenance — is a row in unit_allocations under one constraint:

EXCLUDE USING gist (unit_id WITH =, stay WITH &&)
  WHERE (released_at IS NULL)

Two transactions that both try to take A14 for overlapping nights race inside PostgreSQL; one commits, the other gets 23P01, and the API turns that into a clean 409. No application locking, no read-then-write window, and it holds for a bug, a bulk import and a future channel manager equally. Fifty concurrent requests for one pitch produce exactly one hold.

stay is a GENERATED daterange derived from check_in and check_out, because Prisma has no range type — generated means no code path can update one without the other. The bounds are half-open, which is what makes same-day turnover legal: inclusive bounds would leave every departure day unbookable.

A hold is created before the booking exists and before any payment intent. Without it, a traveller who spends four minutes in 3-D Secure can lose the pitch and still be charged. It is real inventory under the same constraint, not an optimistic guess, and it expires on its own after fifteen minutes.

Bookings, convoys and the attendance registry

A booking is a header over one row per pitch. That shape is the whole design: a convoy — a family arriving with two caravans and a tent — is one reservation, one bill and one arrival over three pitches that are each allocated, moved and released independently.

Each booking_units row owns a unit_allocations row, which is what the exclusion constraint protects. So the guard that makes double-booking physically impossible governs bookings without knowing that bookings exist, and a trigger refuses any booking unit that disagrees with its allocation about the pitch or the dates.

  • The whole booking is one transaction. If the third caravan cannot be placed, the family must not end up with a two-pitch booking and a telephone call. Each pitch is taken inside a savepoint, so one contended pitch rolls back a single attempt and the search moves on rather than losing everything already placed.
  • Totals are derived, never asserted. A trigger recomputes the header from the items on every change, so no path — API, correction, import, psql session — can leave a booking whose header disagrees with its lines. Items are append-only: a correction is a new line with the opposite sign.
  • The state machine is in the database. These are the product’s rules, not one service’s. A booking that went from checked_out back to pending would break the invoice, the statistics and the attendance registry at once. Every transition is recorded by a trigger, so a change made by a script is in the history too.
  • Cancelling frees the pitch in the database. Doing it in the service would be a second place to forget, and a pitch left occupied by a booking that no longer exists is a night nobody can sell.
  • A licence plate is personal data. It is sealed with AES-256-GCM and never returned by the API — only the last four characters, so a human can confirm the right vehicle. Its lookup hash is an HMAC with a dedicated key: plate formats are short and structured enough that an unkeyed digest of every Saudi plate could be precomputed in seconds, which would leave the column as good as plaintext.

The evacuation list needs no PII permission. booking_guests carries an age band and a presence window and nothing that identifies anybody; names and documents arrive at check-in, encrypted, in their own table. Requiring a privileged read at an assembly point at three in the morning would be a safety defect dressed as a privacy feature.

Writes that must not happen twice carry an Idempotency-Key. The key is claimed with an INSERT, so the claim is decided by a primary key rather than by a read-then-write two requests can both pass; a repeat gets the stored response, and a repeat with a different body is refused rather than silently replayed.

Money, dates and numbers

  • Money is bigint minor units plus an explicit char(3) currency. Never a float. Three-decimal currencies exist — KWD, BHD, OMR, JOD, TND, LYD, IQD — and a wrong minor_unit silently multiplies every price in that currency by ten.
  • Exchange rates are snapshotted onto the transaction, so a report in EUR of a booking paid in SAR does not change when the rate moves.
  • Stay dates are plain dates, never timestamps. A night belongs to a local calendar date, so every camping carries an IANA timezone and nightly facts are built per timezone group. Without this, “arrivals today” drifts by a day.
  • Periods use daterange with half-open [check_in, check_out) bounds, which is what makes same-day turnover legal: 10–12 July and 12–15 July do not overlap.
  • weekend_days uses ISO-8601 weekday numbers per country, so {5,6} unambiguously means Friday–Saturday. Hardcoding Saturday–Sunday would break pricing, seasonality and every weekday chart in the launch market.

Pricing: rules, versions and the trace

A price has to be explainable years after it was charged. That single requirement decides the whole design: a rule is editable, a version is not, and publishing is the act that turns one into the other.

TableWhat it holds
rate_plansA named set of rules. One per camping may be the default; a partial unique index enforces it.
pricing_rulesThe editable definition: a charge type, a scope, how it calculates, and the conditions under which it applies.
pricing_rule_versionsA frozen copy with a validity window. Immutable, non-overlapping, append-only.
price_historyWhat a night actually cost, as an observation. What an authority reads.
tax_rulesStatutory taxes by jurisdiction. Reference data: no tenant column, no RLS, no operator may edit one.

The engine lives in packages/domain and is a pure function: no database, no clock, no randomness. Given the same versioned inputs it returns the same quote forever, which is what lets ten thousand generated stays be checked in a second — and what makes a price defensible in a dispute.

  • Resolution is per night, not per stay. A season boundary, a weekend and a public holiday can all fall inside one booking. Averaging across the stay would be simpler and would quietly overcharge Friday and undercharge Tuesday.
  • Modifiers apply in a fixed order — override, then delta, then multiplier, then absolute — with priority breaking ties and the version id breaking those, so two matching rules never depend on the order the database returned them.
  • Specificity is expressed as priority. A rule attached to one unit group is loaded with +1000; operator priority is capped at 1000, so a group-specific rule always outranks a plan-wide one and the ordering stays total.
  • Every line carries its trace — each rule that touched it, with the amount before and after. A modifier that changed nothing is left out, so the trace shows only what actually moved the price.
  • An included tax is extracted, not added. For a 15% inclusive rate the tax inside 115 is 15, not 17.25. Getting this backwards overcharges every guest by the rate — which is why both directions are golden-tested.
-- Two versions of one rule can never be in force at the same moment
ALTER TABLE pricing_rule_versions
  ADD COLUMN valid_range tstzrange
  GENERATED ALWAYS AS (tstzrange(valid_from, valid_to, '[)')) STORED;

ALTER TABLE pricing_rule_versions
  ADD CONSTRAINT ex_rule_versions_no_overlap
  EXCLUDE USING gist (pricing_rule_id WITH =, valid_range WITH &&);

Publishing is idempotent by content: a rule whose definition has not changed keeps the version it has, so pressing the button twice neither fills the history with identical rows nor moves the date a price took effect. Closing an open window is the one change a published version accepts — that is how it is superseded. Everything else, including every DELETE, is refused by a trigger with insufficient_privilege.

Editing a draft and publishing it are different permissions. pricing.write costs nothing to exercise; pricing.publish decides what a guest is charged, so a camping can hand the first to a receptionist without handing over the second. The public quote endpoint reads published versions only — a draft price is never an offer.

Bilingual and right-to-left

Arabic and English are both first-class. Arabic is not English with a flipped stylesheet: it changes layout direction, typography, numerals, calendars, pluralisation and which days are the weekend.

Four kinds of translatable content are kept apart, because conflating them is the common failure: UI strings in repository catalogues; the platform catalogue of facility and accommodation-type names, seeded; tenant content such as camping descriptions, written by the operator; and user-generated text stored as written.

  • Translations live in *_translations side tables, never a JSONB blob: indexable per locale, one row per locale enforced, and partial updates are not a read-modify-write race.
  • Layout uses logical properties only — ms-*, pe-*, start-* — never ml-* or left.
  • Arabic is never letter-spaced or uppercased: spacing breaks glyph joining.
  • Arabic has six plural categories — zero, one, two, few, many, other — so a count is never interpolated into a sentence written for English. Every count-bearing message is an ICU plural in both languages, and npm run verify:i18n refuses a build where an Arabic plural declares fewer than six, where the two catalogues disagree on a key, or where a placeholder exists in one language and not the other.
  • A direction is not a glyph. ← always points left, which in Arabic sends the reader backwards through time, so navigation arrows are chosen by reading direction rather than hard-coded.
  • Latin runs inside Arabic text — booking references, phone numbers, plates, URLs — are bidi-isolated, or they scramble visually.
  • Arabic has six plural categories against English’s two, so counted messages use ICU MessageFormat with all of them.
  • Everything is stored as Gregorian ISO dates; Hijri is a display option shown alongside it, so a booking date is never ambiguous.
  • A camping cannot be published without a name and short description in both languages. A half-translated listing is worse for a traveller than none.

Country compliance packs

The launch market is Saudi Arabia, with Romania and the EU planned. Guest registration law, identity document types, retention periods, tax mechanics, invoicing and statutory reports all differ. A compliance pack is a versioned bundle of configuration and report definitions for one country.

country_profiles is the anchor: required guest fields, allowed document types, retention days, weekend days, default and alternate calendar, tourist tax model, VAT, invoicing profile, privacy regime, jurisdiction levels. The check-in form is generated from it, so an operator cannot be asked for a passport number in a country where only a name is required.

There is no if (country === 'SA') anywhere in business code. Adding a country is: write a pack, seed it, done. That is the difference between a product with a translation and a platform that can operate in both regions.

Tourist tax in particular is not a percentage in most jurisdictions. It is an amount per person per night with exemptions by age, length of stay and residency, set by the locality and changing yearly — so tax rules carry a calculation basis, an exemptions document, locality scoping, effective dating and a legal reference.

Immutability, audit and authority data

Authority dashboards must show numbers that can be re-derived and defended. That constrains what the transactional core is allowed to do.

  • Prices are versioned, never overwritten. Publishing freezes a version; a booking stores the version that produced each line plus a calculation trace, so a dispute two years later is resolved by reading rather than guessing.
  • Financial rows are append-only. A wrong payment is corrected by a reversing row; an invoice is cancelled by a storno invoice.
  • Accounting periods close per camping and month. Edits in an open period are free and recorded; after close they need a distinct permission, a reason, and produce a correction rather than a silent rewrite.
  • Audit rows are written by database triggers, not only by application code, so a change from a maintenance script or a psql session is recorded too. The actor comes from the same transaction-local setting the RLS policies read.
  • Derived columns are excluded from audit diffs. Generating forty pitches updates a counter forty times; recording that would bury the real history.
  • Columns whose names look like credentials are redacted whatever the caller passes.

Guest identity data is split from statistics at the table level. The statistical row holds age band, birth year, nationality and dates — everything statistics need, nothing that identifies a person. The identity row holds the identifying data, encrypted, with a mandatory purge date. Retention can therefore destroy identities without destroying statistics, and authority overnight-stay reports need no personal-data permission at all.

Authority dashboards are aggregate-first with small-cell suppression. Identified access requires an approved legal-basis request bounded by camping and period, step-up two-factor, row caps, per-row access logging and operator notification. There is no bulk export of personal data. A national database of identity documents reachable from a browser by hundreds of public-sector accounts is exactly the system that ends up in a breach headline.

Database conventions

RuleDetail
Primary keysUUIDv7 — time-sortable, so insert-heavy tables keep dense B-tree pages, and not enumerable
Timestampstimestamptz, always UTC
Soft deleteOnly on catalogue and configuration entities. Never on bookings, payments, invoices, facts or audit
Uniqueness with soft deletePartial unique indexes, WHERE deleted_at IS NULL
Tenant columnPresent and NOT NULL even when reachable by join — RLS stays a single indexed equality, and a trigger keeps it agreeing with the parent
EnumsPostgreSQL enums for closed sets; lookup tables for anything an admin can extend
Namingsnake_case, plural tables, constraints prefixed ck_ / uq_ / fk_ / ex_ so an error names something meaningful

Constraints that encode a publish requirement are conditioned on publication. Requiring a complete season unconditionally made it impossible to create a draft at all — an operator cannot fill in a season before the row exists to hold it.

API conventions

/api/v1/public/*        anonymous — marketplace, reference data
/api/v1/auth/*          authentication lifecycle
/api/v1/me/*            the caller's own rows
/api/v1/owner/*         operator console   (organization / camping scope)
/api/v1/authority/*     authority console  (jurisdiction scope, read-only)
/api/v1/admin/*         platform administration

The namespace determines the guard stack, the database connection and the rate-limit bucket. That is not cosmetic: an authority endpoint physically cannot reach a write connection.

  • Errors are RFC 9457 application/problem+json. code is the stable machine contract; titles are localised.
  • Database constraint violations are translated, not swallowed: 409 for uniqueness and overlap, 422 for a check, 403 for row level security, each carrying the constraint name. An opaque 500 tells a caller nothing about whether they made a mistake or found a bug.
  • Idempotency-Key is required on bookings, payments, refunds and holds.
  • Zod schemas are .strict(), so an unexpected key is a 400 rather than silently dropped — which is what makes mass assignment a non-question.
  • Timestamps are ISO-8601 UTC; stay dates are local calendar dates with no timezone.
  • The API is the product. The web app is its first consumer; mobile and integrations use the same endpoints.

Migrations and environments

Each migration directory holds a generated migration.sql and a hand-written post.sql. The runner applies post.sql through the owner connection, tracked by checksum, and each file is idempotent so a re-run is safe.

npm run db:migrate          migrate deploy, then every post.sql
npm run db:seed             reference data, permissions, role presets
npm run db:drift            migrations vs datamodel, on a shadow database
npm run db:verify           reference-data guard tests
npm run db:verify:tenancy   RLS policies, the FORCE control, the runtime plumbing
npm run db:test-users       one active account per role
npm run db:grant            bootstrap the first platform administrator

Three database roles with three jobs: the schema owner runs migrations, app_rw is what the API connects as, and app_ro_reporting is read-only for the authority console. When debugging RLS by hand, connect as the owner and not as postgres — a superuser bypasses RLS unconditionally and FORCE does not apply to it, so it will show you every tenant’s rows and prove nothing.

Talking to the outside world

Nothing outside this system is connected yet — no payment gateway, no ZATCA, no channel manager. The two mechanisms every one of them will need are built first, because both fix problems that are cheap to prevent and expensive to discover.

The outbox fixes the dual write. Any code that changes the database and calls an external system has two ways to be wrong: commit and then fail the call, so the channel never hears that the plot is taken; or make the call and then roll back, so the channel hears about a booking that does not exist. Neither is fixable with a try/catch, because the failure mode is the process dying between the two.

So the intent is written into outbox_messages in the same transaction as the change. If the transaction rolls back the event never existed; if it commits, the event is queued. A dispatcher delivers it afterwards, at least once.

  • Claiming is one statement. FOR UPDATE SKIP LOCKED is what makes several dispatchers safe: each takes rows nobody else holds and none of them waits. A read followed by an update would hand the same message to two workers under any real concurrency.
  • Ordering is per key, not global. A message with an ordering key is only eligible once every earlier message with that key has been delivered. Availability for one camping is the case that forces it: two updates applied out of order leave the channel advertising inventory that was sold, and nothing in the logs says so. Messages with no key run in parallel.
  • A dead dispatcher releases its work. A claim is a lease, not a lock. A process that dies mid-delivery would otherwise strand its messages forever and the queue would silently stop; past the lease they are due again.
  • Delivery is at-least-once, so handlers must be idempotent. That is not a caveat to apologise for — exactly-once delivery over a network does not exist, and pretending otherwise is how systems end up charging twice. The idempotency store from the booking step is the other half of it.
  • A dead letter is loud. After eight attempts with capped exponential backoff the message stops and says so at error level. Something is not being told what happened, and nobody will notice unless it shouts.

The vault holds an operator’s integration secrets. Gateway keys, ZATCA certificates and OTA tokens cannot live in .env beside the platform’s own configuration: they belong to the operator, there is one set per operator, and they have to be rotatable without a deploy.

It is write-only from outside. A secret goes in and the only way it comes out is a use() call that hands it to one server-side callback — there is deliberately no getSecret() returning a string somebody could put in a log line or a response body. What the world may see is which provider, which purpose, a truncated keyed fingerprint so a person can say “the one ending 4f2a”, and the non-secret settings that travel with it. The same source-level check that confines guest identities asserts this file is the only one that opens a credential.

Rotation is a replace rather than an edit, so the audit trail shows what changed and when. Writing the same secret again is a no-op: otherwise a configuration script that re-applies itself would churn the trail on every run and make a real rotation impossible to spot in it.

Licensing and what it costs

Nothing in the stack costs a licence fee, and all of it may be used in a commercial product. That is a scanned result rather than an assumption: of the 264 packages actually installed, 208 are MIT, 22 Apache-2.0, 11 ISC, 12 BSD and 3 MPL-2.0 — and there is no GPL, AGPL or SSPL anywhere in the dependency tree.

ComponentVersionLicence
PostgreSQL17.11PostgreSQL Licence (BSD-style)
PostGIS3.5GPL v2
Redis8.0.2AGPLv3 / RSALv2 / SSPLv1
Node.js22.14MIT
pm26.0.14AGPL-3.0
Caddy2.6.2Apache-2.0
Debian13Free software
Next.js · React · NestJS · Prisma client · Tailwind · Zod—MIT / Apache-2.0
Inter · IBM Plex Sans Arabic—SIL Open Font Licence

Three of those are copyleft, and none of them reaches this application’s code. All three run as separate processes that the platform talks to over a socket — SQL, the Redis protocol, and process supervision. Communicating with a program over a protocol does not make your program a derivative work of it, which is the distinction the GPL family draws between linking and aggregation.

  • PostGIS — GPL v2. An extension loaded into the PostgreSQL server. GPLv2 has no network clause, so running it as a hosted service carries no obligation at all. The obligation appears only if PostGIS binaries are distributed — shipping a container to a customer’s own hardware, say — and then it is to make the PostGIS source available, not ours.
  • Redis — AGPLv3 / RSALv2 / SSPLv1 since 8.0. Used as a cache and rate-limit store from a separate process. The AGPL network clause would bite only if Redis itself were modified and that modified Redis offered over a network; RSALv2 and SSPLv1 forbid offering Redis as a managed service, which is not what this is. If the question is unwelcome at all, Valkey is a drop-in BSD-3 fork under the Linux Foundation — same protocol, same client library, no change beyond the connection string.
  • pm2 — AGPL-3.0. Supervises the two Node processes; nothing links to it. A systemd unit per process is a zero-licence replacement if it is ever unwanted. pm2 also sells a hosted monitoring product, which is neither used nor required.

The useful half of the answer is the other table. The software is free; the services are where the bill is.

WhatExpect to pay
Hosting in a KSA regionRequired by PDPL. The single largest new cost.
SAMA-licensed payment gatewayPer-transaction fees, set by the chosen provider
ZATCA e-invoicingThe authority charges nothing; onboarding needs a CSID per operator
Email deliveryFree to a few hundred a day, paid above that
Maps / GIS for the PRO site mapMetered per load
Weather service with KSA coverageMetered
OTA connectivityBooking.com charges nothing for connectivity; an aggregator would
TLS certificatesFree — Let’s Encrypt, automated by Caddy

One thing that is a licence non-issue but a privacy one. The two font families are openly licensed, but they are fetched from Google’s CDN, which sends every visitor’s IP address to Google. German courts have found that a GDPR violation, and the same reasoning applies under PDPL — on top of the data-residency argument that already points at KSA hosting. Self-hosting the two families removes the question and is a small change.

What is built today

StepDelivered
0 · FoundationsMonorepo, bilingual shell with light and dark, deploy pipeline
1 · Reference dataGeography, currencies, facilities, accommodation and document types, compliance profiles
2 · IdentityRegistration, verification, login, refresh rotation with reuse detection, password reset, TOTP, session inventory
3 · Authorisation58 permissions, 12 role presets, scoped assignments, boot-time coverage assertion, access console
4 · Tenant isolationRLS machinery, database roles, the registry assertion that guards every later table
6 · CatalogOrganisations, campings, bilingual descriptions, facilities with prices, publish checklist
7 · InventoryUnit groups, physical pitches, bulk generation, derived capacity counter
8 · AvailabilityOne allocation table under an exclusion constraint, provisional holds, operator blocks, the availability projection, publishing
9 · PricingA pure engine over versioned rules, immutable published versions, the price ledger, statutory taxes, public quotes, and a preview that shows its working
10 · BookingsConvoys over several pitches, vehicles with sealed plates, frozen charges, a database-enforced state machine, check-in and check-out, and the attendance registry
11 · Calendar & dashboardOne grid of every pitch and every occupancy with its source channel, and a dashboard of occupancy, booked value, channel mix and what needs attention
12 · Guest registryCheck-in against encrypted identity documents, the country’s own required fields, and a PII boundary the build refuses to cross
13 · EntitlementsBase and PRO as data rather than code, a boot-time coverage assertion, and 402 kept distinct from 403 — not allowed to is not the same as not paid for
14 · Outbox & vaultIntent to tell the outside world written in the same transaction as the thing it is about; a write-only credential store that never hands a secret back
15 · PaymentsCash and online, refunds bounded cumulatively by the charge they reverse, derived settlement no code path can contradict, daily takings, and a sandbox gateway standing in for a provider nobody has chosen yet
16 · ZATCA invoicingUBL 2.1 documents, cryptographically stamped and chained so an altered invoice breaks the chain visibly, a QR a phone reads with no network, and submission through the outbox — against a sandbox authority until a real certificate exists
17 · UpkeepSupply status per pitch kept separate from the capability the pitch is sold with, scheduled and recurring work, and withdrawals the database enforces — a pitch cannot be under repair in one table and sellable in another
18 · SuppliesA stock ledger rather than a stock column: what is on hand is derived from every receipt, issue and count and cannot be written directly, and a stock take records the difference so the gap stays visible
20 · ReportingThe month’s figures with booked, collected and outstanding kept apart, occupancy night by night, costs by supplier, and a VAT position taken from invoices so a closed month cannot move
26 · PrivacyConsent that records the lawful basis rather than a yes/no, a thirty-day clock the database owns, nothing disclosed before the requester is verified, and erasure that is partly refusable and says what it kept and why

Deferred on purpose: camping media and versioned policies; the audit hash chain and viewers, though the database-trigger half landed with the first business tables; the authoritative Saudi governorate import; an admin interface for granting roles; and discounts, vouchers and the signed quote token, which belong with the booking step that consumes them.

What comes next

  • Real credentials. Both the payment gateway and the tax authority run against sandboxes that implement the same interfaces a real one will. Connecting them is blocked on a SAMA-licensed provider being named and a Saudi VAT registration being issued — not on code.
  • The channel manager. OTA synchronisation and overbooking protection — the glamping half of the business.
  • Hosting in the Kingdom. PDPL requires Saudi personal data to stay in Saudi Arabia, and this runs in Europe. The most serious open item, and the only one that is not code.

Lessons that kept recurring

Found the hard way while building, each now guarded against, and recorded because every one will be tempting to reintroduce.

  • Code that computes access must not be subject to the access it computes. Scope resolution, scope expansion and a global uniqueness check all read through the RLS-filtered client and therefore saw nothing. Guards also run before the interceptor that publishes the scope, so during authorisation there is nothing to filter by at all. Such reads go through an explicitly named system path.
  • A constraint encoding a publish requirement makes drafts impossible. Completeness rules belong to the publish checklist, or must be conditioned on status. The same mistake in a query: the price preview looked up the default rate plan withstatus = 'active', which made it impossible to price a plan before publishing it — the one thing a preview exists for.
  • A display utility can break a layout invisibly. .ltr-run sets display: inline-block so a Latin run keeps its own box inside Arabic text. On a <td> that removes the cell from the table and the row silently comes apart. The utility now restores table-cell on cells, so the trap cannot catch the next person.
  • FORCE ROW LEVEL SECURITY is not optional. Without it the table owner — the role that runs migrations — bypasses every policy, and the barrier is absent exactly where it is least likely to be noticed.
  • Shell parsing of .env ate a trailing =. IFS='=' read -r key value strips one trailing delimiter, so every base64 secret ending in a single pad character arrived one byte short — silently corrupting the password pepper for everything launched from the deploy script.
  • pm2 restart --update-env does not re-read the ecosystem file. New .env values are ignored until startOrReload.
  • cmd && echo ok is not gated by set -e. Bash ignores the failure of any command in an AND-OR list except the last, so a smoke test written that way reported success over a dead API.
  • A test that cannot fail is not a test. Every guard suite here was proven to fail by deliberately breaking what it checks.