From 44b5e87805559f703424c2fe948f7f80cb72c5bb Mon Sep 17 00:00:00 2001 From: Stefan Date: Sun, 19 Jul 2026 11:47:20 +0100 Subject: [PATCH 01/17] Validate structured storage values --- scripts/mutation/equivalent-mutants.txt | 16 +- src/features/admin/attendee-form-model.ts | 4 +- src/features/admin/attendees.ts | 2 +- src/features/admin/catalog-transfer/import.ts | 4 +- src/features/admin/catalog-transfer/schema.ts | 11 +- .../api/payment-processing/metadata.ts | 13 +- src/features/public/pages.ts | 4 +- src/shared/address-lookup/types.ts | 7 +- src/shared/admin-features.ts | 9 +- src/shared/booking-date-fields.ts | 8 +- src/shared/booking/model.ts | 10 +- src/shared/dates.ts | 10 +- src/shared/db/address-cache.ts | 30 ++- src/shared/db/attendees/capacity/range.ts | 4 +- src/shared/db/attendees/create.ts | 4 +- src/shared/db/attendees/pii.ts | 50 +++-- src/shared/db/attendees/servicing.ts | 6 +- src/shared/db/attendees/update.ts | 4 +- src/shared/db/built-sites.ts | 42 ++-- src/shared/db/capacity.ts | 6 +- src/shared/db/contact-preferences.ts | 26 ++- src/shared/db/groups.ts | 9 +- src/shared/db/listings/table.ts | 34 ++-- src/shared/db/processed-payments.ts | 28 ++- src/shared/db/sumup-checkouts.ts | 14 +- src/shared/db/table.ts | 57 +++++- src/shared/db/token-attempts.ts | 18 +- src/shared/email-renderer.ts | 4 +- src/shared/listing-defaults.ts | 36 ++-- src/shared/listing-parents-rules.ts | 8 +- src/shared/listings-actions.ts | 4 +- src/shared/types.ts | 53 +++-- src/shared/validation/number.ts | 50 +++-- src/shared/validation/stored-json.ts | 46 +++++ src/shared/validation/string.ts | 5 +- src/ui/templates/admin/listings/details.tsx | 4 +- .../templates/admin/listings/form-values.tsx | 4 +- src/ui/templates/tickets.tsx | 4 +- test/shared/admin-features.test.ts | 86 +++++++- test/shared/db/address-cache.test.ts | 9 + test/shared/db/attendees/pii.test.ts | 14 +- test/shared/db/built-sites.test.ts | 11 + test/shared/db/contact-preferences.test.ts | 17 ++ test/shared/db/listings/table.test.ts | 189 ++++++++++++++++-- test/shared/db/processed-payments.test.ts | 11 + test/shared/db/sumup-checkouts.test.ts | 10 + test/shared/db/table.test.ts | 39 ++++ .../cache.test.ts} | 0 .../write-row.test.ts} | 0 test/shared/db/token-attempts.test.ts | 15 +- test/shared/listing-defaults.test.ts | 31 +++ test/shared/validation/number.test.ts | 37 ++++ test/shared/validation/stored-json.test.ts | 63 ++++++ 53 files changed, 934 insertions(+), 246 deletions(-) create mode 100644 src/shared/validation/stored-json.ts rename test/shared/db/{table-cache.test.ts => table/cache.test.ts} (100%) rename test/shared/db/{table-write-row.test.ts => table/write-row.test.ts} (100%) create mode 100644 test/shared/validation/stored-json.test.ts diff --git a/scripts/mutation/equivalent-mutants.txt b/scripts/mutation/equivalent-mutants.txt index b1aab318a0..34d0f55154 100644 --- a/scripts/mutation/equivalent-mutants.txt +++ b/scripts/mutation/equivalent-mutants.txt @@ -71,7 +71,7 @@ src/shared/accounting/manual-entries.ts:209:29 ?? → || # guard error messag src/shared/checkout-ledger.ts:35:72 ?? → || # find(...)?.amount: number|undefined; the only falsy-non-null amount is 0 and 0 ?? 0 === 0 || 0 src/features/settings-bundles.ts:264:40 ?? → || # bundle is a readonly string[] or undefined; every present array, including [], is truthy src/shared/accounting/queries.ts:162:26 || → && # transferActivityBounds: MIN(occurred_at) and MAX(occurred_at) over one table are NULL together (both iff the table is empty), so either-null and both-null coincide -src/shared/admin-features.ts:95:58 ?? → || # find(): AdminFeatureDefinition|undefined; a feature object is always truthy +src/shared/admin-features.ts:121:58 ?? → || # find(): AdminFeatureDefinition|undefined; a feature object is always truthy src/shared/db/admin-features.ts:50:10 __required_setting_condition__ → "" # the placeholder key is never stored: a failed condition always aborts on its NULL value src/shared/db/admin-features.ts:50:10 __required_setting_condition__ → "__required_setting_condition__ mutated" # same as above; no successful statement exposes this key src/shared/db/admin-features.ts:76:49 ?? → || # inUseSql: a non-empty SQL string|undefined, so only undefined reaches the fallback @@ -102,13 +102,13 @@ src/fp.ts:449:49 ?? → || # items?.length is undefined or a non-negative int # undefined, paired null checks already reject both nullish values, optional # conditions/dependencies are objects or arrays, and non-generated primary keys # are overwritten from the input-column fold in either initial-row branch. -src/shared/db/table.ts:282:17 === → == # queryOne returns StoredRow|null, never undefined -src/shared/db/table.ts:349:25 !== → != # paired checks reject both null and undefined before applying a write transform -src/shared/db/table.ts:501:24 ?: → consequent only # generated keys use the consequent; non-generated keys are overwritten by their input-column value -src/shared/db/table.ts:541:28 ?? → || # condition?.args is an array or undefined, and every array is truthy -src/shared/db/table.ts:667:59 ?? → || # dependsOn is a readonly array or undefined, and every array is truthy -src/shared/db/table.ts:694:32 ?? → || # dependsOn is a readonly array or undefined, and every array is truthy -src/shared/db/table.ts:715:6 === → == # wrapNullable constrains T to exclude undefined, so v is T|null +src/shared/db/table.ts:283:17 === → == # queryOne returns StoredRow|null, never undefined +src/shared/db/table.ts:350:25 !== → != # paired checks reject both null and undefined before applying a write transform +src/shared/db/table.ts:502:24 ?: → consequent only # generated keys use the consequent; non-generated keys are overwritten by their input-column value +src/shared/db/table.ts:542:28 ?? → || # condition?.args is an array or undefined, and every array is truthy +src/shared/db/table.ts:667:21 ?? → || # dependsOn is a readonly array or undefined, and every array is truthy +src/shared/db/table.ts:700:32 ?? → || # dependsOn is a readonly array or undefined, and every array is truthy +src/shared/db/table.ts:721:6 === → == # wrapNullable constrains T to exclude undefined, so v is T|null # Login attempt rows store an integer count. For undefined, null, zero, or any # non-zero integer, `(attempts ?? 0) + 1` and `(attempts || 0) + 1` agree. diff --git a/src/features/admin/attendee-form-model.ts b/src/features/admin/attendee-form-model.ts index c4d7fb955b..f7ff006bf7 100644 --- a/src/features/admin/attendee-form-model.ts +++ b/src/features/admin/attendee-form-model.ts @@ -30,8 +30,8 @@ import type { FormParams } from "#shared/form-data.ts"; import { START_DATE_FIELD } from "#shared/order-select.ts"; import { type ContactInfo, + clampDurationDays, type ListingWithCount, - normalizeDurationDays, } from "#shared/types.ts"; import { isIsoDate } from "#shared/validation/date.ts"; import { @@ -256,7 +256,7 @@ export const attendeeBookingsFromLines = ( /** Clamp a submitted day count to the valid range; blank defaults to 1. */ const clampDayCount = (raw: number | null): number => - normalizeDurationDays(raw ?? 1); + clampDurationDays(raw ?? 1); /** * The status an attendee resolves to: their submitted choice, or the public diff --git a/src/features/admin/attendees.ts b/src/features/admin/attendees.ts index a43102b237..2474afc1f2 100644 --- a/src/features/admin/attendees.ts +++ b/src/features/admin/attendees.ts @@ -207,7 +207,7 @@ const buildCreateAttendeeInput = ( const isDaily = listing.listing_type === "daily"; // Customisable daily bookings span the admin's chosen day count (a required, // options-constrained field; any odd value is clamped downstream by - // normalizeDurationDays); other daily bookings use the fixed duration. + // clampDurationDays); other daily bookings use the fixed duration. const durationDays = listing.customisable_days ? Number(values.day_count) : listing.duration_days; diff --git a/src/features/admin/catalog-transfer/import.ts b/src/features/admin/catalog-transfer/import.ts index c2f3613047..538bce0db8 100644 --- a/src/features/admin/catalog-transfer/import.ts +++ b/src/features/admin/catalog-transfer/import.ts @@ -62,12 +62,12 @@ import { seenBefore } from "#shared/seen-before.ts"; import { type AdminLevel, availableDayCounts, + clampDurationDays, type DayPricedListing, type Group, type Listing, type ListingType, type ListingWithCount, - normalizeDurationDays, parseDayPrices, } from "#shared/types.ts"; import { childAddOnError } from "../listings-parents.ts"; @@ -229,7 +229,7 @@ const listingDataToInput = ( const listingToEdge = (listing: Listing): EdgeListing => ({ customisable_days: listing.customisable_days, day_prices: listing.day_prices, - duration_days: normalizeDurationDays(listing.duration_days), + duration_days: clampDurationDays(listing.duration_days), id: listing.id, listing_type: listing.listing_type, months_per_unit: listing.months_per_unit, diff --git a/src/features/admin/catalog-transfer/schema.ts b/src/features/admin/catalog-transfer/schema.ts index 7e2746113e..dfb8f97fb9 100644 --- a/src/features/admin/catalog-transfer/schema.ts +++ b/src/features/admin/catalog-transfer/schema.ts @@ -24,6 +24,7 @@ import { ListingTypeSchema, MAX_DURATION_DAYS, } from "#shared/types.ts"; +import { integerAtLeast } from "#shared/validation/number.ts"; /** * True when `value` is storable in a datetime column: empty (no value), or a @@ -88,16 +89,14 @@ export const CATALOG_TRANSFER_VERSION = 1; * so an out-of-safe-range magnitude like `1e100` — which `Number.isInteger` * accepts — is a field error here rather than being rounded or throwing a raw * error at the storage layer, matching the form's money parser. */ -const intAtLeast = (min: number) => - v.pipe(v.number(), v.safeInteger(), v.minValue(min)); /** A whole non-negative integer (counts, day windows, minor-unit prices). */ -const NonNegativeIntSchema = intAtLeast(0); +const NonNegativeIntSchema = integerAtLeast(0); /** A whole positive integer (durations, quantities). */ -const PositiveIntSchema = intAtLeast(1); +const PositiveIntSchema = integerAtLeast(1); /** A booking duration in whole days: 1..MAX_DURATION_DAYS, matching the listing * form's cap so an over-limit blob is a field error, not silently clamped. */ const DurationDaysSchema = v.pipe( - intAtLeast(1), + integerAtLeast(1), v.maxValue(MAX_DURATION_DAYS, `must be at most ${MAX_DURATION_DAYS} days`), ); /** A single valid contact-field name (email/phone/address/…). */ @@ -122,7 +121,7 @@ const FieldsSchema = v.pipe( * rather than a day that never matches an availability check. */ const BookableDaySchema = v.picklist(VALID_DAY_NAMES); /** A minor-unit price — a non-negative integer. */ -const PriceSchema = intAtLeast(0); +const PriceSchema = integerAtLeast(0); /** A required, trimmed, non-empty name reference. */ const NameRefSchema = v.pipe(v.string(), v.trim(), v.minLength(1)); /** A day-count JSON key: a positive whole number within the bookable range, so a diff --git a/src/features/api/payment-processing/metadata.ts b/src/features/api/payment-processing/metadata.ts index 6d931918d6..6cb1739291 100644 --- a/src/features/api/payment-processing/metadata.ts +++ b/src/features/api/payment-processing/metadata.ts @@ -48,6 +48,9 @@ const parseListingTextAnswerIds = jsonMetaField< Record | undefined >(undefined); +const textOrEmpty = (value: unknown): string => + typeof value === "string" ? value : ""; + /** * Parse booking items from metadata JSON. Returns null when the JSON is * unparseable, not an array, or empty. @@ -108,21 +111,21 @@ export const extractIntent = ( const siteTokenIndex = metadata.site_token_index || undefined; const thankYouUrl = metadata.thank_you_url || undefined; return { - address: metadata.address, + address: textOrEmpty(metadata.address), allocations, balanceAttendeeId, date: metadata.date || null, dayCount, - email: metadata.email, + email: textOrEmpty(metadata.email), items, listingAnswerIds, listingTextAnswerIds, modifiers: parseModifierRefs(metadata.modifiers), - name: metadata.name, - phone: metadata.phone, + name: textOrEmpty(metadata.name), + phone: textOrEmpty(metadata.phone), reservationAmount, siteTokenIndex, - special_instructions: metadata.special_instructions, + special_instructions: textOrEmpty(metadata.special_instructions), thankYouUrl, }; }; diff --git a/src/features/public/pages.ts b/src/features/public/pages.ts index cd4e2d0252..6f4f8079e6 100644 --- a/src/features/public/pages.ts +++ b/src/features/public/pages.ts @@ -30,9 +30,9 @@ import { requirePublicSite } from "#shared/public-site.ts"; import type { ResponseHandler } from "#shared/response-steps.ts"; import { loadSortedListings } from "#shared/sort-listings.ts"; import { + clampDurationDays, type GroupWithMembers, type ListingWithCount, - normalizeDurationDays, } from "#shared/types.ts"; import { parseEmail } from "#shared/validation/email.ts"; import { @@ -81,7 +81,7 @@ export const handleHome: ResponseHandler = () => * fixed daily listing books its whole duration. Mirrors * {@link getBookableStartDates}'s span. */ const cardSpanDays = (listing: ListingWithCount): number => - listing.customisable_days ? 1 : normalizeDurationDays(listing.duration_days); + listing.customisable_days ? 1 : clampDurationDays(listing.duration_days); /** The daily listings NOT bookable on `date`: outside their bookable calendar, * or without capacity for their span starting that day. One remaining query diff --git a/src/shared/address-lookup/types.ts b/src/shared/address-lookup/types.ts index 31d5a928b4..b49dc8c844 100644 --- a/src/shared/address-lookup/types.ts +++ b/src/shared/address-lookup/types.ts @@ -36,7 +36,12 @@ export type AddressLookupProvider = Exclude; /** One matching address: its ready-to-display line, plus the provider's * latitude/longitude when it knows them ("" when it doesn't). */ -export type AddressMatch = { line: string; lat: string; lng: string }; +export const AddressMatchSchema = v.strictObject({ + lat: v.string(), + line: v.string(), + lng: v.string(), +}); +export type AddressMatch = v.InferOutput; /** A successful search: one match per address the provider found. */ export type AddressLookupResult = { addresses: AddressMatch[] }; diff --git a/src/shared/admin-features.ts b/src/shared/admin-features.ts index 57cdf831d2..95969d2074 100644 --- a/src/shared/admin-features.ts +++ b/src/shared/admin-features.ts @@ -1,4 +1,5 @@ import * as v from "valibot"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; /** * The admin features operators can choose to show. This one registry drives the @@ -81,6 +82,7 @@ const EnabledFeaturesSchema = v.pipe( "Every admin feature must have an enabled value", ), ); +const enabledFeaturesJson = defineStoredJson(EnabledFeaturesSchema); const DEFAULT_ENABLED_FEATURES = Object.freeze( Object.fromEntries(FEATURE_KEYS.map((key) => [key, false])), @@ -91,10 +93,13 @@ const DEFAULT_ENABLED_FEATURES = Object.freeze( export const parseEnabledFeatures = (value: string): EnabledFeatures => value === "" ? DEFAULT_ENABLED_FEATURES - : (v.parse(EnabledFeaturesSchema, JSON.parse(value)) as EnabledFeatures); + : (enabledFeaturesJson.read( + value, + "settings.enabled_features", + ) as EnabledFeatures); export const serializeEnabledFeatures = (features: EnabledFeatures): string => - JSON.stringify(v.parse(EnabledFeaturesSchema, features)); + enabledFeaturesJson.write(features, "settings.enabled_features"); export const setFeatureEnabled = ( features: EnabledFeatures, diff --git a/src/shared/booking-date-fields.ts b/src/shared/booking-date-fields.ts index cf8beb8c75..abb758063c 100644 --- a/src/shared/booking-date-fields.ts +++ b/src/shared/booking-date-fields.ts @@ -12,7 +12,7 @@ import { capacityDateFor } from "#shared/capacity-rules.ts"; import type { ListingWithCount } from "#shared/types.ts"; -import { normalizeDurationDays } from "#shared/types.ts"; +import { clampDurationDays } from "#shared/types.ts"; /** The listing facts the row builder reads to derive a booking's date and * duration. Narrower than the full listing so the helper stays pure over the @@ -30,7 +30,7 @@ export type BookingDateSource = Pick< * - A non-customisable `daily` listing spans its fixed `duration_days`. * - A `standard` listing spans one dateless day (no range column). * - * `dayCount` defaults to `1`, and {@link normalizeDurationDays} clamps + * `dayCount` defaults to `1`, and {@link clampDurationDays} clamps * non-finite input back to `1`, so a genuinely optional `dayCount` (a legacy * signed session without `day_count`, modelled as `undefined` on * `BookingIntent`) flows through that default unchanged — missing day count @@ -45,8 +45,8 @@ export const bookingDateFields = ( ): { date: string | null; durationDays: number } => ({ date: capacityDateFor(listing.listing_type, date), durationDays: listing.customisable_days - ? normalizeDurationDays(dayCount) + ? clampDurationDays(dayCount) : listing.listing_type === "daily" - ? normalizeDurationDays(listing.duration_days) + ? clampDurationDays(listing.duration_days) : 1, }); diff --git a/src/shared/booking/model.ts b/src/shared/booking/model.ts index 80a1cc3f3b..eb1bdff905 100644 --- a/src/shared/booking/model.ts +++ b/src/shared/booking/model.ts @@ -3,10 +3,10 @@ import { getBookableStartDates, isBookingRangeValid } from "#shared/dates.ts"; import { ascending, availableDayCounts, + clampDurationDays, dayPriceFor, type Holiday, type ListingWithCount, - normalizeDurationDays, PARENT_CHILD_GROUP_UNITS, type SharedGroupCapacity, } from "#shared/types.ts"; @@ -84,7 +84,7 @@ export const childUsesSameDays = (child: TicketListing): boolean => child.listing.customisable_days || child.listing.listing_type !== "daily" || - normalizeDurationDays(child.listing.duration_days) === days; + clampDurationDays(child.listing.duration_days) === days; /** The order's resolved date is valid for a daily child's own calendar. */ export const childDateOk = @@ -145,7 +145,7 @@ export const childDaysFromParent = ( ): T => { if (parent.customisable_days) return customisableValue; if (parent.listing_type === "daily") { - return normalizeDurationDays(parent.duration_days) as T; + return clampDurationDays(parent.duration_days) as T; } return standardValue; }; @@ -160,7 +160,7 @@ export const fixedParentDays = ( childDaysFromParent( parent, null, - normalizeDurationDays(parent.duration_days), + clampDurationDays(parent.duration_days), ); /** Keeps options that at least one child can support. */ @@ -251,7 +251,7 @@ export const dayCountsChildSupports = ( ): number[] | null => { if (child.listing.customisable_days) return availableDayCounts(child.listing); if (child.listing.listing_type === "daily") { - return [normalizeDurationDays(child.listing.duration_days)]; + return [clampDurationDays(child.listing.duration_days)]; } return null; }; diff --git a/src/shared/dates.ts b/src/shared/dates.ts index 85fa36f4cd..1cdc51b1bd 100644 --- a/src/shared/dates.ts +++ b/src/shared/dates.ts @@ -13,9 +13,9 @@ import { utcToZoned, } from "#shared/timezone.ts"; import { + clampDurationDays, type Holiday, type Listing, - normalizeDurationDays, } from "#shared/types.ts"; /** Month names for display */ @@ -181,9 +181,7 @@ export const getAvailableDates = ( durationOverride?: number, ): string[] => { const range = bookableRange(listing); - const duration = normalizeDurationDays( - durationOverride ?? listing.duration_days, - ); + const duration = clampDurationDays(durationOverride ?? listing.duration_days); return filter((d: string) => isRangeBookable(d, duration, range.bookableDays, holidays, range.end), )(dateRange(range.start, range.end)); @@ -232,7 +230,7 @@ export const isBookingRangeValid = ( if (date < range.start) return false; return isRangeBookable( date, - normalizeDurationDays(days), + clampDurationDays(days), range.bookableDays, holidays, range.end, @@ -250,7 +248,7 @@ export const getNextBookableDate = ( ): string | null => { const range = bookableRange(listing); if (range.bookableDays.length === 0) return null; - const duration = normalizeDurationDays(listing.duration_days); + const duration = clampDurationDays(listing.duration_days); let current = range.start; while (current <= range.end) { diff --git a/src/shared/db/address-cache.ts b/src/shared/db/address-cache.ts index e5b0572336..782f01a2ec 100644 --- a/src/shared/db/address-cache.ts +++ b/src/shared/db/address-cache.ts @@ -10,13 +10,18 @@ */ /* jscpd:ignore-start */ -import type { AddressMatch } from "#shared/address-lookup/types.ts"; +import * as v from "valibot"; +import { + type AddressMatch, + AddressMatchSchema, +} from "#shared/address-lookup/types.ts"; import { decrypt, encrypt } from "#shared/crypto/encryption.ts"; import { hmacHash } from "#shared/crypto/hashing.ts"; import type { BlindIndex, EnvKeyEncrypted } from "#shared/crypto/sealed.ts"; import { execute, queryOne } from "#shared/db/client.ts"; import { ADDRESS_CACHE_MS } from "#shared/limits.ts"; import { nowMs } from "#shared/now.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; /* jscpd:ignore-end */ /** @@ -32,6 +37,10 @@ export const computeAddressSearchIndex = ( const freshCutoffIso = (): string => new Date(nowMs() - ADDRESS_CACHE_MS).toISOString(); +const cachedAddressesJson = defineStoredJson( + v.union([v.array(v.string()), v.array(AddressMatchSchema)]), +); + /** Read a fresh cached result. Null on miss (absent or expired). Rows cached * before matches carried coordinates hold bare line strings; those read as a * miss too, so the next lookup re-fetches the postcode WITH coordinates and @@ -44,12 +53,15 @@ export const getCachedAddresses = async ( [searchIndex, freshCutoffIso()], ); if (!row) return null; - const entries = JSON.parse(await decrypt(row.results)) as ( - | string - | AddressMatch - )[]; - if (entries.some((entry) => typeof entry === "string")) return null; - return entries as AddressMatch[]; + const entries = cachedAddressesJson.read( + await decrypt(row.results), + `address_cache.results for ${searchIndex}`, + ); + return entries.every( + (entry): entry is AddressMatch => typeof entry !== "string", + ) + ? entries + : null; }; /** Cache a lookup result, replacing any previous row for the same search. */ @@ -62,7 +74,9 @@ export const storeCachedAddresses = async ( "ON CONFLICT(search_index) DO UPDATE SET results = excluded.results, created = excluded.created", [ searchIndex, - await encrypt(JSON.stringify(addresses)), + await encrypt( + cachedAddressesJson.write(addresses, "address_cache.results"), + ), new Date(nowMs()).toISOString(), ], ); diff --git a/src/shared/db/attendees/capacity/range.ts b/src/shared/db/attendees/capacity/range.ts index 7b1069ea6d..97de23f64e 100644 --- a/src/shared/db/attendees/capacity/range.ts +++ b/src/shared/db/attendees/capacity/range.ts @@ -1,7 +1,7 @@ import { filter, map, pipe, sumOf } from "#fp"; import { addDays } from "#shared/dates.ts"; import { dateToRange } from "#shared/db/capacity.ts"; -import { normalizeDurationDays } from "#shared/types.ts"; +import { clampDurationDays } from "#shared/types.ts"; /** Convert a nullable date to the stored half-open range. */ export const dateToStartEnd = ( @@ -18,7 +18,7 @@ export const expandDailyRange = ( date: string, durationDays: number, ): string[] => { - const duration = normalizeDurationDays(durationDays); + const duration = clampDurationDays(durationDays); return Array.from({ length: duration }, (_, i) => addDays(date, i)); }; diff --git a/src/shared/db/attendees/create.ts b/src/shared/db/attendees/create.ts index 7b224b4667..84c0f3c4a7 100644 --- a/src/shared/db/attendees/create.ts +++ b/src/shared/db/attendees/create.ts @@ -35,7 +35,7 @@ import { anyModifierSoldOut } from "#shared/db/modifier-usage.ts"; import { type Attendee, type ContactInfo, - normalizeDurationDays, + clampDurationDays, } from "#shared/types.ts"; /* jscpd:ignore-end */ @@ -74,7 +74,7 @@ const buildAttendeeResult = (input: BuildAttendeeInput): Attendee => ({ created: input.created, date: input.date, end_date: input.date - ? addDays(input.date, normalizeDurationDays(input.durationDays ?? 1)) + ? addDays(input.date, clampDurationDays(input.durationDays ?? 1)) : null, kind: input.kind, lat: "", diff --git a/src/shared/db/attendees/pii.ts b/src/shared/db/attendees/pii.ts index 1138569528..e97dba1b46 100644 --- a/src/shared/db/attendees/pii.ts +++ b/src/shared/db/attendees/pii.ts @@ -7,6 +7,7 @@ */ /* jscpd:ignore-start */ +import * as v from "valibot"; import { map } from "#fp"; import { hmacHash } from "#shared/crypto/hashing.ts"; import { @@ -24,33 +25,48 @@ import type { import { settings } from "#shared/db/settings.ts"; import { nowIso } from "#shared/now.ts"; import type { ContactInfo, PiiBlob } from "#shared/types.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; /* jscpd:ignore-end */ /** Current PII blob schema version */ export const PII_BLOB_VERSION = 1; +const PiiBlobSchema: v.GenericSchema = v.strictObject({ + a: v.string(), + e: v.string(), + la: v.optional(v.string()), + lo: v.optional(v.string()), + n: v.string(), + p: v.string(), + pi: v.string(), + s: v.string(), + t: v.string(), + v: v.optional(v.literal(PII_BLOB_VERSION), PII_BLOB_VERSION), +}); +const piiBlobJson = defineStoredJson(PiiBlobSchema); + /** Build a PII blob JSON from contact fields. An unpinned latitude/longitude * ("") is left out of the JSON so blobs without a pin stay as small as before. */ export const buildPiiBlob = (info: AttendeePii): string => - JSON.stringify({ - a: info.address, - e: info.email, - la: info.lat || undefined, - lo: info.lng || undefined, - n: info.name, - p: info.phone, - pi: info.payment_id, - s: info.special_instructions, - t: info.ticket_token, - v: PII_BLOB_VERSION, - } satisfies PiiBlob); + piiBlobJson.write( + { + a: info.address, + e: info.email, + la: info.lat || undefined, + lo: info.lng || undefined, + n: info.name, + p: info.phone, + pi: info.payment_id, + s: info.special_instructions, + t: info.ticket_token, + v: PII_BLOB_VERSION, + }, + "attendees.pii_blob", + ); /** Parse a PII blob JSON back into contact fields (defaults v to 1 for pre-versioned blobs) */ -export const parsePiiBlob = (json: string): PiiBlob => { - const blob = JSON.parse(json) as PiiBlob; - blob.v ??= PII_BLOB_VERSION; - return blob; -}; +export const parsePiiBlob = (json: string): PiiBlob => + piiBlobJson.read(json, "attendees.pii_blob"); /** Encrypt a PII blob JSON string with the public key */ export const encryptPiiBlob = ( diff --git a/src/shared/db/attendees/servicing.ts b/src/shared/db/attendees/servicing.ts index f01163c0ef..1b6e7786b5 100644 --- a/src/shared/db/attendees/servicing.ts +++ b/src/shared/db/attendees/servicing.ts @@ -51,7 +51,7 @@ import { import { settings } from "#shared/db/settings.ts"; import type { TransferInput } from "#shared/ledger/types.ts"; import { nowIso } from "#shared/now.ts"; -import { type Attendee, normalizeDurationDays } from "#shared/types.ts"; +import { type Attendee, clampDurationDays } from "#shared/types.ts"; /* jscpd:ignore-end */ /** An answer chosen for a service event's custom question. Only the `answerId` @@ -195,7 +195,7 @@ const saveServicingAnswers = ( const durationDaysFromRow = (row: ListingAttendeeRow): number | undefined => { if (!row.start_at || !row.end_at) return; const ms = new Date(row.end_at).getTime() - new Date(row.start_at).getTime(); - return normalizeDurationDays(Math.round(ms / 86_400_000)); + return clampDurationDays(Math.round(ms / 86_400_000)); }; const bookingFromRow = (row: ListingAttendeeRow): ListingBooking => { @@ -382,7 +382,7 @@ const desiredLines = ( ); return input.bookings.map((booking) => { const date = booking.date ?? null; - const durationDays = normalizeDurationDays(booking.durationDays ?? 1); + const durationDays = clampDurationDays(booking.durationDays ?? 1); return { ...lineKeyForInput(booking, existingBySlot), date, diff --git a/src/shared/db/attendees/update.ts b/src/shared/db/attendees/update.ts index 08e1909476..e7d02a7c2d 100644 --- a/src/shared/db/attendees/update.ts +++ b/src/shared/db/attendees/update.ts @@ -16,7 +16,7 @@ import { withTransaction, } from "#shared/db/client.ts"; import { settings } from "#shared/db/settings.ts"; -import { type ListingType, normalizeDurationDays } from "#shared/types.ts"; +import { clampDurationDays, type ListingType } from "#shared/types.ts"; /** * Set a line's check-in flag, refusing a no-quantity (quantity 0) line — it @@ -98,7 +98,7 @@ export const recomputeListingBookingRanges = async ( listingId: number, durationDays: number, ): Promise => { - const duration = normalizeDurationDays(durationDays); + const duration = clampDurationDays(durationDays); await execute( `UPDATE listing_attendees SET end_at = REPLACE(datetime(start_at, '+' || ? || ' days'), ' ', 'T') || '.000Z' diff --git a/src/shared/db/built-sites.ts b/src/shared/db/built-sites.ts index 45c9a47b17..100fb427bb 100644 --- a/src/shared/db/built-sites.ts +++ b/src/shared/db/built-sites.ts @@ -13,6 +13,8 @@ import type { ColumnDef, Table, TableSchema } from "#shared/db/table.ts"; import { cachedTable, col, defineTable } from "#shared/db/table.ts"; import { nowIso } from "#shared/now.ts"; import { guardFor } from "#shared/validation/guard.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; +import { OptionalStringSchema } from "#shared/validation/string.ts"; /* jscpd:ignore-end */ /** @@ -63,26 +65,20 @@ export const providerOrBunny = < provider: TProvider, ): "bunny" | TProvider => (value === provider ? provider : "bunny"); -/** Encrypted site data blob shape */ -export interface SiteDataBlob { - /** Database URL (optional, absent in older blobs) */ - d?: string; - /** Database provider (optional, defaults to "bunny" for backward compat) */ - dp?: DbProvider; - /** Hosting provider (optional, defaults to "bunny" for backward compat) */ - hp?: HostingProvider; - /** Site name */ - n: string; - /** Renewal token (optional, present when renewal access exists) */ - rt?: string; - /** Hosting ID — Bunny script ID or Deno app ID (optional, absent in older blobs) */ - s?: string; - /** Database token (optional, absent in older blobs) */ - t?: string; - /** Site URL (default hostname) */ - u: string; - v: typeof SITE_DATA_BLOB_VERSION; -} +/** Encrypted site data blob shape, including fields absent from older blobs. */ +const SiteDataBlobSchema = v.strictObject({ + d: OptionalStringSchema, + dp: v.optional(v.picklist(["bunny", "turso"])), + hp: v.optional(v.picklist(["bunny", "deno"])), + n: v.string(), + rt: OptionalStringSchema, + s: OptionalStringSchema, + t: OptionalStringSchema, + u: v.string(), + v: v.literal(SITE_DATA_BLOB_VERSION), +}); +export type SiteDataBlob = v.InferOutput; +const siteDataJson = defineStoredJson(SiteDataBlobSchema); /** Built site row as stored in the database */ export interface BuiltSiteRow { @@ -382,8 +378,8 @@ const buildSiteDataBlobFromInput = ( column.defaultValue) as string | null; return column.required || value ? [[column.blobKey, value]] : []; }), - ]) as unknown as SiteDataBlob; - return JSON.stringify(blob); + ]); + return siteDataJson.write(blob, "built_sites.site_data"); }; const blobToSiteFields = (blob: SiteDataBlob): BuiltSiteBlobFields => @@ -425,7 +421,7 @@ const toDbColumnValues = ( /** Parse a decrypted site data blob */ export const parseSiteDataBlob = (json: string): SiteDataBlob => - JSON.parse(json) as SiteDataBlob; + siteDataJson.read(json, "built_sites.site_data"); /** Convert a raw DB row (after decryption) to a BuiltSite */ const rowToBuiltSite = (row: BuiltSiteRow): BuiltSite => { diff --git a/src/shared/db/capacity.ts b/src/shared/db/capacity.ts index 56731ff72f..57031599bb 100644 --- a/src/shared/db/capacity.ts +++ b/src/shared/db/capacity.ts @@ -20,7 +20,7 @@ import type { InValue } from "@libsql/client"; import { capacityRuleTypeSql } from "#shared/capacity-rules.ts"; import { addDays } from "#shared/dates.ts"; import { joinStatements, type SqlStatement } from "#shared/db/client.ts"; -import { normalizeDurationDays } from "#shared/types.ts"; +import { clampDurationDays } from "#shared/types.ts"; /** A half-open [startAt, endAt) window of whole days, as timestamps. Also * the shape of an attendee's booked windows on the Logistics tab. */ @@ -38,7 +38,7 @@ export type DayRange = { startAt: string; endAt: string }; * to match, because SQLite TEXT comparison is byte-for-byte and tests * assert the exact stored format. */ export const dateToRange = (date: string, durationDays = 1): DayRange => { - const days = normalizeDurationDays(durationDays); + const days = clampDurationDays(durationDays); const ms = new Date(`${date}T00:00:00Z`).getTime(); const endIso = new Date(ms + days * 86_400_000).toISOString(); return { endAt: endIso, startAt: `${date}T00:00:00Z` }; @@ -293,7 +293,7 @@ export const buildCapacityCondition = ( qty, ); } - const duration = normalizeDurationDays(durationDays); + const duration = clampDurationDays(durationDays); const dayClauses = Array.from({ length: duration }, (_, i) => { const daily = buildDayCapacitySql( { diff --git a/src/shared/db/contact-preferences.ts b/src/shared/db/contact-preferences.ts index 18972e1398..0ce0ea6e84 100644 --- a/src/shared/db/contact-preferences.ts +++ b/src/shared/db/contact-preferences.ts @@ -28,6 +28,9 @@ import { ErrorCode, logError } from "#shared/logger.ts"; import { nowIso, nowMs } from "#shared/now.ts"; import { normalizePhone } from "#shared/phone.ts"; import { guardFor } from "#shared/validation/guard.ts"; +import { integerAtLeast } from "#shared/validation/number.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; +import { OptionalStringSchema } from "#shared/validation/string.ts"; /* jscpd:ignore-end */ export const ContactChannelSchema = v.picklist(["email", "sms"]); @@ -145,12 +148,14 @@ export type ContactRecordLoader = ( privateKey: CryptoKey, ) => Promise; -type StatsBlob = { - c?: number; - t?: string; - s?: string; - n?: string; -}; +const StatsBlobSchema = v.strictObject({ + c: v.optional(integerAtLeast(0)), + n: OptionalStringSchema, + s: OptionalStringSchema, + t: OptionalStringSchema, +}); +type StatsBlob = v.InferOutput; +const statsJson = defineStoredJson(StatsBlobSchema); const EMPTY_STATS: ContactStats = { adminNotes: "", @@ -164,9 +169,10 @@ const parseStats = async ( privateKey: CryptoKey, ): Promise => { if (!blob) return EMPTY_STATS; - const { c, n, s, t } = JSON.parse( + const { c, n, s, t } = statsJson.read( await decryptWithOwnerKey(blob, privateKey), - ) as StatsBlob; + "contact_preferences.stats_blob", + ); return { adminNotes: n ?? "", contactCount: c ?? 0, @@ -300,7 +306,7 @@ const saveStats = async ( args: [ hash, await encryptWithOwnerKey( - JSON.stringify(statsToBlob(stats)), + statsJson.write(statsToBlob(stats), "contact_preferences.stats_blob"), settings.publicKey, ), lastActivity, @@ -351,7 +357,7 @@ export const saveContactRecord = async ( record: ContactRecord, ): Promise => { const blob = await encryptWithOwnerKey( - JSON.stringify(statsToBlob(record)), + statsJson.write(statsToBlob(record), "contact_preferences.stats_blob"), settings.publicKey, ); await execute( diff --git a/src/shared/db/groups.ts b/src/shared/db/groups.ts index f5c6b176e3..7ceda298be 100644 --- a/src/shared/db/groups.ts +++ b/src/shared/db/groups.ts @@ -66,12 +66,16 @@ import type { ListingType, ListingWithCount, } from "#shared/types.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; /* jscpd:ignore-end */ /** Groups are few, so the cache loads the whole set and answers by-id / by-slug * reads from it — same isolate-level TTL as the listings cache. */ const GROUPS_CACHE_TTL_MS = 30_000; +const groupIdsJson = defineStoredJson( + v.array(v.pipe(v.number(), v.safeInteger(), v.minValue(1))), +); /** A package member's per-unit price override and fixed quantity, as parsed from * the group edit form / API. `price` is minor units (0 = no override, use the @@ -241,7 +245,10 @@ export const getListingsByGroupIds = async ( ); const listingsWithGroups: ListingGroups[] = await mapParallel( async (row: GroupListingRow): Promise => ({ - groupIds: v.parse(v.array(v.number()), JSON.parse(row.group_ids)), + groupIds: groupIdsJson.read( + row.group_ids, + `group_listings.group_ids for listing ${row.id}`, + ), member: await decryptListingWithCount(row), }), )(rows); diff --git a/src/shared/db/listings/table.ts b/src/shared/db/listings/table.ts index 2c5a23e67e..f9a29cb59b 100644 --- a/src/shared/db/listings/table.ts +++ b/src/shared/db/listings/table.ts @@ -1,5 +1,6 @@ /** Listing table schema and stored-value transforms. */ +import * as v from "valibot"; import { decrypt, encrypt } from "#shared/crypto/encryption.ts"; import { hmacHash } from "#shared/crypto/hashing.ts"; import type { BlindIndex, EnvKeyEncrypted } from "#shared/crypto/sealed.ts"; @@ -15,15 +16,16 @@ import { decryptImageFilenameOrEmpty } from "#shared/images/broken.ts"; import { ErrorCode, logError } from "#shared/logger.ts"; import { nowIso } from "#shared/now.ts"; import { + clampDurationDays, type DayPrices, + DayPricesSchema, type Listing, type ListingFields, type ListingType, - normalizeDurationDays, - parseDayPrices, } from "#shared/types.ts"; const DEFAULT_BOOKABLE_DAYS: string[] = [...VALID_DAY_NAMES]; +const BookableDaysSchema = v.array(v.string()); /** Listing input fields for create/update (camelCase). */ export type ListingInput = { @@ -95,9 +97,7 @@ const encryptDatetime = ( const decryptDatetime = async (value: EnvKeyEncrypted): Promise => { const decrypted = await decrypt(value); - return decrypted === "" - ? "" - : normalizeUtcDatetime(decrypted, "stored datetime"); + return normalizeUtcDatetime(decrypted, "stored datetime"); }; const writeClosesAt = (value: string | null): Promise => @@ -140,19 +140,9 @@ export const rawListingsTable = defineIdTable( attachment_name: col.encryptedText(encrypt, decrypt), attachment_url: col.encryptedText(encrypt, decrypt), bookable_alone: col.boolean(false), - bookable_days: col.converted({ + bookable_days: col.json(BookableDaysSchema, { + context: "listings.bookable_days", default: () => [...DEFAULT_BOOKABLE_DAYS], - read: (value) => { - const parsed: unknown = JSON.parse(value as string); - if ( - !Array.isArray(parsed) || - !parsed.every((day): day is string => typeof day === "string") - ) { - throw new Error("Stored bookable_days must be a JSON string array"); - } - return parsed; - }, - write: (value) => JSON.stringify(value), }), can_pay_more: col.boolean(false), closes_at: col.transform(writeClosesAt, readClosesAt), @@ -162,11 +152,13 @@ export const rawListingsTable = defineIdTable( default: () => "", ...col.encrypted(writeListingDate, decryptDatetime), }, - day_prices: col.projected((value) => - parseDayPrices(JSON.parse((value as string) ?? "{}")), - ), + day_prices: col.json(DayPricesSchema, { + context: "listings.day_prices", + projected: true, + whenMissing: () => ({}), + }), description: col.encryptedText(encrypt, decrypt), - duration_days: { default: () => 1, write: normalizeDurationDays }, + duration_days: { default: () => 1, write: clampDurationDays }, fields: col.withDefault(() => "email"), hidden: col.boolean(false), image_alt_text: col.projected(readProjectedAltText), diff --git a/src/shared/db/processed-payments.ts b/src/shared/db/processed-payments.ts index ea3e24c1de..ead91934f7 100644 --- a/src/shared/db/processed-payments.ts +++ b/src/shared/db/processed-payments.ts @@ -14,6 +14,7 @@ * - Fresh → return conflict error (still being processed) */ +import * as v from "valibot"; import { decrypt, encrypt } from "#shared/crypto/encryption.ts"; import type { EnvKeyEncrypted, @@ -23,6 +24,7 @@ import { execute, insert, queryOne } from "#shared/db/client.ts"; import { encryptPaymentReference } from "#shared/db/payment-references.ts"; import { STALE_RESERVATION_MS } from "#shared/limits.ts"; import { nowIso, nowMs } from "#shared/now.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; export { STALE_RESERVATION_MS }; @@ -68,11 +70,15 @@ export type ProcessedPayment = { * clear. Keep this shape free of any field that shouldn't round-trip through the * DB encryption key. */ -export type StoredPaymentFailure = { - error: string; - status?: number | undefined; - refunded?: boolean | undefined; -}; +const StoredPaymentFailureSchema = v.strictObject({ + error: v.string(), + refunded: v.optional(v.boolean()), + status: v.optional(v.pipe(v.number(), v.safeInteger())), +}); +export type StoredPaymentFailure = v.InferOutput< + typeof StoredPaymentFailureSchema +>; +const paymentFailureJson = defineStoredJson(StoredPaymentFailureSchema); /** Result of session reservation attempt */ export type ReserveSessionResult = @@ -249,7 +255,12 @@ export const markSessionFailed = async ( ): Promise => { await execute( `UPDATE processed_payments SET failure_data = ? WHERE payment_session_id = ? AND ${UNRESOLVED_RESERVATION}`, - [await encrypt(JSON.stringify(failure)), sessionId], + [ + await encrypt( + paymentFailureJson.write(failure, "processed_payments.failure_data"), + ), + sessionId, + ], ); }; @@ -271,7 +282,10 @@ export const parseSessionFailure = async ( ): Promise => { if (!failureData) return null; try { - return JSON.parse(await decrypt(failureData)) as StoredPaymentFailure; + return paymentFailureJson.read( + await decrypt(failureData), + "processed_payments.failure_data", + ); } catch { return CORRUPT_FAILURE; } diff --git a/src/shared/db/sumup-checkouts.ts b/src/shared/db/sumup-checkouts.ts index c1e9ef22ed..485011751a 100644 --- a/src/shared/db/sumup-checkouts.ts +++ b/src/shared/db/sumup-checkouts.ts @@ -29,6 +29,7 @@ * (30 min) and webhook retry window (2 h) have passed. */ +import * as v from "valibot"; import { decryptWithKey, encryptWithKey } from "#shared/crypto/encryption.ts"; import { hmacHash } from "#shared/crypto/hashing.ts"; import { @@ -39,6 +40,7 @@ import { import type { KeyEncrypted, WrappedKey } from "#shared/crypto/sealed.ts"; import { execute, executeUpdate, insert, queryOne } from "#shared/db/client.ts"; import { nowIso } from "#shared/now.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; type SumupCheckoutRow = { wrapped_key: WrappedKey; @@ -52,6 +54,8 @@ export type SumupCheckoutEntry = { sumupId: string; }; +const metadataJson = defineStoredJson(v.record(v.string(), v.string())); + /** Persist booking metadata for a checkout, encrypted under its reference. */ export const storeSumupCheckout = async ( reference: string, @@ -61,7 +65,10 @@ export const storeSumupCheckout = async ( const [referenceIndex, wrappedKey, ciphertext] = await Promise.all([ hmacHash(reference), wrapKeyWithToken(dataKey, reference), - encryptWithKey(JSON.stringify(metadata), dataKey), + encryptWithKey( + metadataJson.write(metadata, "sumup_checkouts.metadata"), + dataKey, + ), ]); const { sql, args } = insert("sumup_checkouts", { created_at: nowIso(), @@ -111,7 +118,10 @@ export const getSumupCheckout = async ( const dataKey = await unwrapKeyWithToken(row.wrapped_key, reference); const json = await decryptWithKey(row.metadata, dataKey); return { - metadata: JSON.parse(json) as Record, + metadata: metadataJson.read( + json, + `sumup_checkouts.metadata for ${reference}`, + ), sumupId: row.sumup_id, }; }; diff --git a/src/shared/db/table.ts b/src/shared/db/table.ts index d705b5b3e0..18fc2e394c 100644 --- a/src/shared/db/table.ts +++ b/src/shared/db/table.ts @@ -27,6 +27,7 @@ import { } from "#shared/db/client.ts"; import { queryAndMap } from "#shared/db/query.ts"; import { requestCache } from "#shared/request-cache.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; /** * Column definition for a table @@ -719,6 +720,41 @@ const wrapNullable = (v) => v === null ? Promise.resolve(null) : Promise.resolve(fn(v)); +const storedJsonTransforms = ( + schema: TSchema, + context: string, +): { + read: (value: unknown, rowId?: unknown) => v.InferOutput; + write: (value: v.InferOutput) => string; +} => { + const json = defineStoredJson(schema); + return { + read: (value, rowId) => + json.read( + value, + `${context}${rowId === undefined ? "" : ` row ${String(rowId)}`}`, + ), + write: (value) => json.write(value, context), + }; +}; + +interface StoredJsonContext { + context: string; +} + +interface StoredJsonColumnConfig extends StoredJsonContext { + default?: () => T; +} + +interface ProjectedJsonColumnConfig extends StoredJsonContext { + projected: true; + whenMissing: () => T; +} + +type JsonColumnConfig = + | StoredJsonColumnConfig + | ProjectedJsonColumnConfig; + /** * Helper to create column definitions */ @@ -735,7 +771,7 @@ export const col = { converted: (config: { default?: () => App; write: (v: App) => InValue; - read: (raw: InValue) => App; + read: (raw: InValue, rowId?: unknown) => App; }): ColumnDef => ({ default: config.default, read: config.read as (v: App) => App, @@ -778,6 +814,25 @@ export const col = { /** Auto-generated column (like id) */ generated: (): ColumnDef => ({ generated: true }), + /** JSON column validated against one schema on every read and write. */ + json: ( + schema: TSchema, + config: JsonColumnConfig>, + ): ColumnDef> => { + const transforms = storedJsonTransforms(schema, config.context); + if ("projected" in config) { + return col.projected>((value, rowId) => + value === undefined + ? config.whenMissing() + : transforms.read(value, rowId), + ); + } + return col.converted>({ + ...(config.default ? { default: config.default } : {}), + ...transforms, + }); + }, + /** A read-only column that is NOT a physical column on the table: it is * projected into the row by the caller's SELECT (a subquery `AS `), read * back through `read`, and never written (`projected` excludes it from INSERT/ diff --git a/src/shared/db/token-attempts.ts b/src/shared/db/token-attempts.ts index 6a5aaf4dd5..bf900af29b 100644 --- a/src/shared/db/token-attempts.ts +++ b/src/shared/db/token-attempts.ts @@ -21,6 +21,7 @@ */ /* jscpd:ignore-start */ +import * as v from "valibot"; import { hmacHash } from "#shared/crypto/hashing.ts"; import { clearAttemptsFor, lockoutActive } from "#shared/db/attempt-lockout.ts"; import { execute, queryOne } from "#shared/db/client.ts"; @@ -30,6 +31,7 @@ import { TOKEN_WINDOW_MS, } from "#shared/limits.ts"; import { nowMs } from "#shared/now.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; /* jscpd:ignore-end */ @@ -39,6 +41,8 @@ type TokenAttemptRow = { window_start: number; }; +const recentTokensJson = defineStoredJson(v.array(v.string())); + const readRow = (hashedIp: string): Promise => queryOne( "SELECT recent_tokens, locked_until, window_start FROM token_attempts WHERE ip = ?", @@ -74,7 +78,12 @@ export const recordTokenFailure = async ( const windowValid = row && currentMs - row.window_start <= TOKEN_WINDOW_MS; const windowStart = windowValid ? row.window_start : currentMs; - const existing: string[] = windowValid ? JSON.parse(row.recent_tokens) : []; + const existing = windowValid + ? recentTokensJson.read( + row.recent_tokens, + `token_attempts.recent_tokens for ${hashedIp}`, + ) + : []; const merged = new Set(existing); for (const h of hashedTokens) merged.add(h); @@ -90,7 +99,12 @@ export const recordTokenFailure = async ( await execute( "INSERT OR REPLACE INTO token_attempts (ip, recent_tokens, locked_until, window_start, last_attempt) VALUES (?, ?, NULL, ?, ?)", - [hashedIp, JSON.stringify([...merged]), windowStart, currentMs], + [ + hashedIp, + recentTokensJson.write([...merged], "token_attempts.recent_tokens"), + windowStart, + currentMs, + ], ); return false; }; diff --git a/src/shared/email-renderer.ts b/src/shared/email-renderer.ts index 51ecd5c1d7..d5df27789d 100644 --- a/src/shared/email-renderer.ts +++ b/src/shared/email-renderer.ts @@ -20,10 +20,10 @@ import { createBaseLiquidEngine } from "#shared/liquid-engine.ts"; import { ErrorCode, logError } from "#shared/logger.ts"; import { type ContactInfo, + clampDurationDays, type EmailTemplateFormat, type EmailTemplateType, isPaidListing, - normalizeDurationDays, } from "#shared/types.ts"; import { DEFAULT_TEMPLATES } from "#templates/email/defaults.ts"; import type { EmailContent } from "#templates/email/shared.ts"; @@ -94,7 +94,7 @@ const toTemplateEntry = (entry: EmailEntry): TemplateEntry => { const dateRangeLabel = bookedRangeLabel( attendee.date, attendee.end_date, - normalizeDurationDays(listing.duration_days), + clampDurationDays(listing.duration_days), ); return { attendee: { diff --git a/src/shared/listing-defaults.ts b/src/shared/listing-defaults.ts index dfa32d6ded..a9ae1b76b5 100644 --- a/src/shared/listing-defaults.ts +++ b/src/shared/listing-defaults.ts @@ -15,28 +15,27 @@ * This module is pure. Form parsing/validation lives in the feature layer. */ +import * as v from "valibot"; +import { VALID_DAY_NAMES } from "#shared/day-names.ts"; import type { Listing } from "#shared/types.ts"; +import { integerAtLeast } from "#shared/validation/number.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; /** * The operator-configurable defaults. A key is present only when a default is * set; an absent key means "no default — never override". */ -export type ListingDefaults = { - /** Always (`true`) / never (`false`) require logistics. */ - usesLogistics?: boolean; - /** Days of the week daily listings are bookable on. */ - bookableDays?: string[]; - /** Minimum days' notice before a daily booking. */ - minimumDaysBefore?: number; - /** Maximum days ahead a daily booking can be made. */ - maximumDaysAfter?: number; - /** Booking webhook URL. */ - webhookUrl?: string; - /** Post-purchase thank-you redirect URL. */ - thankYouUrl?: string; - /** Whether listings are hidden from public listing pages. */ - hidden?: boolean; -}; +export const ListingDefaultsSchema = v.strictObject({ + bookableDays: v.optional(v.array(v.picklist(VALID_DAY_NAMES))), + hidden: v.optional(v.boolean()), + maximumDaysAfter: v.optional(integerAtLeast(0)), + minimumDaysBefore: v.optional(integerAtLeast(0)), + thankYouUrl: v.optional(v.string()), + usesLogistics: v.optional(v.boolean()), + webhookUrl: v.optional(v.string()), +}); +export type ListingDefaults = v.InferOutput; +const listingDefaultsJson = defineStoredJson(ListingDefaultsSchema); /** How a default is stored, validated, and rendered. */ export type ListingDefaultKind = "bool" | "number" | "url" | "days"; @@ -161,9 +160,10 @@ export const resolveListingDefaults = ( */ export const parseListingDefaults = ( raw: string | undefined, -): ListingDefaults => (raw ? (JSON.parse(raw) as ListingDefaults) : {}); +): ListingDefaults => + raw ? listingDefaultsJson.read(raw, "settings.listing_defaults") : {}; /** Serialize defaults for storage. `JSON.stringify` drops every unset * (`undefined`) key, so only configured defaults are persisted. */ export const serializeListingDefaults = (defaults: ListingDefaults): string => - JSON.stringify(defaults); + listingDefaultsJson.write(defaults, "settings.listing_defaults"); diff --git a/src/shared/listing-parents-rules.ts b/src/shared/listing-parents-rules.ts index f1b259da4e..7fe5bfc6b4 100644 --- a/src/shared/listing-parents-rules.ts +++ b/src/shared/listing-parents-rules.ts @@ -13,9 +13,9 @@ import { t } from "#i18n"; import { availableDayCounts, + clampDurationDays, type DayPrices, dayPriceFor, - normalizeDurationDays, } from "#shared/types.ts"; /** The listing fields an edge-compatibility check reasons about. */ @@ -34,9 +34,7 @@ export type EdgeListing = { * non-`customisable_days` parent (a customisable parent has a *range*, via * {@link availableDayCounts}). */ const parentFixedDuration = (parent: EdgeListing): number => - parent.listing_type === "daily" - ? normalizeDurationDays(parent.duration_days) - : 1; + parent.listing_type === "daily" ? clampDurationDays(parent.duration_days) : 1; /** * Whether `child`'s booking span can match the duration it inherits from @@ -62,7 +60,7 @@ export const durationsCompatible = ( return dayPriceFor(child, parentFixedDuration(parent)) !== null; } if (child.listing_type !== "daily") return true; - const childDuration = normalizeDurationDays(child.duration_days); + const childDuration = clampDurationDays(child.duration_days); return parent.customisable_days ? availableDayCounts(parent).includes(childDuration) : childDuration === parentFixedDuration(parent); diff --git a/src/shared/listings-actions.ts b/src/shared/listings-actions.ts index 086a90a036..1fe86132af 100644 --- a/src/shared/listings-actions.ts +++ b/src/shared/listings-actions.ts @@ -50,11 +50,11 @@ import { generateUniqueSlug, normalizeSlug } from "#shared/slug.ts"; import { deleteListingAttachmentFile } from "#shared/storage.ts"; import { availableDayCounts, + clampDurationDays, type DayPricedListing, type Group, type Listing, type ListingWithCount, - normalizeDurationDays, } from "#shared/types.ts"; import { validateSafeServerFetchUrl } from "#shared/url-safety.ts"; @@ -209,7 +209,7 @@ export const dayPriceFieldsFromInput = ( ): DayPricedListing => ({ customisable_days: input.customisableDays ?? false, day_prices: input.dayPrices ?? {}, - duration_days: normalizeDurationDays(input.durationDays ?? 1), + duration_days: clampDurationDays(input.durationDays ?? 1), }); /** Project a (possibly partial) listing form input onto the edge-compatibility diff --git a/src/shared/types.ts b/src/shared/types.ts index 07a8e10b91..29a1b89b50 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -18,6 +18,7 @@ import type { ModifierTrigger, } from "#shared/price-modifier.ts"; import { guardFor } from "#shared/validation/guard.ts"; +import { boundedInteger, integerAtLeast } from "#shared/validation/number.ts"; import type { NonEmptyString } from "#shared/validation/string.ts"; /** Type guard: a non-null, non-array object (a Record shape). */ @@ -181,22 +182,27 @@ export const hasTicketQuantity = (row: { quantity: number }): boolean => export const MAX_DURATION_DAYS = 90; /** - * The single definition of "a valid booking duration": a whole number of - * days in [1, MAX_DURATION_DAYS]. Non-finite input is invalid and throws. - * - * Every read of `duration_days` and every `durationDays` parameter funnels - * through here so the clamping policy lives in exactly one place — the column - * write, the per-day capacity expansion (JS + SQL), and all display paths - * agree by construction. Idempotent, so applying it to an already-normalized - * value (e.g. a column-clamped `listing.duration_days`) is a safe no-op. + * Booking durations use one safe-integer range with two named policies. Clamp + * is for valid whole numbers outside the supported range. Reject is for + * boundaries where an out-of-range value must fail instead. Neither policy + * accepts fractions, non-finite numbers, or unsafe integers. */ -export const normalizeDurationDays = (value: number): number => { - if (!Number.isFinite(value)) { - throw new Error(`Invalid booking duration: ${String(value)}`); +const durationDays = boundedInteger(1, MAX_DURATION_DAYS); + +/** Clamp a valid whole-day count to the supported booking range. */ +export const clampDurationDays = (value: number): number => { + try { + return durationDays.clamp(value); + } catch (error) { + throw new Error(`Invalid booking duration: ${String(value)}`, { + cause: error, + }); } - return Math.max(1, Math.min(MAX_DURATION_DAYS, Math.floor(value))); }; +/** Reject any value that is not a whole day count in the supported range. */ +export const rejectDurationDays = durationDays.reject; + /** * Per-day-count ticket prices for "customisable days" listings, in minor * units, keyed by the number of days booked. e.g. `{ 1: 1000, 2: 1800 }` @@ -205,6 +211,25 @@ export const normalizeDurationDays = (value: number): number => { */ export type DayPrices = Record; +const DayPriceKeySchema = v.pipe( + v.string(), + v.regex(/^\d+$/), + v.check((value) => { + const days = Number(value); + return days >= 1 && days <= MAX_DURATION_DAYS; + }), +); +const DayPricesRecordSchema = v.record(DayPriceKeySchema, integerAtLeast(0)); + +/** Strict stored shape for per-day-count prices. */ +export const DayPricesSchema = v.pipe( + v.intersect([ + v.custom>(isRecord), + DayPricesRecordSchema, + ]), + v.transform((prices): DayPrices => prices), +); + /** * Build a {@link DayPrices} map from raw entries. `checkEntry` reads one raw * key/value pair and returns the day count and price to keep, `null` to skip @@ -266,7 +291,7 @@ export const ascending = (a: number, b: number): number => a - b; export const availableDayCounts = (listing: DayPricedListing): number[] => { if (!listing.customisable_days) return []; - const max = normalizeDurationDays(listing.duration_days); + const max = clampDurationDays(listing.duration_days); return Object.keys(listing.day_prices) .map(Number) .filter((n) => n >= 1 && n <= max) @@ -283,7 +308,7 @@ export const dayPriceFor = ( days: number, ): number | null => { if (!listing.customisable_days) return null; - const max = normalizeDurationDays(listing.duration_days); + const max = clampDurationDays(listing.duration_days); if (!Number.isInteger(days) || days < 1 || days > max) return null; return listing.day_prices[days] ?? null; }; diff --git a/src/shared/validation/number.ts b/src/shared/validation/number.ts index d7e7f7b6aa..90ff2273e0 100644 --- a/src/shared/validation/number.ts +++ b/src/shared/validation/number.ts @@ -1,5 +1,35 @@ import * as v from "valibot"; import { parseOrNull } from "./parse.ts"; +import { NonEmptyTextSchema } from "./string.ts"; + +export interface BoundedInteger { + /** Clamp valid integers to the range. Malformed numbers still throw. */ + clamp: (value: number) => number; + /** Require a valid integer inside the range. */ + reject: (value: number) => number; +} + +/** A safe whole number no lower than `minimum`. */ +export const integerAtLeast = (minimum: number) => + v.pipe(v.number(), v.safeInteger(), v.minValue(minimum)); + +/** Define explicit reject and clamp policies for one safe-integer range. */ +export const boundedInteger = ( + minimum: number, + maximum: number, +): BoundedInteger => { + const integerSchema = integerAtLeast(Number.MIN_SAFE_INTEGER); + const rangeSchema = v.pipe( + integerSchema, + v.minValue(minimum), + v.maxValue(maximum), + ); + return { + clamp: (value) => + Math.max(minimum, Math.min(maximum, v.parse(integerSchema, value))), + reject: (value) => v.parse(rangeSchema, value), + }; +}; /** * Plain decimal integer strings. The schemas accept digits only, so no signs, @@ -14,19 +44,13 @@ import { parseOrNull } from "./parse.ts"; * Mirrors the schema + parse-helper shape of validation/email.ts and * validation/date.ts as the rest of the app's validation migrates to valibot. */ -const createIntSchema = (minimum: number) => - v.pipe( - v.string(), - v.nonEmpty(), - v.digits(), - v.transform(Number), - v.minValue(minimum), - ); - -type IntSchema = ReturnType; - -const NonNegativeIntSchema = createIntSchema(0); -const PositiveIntSchema = createIntSchema(1); +const NonNegativeIntSchema = v.pipe( + NonEmptyTextSchema, + v.digits(), + v.transform(Number), +); +const PositiveIntSchema = v.pipe(NonNegativeIntSchema, v.minValue(1)); +type IntSchema = v.GenericSchema; const parseIntWithSchema = (schema: IntSchema, value: string): number | null => parseOrNull(schema, value.trim()); diff --git a/src/shared/validation/stored-json.ts b/src/shared/validation/stored-json.ts new file mode 100644 index 0000000000..7874c38dd9 --- /dev/null +++ b/src/shared/validation/stored-json.ts @@ -0,0 +1,46 @@ +import * as v from "valibot"; + +export interface StoredJson { + read: (value: unknown, context: string) => v.InferOutput; + write: (value: v.InferInput, context?: string) => string; +} + +const invalidStoredJson = ( + context: string, + detail: string, + cause: unknown, +): Error => + new Error(`Invalid stored JSON in ${context}: ${detail}`, { cause }); + +/** Define one schema-backed JSON format for both storage reads and writes. */ +export const defineStoredJson = ( + schema: TSchema, +): StoredJson => ({ + read: (value, context) => { + let parsed: unknown; + try { + parsed = JSON.parse(v.parse(v.string(), value)); + } catch (error) { + throw invalidStoredJson(context, String(error), error); + } + const result = v.safeParse(schema, parsed); + if (!result.success) { + throw invalidStoredJson( + context, + result.issues[0]!.message, + result.issues, + ); + } + return result.output; + }, + write: (value, context) => { + const result = v.safeParse(schema, value); + if (!result.success) { + throw new Error( + `Invalid value for stored JSON${context ? ` in ${context}` : ""}`, + { cause: result.issues }, + ); + } + return JSON.stringify(result.output); + }, +}); diff --git a/src/shared/validation/string.ts b/src/shared/validation/string.ts index b594af1643..86aa3026aa 100644 --- a/src/shared/validation/string.ts +++ b/src/shared/validation/string.ts @@ -9,11 +9,12 @@ import { guardFor } from "#shared/validation/guard.ts"; * only production paths into the brand are the helpers below, which validate at * the boundary and let downstream code avoid repeated empty-string checks. */ +export const NonEmptyTextSchema = v.pipe(v.string(), v.nonEmpty()); export const NonEmptyStringSchema = v.pipe( - v.string(), - v.nonEmpty(), + NonEmptyTextSchema, v.brand("NonEmptyString"), ); +export const OptionalStringSchema = v.optional(v.string()); export type NonEmptyString = v.InferOutput; type NonEmptyLiteral = T extends "" ? never : T; diff --git a/src/ui/templates/admin/listings/details.tsx b/src/ui/templates/admin/listings/details.tsx index ae1ed8107a..51cc94f42c 100644 --- a/src/ui/templates/admin/listings/details.tsx +++ b/src/ui/templates/admin/listings/details.tsx @@ -6,9 +6,9 @@ import { formatDatetimeLabel } from "#shared/dates.ts"; import type { ListingAggregateRecalculation } from "#shared/db/listings/aggregates.ts"; import { availableDayCounts, + clampDurationDays, dayPriceFor, type ListingWithCount, - normalizeDurationDays, } from "#shared/types.ts"; import { CopyableInputRow, @@ -41,7 +41,7 @@ const CustomisableDaysRow = ({ listing }: ListingRowProps): JSX.Element => { {t("listings_table.customisable_days")} {t("listings_table.visitors_choose_days", { - max_days: normalizeDurationDays(listing.duration_days), + max_days: clampDurationDays(listing.duration_days), })}{" "} {counts.length > 0 ? ( diff --git a/src/ui/templates/admin/listings/form-values.tsx b/src/ui/templates/admin/listings/form-values.tsx index b3a8c285b4..d30dd0c5df 100644 --- a/src/ui/templates/admin/listings/form-values.tsx +++ b/src/ui/templates/admin/listings/form-values.tsx @@ -19,8 +19,8 @@ import type { ListingTemplate } from "#shared/listing-templates.ts"; import { utcToLocalInput } from "#shared/timezone.ts"; import { type AdminSession, + clampDurationDays, type ListingWithCount, - normalizeDurationDays, } from "#shared/types.ts"; import { moneyPattern } from "#templates/components/price-input.tsx"; import { getListingForm } from "#templates/fields/listing.ts"; @@ -30,7 +30,7 @@ const formatDatetimeLocal = (iso: string | null): string | null => iso ? utcToLocalInput(iso, settings.timezone) : null; export const renderDayPricesFieldset = (listing?: ListingWithCount): string => { - const max = listing ? normalizeDurationDays(listing.duration_days) : 1; + const max = listing ? clampDurationDays(listing.duration_days) : 1; const prices = listing?.day_prices ?? {}; const rows = Array.from({ length: max }, (_, i) => i + 1) .map((n) => { diff --git a/src/ui/templates/tickets.tsx b/src/ui/templates/tickets.tsx index 7ac3a670ae..c8d8a1852e 100644 --- a/src/ui/templates/tickets.tsx +++ b/src/ui/templates/tickets.tsx @@ -17,7 +17,7 @@ import { namesConcealed, packagePrivacyOfDisplay, } from "#shared/package-privacy.ts"; -import { normalizeDurationDays } from "#shared/types.ts"; +import { clampDurationDays } from "#shared/types.ts"; import { headingLayoutPage } from "#templates/components/heading-layout.tsx"; import { escapeHtml } from "#templates/layout.tsx"; import { renderListingImage } from "#templates/public/shared.tsx"; @@ -77,7 +77,7 @@ const computeBookingDateLabel = (entry: TokenEntry): string => bookedRangeLabel( entry.attendee.date, entry.attendee.end_date, - normalizeDurationDays(entry.listing.duration_days), + clampDurationDays(entry.listing.duration_days), ); /** Render the "Add to: …" wallet links section, or "" when purchase-only or no diff --git a/test/shared/admin-features.test.ts b/test/shared/admin-features.test.ts index 5deca8c19f..1a9e537e82 100644 --- a/test/shared/admin-features.test.ts +++ b/test/shared/admin-features.test.ts @@ -13,15 +13,65 @@ const DEFAULT_ENABLED_FEATURES = parseEnabledFeatures(""); describe("admin features", () => { test("defines the complete feature list in display order", () => { - expect(ADMIN_FEATURES.map(({ key, slug }) => ({ key, slug }))).toEqual([ - { key: "site", slug: "site" }, - { key: "attributes", slug: "attributes" }, - { key: "questions", slug: "questions" }, - { key: "modifiers", slug: "modifiers" }, - { key: "logistics", slug: "logistics" }, - { key: "apiKeys", slug: "api-keys" }, - { key: "servicing", slug: "servicing" }, - { key: "money", slug: "money" }, + expect(ADMIN_FEATURES).toEqual([ + { + descriptionKey: "features.site.description", + inUseSql: null, + key: "site", + labelKey: "features.site.name", + slug: "site", + }, + { + descriptionKey: "features.attributes.description", + inUseSql: "EXISTS (SELECT 1 FROM attributes AS attribute)", + key: "attributes", + labelKey: "features.attributes.name", + slug: "attributes", + }, + { + descriptionKey: "features.questions.description", + inUseSql: "EXISTS (SELECT 1 FROM questions AS question)", + key: "questions", + labelKey: "features.questions.name", + slug: "questions", + }, + { + descriptionKey: "features.modifiers.description", + inUseSql: "EXISTS (SELECT 1 FROM modifiers AS modifier)", + key: "modifiers", + labelKey: "features.modifiers.name", + slug: "modifiers", + }, + { + descriptionKey: "features.logistics.description", + inUseSql: + "EXISTS (SELECT 1 FROM logistics_agents AS logisticsAgent) OR EXISTS (SELECT 1 FROM listings AS listing WHERE listing.uses_logistics = 1)", + key: "logistics", + labelKey: "features.logistics.name", + slug: "logistics", + }, + { + descriptionKey: "features.api_keys.description", + inUseSql: "EXISTS (SELECT 1 FROM api_keys AS apiKey)", + key: "apiKeys", + labelKey: "features.api_keys.name", + slug: "api-keys", + }, + { + descriptionKey: "features.servicing.description", + inUseSql: + "EXISTS (SELECT 1 FROM attendees AS attendee WHERE attendee.kind = 'servicing')", + key: "servicing", + labelKey: "features.servicing.name", + slug: "servicing", + }, + { + descriptionKey: "features.money.description", + inUseSql: null, + key: "money", + labelKey: "features.money.name", + slug: "money", + }, ]); }); @@ -99,8 +149,24 @@ describe("admin features", () => { thrown = error; } expect(thrown).toMatchObject({ - message: "Every admin feature must have an enabled value", + message: + "Invalid stored JSON in settings.enabled_features: Every admin feature must have an enabled value", }); + expect((thrown as Error).cause).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + message: "Every admin feature must have an enabled value", + }), + ]), + ); + }); + + test("names the setting when serialization rejects invalid features", () => { + expect(() => + serializeEnabledFeatures({ money: "yes" } as unknown as Parameters< + typeof serializeEnabledFeatures + >[0]), + ).toThrow(/^Invalid value for stored JSON in settings\.enabled_features$/); }); test("finds a feature by slug and returns null for an unknown slug", () => { diff --git a/test/shared/db/address-cache.test.ts b/test/shared/db/address-cache.test.ts index 893ac88346..ed6e0471cc 100644 --- a/test/shared/db/address-cache.test.ts +++ b/test/shared/db/address-cache.test.ts @@ -47,6 +47,15 @@ describeWithEnv("address cache", { db: true }, () => { expect(await getCachedAddresses(index)).toEqual([]); }); + test("rejects invalid address shapes before storing them", async () => { + const index = await computeAddressSearchIndex("easypostcodes", "BAD"); + await expect( + storeCachedAddresses(index, [ + { lat: "1", line: "Missing longitude" }, + ] as unknown as Parameters[1]), + ).rejects.toThrow("Invalid value for stored JSON in address_cache.results"); + }); + test("misses for a search that was never cached", async () => { const index = await computeAddressSearchIndex("easypostcodes", "M1 1AE"); expect(await getCachedAddresses(index)).toBeNull(); diff --git a/test/shared/db/attendees/pii.test.ts b/test/shared/db/attendees/pii.test.ts index a21dce1d4a..0b3767935d 100644 --- a/test/shared/db/attendees/pii.test.ts +++ b/test/shared/db/attendees/pii.test.ts @@ -123,9 +123,17 @@ describe("PII blob encoding", () => { expect("lo" in unpinned).toBe(false); }); - test("parsePiiBlob defaults a missing version but preserves an explicit one", () => { - expect(parsePiiBlob('{"n":"x"}').v).toBe(PII_BLOB_VERSION); - expect(parsePiiBlob('{"n":"x","v":2}').v).toBe(2); + test("parsePiiBlob defaults a missing version", () => { + const blob = JSON.parse(buildPiiBlob(samplePii)); + delete blob.v; + expect(parsePiiBlob(JSON.stringify(blob)).v).toBe(PII_BLOB_VERSION); + }); + + test("parsePiiBlob rejects an unknown version", () => { + const blob = { ...JSON.parse(buildPiiBlob(samplePii)), v: 2 }; + expect(() => parsePiiBlob(JSON.stringify(blob))).toThrow( + "Invalid stored JSON in attendees.pii_blob", + ); }); }); diff --git a/test/shared/db/built-sites.test.ts b/test/shared/db/built-sites.test.ts index f48bc1e77f..0e4dc74161 100644 --- a/test/shared/db/built-sites.test.ts +++ b/test/shared/db/built-sites.test.ts @@ -175,6 +175,17 @@ describeWithEnv("built-sites", { db: true }, () => { expect(parsed.s).toBeUndefined(); }); + test("parseSiteDataBlob rejects malformed JSON and invalid fields", () => { + expect(() => parseSiteDataBlob("{")).toThrow( + "Invalid stored JSON in built_sites.site_data", + ); + expect(() => + parseSiteDataBlob( + JSON.stringify({ hp: "unknown", n: "Site", u: "site.test", v: 1 }), + ), + ).toThrow("Invalid stored JSON in built_sites.site_data"); + }); + test("insertBuiltSite creates a row with encrypted site_data", async () => { const row = await insertBuiltSite("Alpha Site", "alpha.b-cdn.net"); expect(row.id).toBe(1); diff --git a/test/shared/db/contact-preferences.test.ts b/test/shared/db/contact-preferences.test.ts index 9ed7a9fcfc..cab527b436 100644 --- a/test/shared/db/contact-preferences.test.ts +++ b/test/shared/db/contact-preferences.test.ts @@ -248,6 +248,23 @@ describeWithEnv("contact-preferences: contact history", { db: true }, () => { }); }); + test("rejects wrong field types in an encrypted stats blob", async () => { + const pk = await getTestPrivateKey(); + const hash = await hashEmail("invalid-stats@example.com"); + const encrypted = await encryptWithOwnerKey( + JSON.stringify({ c: "2" }), + settings.publicKey, + ); + await execute( + "INSERT INTO contact_preferences (contact_hash, stats_blob) VALUES (?, ?)", + [hash, encrypted], + ); + + await expect(getContactRecord(hash, pk)).rejects.toThrow( + "Invalid stored JSON in contact_preferences.stats_blob", + ); + }); + test("getContactCountFields reads plaintext counts past a corrupt blob", async () => { const hash = await hashEmail("corrupt@example.com"); await execute( diff --git a/test/shared/db/listings/table.test.ts b/test/shared/db/listings/table.test.ts index ba0926f670..091ff7e701 100644 --- a/test/shared/db/listings/table.test.ts +++ b/test/shared/db/listings/table.test.ts @@ -1,16 +1,89 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { encrypt } from "#shared/crypto/encryption.ts"; import { getDb } from "#shared/db/client.ts"; import { getListingWithCount, listingsTable, } from "#shared/db/listings/records.ts"; -import { computeSlugIndex } from "#shared/db/listings/table.ts"; +import { + computeSlugIndex, + type ListingInput, + rawListingsTable, +} from "#shared/db/listings/table.ts"; +import type { DayPrices } from "#shared/types.ts"; import { MAX_DURATION_DAYS } from "#shared/types.ts"; import { describeWithEnv } from "#test-utils/db.ts"; +import { setupErrorSpy } from "#test-utils/error-spy.ts"; describeWithEnv("db > listings", { db: true, triggers: true }, () => { + const errors = setupErrorSpy(); + + test("applies every listing storage default", async () => { + const listing = await listingsTable.insert({ + maxAttendees: 100, + maxPrice: 10000, + name: "defaults", + slug: "storage-defaults", + slugIndex: await computeSlugIndex("storage-defaults"), + }); + const saved = await getListingWithCount(listing.id); + expect(saved).toMatchObject({ + active: true, + assign_built_site: false, + bookable_alone: false, + can_pay_more: false, + customisable_days: false, + duration_days: 1, + fields: "email", + hidden: false, + initial_site_months: 0, + listing_type: "standard", + max_price: 10000, + max_quantity: 1, + maximum_days_after: 90, + minimum_days_before: 1, + months_per_unit: 0, + non_transferable: false, + purchase_only: false, + unit_price: 0, + use_defaults: false, + uses_logistics: false, + }); + }); + + test("applies numeric defaults at the raw table boundary", async () => { + expect(rawListingsTable.schema.duration_days.default?.()).toBe(1); + const listing = await rawListingsTable.insert({ + maxAttendees: 100, + name: "raw defaults", + slug: "raw-storage-defaults", + slugIndex: await computeSlugIndex("raw-storage-defaults"), + } as ListingInput); + expect(listing.duration_days).toBe(1); + expect(listing.max_price).toBe(0); + }); + + test("names each projected image when its stored filename is broken", async () => { + const stored = await encrypt(""); + await rawListingsTable.readColumn("image_thumb_url", stored, 8); + expect(errors.lastMessage()).toContain("listing 8 thumbnail image"); + await rawListingsTable.readColumn("image_url", stored, 9); + expect(errors.lastMessage()).toContain("listing 9 image"); + }); + describe("listing date read transform", () => { + test("reads an encrypted empty stored date as empty", async () => { + expect(await rawListingsTable.readColumn("date", await encrypt(""))).toBe( + "", + ); + }); + + test("names stored datetime when a decrypted date is invalid", async () => { + await expect( + rawListingsTable.readColumn("date", await encrypt("not-a-dateZ")), + ).rejects.toThrow("stored datetime has invalid datetime: not-a-dateZ"); + }); test("returns empty string for no-date listing", async () => { const listing = await listingsTable.insert({ date: "", @@ -77,9 +150,22 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { const saved = await getListingWithCount(listing.id); expect(saved?.closes_at).toBe("2099-12-31T23:59:00.000Z"); }); + + test("names closes_at when rejecting an invalid date", async () => { + await expect( + listingsTable.insert({ + closesAt: "not-a-dateZ", + maxAttendees: 100, + maxPrice: 10000, + name: "test", + slug: "test-closes-invalid", + slugIndex: await computeSlugIndex("test-closes-invalid"), + }), + ).rejects.toThrow("closes_at has invalid datetime: not-a-dateZ"); + }); }); - describe("duration_days write clamp", () => { + describe("duration_days write validation", () => { const insertWithDuration = async (slug: string, durationDays: number) => { const listing = await listingsTable.insert({ durationDays, @@ -92,31 +178,30 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { return (await getListingWithCount(listing.id))!.duration_days; }; - test(`clamps values above MAX_DURATION_DAYS down to ${MAX_DURATION_DAYS}`, async () => { - expect(await insertWithDuration("test-dur-high", 500)).toBe( - MAX_DURATION_DAYS, - ); + test("accepts whole days within the supported range", async () => { + expect( + await insertWithDuration("test-dur-valid", MAX_DURATION_DAYS), + ).toBe(MAX_DURATION_DAYS); }); - test("clamps zero to 1", async () => { + test("clamps whole integers outside the supported range", async () => { + expect( + await insertWithDuration("test-dur-high", MAX_DURATION_DAYS + 1), + ).toBe(MAX_DURATION_DAYS); expect(await insertWithDuration("test-dur-zero", 0)).toBe(1); - }); - - test("clamps negative values to 1", async () => { expect(await insertWithDuration("test-dur-neg", -3)).toBe(1); }); - test("floors fractional values to whole days", async () => { - expect(await insertWithDuration("test-dur-frac", 2.7)).toBe(2); - }); - - test("rejects non-finite values", async () => { - await expect( - insertWithDuration("test-dur-nan", Number.NaN), - ).rejects.toThrow("Invalid booking duration: NaN"); + test("rejects fractional and non-finite values", async () => { + for (const [slug, value] of [ + ["test-dur-frac", 2.7], + ["test-dur-nan", Number.NaN], + ] as const) { + await expect(insertWithDuration(slug, value)).rejects.toThrow(); + } }); - test("clamps on update as well as insert", async () => { + test("clamps an out-of-range update", async () => { const listing = await listingsTable.insert({ maxAttendees: 100, maxPrice: 10000, @@ -124,7 +209,9 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { slug: "test-dur-upd", slugIndex: await computeSlugIndex("test-dur-upd"), }); - await listingsTable.update(listing.id, { durationDays: 1000 }); + await listingsTable.update(listing.id, { + durationDays: MAX_DURATION_DAYS + 1, + }); expect((await getListingWithCount(listing.id))!.duration_days).toBe( MAX_DURATION_DAYS, ); @@ -132,6 +219,23 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { }); describe("bookable_days read transform", () => { + test("rejects malformed JSON stored in the database", async () => { + const listing = await listingsTable.insert({ + maxAttendees: 100, + maxPrice: 10000, + name: "test-bd-json", + slug: "test-bd-json", + slugIndex: await computeSlugIndex("test-bd-json"), + }); + await getDb().execute({ + args: ["[", listing.id], + sql: "UPDATE listings SET bookable_days = ? WHERE id = ?", + }); + await expect(getListingWithCount(listing.id)).rejects.toThrow( + `Invalid stored JSON in listings.bookable_days row ${listing.id}`, + ); + }); + test("rejects non-array JSON stored in the database", async () => { const listing = await listingsTable.insert({ maxAttendees: 100, @@ -145,7 +249,7 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { sql: "UPDATE listings SET bookable_days = ? WHERE id = ?", }); await expect(getListingWithCount(listing.id)).rejects.toThrow( - "Stored bookable_days must be a JSON string array", + `Invalid stored JSON in listings.bookable_days row ${listing.id}`, ); }); @@ -162,8 +266,49 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { sql: "UPDATE listings SET bookable_days = ? WHERE id = ?", }); await expect(getListingWithCount(listing.id)).rejects.toThrow( - "Stored bookable_days must be a JSON string array", + `Invalid stored JSON in listings.bookable_days row ${listing.id}`, ); }); + + test("preserves unknown day names for catalog repair", async () => { + const listing = await listingsTable.insert({ + maxAttendees: 100, + maxPrice: 10000, + name: "test-bd-day", + slug: "test-bd-day", + slugIndex: await computeSlugIndex("test-bd-day"), + }); + await getDb().execute({ + args: ['["Monday","Funday"]', listing.id], + sql: "UPDATE listings SET bookable_days = ? WHERE id = ?", + }); + expect((await getListingWithCount(listing.id))?.bookable_days).toEqual([ + "Monday", + "Funday", + ]); + }); + }); + + describe("day_prices read transform", () => { + test("accepts a stored day-price object", async () => { + expect( + await rawListingsTable.readColumn( + "day_prices", + '{"1":100,"2":180}' as unknown as DayPrices, + ), + ).toEqual({ 1: 100, 2: 180 }); + }); + + test("rejects arrays, invalid keys, and invalid prices", async () => { + for (const stored of ["[]", '{"0":100}', '{"1":"100"}']) { + await expect( + rawListingsTable.readColumn( + "day_prices", + stored as unknown as DayPrices, + 7, + ), + ).rejects.toThrow("Invalid stored JSON in listings.day_prices row 7"); + } + }); }); }); diff --git a/test/shared/db/processed-payments.test.ts b/test/shared/db/processed-payments.test.ts index dde9cf05b5..b54adf1eee 100644 --- a/test/shared/db/processed-payments.test.ts +++ b/test/shared/db/processed-payments.test.ts @@ -1,5 +1,6 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { encrypt } from "#shared/crypto/encryption.ts"; import type { EnvKeyEncrypted } from "#shared/crypto/sealed.ts"; import { getDb, insert } from "#shared/db/client.ts"; import { @@ -171,6 +172,16 @@ describeWithEnv("db > processed payments", { db: true }, () => { expect((result?.error.length ?? 0) > 0).toBe(true); }); + test("parseSessionFailure degrades invalid JSON fields to a terminal failure", async () => { + const result = await parseSessionFailure( + await encrypt('{"error":42,"refunded":"yes"}'), + ); + expect(result).toEqual({ + error: "This payment could not be completed. Please contact support.", + status: 500, + }); + }); + test("re-throws non-unique-constraint errors", async () => { await getDb().execute("DROP TABLE processed_payments"); diff --git a/test/shared/db/sumup-checkouts.test.ts b/test/shared/db/sumup-checkouts.test.ts index caa3004b75..e4d87eae1c 100644 --- a/test/shared/db/sumup-checkouts.test.ts +++ b/test/shared/db/sumup-checkouts.test.ts @@ -57,6 +57,16 @@ describeWithEnv("db > sumup-checkouts", { db: true }, () => { expect(result).toBeNull(); }); + test("rejects non-string metadata before storing it", async () => { + await expect( + storeSumupCheckout(REFERENCE, { + quantity: 2, + } as unknown as Record), + ).rejects.toThrow( + "Invalid value for stored JSON in sumup_checkouts.metadata", + ); + }); + test("keeps rows isolated per reference", async () => { const otherReference = crypto.randomUUID(); const otherMetadata = { ...METADATA, name: "Bob Other" }; diff --git a/test/shared/db/table.test.ts b/test/shared/db/table.test.ts index 809ac95c02..38da42a05e 100644 --- a/test/shared/db/table.test.ts +++ b/test/shared/db/table.test.ts @@ -1,5 +1,6 @@ import { expect } from "@std/expect"; import { it as test } from "@std/testing/bdd"; +import * as v from "valibot"; import type { BlindIndex } from "#shared/crypto/sealed.ts"; import { listingsTable } from "#shared/db/listings/records.ts"; import { describeWithEnv } from "#test-utils/db.ts"; @@ -87,6 +88,44 @@ describeWithEnv("db > table utilities", { db: true }, () => { expect(await def.write?.(true)).toBe(1); }); + test("col.json validates physical column reads and writes with row context", async () => { + const { col } = await import("#shared/db/table.ts"); + const def = col.json(v.array(v.string()), { + context: "records.items", + default: () => [], + }); + expect(def.default?.()).toEqual([]); + expect(await def.read?.('["one"]' as unknown as string[], 4)).toEqual([ + "one", + ]); + expect(await def.write?.(["two"])).toBe('["two"]'); + expect(() => def.read?.("[1]" as unknown as string[], 4)).toThrow( + "Invalid stored JSON in records.items row 4", + ); + expect(() => def.read?.("{}" as unknown as string[])).toThrow( + /^Invalid stored JSON in records\.items:/, + ); + const required = col.json(v.array(v.string()), { + context: "records.required_items", + }); + expect(required.default).toBeUndefined(); + expect(await required.write?.(["required"])).toBe('["required"]'); + }); + + test("col.json gives a missing projection its declared value", async () => { + const { col } = await import("#shared/db/table.ts"); + const def = col.json(v.array(v.string()), { + context: "records.items", + projected: true, + whenMissing: () => [], + }); + expect(def.projected).toBe(true); + expect(await def.read?.(undefined as unknown as string[], 4)).toEqual([]); + expect(await def.read?.('["one"]' as unknown as string[], 4)).toEqual([ + "one", + ]); + }); + test("col.transform creates column with custom transforms", async () => { const { col } = await import("#shared/db/table.ts"); const write = (v: string) => v.toUpperCase(); diff --git a/test/shared/db/table-cache.test.ts b/test/shared/db/table/cache.test.ts similarity index 100% rename from test/shared/db/table-cache.test.ts rename to test/shared/db/table/cache.test.ts diff --git a/test/shared/db/table-write-row.test.ts b/test/shared/db/table/write-row.test.ts similarity index 100% rename from test/shared/db/table-write-row.test.ts rename to test/shared/db/table/write-row.test.ts diff --git a/test/shared/db/token-attempts.test.ts b/test/shared/db/token-attempts.test.ts index c84e982bb3..68cf467880 100644 --- a/test/shared/db/token-attempts.test.ts +++ b/test/shared/db/token-attempts.test.ts @@ -10,7 +10,7 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; import { FakeTime } from "@std/testing/time"; import { hmacHash } from "#shared/crypto/hashing.ts"; -import { queryOne } from "#shared/db/client.ts"; +import { execute, queryOne } from "#shared/db/client.ts"; import { clearTokenAttempts, isTokenRateLimited, @@ -125,6 +125,19 @@ describeWithEnv("db > token-attempts", { db: true }, () => { expect(await isTokenRateLimited(ip)).toBe(false); }); + test("rejects invalid stored token arrays", async () => { + const ip = "10.0.0.12"; + const hashedIp = await hmacHash(ip); + await execute( + "INSERT INTO token_attempts (ip, recent_tokens, window_start, last_attempt) VALUES (?, ?, ?, ?)", + [hashedIp, '["valid",2]', Date.now(), Date.now()], + ); + + await expect(recordTokenFailure(ip, ["new"])).rejects.toThrow( + `Invalid stored JSON in token_attempts.recent_tokens for ${hashedIp}`, + ); + }); + test("locks when a single request supplies MAX_TOKEN_404S distinct tokens", async () => { const ip = "10.0.0.9"; const locked = await recordTokenFailure( diff --git a/test/shared/listing-defaults.test.ts b/test/shared/listing-defaults.test.ts index c91104caa4..08f3d6477b 100644 --- a/test/shared/listing-defaults.test.ts +++ b/test/shared/listing-defaults.test.ts @@ -229,6 +229,37 @@ describe("shared > listing-defaults > parse/serialize round-trip", () => { expect(parseListingDefaults(undefined)).toEqual({}); expect(parseListingDefaults("")).toEqual({}); }); + + test("rejects malformed JSON and invalid stored fields", () => { + expect(() => parseListingDefaults("{")).toThrow( + /^Invalid stored JSON in settings\.listing_defaults:/, + ); + expect(() => parseListingDefaults('{"bookableDays":["Monday",2]}')).toThrow( + "Invalid stored JSON in settings.listing_defaults", + ); + expect(() => parseListingDefaults('{"hidden":"yes"}')).toThrow( + "Invalid stored JSON in settings.listing_defaults", + ); + expect(() => parseListingDefaults('{"minimumDaysBefore":-1}')).toThrow(); + expect(() => parseListingDefaults('{"maximumDaysAfter":-1}')).toThrow(); + }); + + test("allows zero-day booking windows", () => { + expect( + parseListingDefaults( + serializeListingDefaults({ + maximumDaysAfter: 0, + minimumDaysBefore: 0, + }), + ), + ).toEqual({ maximumDaysAfter: 0, minimumDaysBefore: 0 }); + }); + + test("names the setting when serialization rejects invalid defaults", () => { + expect(() => + serializeListingDefaults({ hidden: "yes" } as unknown as ListingDefaults), + ).toThrow(/^Invalid value for stored JSON in settings\.listing_defaults$/); + }); }); describe("shared > listing-defaults > LISTING_DEFAULT_FIELDS", () => { diff --git a/test/shared/validation/number.test.ts b/test/shared/validation/number.test.ts index 1ff80a0ff4..c8c8bfe982 100644 --- a/test/shared/validation/number.test.ts +++ b/test/shared/validation/number.test.ts @@ -1,11 +1,48 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; import { + boundedInteger, parseNonNegativeInt, parsePositiveInt, parsePositiveIntId, } from "#shared/validation/number.ts"; +describe("boundedInteger", () => { + const days = boundedInteger(1, 90); + + test("reject policy accepts safe integers within the range", () => { + expect(days.reject(1)).toBe(1); + expect(days.reject(45)).toBe(45); + expect(days.reject(90)).toBe(90); + }); + + test("reject policy rejects integers outside the range", () => { + expect(() => days.reject(0)).toThrow(); + expect(() => days.reject(91)).toThrow(); + }); + + test("clamp policy clamps valid integers outside the range", () => { + expect(days.clamp(-2)).toBe(1); + expect(days.clamp(500)).toBe(90); + }); + + test("clamp policy leaves valid integers within the range unchanged", () => { + expect(days.clamp(37)).toBe(37); + }); + + test("both policies reject malformed numbers", () => { + for (const value of [ + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + Number.MAX_SAFE_INTEGER + 1, + ]) { + expect(() => days.reject(value)).toThrow(); + expect(() => days.clamp(value)).toThrow(); + } + }); +}); + describe("parsePositiveIntId", () => { test("parses plain positive integers, dropping leading zeros", () => { expect(parsePositiveIntId("5")).toBe(5); diff --git a/test/shared/validation/stored-json.test.ts b/test/shared/validation/stored-json.test.ts new file mode 100644 index 0000000000..c1059ee16f --- /dev/null +++ b/test/shared/validation/stored-json.test.ts @@ -0,0 +1,63 @@ +import { expect } from "@std/expect"; +import { describe, it as test } from "@std/testing/bdd"; +import * as v from "valibot"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; + +const entriesJson = defineStoredJson( + v.array(v.strictObject({ id: v.number(), name: v.string() })), +); + +describe("defineStoredJson", () => { + test("round-trips values that match the schema", () => { + const entries = [{ id: 1, name: "First" }]; + expect( + entriesJson.read(entriesJson.write(entries), "test.entries"), + ).toEqual(entries); + }); + + test("rejects malformed JSON with storage context", () => { + expect(() => entriesJson.read("{", "test.entries row 4")).toThrow( + "Invalid stored JSON in test.entries row 4", + ); + }); + + test("rejects the wrong top-level shape", () => { + expect(() => entriesJson.read('{"id":1}', "test.entries")).toThrow( + "Invalid stored JSON in test.entries", + ); + }); + + test("rejects wrong element types", () => { + expect(() => + entriesJson.read('[{"id":"1","name":"First"}]', "test.entries"), + ).toThrow("Invalid stored JSON in test.entries"); + }); + + test("rejects extra object fields", () => { + expect(() => + entriesJson.read( + '[{"id":1,"name":"First","extra":true}]', + "test.entries", + ), + ).toThrow("Invalid stored JSON in test.entries"); + }); + + test("validates values before writing", () => { + expect(() => + entriesJson.write([{ id: 1, name: 2 }] as unknown as Parameters< + typeof entriesJson.write + >[0]), + ).toThrow(/^Invalid value for stored JSON$/); + }); + + test("names the storage context when a write is invalid", () => { + expect(() => + entriesJson.write( + [{ id: 1, name: 2 }] as unknown as Parameters< + typeof entriesJson.write + >[0], + "test.entries", + ), + ).toThrow("Invalid value for stored JSON in test.entries"); + }); +}); From 703c76d50f98e15b6e2f5b5c02a32efb6917777e Mon Sep 17 00:00:00 2001 From: Stefan Date: Sun, 19 Jul 2026 16:22:50 +0100 Subject: [PATCH 02/17] Address structured storage review feedback --- scripts/mutation/equivalent-mutants.txt | 15 ++- src/features/admin/attendees.ts | 6 +- .../api/payment-processing/metadata.ts | 13 +-- src/shared/db/built-sites.ts | 2 +- src/shared/payment-helpers.ts | 9 +- src/shared/types.ts | 5 +- src/shared/validation/number.ts | 5 +- .../single-ticket-refunds.test.ts | 42 +------ test/shared/db/built-sites.test.ts | 82 ++++++++++++- test/shared/db/listings/table.test.ts | 10 ++ test/shared/logger/log-output.test.ts | 21 +--- .../payment-helpers/build-items.test.ts | 12 ++ test/shared/payment-helpers/dispatch.test.ts | 109 +++++++++++++++++- test/shared/payment-helpers/limits.test.ts | 10 ++ test/shared/payment-helpers/metadata.test.ts | 2 + test/shared/payments.test.ts | 18 +-- test/shared/validation/number.test.ts | 4 + test/test-utils/debug-log.ts | 17 +++ 18 files changed, 284 insertions(+), 98 deletions(-) create mode 100644 test/test-utils/debug-log.ts diff --git a/scripts/mutation/equivalent-mutants.txt b/scripts/mutation/equivalent-mutants.txt index 2e780ce0c9..ca7b6a7a10 100644 --- a/scripts/mutation/equivalent-mutants.txt +++ b/scripts/mutation/equivalent-mutants.txt @@ -241,7 +241,20 @@ src/shared/db/attendees/capacity/groups.ts:166:55 ?? → || # membership.get( src/shared/db/attendees/capacity/groups.ts:178:39 ?? → || # membership.get(): number[]|undefined — an array is always truthy # v2 signed metadata (Phase 2d). -src/shared/payment-helpers.ts:159:24 ?? → || # toBookingItems intent.allocations: ChildAllocation[]|undefined — an array is always truthy, undefined→[] either way +src/shared/payment-helpers.ts:168:24 ?? → || # toBookingItems intent.allocations: ChildAllocation[]|undefined — an array is always truthy, undefined→[] either way +src/shared/payment-helpers.ts:539:16 || → && # parsed JSON null/falsy primitives return {} in both forms; truthy primitives expose none of PACKED_KEYS and also produce {} +src/shared/payment-helpers.ts:598:40 ?? → || # metadata field length is undefined or a non-negative integer; 0 and undefined both use 0 + +# Built-site form writes cannot change assignment/renewal state, so omitted raw +# inputs preserve the same defaults/current values. Blob strings are either +# truthy or have the same falsy fallback. +src/shared/db/built-sites.ts:163:57 ?? → || # assigned IDs are positive generated IDs or null; renewal indexes are non-empty HMAC strings or null +src/shared/db/built-sites.ts:178:15 assignedAttendeeId → "" # not in BuiltSiteFormInput; inserts default null and form updates preserve the existing raw value +src/shared/db/built-sites.ts:186:15 assignedListingId → "" # not in BuiltSiteFormInput; inserts default null and form updates preserve the existing raw value +src/shared/db/built-sites.ts:194:15 readOnlyFrom → "" # not in BuiltSiteFormInput; inserts default "" and form updates preserve the existing raw value +src/shared/db/built-sites.ts:202:15 renewalTokenIndex → "" # not in BuiltSiteFormInput; inserts default null and form updates preserve the existing raw value +src/shared/db/built-sites.ts:377:71 ?? → || # blob input strings use "" as their fallback, providers are non-empty, and renewalToken uses null +src/shared/db/built-sites.ts:391:54 ?? → || # validated optional strings use "" as their fallback, providers are non-empty, and renewalToken is null or non-empty # Settings registry: readOnly is optional but can only be true when present, so # `"readOnly" in accessor && accessor.readOnly` and `... || accessor.readOnly` diff --git a/src/features/admin/attendees.ts b/src/features/admin/attendees.ts index 2474afc1f2..e9ad3aa4b3 100644 --- a/src/features/admin/attendees.ts +++ b/src/features/admin/attendees.ts @@ -205,9 +205,9 @@ const buildCreateAttendeeInput = ( const { name, email, phone, address, special_instructions, quantity, date } = values; const isDaily = listing.listing_type === "daily"; - // Customisable daily bookings span the admin's chosen day count (a required, - // options-constrained field; any odd value is clamped downstream by - // clampDurationDays); other daily bookings use the fixed duration. + // Customisable daily bookings span the admin's chosen day count. The shared + // boundary clamps whole numbers outside its range and rejects malformed + // numbers. Other daily bookings use the fixed duration. const durationDays = listing.customisable_days ? Number(values.day_count) : listing.duration_days; diff --git a/src/features/api/payment-processing/metadata.ts b/src/features/api/payment-processing/metadata.ts index 6cb1739291..6d931918d6 100644 --- a/src/features/api/payment-processing/metadata.ts +++ b/src/features/api/payment-processing/metadata.ts @@ -48,9 +48,6 @@ const parseListingTextAnswerIds = jsonMetaField< Record | undefined >(undefined); -const textOrEmpty = (value: unknown): string => - typeof value === "string" ? value : ""; - /** * Parse booking items from metadata JSON. Returns null when the JSON is * unparseable, not an array, or empty. @@ -111,21 +108,21 @@ export const extractIntent = ( const siteTokenIndex = metadata.site_token_index || undefined; const thankYouUrl = metadata.thank_you_url || undefined; return { - address: textOrEmpty(metadata.address), + address: metadata.address, allocations, balanceAttendeeId, date: metadata.date || null, dayCount, - email: textOrEmpty(metadata.email), + email: metadata.email, items, listingAnswerIds, listingTextAnswerIds, modifiers: parseModifierRefs(metadata.modifiers), - name: textOrEmpty(metadata.name), - phone: textOrEmpty(metadata.phone), + name: metadata.name, + phone: metadata.phone, reservationAmount, siteTokenIndex, - special_instructions: textOrEmpty(metadata.special_instructions), + special_instructions: metadata.special_instructions, thankYouUrl, }; }; diff --git a/src/shared/db/built-sites.ts b/src/shared/db/built-sites.ts index 100fb427bb..b7f25c7d3d 100644 --- a/src/shared/db/built-sites.ts +++ b/src/shared/db/built-sites.ts @@ -75,7 +75,7 @@ const SiteDataBlobSchema = v.strictObject({ s: OptionalStringSchema, t: OptionalStringSchema, u: v.string(), - v: v.literal(SITE_DATA_BLOB_VERSION), + v: v.optional(v.literal(SITE_DATA_BLOB_VERSION), SITE_DATA_BLOB_VERSION), }); export type SiteDataBlob = v.InferOutput; const siteDataJson = defineStoredJson(SiteDataBlobSchema); diff --git a/src/shared/payment-helpers.ts b/src/shared/payment-helpers.ts index 51bf9aa060..5e74906a2f 100644 --- a/src/shared/payment-helpers.ts +++ b/src/shared/payment-helpers.ts @@ -3,6 +3,7 @@ * Eliminates duplication between stripe.ts/square.ts and their provider adapters. */ +import * as v from "valibot"; import { lazyRef, map } from "#fp"; import { signedEdgeFor } from "#shared/booking/signed-metadata.ts"; import type { @@ -619,13 +620,15 @@ export const enforceMetadataLimits = ( }; /** - * Validate that session metadata contains required fields (name + items). + * Validate that every metadata value is text and required fields are present. */ +const ProviderMetadataSchema = v.record(v.string(), v.string()); + export const hasRequiredSessionMetadata = ( metadata: Record | null | undefined, ): metadata is SessionMetadata => { - if (!metadata?.name) return false; - return !!metadata.items; + if (!v.is(ProviderMetadataSchema, metadata)) return false; + return !!metadata.name && !!metadata.items; }; /** diff --git a/src/shared/types.ts b/src/shared/types.ts index 29a1b89b50..709e12fc9a 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -200,9 +200,6 @@ export const clampDurationDays = (value: number): number => { } }; -/** Reject any value that is not a whole day count in the supported range. */ -export const rejectDurationDays = durationDays.reject; - /** * Per-day-count ticket prices for "customisable days" listings, in minor * units, keyed by the number of days booked. e.g. `{ 1: 1000, 2: 1800 }` @@ -213,7 +210,7 @@ export type DayPrices = Record; const DayPriceKeySchema = v.pipe( v.string(), - v.regex(/^\d+$/), + v.regex(/^[1-9]\d*$/), v.check((value) => { const days = Number(value); return days >= 1 && days <= MAX_DURATION_DAYS; diff --git a/src/shared/validation/number.ts b/src/shared/validation/number.ts index 90ff2273e0..763088cee9 100644 --- a/src/shared/validation/number.ts +++ b/src/shared/validation/number.ts @@ -10,7 +10,9 @@ export interface BoundedInteger { } /** A safe whole number no lower than `minimum`. */ -export const integerAtLeast = (minimum: number) => +export const integerAtLeast = ( + minimum: number, +): v.GenericSchema => v.pipe(v.number(), v.safeInteger(), v.minValue(minimum)); /** Define explicit reject and clamp policies for one safe-integer range. */ @@ -48,6 +50,7 @@ const NonNegativeIntSchema = v.pipe( NonEmptyTextSchema, v.digits(), v.transform(Number), + v.safeInteger(), ); const PositiveIntSchema = v.pipe(NonNegativeIntSchema, v.minValue(1)); type IntSchema = v.GenericSchema; diff --git a/test/lib/server-webhooks/single-ticket-refunds.test.ts b/test/lib/server-webhooks/single-ticket-refunds.test.ts index 9765a5dc7c..55c33a097f 100644 --- a/test/lib/server-webhooks/single-ticket-refunds.test.ts +++ b/test/lib/server-webhooks/single-ticket-refunds.test.ts @@ -18,8 +18,8 @@ import { setupStripe } from "#test-utils/settings.ts"; import { checkoutSessionEvent, expectKeptAsQuantityZeroAndRefunded, + expectWebhookIgnored, expectWebhookKeptAndRefunded, - expectWebhookProcessed, stubRefundPayment, } from "#test-utils/webhooks.ts"; @@ -134,7 +134,7 @@ describeWithEnv( } }); - test("webhook single-ticket defaults email to empty when metadata email is not a string", async () => { + test("webhook does not fulfil a session with non-text metadata", async () => { await setupStripe(); const listing = await createTestListing({ @@ -142,13 +142,13 @@ describeWithEnv( unitPrice: 1000, }); - await expectWebhookProcessed( + await expectWebhookIgnored( checkoutSessionEvent({ amountTotal: 1000, eventId: "evt_no_email_single", metadata: signedMeta( { - email: 12345 as unknown as string, // not a string -> coerced to "" by extractSessionMetadata + email: 12345 as unknown as string, items: singleItem(listing.id, 1, 1000), name: "No Email Single", }, @@ -163,39 +163,7 @@ describeWithEnv( "#shared/db/attendees/queries.ts" ); const attendees = await getAttendeesRaw(listing.id); - expect(attendees.length).toBe(1); - }); - - test("webhook multi-ticket defaults email to empty when metadata email is not a string", async () => { - await setupStripe(); - - const listing = await createTestListing({ - maxAttendees: 50, - unitPrice: 500, - }); - - await expectWebhookProcessed( - checkoutSessionEvent({ - amountTotal: 500, - eventId: "evt_no_email_multi", - metadata: signedMeta( - { - email: true as unknown as string, // not a string -> coerced to "" by extractSessionMetadata - items: JSON.stringify([{ e: listing.id, p: 500, q: 1 }]), - name: "No Email Multi", - }, - 500, - ), - paymentIntent: "pi_wh_no_email_multi", - sessionId: "cs_wh_no_email_multi", - }), - ); - - const { getAttendeesRaw } = await import( - "#shared/db/attendees/queries.ts" - ); - const attendees = await getAttendeesRaw(listing.id); - expect(attendees.length).toBe(1); + expect(attendees).toEqual([]); }); }, ); diff --git a/test/shared/db/built-sites.test.ts b/test/shared/db/built-sites.test.ts index 0e4dc74161..18af03e713 100644 --- a/test/shared/db/built-sites.test.ts +++ b/test/shared/db/built-sites.test.ts @@ -1,5 +1,6 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { getAllCacheStats } from "#shared/cache-registry.ts"; import { assignBuiltSite, builtSites, @@ -11,11 +12,13 @@ import { insertBuiltSite, isUpdateTier, parseSiteDataBlob, + providerOrBunny, siteAcceptsDeployTier, siteBaseUrl, UPDATE_TIERS, updateBuiltSiteRenewalState, } from "#shared/db/built-sites.ts"; +import { execute } from "#shared/db/client.ts"; import { describeWithEnv } from "#test-utils/db.ts"; const formBlob = async ( @@ -25,6 +28,14 @@ const formBlob = async ( return parseSiteDataBlob(values.site_data as string); }; +describe("providerOrBunny", () => { + test("keeps named providers and defaults other values to Bunny", () => { + expect(providerOrBunny("deno", "deno")).toBe("deno"); + expect(providerOrBunny("turso", "turso")).toBe("turso"); + expect(providerOrBunny("", "deno")).toBe("bunny"); + }); +}); + describe("siteBaseUrl", () => { test("prepends https:// to a bare hostname", () => { expect(siteBaseUrl("site.b-cdn.net")).toBe("https://site.b-cdn.net"); @@ -163,16 +174,27 @@ describeWithEnv("built-sites", { db: true }, () => { expect(parsed.v).toBe(1); }); - test("parseSiteDataBlob handles legacy blobs without db keys", () => { + test("parseSiteDataBlob handles legacy blobs without db keys or a version", () => { const legacyBlob = JSON.stringify({ n: "Old Site", u: "old.b-cdn.net", - v: 1, }); const parsed = parseSiteDataBlob(legacyBlob); expect(parsed.d).toBeUndefined(); expect(parsed.t).toBeUndefined(); expect(parsed.s).toBeUndefined(); + expect(parsed.v).toBe(1); + + const providers = parseSiteDataBlob( + JSON.stringify({ + dp: "turso", + hp: "deno", + n: "Provider Site", + u: "provider.b-cdn.net", + }), + ); + expect(providers.dp).toBe("turso"); + expect(providers.hp).toBe("deno"); }); test("parseSiteDataBlob rejects malformed JSON and invalid fields", () => { @@ -186,6 +208,20 @@ describeWithEnv("built-sites", { db: true }, () => { ).toThrow("Invalid stored JSON in built_sites.site_data"); }); + test("toDbValues identifies invalid site data", () => { + expect(() => + builtSitesCrudTable.toDbValues({ + assignable: false, + dbToken: "", + dbUrl: "", + hostingId: "", + hostingProvider: "invalid" as never, + name: "Invalid Provider", + siteUrl: "invalid.b-cdn.net", + }), + ).toThrow("Invalid value for stored JSON in built_sites.site_data"); + }); + test("insertBuiltSite creates a row with encrypted site_data", async () => { const row = await insertBuiltSite("Alpha Site", "alpha.b-cdn.net"); expect(row.id).toBe(1); @@ -235,9 +271,17 @@ describeWithEnv("built-sites", { db: true }, () => { }); test("getAllBuiltSites returns decrypted sites sorted by name", async () => { - await insertBuiltSite("Charlie", "charlie.b-cdn.net"); - await insertBuiltSite("Alpha", "alpha.b-cdn.net"); - await insertBuiltSite("Bravo", "bravo.b-cdn.net"); + const charlie = await insertBuiltSite("Charlie", "charlie.b-cdn.net"); + const alpha = await insertBuiltSite("Alpha", "alpha.b-cdn.net"); + const bravo = await insertBuiltSite("Bravo", "bravo.b-cdn.net"); + await execute( + `UPDATE built_sites SET created = CASE id + WHEN ? THEN '2026-01-03T00:00:00.000Z' + WHEN ? THEN '2026-01-02T00:00:00.000Z' + WHEN ? THEN '2026-01-01T00:00:00.000Z' + ELSE created END`, + [charlie.id, alpha.id, bravo.id], + ); const sites = await builtSites.getAll(); expect(sites).toHaveLength(3); @@ -299,7 +343,17 @@ describeWithEnv("built-sites", { db: true }, () => { expect(value).toBe("Test"); }); - test("inputKeyMap exposes form-facing fields", () => { + test("raw nullable columns preserve falsy stored values", async () => { + expect(await builtSites.table.readColumn("assigned_attendee_id", 0)).toBe( + 0, + ); + expect(await builtSites.table.readColumn("renewal_token_index", "")).toBe( + "", + ); + }); + + test("exposes CRUD table metadata", () => { + expect(builtSitesCrudTable.name).toBe("built_sites"); expect(builtSitesCrudTable.inputKeyMap).toEqual({ assignable: "assignable", db_provider: "dbProvider", @@ -437,10 +491,26 @@ describeWithEnv("built-sites", { db: true }, () => { test("toDbValues handles partial input with missing fields", async () => { const values = await builtSitesCrudTable.toDbValues({}); const parsed = parseSiteDataBlob(values.site_data as string); + expect(values.assignable).toBe(0); expect(parsed.n).toBe(""); expect(parsed.u).toBe(""); }); + test("legacy rows default to Bunny providers", async () => { + const row = await builtSites.table.insert({ + siteData: JSON.stringify({ n: "Legacy", u: "legacy.b-cdn.net" }), + }); + const site = await builtSitesCrudTable.findById(row.id); + expect(site!.hostingProvider).toBe("bunny"); + expect(site!.dbProvider).toBe("bunny"); + }); + + test("cache stats identify the built sites cache", () => { + expect( + getAllCacheStats().filter(({ name }) => name === "built_sites"), + ).toHaveLength(1); + }); + test("toDbValues sets assignable to 1 when true", async () => { const values = await builtSitesCrudTable.toDbValues({ assignable: true, diff --git a/test/shared/db/listings/table.test.ts b/test/shared/db/listings/table.test.ts index 091ff7e701..5bd9f79af6 100644 --- a/test/shared/db/listings/table.test.ts +++ b/test/shared/db/listings/table.test.ts @@ -310,5 +310,15 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { ).rejects.toThrow("Invalid stored JSON in listings.day_prices row 7"); } }); + + test("rejects colliding canonical and leading-zero day keys", async () => { + await expect( + rawListingsTable.readColumn( + "day_prices", + '{"01":100,"1":200}' as unknown as DayPrices, + 7, + ), + ).rejects.toThrow("Invalid stored JSON in listings.day_prices row 7"); + }); }); }); diff --git a/test/shared/logger/log-output.test.ts b/test/shared/logger/log-output.test.ts index 3ee1f76c45..a2fed2d076 100644 --- a/test/shared/logger/log-output.test.ts +++ b/test/shared/logger/log-output.test.ts @@ -8,6 +8,7 @@ import { logRequest, setSuppressRequestLogs, } from "#shared/logger.ts"; +import { useDebugLogSpy } from "#test-utils/debug-log.ts"; import { withEnv } from "#test-utils/env.ts"; describe("logRequest", () => { @@ -74,39 +75,29 @@ describe("logRequest", () => { }); describe("logDebug", () => { - let debugSpy: Spy; - - beforeEach(() => { - setSuppressDebugLogs(false); - debugSpy = spy(console, "debug"); - }); - - afterEach(() => { - debugSpy.restore(); - setSuppressDebugLogs(null); - }); + const debugSpy = useDebugLogSpy(); test("formats message with category prefix", () => { logDebug("Setup", "Validation passed"); - expect(debugSpy.calls[0]?.args[0]).toBe("[Setup] Validation passed"); + expect(debugSpy().calls[0]?.args[0]).toBe("[Setup] Validation passed"); }); test("suppresses output when setSuppressDebugLogs(true)", () => { setSuppressDebugLogs(true); logDebug("Migration", "Step 1"); - expect(debugSpy.calls.length).toBe(0); + expect(debugSpy().calls.length).toBe(0); }); test("falls back to the TEST_SUPPRESS_DEBUG_LOGS env var when no override is set", () => { setSuppressDebugLogs(null); using _env = withEnv({ TEST_SUPPRESS_DEBUG_LOGS: "1" }); logDebug("Migration", "Step 1"); - expect(debugSpy.calls.length).toBe(0); + expect(debugSpy().calls.length).toBe(0); }); test("emits output when setSuppressDebugLogs(false)", () => { logDebug("Migration", "Step 1"); - expect(debugSpy.calls.length).toBe(1); + expect(debugSpy().calls.length).toBe(1); }); }); diff --git a/test/shared/payment-helpers/build-items.test.ts b/test/shared/payment-helpers/build-items.test.ts index dbafae0fe8..6b957b284c 100644 --- a/test/shared/payment-helpers/build-items.test.ts +++ b/test/shared/payment-helpers/build-items.test.ts @@ -3,6 +3,7 @@ import { describe, it as test } from "@std/testing/bdd"; import { priceCheckout } from "#shared/checkout-pricing.ts"; import { hmacHash } from "#shared/crypto/hashing.ts"; import { + assembleCheckoutMetadata, buildItemsMetadata, extractSessionMetadata, packMetadata, @@ -128,6 +129,17 @@ describeWithEnv( ), ).toBe(false); }); + + test("assembles Square metadata with small fields packed", async () => { + const wire = await assembleCheckoutMetadata( + "square", + intent, + priceCheckout(intent).total, + ); + + expect("phone" in wire).toBe(false); + expect(JSON.parse(wire.b!)).toMatchObject({ phone: "07700900000" }); + }); }, ); diff --git a/test/shared/payment-helpers/dispatch.test.ts b/test/shared/payment-helpers/dispatch.test.ts index 796c0ba9ca..f12fce7a5b 100644 --- a/test/shared/payment-helpers/dispatch.test.ts +++ b/test/shared/payment-helpers/dispatch.test.ts @@ -1,16 +1,23 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { spy } from "@std/testing/mock"; import { ErrorCode } from "#shared/logger.ts"; import { + cachedClientFactory, createWithClient, hasRequiredSessionMetadata, PaymentUserError, + parseWebhookPayload, safeAsync, toCheckoutResult, + validatedPaymentSession, } from "#shared/payment-helpers.ts"; -import { isPaymentStatus } from "#shared/payments.ts"; +import { isPaymentStatus, type SessionMetadata } from "#shared/payments.ts"; +import { useDebugLogSpy } from "#test-utils/debug-log.ts"; describe("payment-helpers", () => { + const debugSpy = useDebugLogSpy(); + describe("hasRequiredSessionMetadata", () => { test("returns false for null/undefined", () => { expect(hasRequiredSessionMetadata(null)).toBe(false); @@ -54,6 +61,16 @@ describe("payment-helpers", () => { }), ).toBe(true); }); + + test("returns false when a present metadata value is not text", () => { + expect( + hasRequiredSessionMetadata({ + email: 123 as unknown as string, + items: "[]", + name: "Alice", + }), + ).toBe(false); + }); }); describe("isPaymentStatus", () => { @@ -89,13 +106,72 @@ describe("payment-helpers", () => { }); test("re-throws PaymentUserError", async () => { + const error = new PaymentUserError("Bad phone"); + expect(error.name).toBe("PaymentUserError"); await expect( - safeAsync( - () => Promise.reject(new PaymentUserError("Bad phone")), - ErrorCode.PAYMENT_CHECKOUT, - ), + safeAsync(() => Promise.reject(error), ErrorCode.PAYMENT_CHECKOUT), ).rejects.toThrow("Bad phone"); }); + + test("logs unknown for a non-Error rejection", async () => { + const errorSpy = spy(console, "error"); + try { + await safeAsync( + () => Promise.reject("string error"), + ErrorCode.PAYMENT_CHECKOUT, + ); + expect(errorSpy.calls[0]?.args[0]).toBe( + '[Error] E_PAYMENT_CHECKOUT detail="unknown"', + ); + } finally { + errorSpy.restore(); + } + }); + }); + + describe("cachedClientFactory", () => { + test("logs missing configuration and the chosen creation message", async () => { + let config: string | null = null; + const cache = cachedClientFactory({ + create: (value: string) => ({ value }), + createMessage: () => "", + getConfig: () => config, + isSameConfig: (a, b) => a === b, + missingMessage: "No secret key configured", + provider: "Stripe", + }); + + expect(await cache.getClient()).toBeNull(); + config = "secret"; + expect(await cache.getClient()).toEqual({ value: "secret" }); + expect(debugSpy().calls.map((call) => call.args[0])).toEqual([ + "[Stripe] No secret key configured", + "[Stripe] ", + ]); + }); + + test("reuses and logs the cached client", async () => { + const client = { value: "secret" }; + let createCalls = 0; + const cache = cachedClientFactory({ + create: () => { + createCalls += 1; + return client; + }, + getConfig: () => "secret", + isSameConfig: (a, b) => a === b, + missingMessage: "No secret key configured", + provider: "Stripe", + }); + + expect(await cache.getClient()).toBe(client); + expect(await cache.getClient()).toBe(client); + expect(createCalls).toBe(1); + expect(debugSpy().calls.map((call) => call.args[0])).toEqual([ + "[Stripe] Creating new Stripe client", + "[Stripe] Using cached Stripe client", + ]); + }); }); describe("createWithClient", () => { @@ -159,6 +235,29 @@ describe("payment-helpers", () => { toCheckoutResult("", "https://pay.example.com", "Stripe"), ).toBeNull(); expect(toCheckoutResult("sess_1", "", "Payment")).toBeNull(); + expect(debugSpy().calls[0]?.args[0]).toBe( + "[Stripe] Checkout result missing session ID or URL", + ); + }); + }); + + test("validatedPaymentSession includes a supplied creation time", () => { + const createdAt = "2026-07-19T12:00:00.000Z"; + const session = validatedPaymentSession({ + amountTotal: 1000, + createdAt, + id: "session-1", + metadata: { items: "[]", name: "Alice" } as SessionMetadata, + paymentReference: "payment-1", + paymentStatus: "paid", }); + + expect(session.createdAt).toBe(createdAt); + }); + + test("parseWebhookPayload returns the invalid JSON error", () => { + expect(parseWebhookPayload("not JSON", ErrorCode.PAYMENT_CHECKOUT)).toEqual( + { error: "Invalid JSON payload", valid: false }, + ); }); }); diff --git a/test/shared/payment-helpers/limits.test.ts b/test/shared/payment-helpers/limits.test.ts index 2f95ca91f0..e308409be8 100644 --- a/test/shared/payment-helpers/limits.test.ts +++ b/test/shared/payment-helpers/limits.test.ts @@ -218,6 +218,12 @@ describe("payment-helpers", () => { }); describe("metadata packing codec", () => { + test("packs one balance attendee id", () => { + expect(packMetadata({ balance_attendee_id: "42" })).toEqual({ + b: '{"balance_attendee_id":"42"}', + }); + }); + test("packs the small fields into one `b` entry and drops them", () => { const packed = packMetadata({ _origin: "x", @@ -307,4 +313,8 @@ describe("payment-helpers", () => { expect(extracted.date).toBe("2026-07-01"); }); }); + + test("an absent option field fits a zero-length limit", () => { + expect(enforceMetadataLimits({}, 0)).toEqual({}); + }); }); diff --git a/test/shared/payment-helpers/metadata.test.ts b/test/shared/payment-helpers/metadata.test.ts index a62b4080f7..05a990b65c 100644 --- a/test/shared/payment-helpers/metadata.test.ts +++ b/test/shared/payment-helpers/metadata.test.ts @@ -113,6 +113,7 @@ describe("payment-helpers", () => { test("single-listing metadata survives full pipeline", () => { const metadata = buildMetadata({ address: "123 Main St", + balanceAttendeeId: 42, date: "2026-02-10", email: "alice@example.com", items: [{ e: 42, p: 0, q: 3 }], @@ -131,6 +132,7 @@ describe("payment-helpers", () => { expect(extracted.email).toBe("alice@example.com"); expect(extracted.phone).toBe("+1234567890"); expect(extracted.address).toBe("123 Main St"); + expect(extracted.balance_attendee_id).toBe("42"); expect(extracted.special_instructions).toBe("No nuts"); expect(extracted.date).toBe("2026-02-10"); expect(JSON.parse(extracted.answer_ids)).toEqual({ "42": [10, 20] }); diff --git a/test/shared/payments.test.ts b/test/shared/payments.test.ts index 1116b3e51d..c649affa8e 100644 --- a/test/shared/payments.test.ts +++ b/test/shared/payments.test.ts @@ -1,9 +1,7 @@ import { expect } from "@std/expect"; -import { afterEach, beforeEach, describe, it as test } from "@std/testing/bdd"; -import { type Spy, spy } from "@std/testing/mock"; +import { describe, it as test } from "@std/testing/bdd"; import * as v from "valibot"; import { ALL_SETTINGS_KEYS, settings } from "#shared/db/settings.ts"; -import { setSuppressDebugLogs } from "#shared/log-settings.ts"; import { type BookingItem, BookingItemsSchema, @@ -11,6 +9,7 @@ import { isPaymentStatus, } from "#shared/payments.ts"; import { describeWithEnv } from "#test-utils/db.ts"; +import { useDebugLogSpy } from "#test-utils/debug-log.ts"; /** A minimal booking line that satisfies every schema rule; spread and override * one field per case to probe a single boundary in isolation. Each line is @@ -114,18 +113,9 @@ describe("BookingItemsSchema", () => { }); describeWithEnv("getActivePaymentProvider", { db: true }, () => { - let debugSpy: Spy; + const debugSpy = useDebugLogSpy(); const debugLogged = (needle: string): boolean => - debugSpy.calls.some((call) => String(call.args[0]).includes(needle)); - - beforeEach(() => { - setSuppressDebugLogs(false); - debugSpy = spy(console, "debug"); - }); - afterEach(() => { - debugSpy.restore(); - setSuppressDebugLogs(null); - }); + debugSpy().calls.some((call) => String(call.args[0]).includes(needle)); test("returns null when no provider is configured", async () => { expect(await getActivePaymentProvider()).toBeNull(); diff --git a/test/shared/validation/number.test.ts b/test/shared/validation/number.test.ts index c8c8bfe982..a7006605b3 100644 --- a/test/shared/validation/number.test.ts +++ b/test/shared/validation/number.test.ts @@ -80,6 +80,10 @@ describe("parseNonNegativeInt", () => { expect(parseNonNegativeInt(value)).toBeNull(); } }); + + test("rejects integers above JavaScript's safe range", () => { + expect(parseNonNegativeInt(String(Number.MAX_SAFE_INTEGER + 1))).toBeNull(); + }); }); describe("parsePositiveInt", () => { diff --git a/test/test-utils/debug-log.ts b/test/test-utils/debug-log.ts new file mode 100644 index 0000000000..1da3d72404 --- /dev/null +++ b/test/test-utils/debug-log.ts @@ -0,0 +1,17 @@ +import { afterEach, beforeEach } from "@std/testing/bdd"; +import { type Spy, spy } from "@std/testing/mock"; +import { setSuppressDebugLogs } from "#shared/log-settings.ts"; + +/** Capture debug output for each test and restore global logging afterwards. */ +export const useDebugLogSpy = (): (() => Spy) => { + let debugSpy: Spy; + beforeEach(() => { + setSuppressDebugLogs(false); + debugSpy = spy(console, "debug"); + }); + afterEach(() => { + debugSpy.restore(); + setSuppressDebugLogs(null); + }); + return () => debugSpy; +}; From e9d82c7545c2d84387497ce89f04ad0007d75c28 Mon Sep 17 00:00:00 2001 From: Stefan Date: Sun, 19 Jul 2026 17:24:39 +0100 Subject: [PATCH 03/17] Reject malformed listing API fields --- scripts/mutation/equivalent-mutants.txt | 9 +++ src/features/admin/api.ts | 38 +++++++++- .../admin/api.test.ts} | 38 +++++++++- .../routes/admin-api-listings-read.test.ts} | 71 +++++++++++++++++++ .../routes/admin-api-listings-update.test.ts} | 51 ++++++++++++- .../admin-api/listings/lifecycle.test.ts | 26 +++++-- 6 files changed, 222 insertions(+), 11 deletions(-) rename test/{admin-api-listings/input-parsers.test.ts => features/admin/api.test.ts} (85%) rename test/{admin-api-listings/read.test.ts => integration/routes/admin-api-listings-read.test.ts} (50%) rename test/{admin-api-listings/update.test.ts => integration/routes/admin-api-listings-update.test.ts} (87%) diff --git a/scripts/mutation/equivalent-mutants.txt b/scripts/mutation/equivalent-mutants.txt index ca7b6a7a10..a9eeac232e 100644 --- a/scripts/mutation/equivalent-mutants.txt +++ b/scripts/mutation/equivalent-mutants.txt @@ -256,6 +256,15 @@ src/shared/db/built-sites.ts:202:15 renewalTokenIndex → "" # not in BuiltSi src/shared/db/built-sites.ts:377:71 ?? → || # blob input strings use "" as their fallback, providers are non-empty, and renewalToken uses null src/shared/db/built-sites.ts:391:54 ?? → || # validated optional strings use "" as their fallback, providers are non-empty, and renewalToken is null or non-empty +# Admin listing API fallbacks receive only objects, arrays, positive ids, or +# nullish values, so no valid request can distinguish these operators. +src/features/admin/api.ts:342:66 ?? → || # stored listing lookup returns a ListingWithCount object or null; listing objects are truthy +src/features/admin/api.ts:373:25 ?? → || # parsed group ids are an array or undefined; every array, including [], is truthy +src/features/admin/api.ts:492:30 1 → 0 # the mutation changes sentinel -1 to -0; positive listing ids match neither value +src/features/admin/api.ts:534:19 ?? → || # groupIds is an array or undefined; every array, including [], is truthy +src/features/admin/api.ts:547:43 ?? → || # an existing listing id is positive and truthy, otherwise optional access yields undefined +src/features/admin/api.ts:549:38 ?? → || # groupIds is an array or undefined; every array, including [], is truthy + # Settings registry: readOnly is optional but can only be true when present, so # `"readOnly" in accessor && accessor.readOnly` and `... || accessor.readOnly` # make the same if-condition decision for every valid accessor. diff --git a/src/features/admin/api.ts b/src/features/admin/api.ts index d53a45153b..5a7e40fcef 100644 --- a/src/features/admin/api.ts +++ b/src/features/admin/api.ts @@ -8,6 +8,7 @@ */ /* jscpd:ignore-start */ +import * as v from "valibot"; import { mapById, reduce } from "#fp"; import { groupApiRoutes } from "#routes/admin/api-groups.ts"; import { holidayApiRoutes } from "#routes/admin/api-holidays.ts"; @@ -157,6 +158,38 @@ const optionalFields: FieldMapping[] = [ ["bookable_alone", "bookableAlone", "boolean"], ]; +interface ApiBodyFieldRule { + apiKey: string; + error: string; + schema: v.GenericSchema; +} + +const API_BODY_FIELD_RULES: ApiBodyFieldRule[] = [ + { + apiKey: "bookable_days", + error: "bookable_days must contain only text", + schema: v.array(v.string()), + }, + { + apiKey: "duration_days", + error: "duration_days must be a safe integer", + schema: v.pipe(v.number(), v.safeInteger()), + }, +]; + +/** Reject malformed mapped values before they can reach domain or storage code. */ +const validateApiBodyFields = ( + body: Record, +): ParseResult => { + const invalid = API_BODY_FIELD_RULES.find( + ({ apiKey, schema }) => + body[apiKey] !== undefined && !v.is(schema, body[apiKey]), + ); + return invalid + ? { error: invalid.error, ok: false } + : { input: undefined, ok: true }; +}; + /** * Parse a day_prices object from a JSON body into DayPrices. Keeps only * positive-integer day counts mapped to numeric prices; everything else is @@ -249,12 +282,13 @@ const existingToDefaults = (existing: ListingWithCount): FieldRecord => // Body → ListingInput converters // ============================================================================= -/** Parse the request's group ids, then either bail with the parse error or hand - * the ids to `build` to finish producing the listing input. */ +/** Validate mapped fields and group ids before building the listing input. */ const withParsedGroupIds = ( body: Record, build: (groupIds: number[] | undefined) => Promise>, ): Promise> => { + const fields = validateApiBodyFields(body); + if (!fields.ok) return Promise.resolve(fields); const groups = parseGroupIds(body.group_ids); return groups.ok ? build(groups.input) : Promise.resolve(groups); }; diff --git a/test/admin-api-listings/input-parsers.test.ts b/test/features/admin/api.test.ts similarity index 85% rename from test/admin-api-listings/input-parsers.test.ts rename to test/features/admin/api.test.ts index d5779a694f..882f392997 100644 --- a/test/admin-api-listings/input-parsers.test.ts +++ b/test/features/admin/api.test.ts @@ -15,6 +15,12 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { if (!result.ok) expect(result.error).toBe("name is required"); }); + test("returns error for a whitespace-only name", async () => { + const result = await bodyToCreateInput({ max_attendees: 10, name: " " }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toBe("name is required"); + }); + test("returns error for missing max_attendees", async () => { const result = await bodyToCreateInput({ name: "Test" }); expect(result.ok).toBe(false); @@ -23,24 +29,54 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { } }); + test("returns error when max_attendees is zero", async () => { + const result = await bodyToCreateInput({ + max_attendees: 0, + name: "Test", + }); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toBe("max_attendees is required and must be >= 1"); + } + }); + test("handles all field types correctly", async () => { const result = await bodyToCreateInput({ active: false, + bookable_alone: true, bookable_days: ["Monday"], closes_at: "2026-06-14T23:59:00Z", date: "2026-06-15T10:00:00Z", + day_prices: { 0: 900, 1: 1200 }, + duration_days: 3, max_attendees: 10, + max_price: 5000, name: "Test", }); expect(result.ok).toBe(true); if (result.ok) { expect(result.input.active).toBe(false); + expect(result.input.bookableAlone).toBe(true); expect(result.input.bookableDays).toEqual(["Monday"]); + expect(result.input.date).toBe("2026-06-15T10:00:00Z"); + expect(result.input.dayPrices).toEqual({ 1: 1200 }); + expect(result.input.durationDays).toBe(3); + expect(result.input.maxPrice).toBe(5000); expect(result.input.slug).toBeTruthy(); } }); + test("defaults max_price to zero", async () => { + const result = await bodyToCreateInput({ + max_attendees: 10, + name: "No Maximum Price", + }); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.input.maxPrice).toBe(0); + }); + test("rejects a non-array group_ids", async () => { const result = await bodyToCreateInput({ group_ids: "5", @@ -48,7 +84,7 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { name: "Bad Groups", }); expect(result.ok).toBe(false); - if (!result.ok) expect(result.error).toContain("must be an array"); + if (!result.ok) expect(result.error).toBe("group_ids must be an array"); }); test("rejects group_ids with non-positive-integer entries", async () => { diff --git a/test/admin-api-listings/read.test.ts b/test/integration/routes/admin-api-listings-read.test.ts similarity index 50% rename from test/admin-api-listings/read.test.ts rename to test/integration/routes/admin-api-listings-read.test.ts index db7df9d356..601ff115c5 100644 --- a/test/admin-api-listings/read.test.ts +++ b/test/integration/routes/admin-api-listings-read.test.ts @@ -5,6 +5,7 @@ import { assertJson } from "#test-utils/assertions.ts"; import { describeWithEnv } from "#test-utils/db.ts"; import { createTestListing } from "#test-utils/db-helpers/listings.ts"; import { mockRequest } from "#test-utils/mocks.ts"; +import { bookingPageHtml } from "#test-utils/parents.ts"; import { apiRequest, createTestApiKeyToken, @@ -63,4 +64,74 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { ); }); }); + + describe("listing child IDs", () => { + test("rejects child_listing_ids when it is not an array", async () => { + const listing = await createTestListing({ name: "Array required" }); + + await assertJson( + apiRequest(`/api/admin/listings/${listing.id}`, { + body: { child_listing_ids: "1" }, + method: "PUT", + }), + 400, + (body) => { + expect(body.error).toBe( + "child_listing_ids must be an array of listing ids", + ); + }, + ); + }); + + test("accepts listing ID 1 as a positive integer", async () => { + const listing = await createTestListing({ name: "Positive IDs" }); + + await assertJson( + apiRequest(`/api/admin/listings/${listing.id}`, { + body: { child_listing_ids: [1] }, + method: "PUT", + }), + 200, + ); + }); + + test("rejects a fractional child listing ID", async () => { + const listing = await createTestListing({ name: "Integer IDs" }); + + await assertJson( + apiRequest(`/api/admin/listings/${listing.id}`, { + body: { child_listing_ids: [1.5] }, + method: "PUT", + }), + 400, + (body) => { + expect(body.error).toBe( + "child_listing_ids must contain only positive integer listing ids", + ); + }, + ); + }); + + test("creates a parent with the first listing as its child", async () => { + const child = await createTestListing({ name: "First child" }); + let parentSlug = ""; + + await assertJson( + apiRequest("/api/admin/listings", { + body: { + child_listing_ids: [child.id], + max_attendees: 10, + name: "New parent", + }, + method: "POST", + }), + 201, + (body) => { + parentSlug = body.listing.slug; + }, + ); + + expect(await bookingPageHtml(parentSlug)).toContain("First child"); + }); + }); }); diff --git a/test/admin-api-listings/update.test.ts b/test/integration/routes/admin-api-listings-update.test.ts similarity index 87% rename from test/admin-api-listings/update.test.ts rename to test/integration/routes/admin-api-listings-update.test.ts index d3a67b7aeb..c47be6aae0 100644 --- a/test/admin-api-listings/update.test.ts +++ b/test/integration/routes/admin-api-listings-update.test.ts @@ -1,6 +1,10 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; -import { assertJson, expectRejectsEmptyName } from "#test-utils/assertions.ts"; +import { + assertAdminHtml, + assertJson, + expectRejectsEmptyName, +} from "#test-utils/assertions.ts"; import { describeWithEnv } from "#test-utils/db.ts"; import { createTestGroup } from "#test-utils/db-helpers/groups.ts"; import { createTestListing } from "#test-utils/db-helpers/listings.ts"; @@ -58,6 +62,34 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { await expectRejectsEmptyName(`/api/admin/listings/${listing.id}`); }); + test("returns 400 for a fractional duration", async () => { + const listing = await createTestListing({ name: "Whole Days" }); + await assertJson( + apiRequest(`/api/admin/listings/${listing.id}`, { + body: { duration_days: 2.5 }, + method: "PUT", + }), + 400, + (body) => { + expect(body.error).toBe("duration_days must be a safe integer"); + }, + ); + }); + + test("returns 400 when a bookable day is not text", async () => { + const listing = await createTestListing({ name: "Named Days" }); + await assertJson( + apiRequest(`/api/admin/listings/${listing.id}`, { + body: { bookable_days: ["Monday", 2] }, + method: "PUT", + }), + 400, + (body) => { + expect(body.error).toBe("bookable_days must contain only text"); + }, + ); + }); + test("rejects duplicate slug", async () => { const listing1 = await createTestListing({ name: "Listing One" }); const listing2 = await createTestListing({ name: "Listing Two" }); @@ -89,6 +121,23 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { }, ); }); + + test("links an update to the listing activity page", async () => { + const listing = await createTestListing({ name: "Activity before" }); + + await assertJson( + apiRequest(`/api/admin/listings/${listing.id}`, { + body: { name: "Activity after" }, + method: "PUT", + }), + 200, + ); + + await assertAdminHtml( + `/admin/listing/${listing.id}/activity`, + "Listing 'Activity after' updated", + ); + }); }); describe("PUT /api/admin/listings/:listingId - comprehensive field updates", () => { diff --git a/test/integration/server/admin-api/listings/lifecycle.test.ts b/test/integration/server/admin-api/listings/lifecycle.test.ts index db1e4a4bd4..1838da7b9b 100644 --- a/test/integration/server/admin-api/listings/lifecycle.test.ts +++ b/test/integration/server/admin-api/listings/lifecycle.test.ts @@ -5,6 +5,7 @@ import { invalidateListingsCache, listingsTable, } from "#shared/db/listings/records.ts"; +import { wasActivityLogged } from "#test-utils/activity-log.ts"; import { assertJson } from "#test-utils/assertions.ts"; import { describeWithEnv } from "#test-utils/db.ts"; import { createTestListing } from "#test-utils/db-helpers/listings.ts"; @@ -30,6 +31,11 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { invalidateListingsCache(); const deleted = await getListingWithCount(listing.id); expect(deleted).toBeNull(); + expect( + await wasActivityLogged( + "Listing 'Delete Me' deleted (0 attendee(s) removed)", + ), + ).toBe(true); }); test("rejects with wrong confirm_identifier", async () => { @@ -42,7 +48,9 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { }), 400, (body) => { - expect(body.error).toContain("Listing name does not match"); + expect(body.error).toBe( + "Listing name does not match. Please provide the exact listing name in confirm_identifier.", + ); }, ); }); @@ -70,12 +78,16 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { }); test("returns 404 for non-existent listing", async () => { - const response = await apiRequest("/api/admin/listings/99999", { - body: { confirm_identifier: "Ghost" }, - method: "DELETE", - }); - - expect(response.status).toBe(404); + await assertJson( + apiRequest("/api/admin/listings/99999", { + body: { confirm_identifier: "Ghost" }, + method: "DELETE", + }), + 404, + (body) => { + expect(body.error).toBe("Listing not found"); + }, + ); }); }); From 43bfa108b278175c7ab1f8915adbaf83e6334a4e Mon Sep 17 00:00:00 2001 From: stefan burke <83819576+stefan-burke@users.noreply.github.com> Date: Sun, 19 Jul 2026 19:21:07 +0000 Subject: [PATCH 04/17] Improve checkout screenshot fixtures (#1868) * Fix reservation balance summaries * Extend external screenshot scenarios * Fix mobile booking controls * Address reservation balance review * Derive balance query arguments * Clarify reservation order totals * Improve paid checkout screenshots * Start Stripe mock for screenshots * Clean up failed screenshot startup * Clean up all screenshot resources --- scripts/screenshots.ts | 76 +++++++++++++++++-------- scripts/screenshots/server.ts | 26 +++++++++ src/ui/static/style.scss | 3 +- test/scripts/screenshots-server.test.ts | 58 ++++++++++++++++++- 4 files changed, 137 insertions(+), 26 deletions(-) diff --git a/scripts/screenshots.ts b/scripts/screenshots.ts index 0d4d010dd2..c12017abec 100644 --- a/scripts/screenshots.ts +++ b/scripts/screenshots.ts @@ -3,7 +3,7 @@ import { chromium, type Page } from "playwright"; import sharp from "sharp"; import { browserLaunchOptions } from "./browser-options.ts"; import { rethrowUnlessNotFound } from "./not-found.ts"; -import { denoCommand, removeTree, runDeno } from "./process.ts"; +import { denoCommand, removeTree, runDeno, stopProcess } from "./process.ts"; import { isCompactWidth, isolateElementCss, @@ -18,19 +18,30 @@ import { loadScreenshotScenario, type ScreenshotScenario, } from "./screenshots/scenario.ts"; -import { waitForHealthy } from "./screenshots/server.ts"; -import { findAvailablePort } from "./stripe-mock.ts"; +import { + type StartupCleanup, + startWithFailureCleanup, + waitForHealthy, +} from "./screenshots/server.ts"; +import { + findAvailablePort, + startStripeMock, + stripeMockEnv, +} from "./stripe-mock.ts"; const ROOT = dirname(dirname(fromFileUrl(import.meta.url))); const DB_KEY = "MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY="; const USERNAME = "screenshots"; const PASSWORD = "screenshots-password"; +const STRIPE_KEY = "sk_test_mock"; const TIMEOUT_MS = 60_000; const RETRY_MS = 200; +const STOP_TIMEOUT_MS = 2_000; const MOBILE_VIEWPORT = { height: 844, width: 390 }; interface AppServer { baseUrl: string; + enableStripe: () => Promise; stop: () => Promise; } @@ -111,23 +122,30 @@ const SCENES: Record = { users: { path: at("/admin/users") }, }; -const startServer = async (): Promise => { - const build = await runDeno(["task", "build:static"], ROOT); - if (!build.success) throw new Error("Could not build static assets."); +const startAppServer = async ({ + add, + run, +}: StartupCleanup): Promise => { + const stripeMock = await startStripeMock(); + add(stripeMock.stop); const tempDir = await Deno.makeTempDir({ prefix: "tickets-screenshots-" }); + add(() => removeTree(tempDir)); const port = findAvailablePort(); const baseUrl = `http://127.0.0.1:${port}`; + const dbUrl = `file:${join(tempDir, "screenshots.db")}`; const child = denoCommand(["run", "-A", "src/index.ts"], { cwd: ROOT, env: { ...Deno.env.toObject(), + ...stripeMockEnv(stripeMock.port), DB_ENCRYPTION_KEY: DB_KEY, - DB_URL: `file:${join(tempDir, "screenshots.db")}`, + DB_URL: dbUrl, PORT: String(port), }, stderr: "inherit", stdout: "null", }).spawn(); + add(() => stopProcess(child, STOP_TIMEOUT_MS)); const deadline = Date.now() + TIMEOUT_MS; const healthy = await waitForHealthy( @@ -138,22 +156,28 @@ const startServer = async (): Promise => { if (healthy) { return { baseUrl, - stop: async () => { - try { - child.kill("SIGTERM"); - await child.status; - } finally { - await removeTree(tempDir); - } + enableStripe: async () => { + Deno.env.set("DB_ENCRYPTION_KEY", DB_KEY); + Deno.env.set("DB_URL", dbUrl); + const { settings } = await import("#shared/db/settings.ts"); + await settings.update.stripe.activate({ + secretKey: STRIPE_KEY, + webhookEndpointId: "we_screenshots", + webhookSecret: "whsec_screenshots", + }); }, + stop: run, }; } - child.kill("SIGKILL"); - await child.status; - await removeTree(tempDir); throw new Error("The screenshot app did not start within 60 seconds."); }; +const startServer = async (): Promise => { + const build = await runDeno(["task", "build:static"], ROOT); + if (!build.success) throw new Error("Could not build static assets."); + return await startWithFailureCleanup(startAppServer); +}; + const submit = async (page: Page, formSelector: string): Promise => { const form = page.locator(formSelector); await Promise.all([ @@ -184,13 +208,15 @@ const setupAdmin = async ( await page.goto(`${baseUrl}/admin/settings`); await page.locator('[name="business_email"]').fill("hello@example.com"); await submit(page, 'form[action="/admin/settings/business-email"]'); - await page.goto(`${baseUrl}/admin/settings`); - await page.locator('[name="payment_provider"][value="none"]').check(); - await submit(page, 'form[action="/admin/settings/payment-provider"]'); }; -const setupApp = async (page: Page, baseUrl: string): Promise => { +const setupApp = async ( + page: Page, + server: AppServer, +): Promise => { + const { baseUrl } = server; await setupAdmin(page, baseUrl); + await server.enableStripe(); await page.goto(`${baseUrl}/admin/seeds`); await page.locator('[name="listing_count"]').fill("5"); await page.locator('[name="attendees_per_listing"]').fill("8"); @@ -346,10 +372,12 @@ const capturePreparedPage = async ( const captureScenario = async ( scenario: ScreenshotScenario, page: Page, - baseUrl: string, + server: AppServer, outputDir: string, ): Promise => { + const { baseUrl } = server; await setupAdmin(page, baseUrl, scenario.setupUsername); + await server.enableStripe(); await applyTheme( page, baseUrl, @@ -421,10 +449,10 @@ const main = async (): Promise => { const page = await context.newPage(); page.setDefaultTimeout(TIMEOUT_MS); if (scenario) { - await captureScenario(scenario, page, server.baseUrl, outputDir); + await captureScenario(scenario, page, server, outputDir); return; } - const sceneContext = await setupApp(page, server.baseUrl); + const sceneContext = await setupApp(page, server); for (const theme of options.themes) { const themeDir = join(outputDir, theme); await Deno.mkdir(themeDir, { recursive: true }); diff --git a/scripts/screenshots/server.ts b/scripts/screenshots/server.ts index 60fcaf45a3..179990667e 100644 --- a/scripts/screenshots/server.ts +++ b/scripts/screenshots/server.ts @@ -1,3 +1,29 @@ +import { + type CleanupTask, + failAfterCleanups, + runCleanups, +} from "../cleanup.ts"; + +export interface StartupCleanup { + add: (cleanup: CleanupTask) => void; + run: () => Promise; +} + +export const startWithFailureCleanup = async ( + start: (cleanup: StartupCleanup) => Promise, +): Promise => { + const cleanups: CleanupTask[] = []; + const cleanup: StartupCleanup = { + add: (task) => cleanups.unshift(task), + run: () => runCleanups(cleanups), + }; + try { + return await start(cleanup); + } catch (error) { + return await failAfterCleanups(error, cleanups); + } +}; + export const waitForHealthy = async ( request: () => Promise, wait: () => Promise, diff --git a/src/ui/static/style.scss b/src/ui/static/style.scss index 8e8e25357b..79463c2c51 100644 --- a/src/ui/static/style.scss +++ b/src/ui/static/style.scss @@ -1193,7 +1193,8 @@ label > input[type="number"] { } label > select[name="quantity"], -label > select[name^="quantity_"] { +label > select[name^="quantity_"], +label > select[name^="child_qty_"] { width: 8ch; flex: 0 0 auto; } diff --git a/test/scripts/screenshots-server.test.ts b/test/scripts/screenshots-server.test.ts index 4495ed825f..e138809bdd 100644 --- a/test/scripts/screenshots-server.test.ts +++ b/test/scripts/screenshots-server.test.ts @@ -1,6 +1,9 @@ import { expect } from "@std/expect"; import { describe, it } from "@std/testing/bdd"; -import { waitForHealthy } from "../../scripts/screenshots/server.ts"; +import { + startWithFailureCleanup, + waitForHealthy, +} from "../../scripts/screenshots/server.ts"; const expectOneRetry = async ( request: () => Promise, @@ -19,6 +22,59 @@ const expectOneRetry = async ( }; describe("screenshot server", () => { + it("stops an acquired resource when startup fails", async () => { + const startupError = new Error("startup failed"); + const stops: string[] = []; + + await expect( + startWithFailureCleanup(({ add }) => { + add(() => { + stops.push("first"); + }); + add(() => { + stops.push("second"); + }); + return Promise.reject(startupError); + }), + ).rejects.toBe(startupError); + expect(stops).toEqual(["second", "first"]); + }); + + it("hands cleanup ownership to a successful startup", async () => { + let stops = 0; + + const stop = await startWithFailureCleanup(({ add, run }) => { + add(() => { + stops += 1; + }); + return Promise.resolve(run); + }); + expect(stops).toBe(0); + await stop(); + expect(stops).toBe(1); + }); + + it("runs every cleanup when one fails", async () => { + const cleanupError = new Error("cleanup failed"); + let finalCleanupRan = false; + + await expect( + startWithFailureCleanup(({ add }) => { + add(() => { + finalCleanupRan = true; + }); + add(() => Promise.reject(cleanupError)); + return Promise.reject(new Error("startup failed")); + }), + ).rejects.toEqual( + new AggregateError( + [new Error("startup failed"), cleanupError], + "Multiple errors occurred", + ), + ); + expect(finalCleanupRan).toBe(true); + }); + it("waits before retrying a non-OK response", async () => { const responses = [ new Response("Starting", { status: 503 }), From 1111bfa600a8e57fca21b4a059bf46245ed53095 Mon Sep 17 00:00:00 2001 From: Stefan Date: Sun, 19 Jul 2026 20:37:52 +0100 Subject: [PATCH 05/17] Remove unused integer rejection policy --- src/shared/types.ts | 12 ++++---- src/shared/validation/number.ts | 25 ++++------------- test/shared/validation/number.test.ts | 32 +++++++--------------- test/ui/client/admin/order-gallery.test.ts | 17 ++++++------ 4 files changed, 29 insertions(+), 57 deletions(-) diff --git a/src/shared/types.ts b/src/shared/types.ts index 709e12fc9a..71a4db1b80 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -18,7 +18,7 @@ import type { ModifierTrigger, } from "#shared/price-modifier.ts"; import { guardFor } from "#shared/validation/guard.ts"; -import { boundedInteger, integerAtLeast } from "#shared/validation/number.ts"; +import { clampInteger, integerAtLeast } from "#shared/validation/number.ts"; import type { NonEmptyString } from "#shared/validation/string.ts"; /** Type guard: a non-null, non-array object (a Record shape). */ @@ -182,17 +182,15 @@ export const hasTicketQuantity = (row: { quantity: number }): boolean => export const MAX_DURATION_DAYS = 90; /** - * Booking durations use one safe-integer range with two named policies. Clamp - * is for valid whole numbers outside the supported range. Reject is for - * boundaries where an out-of-range value must fail instead. Neither policy - * accepts fractions, non-finite numbers, or unsafe integers. + * Booking durations clamp valid whole numbers to one safe-integer range. + * Fractions, non-finite numbers, and unsafe integers are rejected. */ -const durationDays = boundedInteger(1, MAX_DURATION_DAYS); +const clampBookingDuration = clampInteger(1, MAX_DURATION_DAYS); /** Clamp a valid whole-day count to the supported booking range. */ export const clampDurationDays = (value: number): number => { try { - return durationDays.clamp(value); + return clampBookingDuration(value); } catch (error) { throw new Error(`Invalid booking duration: ${String(value)}`, { cause: error, diff --git a/src/shared/validation/number.ts b/src/shared/validation/number.ts index 763088cee9..455a433d6d 100644 --- a/src/shared/validation/number.ts +++ b/src/shared/validation/number.ts @@ -2,35 +2,20 @@ import * as v from "valibot"; import { parseOrNull } from "./parse.ts"; import { NonEmptyTextSchema } from "./string.ts"; -export interface BoundedInteger { - /** Clamp valid integers to the range. Malformed numbers still throw. */ - clamp: (value: number) => number; - /** Require a valid integer inside the range. */ - reject: (value: number) => number; -} - /** A safe whole number no lower than `minimum`. */ export const integerAtLeast = ( minimum: number, ): v.GenericSchema => v.pipe(v.number(), v.safeInteger(), v.minValue(minimum)); -/** Define explicit reject and clamp policies for one safe-integer range. */ -export const boundedInteger = ( +/** Clamp safe whole numbers to a range. Malformed numbers still throw. */ +export const clampInteger = ( minimum: number, maximum: number, -): BoundedInteger => { +): ((value: number) => number) => { const integerSchema = integerAtLeast(Number.MIN_SAFE_INTEGER); - const rangeSchema = v.pipe( - integerSchema, - v.minValue(minimum), - v.maxValue(maximum), - ); - return { - clamp: (value) => - Math.max(minimum, Math.min(maximum, v.parse(integerSchema, value))), - reject: (value) => v.parse(rangeSchema, value), - }; + return (value) => + Math.max(minimum, Math.min(maximum, v.parse(integerSchema, value))); }; /** diff --git a/test/shared/validation/number.test.ts b/test/shared/validation/number.test.ts index a7006605b3..7b6f9df351 100644 --- a/test/shared/validation/number.test.ts +++ b/test/shared/validation/number.test.ts @@ -1,44 +1,32 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; import { - boundedInteger, + clampInteger, parseNonNegativeInt, parsePositiveInt, parsePositiveIntId, } from "#shared/validation/number.ts"; -describe("boundedInteger", () => { - const days = boundedInteger(1, 90); +describe("clampInteger", () => { + const clampDays = clampInteger(1, 90); - test("reject policy accepts safe integers within the range", () => { - expect(days.reject(1)).toBe(1); - expect(days.reject(45)).toBe(45); - expect(days.reject(90)).toBe(90); + test("clamps valid integers outside the range", () => { + expect(clampDays(-2)).toBe(1); + expect(clampDays(500)).toBe(90); }); - test("reject policy rejects integers outside the range", () => { - expect(() => days.reject(0)).toThrow(); - expect(() => days.reject(91)).toThrow(); + test("leaves valid integers within the range unchanged", () => { + expect(clampDays(37)).toBe(37); }); - test("clamp policy clamps valid integers outside the range", () => { - expect(days.clamp(-2)).toBe(1); - expect(days.clamp(500)).toBe(90); - }); - - test("clamp policy leaves valid integers within the range unchanged", () => { - expect(days.clamp(37)).toBe(37); - }); - - test("both policies reject malformed numbers", () => { + test("rejects malformed numbers", () => { for (const value of [ 1.5, Number.NaN, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1, ]) { - expect(() => days.reject(value)).toThrow(); - expect(() => days.clamp(value)).toThrow(); + expect(() => clampDays(value)).toThrow(); } }); }); diff --git a/test/ui/client/admin/order-gallery.test.ts b/test/ui/client/admin/order-gallery.test.ts index 42a2712e97..44d86b3d78 100644 --- a/test/ui/client/admin/order-gallery.test.ts +++ b/test/ui/client/admin/order-gallery.test.ts @@ -44,14 +44,6 @@ const stash = createGlobalStash(); // test on a virtual clock so settle() skips past it instantly instead of each // test genuinely sleeping 300ms. const clock: { time: FakeTime | null } = { time: null }; -beforeEach(() => { - clock.time = new FakeTime(); -}); -afterEach(() => { - clock.time?.restore(); - clock.time = null; - stash.restore(); -}); /** Install the DOM and a scripted availability endpoint, then boot the * script. `responses` are consumed one per request; when empty the endpoint @@ -122,6 +114,15 @@ const settle = async (): Promise => { }; describe("initOrderGallery", () => { + beforeEach(() => { + clock.time = new FakeTime(); + }); + afterEach(() => { + clock.time?.restore(); + clock.time = null; + stash.restore(); + }); + test("does nothing on a page without the gallery form", () => { const window = new Window({ url: "https://tickets.test/" }); window.document.body.innerHTML = "

No gallery here

"; From 209e1e62677f56cf5168547720a88650e863e9cb Mon Sep 17 00:00:00 2001 From: Stefan Date: Sun, 19 Jul 2026 20:54:57 +0100 Subject: [PATCH 06/17] Enforce order gallery clock setup --- test/ui/client/admin/order-gallery.test.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/test/ui/client/admin/order-gallery.test.ts b/test/ui/client/admin/order-gallery.test.ts index 44d86b3d78..e60842e3bf 100644 --- a/test/ui/client/admin/order-gallery.test.ts +++ b/test/ui/client/admin/order-gallery.test.ts @@ -45,6 +45,11 @@ const stash = createGlobalStash(); // test genuinely sleeping 300ms. const clock: { time: FakeTime | null } = { time: null }; +const getClock = (): FakeTime => { + if (clock.time === null) throw new Error("Fake clock was not installed"); + return clock.time; +}; + /** Install the DOM and a scripted availability endpoint, then boot the * script. `responses` are consumed one per request; when empty the endpoint * answers "everything fine, no states". */ @@ -109,8 +114,8 @@ const harness = (html = GALLERY_HTML) => { * response microtasks (tickAsync flushes them BEFORE advancing, so the * fired callback's await chain needs one more round). */ const settle = async (): Promise => { - await clock.time!.tickAsync(300); - await clock.time!.runMicrotasks(); + await getClock().tickAsync(300); + await getClock().runMicrotasks(); }; describe("initOrderGallery", () => { @@ -118,7 +123,8 @@ describe("initOrderGallery", () => { clock.time = new FakeTime(); }); afterEach(() => { - clock.time?.restore(); + // beforeEach always installs the clock; teardown must fail if that changes. + getClock().restore(); clock.time = null; stash.restore(); }); From 7cd215d98663fc69596b23c22c8fe1a969614d81 Mon Sep 17 00:00:00 2001 From: stefan burke <83819576+stefan-burke@users.noreply.github.com> Date: Sun, 19 Jul 2026 21:13:26 +0000 Subject: [PATCH 07/17] Normalize repeated form choices and table layouts (#1866) * Normalize declarative form inputs * Consolidate declarative input handling * Address declarative input review feedback * Unify declarative input sources * Address final declarative input review * Use functional column layout parsing --- scripts/mutation/equivalent-mutants.txt | 8 + src/features/admin/aggregate-recalculation.ts | 14 +- src/features/admin/dashboard.ts | 10 +- src/features/admin/entity-write-tab.ts | 2 +- src/features/admin/listings-edit.ts | 2 +- src/features/admin/logistics-agent-page.tsx | 2 +- src/features/admin/modifiers.ts | 2 +- src/features/admin/settings-general.ts | 36 ++-- .../admin/settings-listing-defaults.ts | 21 +- src/shared/column-layout.ts | 172 +++++++++++++++++ src/shared/column-order.ts | 114 +---------- src/shared/columns/attendee-columns.ts | 26 +-- src/shared/columns/listing-columns.ts | 52 ++--- src/shared/day-names.ts | 4 +- src/shared/db/settings.ts | 11 ++ src/shared/form-data.ts | 26 ++- src/shared/forms/definition.ts | 34 +--- src/shared/forms/saved-data.ts | 1 + src/shared/forms/submitted-value.ts | 10 - src/shared/forms/validation.ts | 77 ++++---- src/ui/templates/admin/dashboard.tsx | 27 ++- src/ui/templates/admin/groups/overview.tsx | 11 +- src/ui/templates/admin/guide/operations.tsx | 20 +- src/ui/templates/admin/ledger/entry-pages.tsx | 4 +- src/ui/templates/admin/listing-table.tsx | 12 +- src/ui/templates/admin/news.tsx | 4 +- src/ui/templates/admin/questions.tsx | 2 +- .../templates/admin/settings/column-order.tsx | 16 +- src/ui/templates/admin/site-pages.tsx | 4 +- src/ui/templates/attendee-table.tsx | 47 ++--- .../admin/aggregate-recalculation.test.ts | 153 +++++++++++++++ test/features/admin/dashboard.test.ts | 79 ++++++++ .../admin/dashboard/listings-csv.test.ts} | 5 + test/features/admin/dashboard/log.test.ts | 74 +++++++ .../admin/settings-listing-defaults.test.ts | 29 ++- .../server/listings/create-validation.test.ts | 15 ++ .../server/settings/column-order.test.ts | 26 ++- .../server/settings}/listing-defaults.test.ts | 3 + test/lib/server-editor.test.ts | 3 +- .../lib/server-images/attachment-edit.test.ts | 7 +- test/lib/server-images/create.test.ts | 7 +- .../server-listings/log-and-activity.test.ts | 70 +------ test/shared/column-layout.test.ts | 118 ++++++++++++ test/shared/column-order.test.ts | 171 ++-------------- test/shared/columns/attendee-columns.test.ts | 25 +-- test/shared/dates/pinned-values.test.ts | 19 +- test/shared/day-names.test.ts | 23 +++ test/shared/db/attendees/api/errors.test.ts | 2 +- test/shared/form-data.test.ts | 42 ++++ .../forms/definition/define-form.test.ts | 2 +- .../forms/definition/field-schema.test.ts | 52 +++-- test/shared/forms/validation.test.ts | 182 ++++++++++++++++-- test/test-utils/db-helpers/listing-forms.ts | 81 ++++---- test/test-utils/db-helpers/request.ts | 14 +- test/test-utils/form-values.test.ts | 18 ++ test/test-utils/form-values.ts | 24 +++ test/test-utils/mocks.ts | 16 +- test/test-utils/session.ts | 3 +- test/test-utils/validation.ts | 21 +- test/ui/templates/admin/dashboard.test.ts | 5 +- test/ui/templates/admin/ledger/forms.test.ts | 2 +- .../templates/attendee-table/template.test.ts | 31 +-- test/ui/templates/fields/listing.test.ts | 33 +++- 63 files changed, 1366 insertions(+), 760 deletions(-) create mode 100644 src/shared/column-layout.ts create mode 100644 test/features/admin/aggregate-recalculation.test.ts create mode 100644 test/features/admin/dashboard.test.ts rename test/{lib/server-listings-csv.test.ts => features/admin/dashboard/listings-csv.test.ts} (87%) create mode 100644 test/features/admin/dashboard/log.test.ts rename test/{lib/server-settings => integration/server/settings}/listing-defaults.test.ts (99%) create mode 100644 test/shared/column-layout.test.ts create mode 100644 test/shared/day-names.test.ts create mode 100644 test/test-utils/form-values.test.ts create mode 100644 test/test-utils/form-values.ts diff --git a/scripts/mutation/equivalent-mutants.txt b/scripts/mutation/equivalent-mutants.txt index b3e84213d0..c61ed71b60 100644 --- a/scripts/mutation/equivalent-mutants.txt +++ b/scripts/mutation/equivalent-mutants.txt @@ -28,6 +28,14 @@ # ` — exit 0 means lint did not kill it. src/ui/templates/components/data-table.tsx:85:43 0 → -1 # For the only changed case, an empty array, both branches render the same empty tbody; non-empty arrays make both comparisons false +src/shared/form-data.ts:16:33 ?? → || # trim returns a string, and its only falsy value is the empty string supplied by the fallback +src/shared/form-data.ts:35:23 !== → != # parsePositiveIntId returns number|null and cannot return undefined, so strict and loose inequality agree when comparing it with null +src/shared/forms/validation.ts:51:8 === → == # value is string|number|null and cannot be undefined, so strict and loose equality agree when comparing it with null +src/shared/forms/validation.ts:69:10 === → == # readSubmittedFieldValue returns string|null and cannot return undefined, so strict and loose equality agree when comparing it with null +src/shared/forms/validation.ts:101:46 = → += # this assignment runs only when trimmed is the empty string, so replacing it and appending to it produce the same defaultValue +src/shared/forms/validation.ts:105:16 !== → != # validateFieldText returns string|null and cannot return undefined, so strict and loose inequality agree when comparing it with null +src/features/admin/settings-listing-defaults.ts:53:15 === → == # parseNonNegativeInt returns number|null and cannot return undefined, so strict and loose equality agree when comparing it with null +src/features/admin/dashboard.ts:235:65 1 → 2 # The query needs any number above the 200-row display limit only to detect overflow; both limits produce the same truncated flag and the same first 200 displayed rows src/features/admin/entity-pages.ts:275:24 ?? → || # opts.query is a URLSearchParams object when present, so it is always truthy src/features/admin/site-content-page.ts:87:38 ?? → || # extraTabs is an array when present, and arrays are always truthy diff --git a/src/features/admin/aggregate-recalculation.ts b/src/features/admin/aggregate-recalculation.ts index dbce711714..0b0a62235a 100644 --- a/src/features/admin/aggregate-recalculation.ts +++ b/src/features/admin/aggregate-recalculation.ts @@ -1,4 +1,5 @@ /* jscpd:ignore-start */ + import { AUTH_FORM, requireSessionOr, withAuth } from "#routes/auth.ts"; import { htmlResponse, redirect } from "#routes/response.ts"; import { getFlash } from "#shared/flash-context.ts"; @@ -35,10 +36,13 @@ export const parseEditableAggregateForm = ( export const selectedRecalculationFields = ( form: FormParams, - allowed: readonly T[], + allowed: readonly [T, ...T[]], ): T[] => { - const selected = new Set(form.getAll(RECALCULATE_FIELD_NAME)); - return allowed.filter((field) => selected.has(field)); + const selection = form.getRepeatedPicklist(RECALCULATE_FIELD_NAME, allowed); + if (!selection.ok) { + throw new Error(`Invalid recalculation field: ${selection.error}`); + } + return selection.value; }; /** @@ -51,7 +55,7 @@ export const selectedRecalculationFields = ( */ export const runRecalculatePost = async (config: { form: FormParams; - fields: readonly T[]; + fields: readonly [T, ...T[]]; /** Re-render the recalculate page with the "choose a field" error. */ renderChoose: ResponseHandler; reset: (selected: T[]) => Promise; @@ -108,7 +112,7 @@ export const createRecalculateHandlers = (config: { error?: string, success?: string, ) => Promise; - fields: readonly F[]; + fields: readonly [F, ...F[]]; entityId: (entity: T) => number; reset: (entityId: number, selected: F[]) => Promise; log: (entity: T) => Promise; diff --git a/src/features/admin/dashboard.ts b/src/features/admin/dashboard.ts index 7dc7f5f937..fc59de32a6 100644 --- a/src/features/admin/dashboard.ts +++ b/src/features/admin/dashboard.ts @@ -149,7 +149,7 @@ const handleAdminGet = (request: Request): Promise => newestAttendees, successMessage, stats, - settings.listingColumnOrder, + settings.listingColumnLayout, activeType, holidays, unbookableIds, @@ -170,7 +170,9 @@ const handleAdminListingsGet: TypedRouteHandler<"GET /admin/listings"> = return adminListingsPage( listings, session, - settings.listingColumnOrder, + session.adminLevel === "editor" + ? undefined + : settings.listingColumnLayout, await loadListingAttributeFilterContext(request, listings), ); }); @@ -232,9 +234,7 @@ const handleAdminLog: TypedRouteHandler<"GET /admin/log"> = sessionPage( async (session) => { const entries = await getAllActivityLog(LOG_DISPLAY_LIMIT + 1); const truncated = entries.length > LOG_DISPLAY_LIMIT; - const displayEntries = truncated - ? entries.slice(0, LOG_DISPLAY_LIMIT) - : entries; + const displayEntries = entries.slice(0, LOG_DISPLAY_LIMIT); const refs = await loadActivityLogRefs(displayEntries); return adminGlobalActivityLogPage(displayEntries, truncated, session, refs); }, diff --git a/src/features/admin/entity-write-tab.ts b/src/features/admin/entity-write-tab.ts index 963ab54989..f14787d71c 100644 --- a/src/features/admin/entity-write-tab.ts +++ b/src/features/admin/entity-write-tab.ts @@ -35,7 +35,7 @@ export const submittedValueProps = ( rejected ? { error: rejected.error, - values: Object.fromEntries(rejected.form.entries()), + values: rejected.form.toRenderValues(), } : {}; diff --git a/src/features/admin/listings-edit.ts b/src/features/admin/listings-edit.ts index 599aa29773..37c5891216 100644 --- a/src/features/admin/listings-edit.ts +++ b/src/features/admin/listings-edit.ts @@ -222,7 +222,7 @@ const renderCreateListingError = async ( // re-renders their selection rather than dropping every group. selectedGroupIds: parseGroupIds(form), templateId, - values: Object.fromEntries(form.entries()), + values: form.toRenderValues(), }, 400, ); diff --git a/src/features/admin/logistics-agent-page.tsx b/src/features/admin/logistics-agent-page.tsx index 786cadf4b2..fb461adf6a 100644 --- a/src/features/admin/logistics-agent-page.tsx +++ b/src/features/admin/logistics-agent-page.tsx @@ -56,7 +56,7 @@ export const logisticsAgentPage: EditEntityPage = ...(rejected ? { error: rejected.error, - values: Object.fromEntries(rejected.form.entries()), + values: rejected.form.toRenderValues(), } : {}), }); diff --git a/src/features/admin/modifiers.ts b/src/features/admin/modifiers.ts index b9da2a35c1..8d7410a831 100644 --- a/src/features/admin/modifiers.ts +++ b/src/features/admin/modifiers.ts @@ -316,7 +316,7 @@ const modifierPage: EditEntityPage = defineEditEntityPage({ modifier, ctx.session, rejected?.error, - rejected ? Object.fromEntries(rejected.form.entries()) : undefined, + rejected?.form.toRenderValues(), ), guard: requireSessionOr, guideFooter: () => Promise.resolve(ModifiersGuideFooter()), diff --git a/src/features/admin/settings-general.ts b/src/features/admin/settings-general.ts index f0aae4f2ad..1bd42dfbf0 100644 --- a/src/features/admin/settings-general.ts +++ b/src/features/admin/settings-general.ts @@ -15,9 +15,7 @@ import { settingsHandler, settingsToggle, } from "#routes/admin/settings-helpers.ts"; -import { validateColumnTemplate } from "#shared/column-order.ts"; -import { ATTENDEE_TABLE_COLUMNS } from "#shared/columns/attendee-columns.ts"; -import { LISTING_TABLE_COLUMNS } from "#shared/columns/listing-columns.ts"; +import { COLUMN_LAYOUTS } from "#shared/column-layout.ts"; import { clearSessionCookie } from "#shared/cookies.ts"; import { logActivity } from "#shared/db/activityLog.ts"; import { settings } from "#shared/db/settings.ts"; @@ -194,24 +192,28 @@ export const handleBookingFeePost = settingsHandler({ * Build a column-order settings handler for the listing or attendee table. * Handles POST /admin/settings/{listing,attendee}-column-order - owner only */ -const columnOrderHandler = (kind: "listing" | "attendee") => { - const columns = - kind === "listing" ? LISTING_TABLE_COLUMNS : ATTENDEE_TABLE_COLUMNS; - const update = - kind === "listing" - ? settings.update.listingColumnOrder - : settings.update.attendeeColumnOrder; - const label = - kind === "listing" ? "Listing column order" : "Attendee column order"; +const COLUMN_ORDER_SETTINGS = { + attendee: { + label: "Attendee column order", + update: settings.update.attendeeColumnOrder, + }, + listing: { + label: "Listing column order", + update: settings.update.listingColumnOrder, + }, +}; + +type ConfigurableColumnLayoutKind = keyof typeof COLUMN_ORDER_SETTINGS; + +const columnOrderHandler = (kind: ConfigurableColumnLayoutKind) => { + const config = COLUMN_ORDER_SETTINGS[kind]; return settingsHandler({ advanced: true, extract: (form) => form.getString("column_order").trim(), formId: `settings-${kind}-column-order`, - label, - save: (value) => update(value), - // Empty value clears to the default column order - validate: (value) => - value ? validateColumnTemplate(value, Object.keys(columns)) : null, + label: config.label, + save: config.update, + validate: COLUMN_LAYOUTS[kind].validate, }); }; diff --git a/src/features/admin/settings-listing-defaults.ts b/src/features/admin/settings-listing-defaults.ts index 307098dbcc..830f9ae88f 100644 --- a/src/features/admin/settings-listing-defaults.ts +++ b/src/features/admin/settings-listing-defaults.ts @@ -80,22 +80,23 @@ const parseUrlField = ( /** Parse the bookable-days default: only set when its enable box is ticked, with * at least one valid day (in canonical order). */ const parseDaysField = (form: FormParams): FieldParse => { - if (form.getString("default_bookable_days_enabled") !== "1") return {}; - const submittedDays = form.getAll("default_bookable_days"); - const invalidDay = submittedDays.find( - (submittedDay) => - !VALID_DAY_NAMES.some((validDay) => validDay === submittedDay), + if (!form.getFlag("default_bookable_days_enabled")) return {}; + const selection = form.getRepeatedPicklist( + "default_bookable_days", + VALID_DAY_NAMES, ); - if (invalidDay !== undefined) + if (!selection.ok) { return { error: t("fields.validation.invalid_day", { - day: invalidDay, + day: selection.error, valid: VALID_DAY_NAMES.join(", "), }), }; - const days = VALID_DAY_NAMES.filter((day) => submittedDays.includes(day)); - if (days.length === 0) return { error: t("listing_defaults.days_required") }; - return { value: days }; + } + if (selection.value.length === 0) { + return { error: t("listing_defaults.days_required") }; + } + return { value: selection.value }; }; /** Per-kind parser. The `Record` is keyed by {@link ListingDefaultKind}, so a diff --git a/src/shared/column-layout.ts b/src/shared/column-layout.ts new file mode 100644 index 0000000000..29f0831161 --- /dev/null +++ b/src/shared/column-layout.ts @@ -0,0 +1,172 @@ +/** Parse and validate configurable table column layouts without loading the + * Liquid rendering engine used later to format cell values. */ + +import * as v from "valibot"; +import { reduce } from "#fp"; +import type { Result } from "#shared/result.ts"; + +export type ColumnLayout = { + readonly columnKeys: readonly TColumn[]; + readonly filters: ReadonlyMap; +}; + +const LIQUID_TAG_RE = /\{\{\s*([^}]+?)\s*\}\}/g; + +const parseTagBody = ( + body: string, +): { key: string; filter: string | undefined } => { + const pipeIdx = body.indexOf("|"); + if (pipeIdx === -1) return { filter: undefined, key: body.trim() }; + return { filter: body.trim(), key: body.slice(0, pipeIdx).trim() }; +}; + +interface LayoutParts { + columns: T[]; + filters: Map; + seen: Set; +} + +type CollectedLayout = Result>; + +type ParsedLayout = Result< + Pick, "columns" | "filters"> +>; + +type ColumnSchema = v.GenericSchema & { + readonly options: readonly string[]; +}; + +const collectColumnTag = + (schema: TSchema) => + ( + result: CollectedLayout>, + match: RegExpMatchArray, + ): CollectedLayout> => { + if (!result.ok) return result; + const { key, filter } = parseTagBody(match[1]!); + const parsed = v.safeParse(schema, key); + if (!parsed.success) { + return { + error: `Unknown column "${key}". Available columns: ${schema.options.join(", ")}`, + ok: false, + }; + } + const option = parsed.output; + const { columns, filters, seen } = result.value; + if (!seen.has(option)) { + seen.add(option); + columns.push(option); + if (filter) filters.set(option, filter); + } + return result; + }; + +const parseColumnTemplate = ( + template: string, + schema: TSchema, +): ParsedLayout> => { + const collected = reduce(collectColumnTag(schema), { + ok: true, + value: { + columns: [], + filters: new Map(), + seen: new Set(), + }, + } satisfies CollectedLayout>)([ + ...template.matchAll(LIQUID_TAG_RE), + ]); + if (!collected.ok) return collected; + const { columns, filters } = collected.value; + + if (columns.length === 0) { + return { error: "Template must include at least one column", ok: false }; + } + + return { ok: true, value: { columns, filters } }; +}; + +export const buildDefaultTemplate = (keys: readonly string[]): string => + keys.map((key) => `{{${key}}}`).join(", "); + +const defineColumnLayout = < + const TDefault extends readonly [string, ...string[]], + const TExtra extends readonly string[], +>( + defaultOrder: TDefault, + extra: TExtra, +) => { + const [first, ...rest] = defaultOrder; + const schema = v.picklist([first, ...rest, ...extra]); + const defaultLayout: ColumnLayout = { + columnKeys: defaultOrder, + filters: new Map(), + }; + return { + defaultLayout, + defaultOrder, + defaultTemplate: buildDefaultTemplate(defaultOrder), + options: schema.options as readonly (TDefault[number] | TExtra[number])[], + parse(template: string): ColumnLayout { + if (!template) return defaultLayout; + const result = parseColumnTemplate(template, schema); + if (!result.ok) throw new Error(result.error); + return { + columnKeys: result.value.columns, + filters: result.value.filters, + }; + }, + schema, + validate(template: string): string | null { + if (!template) return null; + const result = parseColumnTemplate(template, schema); + return result.ok ? null : result.error; + }, + }; +}; + +export const COLUMN_LAYOUTS = { + attendee: defineColumnLayout( + [ + "status", + "date", + "name", + "listings", + "email", + "phone", + "address", + "special_instructions", + "answers", + "qty", + "ticket", + "registered", + ], + [], + ), + listing: defineColumnLayout( + [ + "name", + "description", + "status", + "attendees", + "tickets", + "revenue", + "cost", + "profit", + "created", + ], + ["date", "location", "price", "renewal"], + ), +}; + +export type ColumnLayoutKind = keyof typeof COLUMN_LAYOUTS; +export type ListingColumn = + (typeof COLUMN_LAYOUTS)["listing"]["options"][number]; +export type AttendeeColumn = + (typeof COLUMN_LAYOUTS)["attendee"]["options"][number]; + +export type ListingColumnLayout = ReturnType< + (typeof COLUMN_LAYOUTS)["listing"]["parse"] +>; +export type AttendeeColumnLayout = ReturnType< + (typeof COLUMN_LAYOUTS)["attendee"]["parse"] +>; diff --git a/src/shared/column-order.ts b/src/shared/column-order.ts index 125e26f4e3..8980f6b467 100644 --- a/src/shared/column-order.ts +++ b/src/shared/column-order.ts @@ -10,8 +10,8 @@ * {{price | currency}} → "£25.00" */ +import { once } from "#fp"; import { createBaseLiquidEngine } from "#shared/liquid-engine.ts"; -import { requireSuccess } from "#shared/result.ts"; // --------------------------------------------------------------------------- // Types @@ -53,108 +53,7 @@ export type ColumnGenerators = Record< // `currency` is custom; `date` is a LiquidJS built-in (strftime on Date objects). // ISO string → Date conversion happens in renderFilteredValue before calling Liquid. -const engine = createBaseLiquidEngine(); - -// --------------------------------------------------------------------------- -// Template parsing — regex-based extraction + validation -// --------------------------------------------------------------------------- - -/** Regex to extract Liquid output tags: {{ expression }} */ -const LIQUID_TAG_RE = /\{\{\s*([^}]+?)\s*\}\}/g; - -/** - * Extract the column key and optional filter expression from a Liquid tag body. - * "name" → { key: "name", filter: undefined } - * "date | date: \"%B\"" → { key: "date", filter: "date | date: \"%B\"" } - */ -const parseTagBody = ( - body: string, -): { key: string; filter: string | undefined } => { - const pipeIdx = body.indexOf("|"); - if (pipeIdx === -1) return { filter: undefined, key: body.trim() }; - return { filter: body.trim(), key: body.slice(0, pipeIdx).trim() }; -}; - -/** - * Parse a column-order template and extract the ordered list of column keys - * plus any per-column Liquid filter expressions. - * - * Validation is done by checking extracted keys against the valid set. - * No Liquid engine is needed for validation — just regex + Set.has(). - */ -const parseColumnTemplate = ( - template: string, - validKeys: readonly string[], -): - | { ok: true; columns: string[]; filters: Map } - | { - ok: false; - error: string; - } => { - const validKeySet = new Set(validKeys); - const columns: string[] = []; - const filters = new Map(); - const seen = new Set(); - - for (const match of template.matchAll(LIQUID_TAG_RE)) { - const { key, filter } = parseTagBody(match[1]!); - if (!validKeySet.has(key)) { - return { - error: `Unknown column "${key}". Available columns: ${validKeys.join( - ", ", - )}`, - ok: false, - }; - } - if (!seen.has(key)) { - seen.add(key); - columns.push(key); - if (filter) filters.set(key, filter); - } - } - - if (columns.length === 0) { - return { error: "Template must include at least one column", ok: false }; - } - - return { columns, filters, ok: true }; -}; - -/** - * Validate a column-order template without extracting columns. - * Returns null if valid, or an error message string if invalid. - */ -export const validateColumnTemplate = ( - template: string, - validKeys: readonly string[], -): string | null => { - const result = parseColumnTemplate(template, validKeys); - return result.ok ? null : result.error; -}; - -/** - * Build a default template from an ordered list of column keys. - * Produces e.g. "{{name}}, {{description}}, {{actions}}" - */ -export const buildDefaultTemplate = (keys: readonly string[]): string => - keys.map((k) => `{{${k}}}`).join(", "); - -/** - * Parse a template and return column keys and filters. - * Shared by all listing/attendee table renderers. - */ -export const resolveColumnLayout = ( - template: string, - validKeys: readonly string[], - defaultOrder: readonly string[], -): { columnKeys: string[]; filters: Map } => { - if (!template) { - return { columnKeys: [...defaultOrder], filters: new Map() }; - } - const result = parseColumnTemplate(template, validKeys); - requireSuccess(result); - return { columnKeys: result.columns, filters: result.filters }; -}; +const getEngine = once(createBaseLiquidEngine); /** Matches only when `date` is the first filter applied to the raw value */ const FIRST_FILTER_IS_DATE_RE = /^[^|]*\|\s*date\b/; @@ -184,7 +83,7 @@ export const renderFilteredValue = ( const d = new Date(rawValue); if (!Number.isNaN(d.getTime())) contextValue = d; } - const result = engine.parseAndRenderSync(`{{ ${expression} }}`, { + const result = getEngine().parseAndRenderSync(`{{ ${expression} }}`, { [key]: contextValue, }); return result.trim(); @@ -196,15 +95,16 @@ export const renderFilteredValue = ( */ export const renderCells = ( row: TRow, - columnKeys: string[], + columnKeys: readonly string[], generators: ColumnGenerators, opts: TOpts, - filters: Map, + filters: ReadonlyMap, escapeHtml: (s: string) => string, ): string => { const cells: string[] = []; for (const key of columnKeys) { - const col = generators[key]!; + const col = generators[key]; + if (col === undefined) throw new Error(`Unknown column: ${key}`); const filterExpr = filters.get(key); const useFilter = filterExpr && col.rawValue; const content = useFilter diff --git a/src/shared/columns/attendee-columns.ts b/src/shared/columns/attendee-columns.ts index 470a674323..383f44bb63 100644 --- a/src/shared/columns/attendee-columns.ts +++ b/src/shared/columns/attendee-columns.ts @@ -7,7 +7,8 @@ import { t } from "#i18n"; import { attendeeAdminPath } from "#shared/attendee-links.ts"; -import type { ColumnDef, ColumnGenerators } from "#shared/column-order.ts"; +import type { AttendeeColumn } from "#shared/column-layout.ts"; +import type { ColumnDef } from "#shared/column-order.ts"; import { formatDateLabel, formatDatetimeShort } from "#shared/dates.ts"; import { isServicing } from "#shared/db/attendees/kind.ts"; import { nonBlankLines } from "#shared/lines.ts"; @@ -218,10 +219,7 @@ const formatInstructionsInline = (instructions: string): string => { // --------------------------------------------------------------------------- /** All available attendee table columns */ -export const ATTENDEE_TABLE_COLUMNS: ColumnGenerators< - AttendeeTableRow, - AttendeeColumnOpts -> = { +export const ATTENDEE_TABLE_COLUMNS = { address, answers, date, @@ -234,20 +232,4 @@ export const ATTENDEE_TABLE_COLUMNS: ColumnGenerators< special_instructions, status, ticket, -}; - -/** Default column order for the attendee table */ -export const ATTENDEE_DEFAULT_ORDER = [ - "status", - "date", - "name", - "listings", - "email", - "phone", - "address", - "special_instructions", - "answers", - "qty", - "ticket", - "registered", -] as const; +} satisfies Record; diff --git a/src/shared/columns/listing-columns.ts b/src/shared/columns/listing-columns.ts index d0b09261d3..05c8958ac4 100644 --- a/src/shared/columns/listing-columns.ts +++ b/src/shared/columns/listing-columns.ts @@ -6,7 +6,8 @@ * cell rendering, and guide documentation. */ -import type { ColumnDef, ColumnGenerators } from "#shared/column-order.ts"; +import type { ColumnLayout, ListingColumn } from "#shared/column-layout.ts"; +import type { ColumnDef } from "#shared/column-order.ts"; import { formatCurrency } from "#shared/currency.ts"; import type { ListingWithCount } from "#shared/types.ts"; import { escapeHtml } from "#templates/layout.tsx"; @@ -125,7 +126,7 @@ const renewal: ListingCol = { // --------------------------------------------------------------------------- /** All available listing table columns */ -export const LISTING_TABLE_COLUMNS: ColumnGenerators = { +export const LISTING_TABLE_COLUMNS = { attendees, cost, created, @@ -139,41 +140,13 @@ export const LISTING_TABLE_COLUMNS: ColumnGenerators = { revenue, status, tickets, -}; - -/** Default column order for the listing table */ -export const LISTING_DEFAULT_ORDER = [ - "name", - "description", - "status", - "attendees", - "tickets", - "revenue", - "cost", - "profit", - "created", -] as const; +} satisfies Record; /** Listing columns shown to editors: the ledger-derived money columns * (revenue/cost/profit) are omitted entirely — not just unordered — so a saved * column template can never surface them, and the name links to the edit form * rather than the forbidden detail page. */ -export const EDITOR_LISTING_TABLE_COLUMNS: ColumnGenerators = - { - attendees, - created, - date, - description, - location, - name: editorName, - price, - renewal, - status, - tickets, - }; - -/** Default column order for the editor listing table (no money columns). */ -export const EDITOR_LISTING_DEFAULT_ORDER = [ +export const EDITOR_LISTING_COLUMN_KEYS = [ "name", "description", "status", @@ -181,3 +154,18 @@ export const EDITOR_LISTING_DEFAULT_ORDER = [ "tickets", "created", ] as const; +type EditorListingColumn = (typeof EDITOR_LISTING_COLUMN_KEYS)[number]; + +export const EDITOR_LISTING_TABLE_COLUMNS = { + attendees, + created, + description, + name: editorName, + status, + tickets, +} satisfies Record; + +export const EDITOR_LISTING_LAYOUT: ColumnLayout = { + columnKeys: EDITOR_LISTING_COLUMN_KEYS, + filters: new Map(), +}; diff --git a/src/shared/day-names.ts b/src/shared/day-names.ts index ca522ae7a1..549add9916 100644 --- a/src/shared/day-names.ts +++ b/src/shared/day-names.ts @@ -15,5 +15,7 @@ export const DAY_NAMES = [ "Saturday", ] as const; +const [sunday, ...mondayFirst] = DAY_NAMES; + /** Valid day names for bookable_days (Monday-first for display) */ -export const VALID_DAY_NAMES = [...DAY_NAMES.slice(1), DAY_NAMES[0]!]; +export const VALID_DAY_NAMES = [...mondayFirst, sunday] as const; diff --git a/src/shared/db/settings.ts b/src/shared/db/settings.ts index 3bce3a6591..685808bc07 100644 --- a/src/shared/db/settings.ts +++ b/src/shared/db/settings.ts @@ -34,6 +34,11 @@ import { type EnabledFeatures, parseEnabledFeatures, } from "#shared/admin-features.ts"; +import { + type AttendeeColumnLayout, + COLUMN_LAYOUTS, + type ListingColumnLayout, +} from "#shared/column-layout.ts"; import { encrypt } from "#shared/crypto/encryption.ts"; import { boolUpdate, @@ -150,6 +155,9 @@ const settingsBase = { }, // --- Apple Wallet --- appleWallet: appleWallet.createReadSettings(snap as (k: string) => string), + get attendeeColumnLayout(): AttendeeColumnLayout { + return COLUMN_LAYOUTS.attendee.parse(snap("attendee_column_order")); + }, get autoPurgeOrphans(): boolean { return snap("auto_purge_orphans"); }, @@ -231,6 +239,9 @@ const settingsBase = { // --- Google Wallet --- googleWallet: googleWallet.createReadSettings(snap as (k: string) => string), invalidateCache, + get listingColumnLayout(): ListingColumnLayout { + return COLUMN_LAYOUTS.listing.parse(snap("listing_column_order")); + }, get listingDefaults(): ListingDefaults { return parseListingDefaults(snap(CONFIG_KEYS.LISTING_DEFAULTS)); }, diff --git a/src/shared/form-data.ts b/src/shared/form-data.ts index df77df726b..4d711ed1ff 100644 --- a/src/shared/form-data.ts +++ b/src/shared/form-data.ts @@ -2,6 +2,7 @@ * Utilities for reading values from form data (URLSearchParams). */ +import type { Result } from "#shared/result.ts"; import { parseNonNegativeInt, parsePositiveIntId, @@ -24,8 +25,7 @@ export class FormParams extends URLSearchParams { /** A single field parsed as a strict non-negative integer, or null when blank/invalid. */ getOptionalInt(key: string): number | null { - const raw = this.getString(key); - return raw === "" ? null : parseNonNegativeInt(raw); + return parseNonNegativeInt(this.getString(key)); } /** All repeated values parsed as strict positive decimal ids, dropping invalid values. */ @@ -34,4 +34,26 @@ export class FormParams extends URLSearchParams { .map(parsePositiveIntId) .filter((n) => n !== null); } + + /** Validate a repeated field and return selected values in declared order. */ + getRepeatedPicklist( + key: string, + allowed: readonly T[], + ): Result { + const supplied = this.getAll(key); + const invalid = supplied.find( + (value) => !allowed.some((option) => option === value), + ); + if (invalid !== undefined) return { error: invalid, ok: false }; + const selected = new Set(supplied); + return { ok: true, value: allowed.filter((value) => selected.has(value)) }; + } + + /** Values for re-rendering a rejected form. Repeated controls use the comma + * format consumed by checkbox-group fields instead of losing all but one. */ + toRenderValues(): Record { + return Object.fromEntries( + [...new Set(this.keys())].map((key) => [key, this.getAll(key).join(",")]), + ); + } } diff --git a/src/shared/forms/definition.ts b/src/shared/forms/definition.ts index 369e2dab8b..d8599e4454 100644 --- a/src/shared/forms/definition.ts +++ b/src/shared/forms/definition.ts @@ -1,3 +1,4 @@ +import { reduce } from "#fp"; import type { FormParams } from "#shared/form-data.ts"; import { type Field, @@ -6,7 +7,6 @@ import { } from "#shared/forms/field.ts"; import { renderField, renderFields } from "#shared/forms/rendering.tsx"; import { - type FieldValueNormalizer, type ValidationResult, validateForm, } from "#shared/forms/validation.ts"; @@ -55,10 +55,6 @@ export type FormValues = ? FormValuesFor : never; -type FormFieldRenderHelper = { - render: (value?: string) => string; -}; - type FormSectionId = TFields[number] extends infer TField ? TField extends { section: infer TSection extends string } @@ -78,8 +74,7 @@ export type FormDefinition< id: string; fields: TFields; render: (values?: FormRenderValuesFor) => string; - renderFields: (values?: FormRenderValuesFor) => string; - field: (name: TFields[number]["name"]) => FormFieldRenderHelper; + renderField: (name: TFields[number]["name"], value?: string) => string; section: ( id: FormSectionId, values?: FormRenderValuesFor, @@ -91,11 +86,6 @@ export type FormDefinition< ) => ValidationResult>; }; -const normalizeSelectValue: FieldValueNormalizer = ( - field: Field, - value: string | number | null, -) => (field.type === "select" && value === "" ? null : value); - /** Define a typed form schema that can render and validate from one source. */ export const defineForm = < TFields extends FormFieldDefinitions, @@ -108,15 +98,16 @@ export const defineForm = < context: TContext, ) => string | null; }): FormDefinition => { - const fields = config.fields.map((field) => { + const fields = config.fields; + const fieldMap = reduce((map: Map, field: Field) => { if (field.type === "select") { requireChoiceOptions(field.label, field.options); } else if (field.type === "checkbox-group") { requireCheckboxOptions(field.label, field.options); } - return field; - }); - const fieldMap = new Map(fields.map((field) => [field.name, field] as const)); + map.set(field.name, field); + return map; + }, new Map())([...fields]); const sectionIds = [ ...new Set( fields.flatMap((field) => @@ -135,11 +126,7 @@ export const defineForm = < form: FormParams, context?: TContext, ): ValidationResult> => { - const base = validateForm>( - form, - fields, - normalizeSelectValue, - ); + const base = validateForm>(form, fields); if (!base.valid) return base; const values = base.values; @@ -165,13 +152,10 @@ export const defineForm = < }; return { - field: (name) => ({ - render: (value = "") => renderField(fieldByName(name), value), - }), fields: config.fields, id: config.id, render, - renderFields: render, + renderField: (name, value = "") => renderField(fieldByName(name), value), section, sections: sectionIds, validate, diff --git a/src/shared/forms/saved-data.ts b/src/shared/forms/saved-data.ts index ae34e08810..96cb016860 100644 --- a/src/shared/forms/saved-data.ts +++ b/src/shared/forms/saved-data.ts @@ -33,5 +33,6 @@ export const savedFormValue = (name: string): string => export const getSavedFieldValue = (field: Field): string => { const form = savedFormScope.current().form; if (!form || SENSITIVE_FIELD_TYPES.has(field.type)) return ""; + if (field.type === "checkbox-group") return form.getAll(field.name).join(","); return readSubmittedFieldValue(form, field) ?? ""; }; diff --git a/src/shared/forms/submitted-value.ts b/src/shared/forms/submitted-value.ts index 2ecba8255a..d84c2e4dc9 100644 --- a/src/shared/forms/submitted-value.ts +++ b/src/shared/forms/submitted-value.ts @@ -13,21 +13,11 @@ const getDatetimeValue = (form: FormParams, name: string): string | null => { return null; }; -const parseCheckboxGroup = (form: FormParams, name: string): string => - form - .getAll(name) - .map((value) => value.trim()) - .filter((value) => value) - .join(","); - /** Read one field from submitted form data using the field's input shape. */ export const readSubmittedFieldValue = ( form: FormParams, field: Field, ): string | null => { - if (field.type === "checkbox-group") { - return parseCheckboxGroup(form, field.name); - } if (field.type === "datetime") { return getDatetimeValue(form, field.name); } diff --git a/src/shared/forms/validation.ts b/src/shared/forms/validation.ts index 196a70fd6d..8e3252b2cf 100644 --- a/src/shared/forms/validation.ts +++ b/src/shared/forms/validation.ts @@ -1,4 +1,3 @@ -import * as v from "valibot"; import { t } from "#i18n"; import type { FormParams } from "#shared/form-data.ts"; import type { ChoiceField, Field } from "#shared/forms/field.ts"; @@ -8,11 +7,6 @@ import { } from "#shared/forms/submitted-value.ts"; import type { FieldValues } from "#shared/forms/values.ts"; -export type FieldValueNormalizer = ( - field: Field, - value: string | number | null, -) => string | number | null; - export type ValidationResult = | { valid: true; values: T } | { valid: false; error: string }; @@ -27,36 +21,32 @@ const parseFieldValue = ( ): string | number | null => field.parse ? field.parse(trimmed) - : field.type === "number" - ? trimmed - ? Number(trimmed) - : null - : trimmed; - -const choiceSchema = ( - field: ChoiceField<"select" | "checkbox-group">, -): v.PicklistSchema => { - const [first, ...rest] = field.options; - return v.picklist([first.value, ...rest.map((option) => option.value)]); -}; + : field.type === "select" && !trimmed + ? null + : field.type === "number" + ? trimmed + ? Number(trimmed) + : null + : trimmed; const hasInvalidChoice = ( - field: ChoiceField<"select" | "checkbox-group">, + field: ChoiceField<"select">, value: string, -): boolean => { - const values = - field.type === "checkbox-group" - ? value.split(",").map((choice) => choice.trim()) - : [value]; - const schema = choiceSchema(field); - return values.some((choice) => !v.safeParse(schema, choice).success); -}; +): boolean => !field.options.some((option) => option.value === value); const requiredFieldError = (field: Field): FieldValidationResult => ({ error: field.requiredMessage ?? `${field.label} is required`, valid: false, }); +const invalidFieldMessage = (field: Field): string => + field.invalidMessage ?? t("error.field_invalid", { label: field.label }); + +const invalidFieldError = (field: Field): FieldValidationResult => ({ + error: invalidFieldMessage(field), + valid: false, +}); + const isUnusableParsedValue = (value: string | number | null): boolean => value === null || (typeof value === "number" && !Number.isFinite(value)); @@ -64,6 +54,17 @@ const collectFieldValue = ( form: FormParams, field: Field, ): string | FieldValidationResult => { + if (field.type === "checkbox-group") { + const selection = form.getRepeatedPicklist( + field.name, + field.options.map((option) => option.value), + ); + if (!selection.ok) { + const error = field.validate?.(selection.error); + return error ? { error, valid: false } : invalidFieldError(field); + } + return selection.value.join(","); + } const raw = readSubmittedFieldValue(form, field); if (raw === null) return { error: DATETIME_PARTIAL_ERROR, valid: false }; return raw; @@ -74,14 +75,8 @@ const validateFieldText = (field: Field, value: string): string | null => { const error = field.validate(value); if (error) return error; } - if ( - value && - (field.type === "select" || field.type === "checkbox-group") && - hasInvalidChoice(field, value) - ) { - return ( - field.invalidMessage ?? t("error.field_invalid", { label: field.label }) - ); + if (value && field.type === "select" && hasInvalidChoice(field, value)) { + return invalidFieldMessage(field); } if ( "maxlength" in field && @@ -107,16 +102,11 @@ const validateSingleField = ( if (field.required && !trimmed) return requiredFieldError(field); const textError = validateFieldText(field, trimmed); - if (textError) return { error: textError, valid: false }; + if (textError !== null) return { error: textError, valid: false }; const value = parseFieldValue(field, trimmed); if (trimmed && isUnusableParsedValue(value)) { - return { - error: - field.invalidMessage ?? - t("error.field_invalid", { label: field.label }), - valid: false, - }; + return invalidFieldError(field); } return { valid: true, value }; }; @@ -124,13 +114,12 @@ const validateSingleField = ( export const validateForm = ( form: FormParams, fields: readonly Field[], - normalizeValue: FieldValueNormalizer = (_field, value) => value, ): ValidationResult => { const values: FieldValues = {}; for (const field of fields) { const result = validateSingleField(form, field); if (!result.valid) return result; - values[field.name] = normalizeValue(field, result.value); + values[field.name] = result.value; } return { valid: true, values: values as T }; }; diff --git a/src/ui/templates/admin/dashboard.tsx b/src/ui/templates/admin/dashboard.tsx index 25540521ba..f85cbe7012 100644 --- a/src/ui/templates/admin/dashboard.tsx +++ b/src/ui/templates/admin/dashboard.tsx @@ -5,11 +5,13 @@ import { filter, joinStrings, map, pipe, unique } from "#fp"; import { t } from "#i18n"; import { groupAttendeeRows } from "#shared/attendee-table-rows.ts"; -import { resolveColumnLayout } from "#shared/column-order.ts"; import { - EDITOR_LISTING_DEFAULT_ORDER, + COLUMN_LAYOUTS, + type ListingColumnLayout, +} from "#shared/column-layout.ts"; +import { + EDITOR_LISTING_LAYOUT, EDITOR_LISTING_TABLE_COLUMNS, - LISTING_DEFAULT_ORDER, LISTING_TABLE_COLUMNS, } from "#shared/columns/listing-columns.ts"; import { getEffectiveDomain } from "#shared/config.ts"; @@ -223,18 +225,15 @@ export const adminDashboardPage = ( newestAttendees: DisplayAttendee[] = [], successMessage?: string, stats?: ActiveListingStats | null, - listingColumnTemplate?: string, + listingColumnLayout?: ListingColumnLayout, activeType: ListingFilter = "all", upcomingHolidays: Holiday[] = [], unbookableIds: ReadonlySet = new Set(), upcomingServicingEvents: ServicingEventSummary[] = [], attributeFilterView: ListingAttributeFilterView = emptyAttributeFilterView(), ): string => { - const { columnKeys, filters } = resolveColumnLayout( - listingColumnTemplate ?? "", - Object.keys(LISTING_TABLE_COLUMNS), - LISTING_DEFAULT_ORDER, - ); + const { columnKeys, filters } = + listingColumnLayout ?? COLUMN_LAYOUTS.listing.defaultLayout; // Type filter narrows the listing table only; the stats, multi-booking, and // newest-attendee sections below stay based on the full set. Offer the bar @@ -312,7 +311,7 @@ export const adminDashboardPage = ( export const adminListingsPage = ( listings: ListingWithCount[], session: AdminSession, - listingColumnTemplate?: string, + listingColumnLayout?: ListingColumnLayout, attributeFilterView: ListingAttributeFilterView = emptyAttributeFilterView(), ): string => { // Editors see a money-free, edit-linked table on a fixed order (their saved @@ -322,11 +321,9 @@ export const adminListingsPage = ( const columns = isEditor ? EDITOR_LISTING_TABLE_COLUMNS : LISTING_TABLE_COLUMNS; - const { columnKeys, filters } = resolveColumnLayout( - isEditor ? "" : (listingColumnTemplate ?? ""), - Object.keys(columns), - isEditor ? EDITOR_LISTING_DEFAULT_ORDER : LISTING_DEFAULT_ORDER, - ); + const { columnKeys, filters } = isEditor + ? EDITOR_LISTING_LAYOUT + : (listingColumnLayout ?? COLUMN_LAYOUTS.listing.defaultLayout); const activeListings = activeOnly(listings); const deactivatedListings = filter((e: ListingWithCount) => !e.active)( listings, diff --git a/src/ui/templates/admin/groups/overview.tsx b/src/ui/templates/admin/groups/overview.tsx index 3e62fdc5e3..32b1705986 100644 --- a/src/ui/templates/admin/groups/overview.tsx +++ b/src/ui/templates/admin/groups/overview.tsx @@ -1,11 +1,6 @@ import { sumOf } from "#fp"; import { t } from "#i18n"; import type { ListingMoneyTotals } from "#shared/accounting/listing-money-totals.ts"; -import { resolveColumnLayout } from "#shared/column-order.ts"; -import { - LISTING_DEFAULT_ORDER, - LISTING_TABLE_COLUMNS, -} from "#shared/columns/listing-columns.ts"; import { settings } from "#shared/db/settings.ts"; import { buildEmbedSnippets } from "#shared/embed.ts"; import { isReadOnly } from "#shared/env.ts"; @@ -183,11 +178,7 @@ export const GroupOverviewPanel = ({ shareable: boolean; questionData?: TableQuestionData; }): JSX.Element => { - const { columnKeys, filters } = resolveColumnLayout( - settings.listingColumnOrder, - Object.keys(LISTING_TABLE_COLUMNS), - LISTING_DEFAULT_ORDER, - ); + const { columnKeys, filters } = settings.listingColumnLayout; const listingRows = renderListingRows({ columnKeys, emptyText: t("groups.detail.no_listings"), diff --git a/src/ui/templates/admin/guide/operations.tsx b/src/ui/templates/admin/guide/operations.tsx index 32c1dbe0c5..19f3c0dfe3 100644 --- a/src/ui/templates/admin/guide/operations.tsx +++ b/src/ui/templates/admin/guide/operations.tsx @@ -2,15 +2,9 @@ * Admin guide — Operations sections. */ -import { buildDefaultTemplate } from "#shared/column-order.ts"; -import { - ATTENDEE_DEFAULT_ORDER, - ATTENDEE_TABLE_COLUMNS, -} from "#shared/columns/attendee-columns.ts"; -import { - LISTING_DEFAULT_ORDER, - LISTING_TABLE_COLUMNS, -} from "#shared/columns/listing-columns.ts"; +import { COLUMN_LAYOUTS } from "#shared/column-layout.ts"; +import { ATTENDEE_TABLE_COLUMNS } from "#shared/columns/attendee-columns.ts"; +import { LISTING_TABLE_COLUMNS } from "#shared/columns/listing-columns.ts"; import { Raw } from "#shared/jsx/jsx-runtime.ts"; import { columnReferenceTable, @@ -20,9 +14,9 @@ import { } from "#templates/admin/guide/components.tsx"; /** The "Default order: ``" line a table-columns FAQ answer opens with. */ -const defaultOrderParagraph = (order: readonly string[]): JSX.Element => ( +const defaultOrderParagraph = (template: string): JSX.Element => (

- Default order: {buildDefaultTemplate(order)} + Default order: {template}

); @@ -139,14 +133,14 @@ export const operationsSections = (): GuideSection[] => [ custom( "listing_table_columns", <> - {defaultOrderParagraph(LISTING_DEFAULT_ORDER)} + {defaultOrderParagraph(COLUMN_LAYOUTS.listing.defaultTemplate)} , ), custom( "attendee_table_columns", <> - {defaultOrderParagraph(ATTENDEE_DEFAULT_ORDER)} + {defaultOrderParagraph(COLUMN_LAYOUTS.attendee.defaultTemplate)}

Columns referencing absent data (e.g. {"{{email}}"}{" "} when no attendees have an email) are hidden automatically even when diff --git a/src/ui/templates/admin/ledger/entry-pages.tsx b/src/ui/templates/admin/ledger/entry-pages.tsx index 369b221820..0cffd6b441 100644 --- a/src/ui/templates/admin/ledger/entry-pages.tsx +++ b/src/ui/templates/admin/ledger/entry-pages.tsx @@ -103,7 +103,7 @@ export const adminLedgerEntryAddPage = ({ action={`/admin/ledger/${account.type}/${account.id}/add`} afterFields={} buttonText={t("admin.ledger.add.submit")} - fieldsHtml={defineLedgerEntryAddForm(options).renderFields(values)} + fieldsHtml={defineLedgerEntryAddForm(options).render(values)} icon="plus" returnUrl={returnUrl} > @@ -135,7 +135,7 @@ export const adminLedgerEntryEditPage = ({ diff --git a/src/ui/templates/admin/listing-table.tsx b/src/ui/templates/admin/listing-table.tsx index 7cf6b3952e..b52f0bd8d0 100644 --- a/src/ui/templates/admin/listing-table.tsx +++ b/src/ui/templates/admin/listing-table.tsx @@ -23,8 +23,8 @@ import { escapeHtml } from "#templates/layout.tsx"; /** The ordered column layout a listings table (or single row) renders from. */ type ListingColumnArgs = { - columnKeys: string[]; - filters: Map; + columnKeys: readonly string[]; + filters: ReadonlyMap; columns?: ColumnGenerators; }; @@ -51,7 +51,7 @@ export const ListingRow = ({ /** The subset of `columnKeys` that the given column set actually defines. */ export const validListingColumnKeys = ( - columnKeys: string[], + columnKeys: readonly string[], columns: ColumnGenerators, ): string[] => columnKeys.filter((key) => columns[key]); @@ -82,7 +82,7 @@ export const renderListingRows = ({ /** Render the listing table with dynamic column keys. `columns` defaults to the * staff column set; the editor variant passes its money-free set. */ export const renderListingTable = ( - columnKeys: string[], + columnKeys: readonly string[], rows: string, columns: ColumnGenerators = LISTING_TABLE_COLUMNS, ): string => { @@ -95,8 +95,8 @@ export const renderListingTable = ( export const renderListingsTableSection = ( listings: ListingWithCount[], - columnKeys: string[], - filters: Map, + columnKeys: readonly string[], + filters: ReadonlyMap, columns: ColumnGenerators = LISTING_TABLE_COLUMNS, ): string => { const listingRows = renderListingRows({ diff --git a/src/ui/templates/admin/news.tsx b/src/ui/templates/admin/news.tsx index bfbe6bb7a1..99c8af0ef7 100644 --- a/src/ui/templates/admin/news.tsx +++ b/src/ui/templates/admin/news.tsx @@ -73,7 +73,7 @@ export const adminNewsNewPage = ( active: ACTIVE, children: ( <> - + {t("news.create_submit")} ), @@ -88,7 +88,7 @@ export const adminNewsNewPage = ( export const newsEditPanel = (post: NewsPost): JSX.Element => contentEditPanel( `${LIST}/${post.id}/edit`, - newsPostEditForm.renderFields(newsPostToValues(post)), + newsPostEditForm.render(newsPostToValues(post)), ); export const adminNewsDeletePage = ( diff --git a/src/ui/templates/admin/questions.tsx b/src/ui/templates/admin/questions.tsx index 044c78c3ed..00cf7448de 100644 --- a/src/ui/templates/admin/questions.tsx +++ b/src/ui/templates/admin/questions.tsx @@ -222,7 +222,7 @@ export const adminQuestionPage = ( action={`/admin/questions/${question.id}/edit`} submitLabel={t("questions.edit.update")} > - + {question.display_type === "free_text" ? ( // Free-text questions can't become choice questions (it would orphan // any stored text answers), so lock the type rather than offering it. diff --git a/src/ui/templates/admin/settings/column-order.tsx b/src/ui/templates/admin/settings/column-order.tsx index 4427e4f92e..eda8c9419f 100644 --- a/src/ui/templates/admin/settings/column-order.tsx +++ b/src/ui/templates/admin/settings/column-order.tsx @@ -8,23 +8,17 @@ /* jscpd:ignore-start */ import { t } from "#i18n"; -import { buildDefaultTemplate } from "#shared/column-order.ts"; -import { - ATTENDEE_DEFAULT_ORDER, - ATTENDEE_TABLE_COLUMNS, -} from "#shared/columns/attendee-columns.ts"; -import { - LISTING_DEFAULT_ORDER, - LISTING_TABLE_COLUMNS, -} from "#shared/columns/listing-columns.ts"; +import { COLUMN_LAYOUTS } from "#shared/column-layout.ts"; +import { ATTENDEE_TABLE_COLUMNS } from "#shared/columns/attendee-columns.ts"; +import { LISTING_TABLE_COLUMNS } from "#shared/columns/listing-columns.ts"; import { Raw } from "#shared/jsx/jsx-runtime.ts"; import type { AdvancedSettingsPageState } from "#templates/admin/settings-advanced.tsx"; import { textSettingsSection } from "#templates/components/settings-field-section.tsx"; /* jscpd:ignore-end */ -const listingDefault = buildDefaultTemplate(LISTING_DEFAULT_ORDER); -const attendeeDefault = buildDefaultTemplate(ATTENDEE_DEFAULT_ORDER); +const listingDefault = COLUMN_LAYOUTS.listing.defaultTemplate; +const attendeeDefault = COLUMN_LAYOUTS.attendee.defaultTemplate; /** Render available column tags as helper text */ const AvailableTags = ({ diff --git a/src/ui/templates/admin/site-pages.tsx b/src/ui/templates/admin/site-pages.tsx index 239e354045..dc9de3b6cf 100644 --- a/src/ui/templates/admin/site-pages.tsx +++ b/src/ui/templates/admin/site-pages.tsx @@ -177,7 +177,7 @@ export const adminSitePageNewPage = ( t("site.pages.new_title"), LIST, session, - sitePageForm.renderFields(), + sitePageForm.render(), error, {t("site.pages.create_submit")}, ); @@ -220,7 +220,7 @@ const ItemPicker = ({ export const sitePageEditPanel = (page: SitePage): JSX.Element => contentEditPanel( `${LIST}/${page.id}/edit`, - sitePageEditForm.renderFields(contentFieldValues(page)), + sitePageEditForm.render(contentFieldValues(page)), ); /** The Items tab's panel: the page's current contents (reorderable, each diff --git a/src/ui/templates/attendee-table.tsx b/src/ui/templates/attendee-table.tsx index bb8050ecfe..95727d6963 100644 --- a/src/ui/templates/attendee-table.tsx +++ b/src/ui/templates/attendee-table.tsx @@ -14,15 +14,12 @@ import { joinStrings, map, pipe, sort } from "#fp"; import { t } from "#i18n"; -import { - getHeaderText, - renderCells, - resolveColumnLayout, -} from "#shared/column-order.ts"; -import { - ATTENDEE_DEFAULT_ORDER, - ATTENDEE_TABLE_COLUMNS, -} from "#shared/columns/attendee-columns.ts"; +import type { + AttendeeColumn, + AttendeeColumnLayout, +} from "#shared/column-layout.ts"; +import { getHeaderText, renderCells } from "#shared/column-order.ts"; +import { ATTENDEE_TABLE_COLUMNS } from "#shared/columns/attendee-columns.ts"; import { isServicing } from "#shared/db/attendees/kind.ts"; import type { QuestionWithAnswers } from "#shared/db/question-types.ts"; import type { AttendeeQuestionData } from "#shared/db/questions/attendee-answers/reads.ts"; @@ -75,8 +72,8 @@ export type AttendeeTableOptions = { presorted?: boolean; /** Question data for the Answers column */ questionData?: TableQuestionData | undefined; - /** Liquid template controlling column order (e.g. "{{name}}, {{email}}, {{qty}}") */ - columnTemplate?: string; + /** Pre-parsed layout controlling column order and filters */ + columnLayout?: AttendeeColumnLayout; }; // --------------------------------------------------------------------------- @@ -87,7 +84,7 @@ export type AttendeeTableOptions = { const computeVisibilityMap = ( rows: AttendeeTableRow[], opts: AttendeeTableOptions, -): Record => { +): Record => { const showCheckin = opts.showCheckin !== false; return { address: rows.some((r) => !!r.attendee.address), @@ -111,15 +108,13 @@ const computeVisibilityMap = ( /** Get the ordered list of visible column keys and their filter expressions */ const getColumnLayout = ( - visMap: Record, - columnTemplate?: string, -): { visibleColumns: string[]; filters: Map } => { - const template = columnTemplate || settings.attendeeColumnOrder; - const { columnKeys, filters } = resolveColumnLayout( - template, - Object.keys(ATTENDEE_TABLE_COLUMNS), - ATTENDEE_DEFAULT_ORDER, - ); + visMap: Record, + columnLayout?: AttendeeColumnLayout, +): { + visibleColumns: AttendeeColumn[]; + filters: ReadonlyMap; +} => { + const { columnKeys, filters } = columnLayout ?? settings.attendeeColumnLayout; return { filters, visibleColumns: columnKeys.filter((k) => visMap[k]), @@ -259,9 +254,9 @@ const createStatusRenderer = /** Render a single attendee row using ordered column defs */ const AttendeeRow = ( row: AttendeeTableRow, - visibleColumns: string[], + visibleColumns: AttendeeColumn[], colOpts: AttendeeColumnOpts, - filters: Map, + filters: ReadonlyMap, ): string => ` { const visMap = computeVisibilityMap(orderedRows, opts); const { visibleColumns, filters } = getColumnLayout( visMap, - opts.columnTemplate, + opts.columnLayout, ); const colCount = visibleColumns.length; @@ -319,8 +314,8 @@ export const AttendeeTable = (opts: AttendeeTableOptions): string => { }`; const headers = pipe( - map((key: string) => { - const col = ATTENDEE_TABLE_COLUMNS[key]!; + map((key: AttendeeColumn) => { + const col = ATTENDEE_TABLE_COLUMNS[key]; const cls = col.headerClassName; return `${getHeaderText(col)}`; }), diff --git a/test/features/admin/aggregate-recalculation.test.ts b/test/features/admin/aggregate-recalculation.test.ts new file mode 100644 index 0000000000..156ea090e2 --- /dev/null +++ b/test/features/admin/aggregate-recalculation.test.ts @@ -0,0 +1,153 @@ +import { expect } from "@std/expect"; +import { describe, it as test } from "@std/testing/bdd"; +import { + createRecalculatePageRenderer, + parseEditableAggregateForm, + runRecalculatePost, + selectedRecalculationFields, +} from "#routes/admin/aggregate-recalculation.ts"; +import { parseFlashValue } from "#shared/cookies.ts"; +import { FormParams } from "#shared/form-data.ts"; +import type { Field } from "#shared/forms/field.ts"; +import { runWithRequestId } from "#shared/logger.ts"; + +const FIELDS = ["income", "tickets"] as const; + +describe("selectedRecalculationFields", () => { + test("returns selected fields in their declared order", () => { + expect( + selectedRecalculationFields( + new FormParams("recalculate_fields=tickets&recalculate_fields=income"), + FIELDS, + ), + ).toEqual(["income", "tickets"]); + }); + + test("returns no fields when none were submitted", () => { + expect(selectedRecalculationFields(new FormParams(), FIELDS)).toEqual([]); + }); + + test("rejects the first unknown field", () => { + expect(() => + selectedRecalculationFields( + new FormParams("recalculate_fields=income&recalculate_fields=bogus"), + FIELDS, + ), + ).toThrow("Invalid recalculation field: bogus"); + }); +}); + +const editableFields: Field[] = [{ label: "Name", name: "name", type: "text" }]; + +describe("parseEditableAggregateForm", () => { + test("skips an aggregate whose fields were not submitted", () => { + expect( + parseEditableAggregateForm( + new FormParams({ other: "value" }), + editableFields, + (values) => values, + ), + ).toEqual({ input: null, ok: true }); + }); + + test("parses an aggregate when one of its fields was submitted", () => { + expect( + parseEditableAggregateForm<{ name: string }, string>( + new FormParams({ name: "New name" }), + editableFields, + (values) => values.name, + ), + ).toEqual({ input: "New name", ok: true }); + }); +}); + +describe("runRecalculatePost", () => { + test("renders the choice error without changing aggregates", async () => { + let resetCount = 0; + let logCount = 0; + const response = await runRecalculatePost({ + fields: FIELDS, + form: new FormParams(), + log: () => { + logCount += 1; + return Promise.resolve(); + }, + renderChoose: () => new Response("Choose a field", { status: 400 }), + reset: () => { + resetCount += 1; + return Promise.resolve(); + }, + successMessage: "Recalculated.", + successPath: "/admin/listings/1/edit", + }); + + expect(response.status).toBe(400); + expect(await response.text()).toBe("Choose a field"); + expect(resetCount).toBe(0); + expect(logCount).toBe(0); + }); + + test("resets selected aggregates, logs, and redirects", async () => { + const calls: string[] = []; + const response = await runWithRequestId(() => + runRecalculatePost({ + fields: FIELDS, + form: new FormParams("recalculate_fields=tickets"), + log: () => { + calls.push("log"); + return Promise.resolve(); + }, + renderChoose: () => new Response("wrong branch", { status: 400 }), + reset: (selected) => { + calls.push(`reset:${selected.join(",")}`); + return Promise.resolve(); + }, + successMessage: "Recalculated.", + successPath: "/admin/listings/1/edit", + }), + ); + + expect(calls).toEqual(["reset:tickets", "log"]); + expect(response.status).toBe(302); + expect(response.headers.get("location")).toMatch( + /^\/admin\/listings\/1\/edit\?flash=[a-f0-9]+$/, + ); + const cookieValue = response.headers + .get("set-cookie") + ?.split("=")[1] + ?.split(";")[0]; + if (cookieValue === undefined) throw new Error("Missing flash cookie"); + expect(parseFlashValue(cookieValue)).toEqual({ + error: undefined, + formToken: undefined, + info: undefined, + result: undefined, + success: "Recalculated.", + }); + }); +}); + +describe("createRecalculatePageRenderer", () => { + test("renders the snapshot and success response", async () => { + const render = createRecalculatePageRenderer( + (entity: { id: number }) => Promise.resolve(`snapshot-${entity.id}`), + (entity, snapshot, session: string, error, success) => + [entity.id, snapshot, session, error, success].join("|"), + ); + const response = await render({ id: 3 }, "owner", undefined, "Saved."); + + expect(response.status).toBe(200); + expect(await response.text()).toBe("3|snapshot-3|owner||Saved."); + }); + + test("uses status 400 when rendering an error", async () => { + const render = createRecalculatePageRenderer( + () => Promise.resolve("snapshot"), + (_entity: string, _snapshot, _session: string, error) => error ?? "", + ); + const response = await render("entity", "owner", "Choose a field"); + + expect(response.status).toBe(400); + expect(await response.text()).toBe("Choose a field"); + }); +}); diff --git a/test/features/admin/dashboard.test.ts b/test/features/admin/dashboard.test.ts new file mode 100644 index 0000000000..9a3f05623e --- /dev/null +++ b/test/features/admin/dashboard.test.ts @@ -0,0 +1,79 @@ +import { expect } from "@std/expect"; +import { describe, it as test } from "@std/testing/bdd"; +import { loginResponse } from "#routes/admin/dashboard.ts"; +import { describeWithEnv } from "#test-utils/db.ts"; +import { createTestAttendee } from "#test-utils/db-helpers/attendees.ts"; +import { awaitTestRequest } from "#test-utils/mocks.ts"; +import { + createTestAgentSession, + createTestEditorSession, + getTestSession, + setupListingAndLogin, +} from "#test-utils/session.ts"; +import { withSetting } from "#test-utils/settings.ts"; + +describeWithEnv("admin listings route", { db: true }, () => { + test("editor listings ignore an invalid owner column layout", async () => { + const { cookie } = await createTestEditorSession(); + const response = await withSetting( + { listing_column_order: "{{unknown}}" }, + () => awaitTestRequest("/admin/listings", { cookie }), + ); + expect(response.status).toBe(200); + expect(await response.text()).toContain("Listings"); + }); + + test("owner listings use the saved column layout", async () => { + const { cookie } = await getTestSession(); + const html = await withSetting( + { listing_column_order: "{{name}}" }, + async () => + (await awaitTestRequest("/admin/listings", { cookie })).text(), + ); + expect(html).toContain("Listing Name"); + expect(html).not.toContain("Status"); + }); + + test("dashboard redirects non-dashboard roles to their own landing pages", async () => { + const { cookie: agentCookie } = await createTestAgentSession(); + const { cookie: editorCookie } = await createTestEditorSession(); + expect( + (await awaitTestRequest("/admin/", { cookie: agentCookie })).headers.get( + "location", + ), + ).toBe("/admin/deliveries"); + expect( + (await awaitTestRequest("/admin/", { cookie: editorCookie })).headers.get( + "location", + ), + ).toBe("/admin/listings"); + }); + + test("dashboard shows only the ten newest attendees", async () => { + const { cookie, listing } = await setupListingAndLogin(); + for (let index = 0; index < 11; index++) { + await createTestAttendee( + listing.id, + listing.slug, + `Guest ${index}`, + `guest-${index}@example.com`, + ); + } + const html = await (await awaitTestRequest("/admin/", { cookie })).text(); + expect(html.match(/Guest \d+/g)).toHaveLength(10); + }); +}); + +describe("loginResponse", () => { + test("uses status 200 by default", async () => { + expect( + (await loginResponse(new Request("http://localhost/admin/"))).status, + ).toBe(200); + }); + + test("uses the supplied status", async () => { + expect( + (await loginResponse(new Request("http://localhost/admin/"), 418)).status, + ).toBe(418); + }); +}); diff --git a/test/lib/server-listings-csv.test.ts b/test/features/admin/dashboard/listings-csv.test.ts similarity index 87% rename from test/lib/server-listings-csv.test.ts rename to test/features/admin/dashboard/listings-csv.test.ts index aa14432993..f057c078bc 100644 --- a/test/lib/server-listings-csv.test.ts +++ b/test/features/admin/dashboard/listings-csv.test.ts @@ -1,5 +1,6 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { wasActivityLogged } from "#test-utils/activity-log.ts"; import { testRequiresAuth } from "#test-utils/assertions.ts"; import { describeWithEnv } from "#test-utils/db.ts"; import { createTestListing } from "#test-utils/db-helpers/listings.ts"; @@ -26,6 +27,7 @@ describeWithEnv("server (admin listings CSV)", { db: true }, () => { const csv = await response.text(); expect(csv.split("\n")[0]).toContain("Name,Status,Type"); expect(csv).toContain("Gala Night"); + expect(await wasActivityLogged("Listings CSV exported")).toBe(true); }); test("filters the export to one type and names the file by type", async () => { @@ -38,6 +40,9 @@ describeWithEnv("server (admin listings CSV)", { db: true }, () => { const csv = await response.text(); expect(csv).toContain("Daily One"); expect(csv).not.toContain("Standard One"); + expect( + await wasActivityLogged("Listings CSV exported (type: daily)"), + ).toBe(true); }); }); }); diff --git a/test/features/admin/dashboard/log.test.ts b/test/features/admin/dashboard/log.test.ts new file mode 100644 index 0000000000..c5439aec1c --- /dev/null +++ b/test/features/admin/dashboard/log.test.ts @@ -0,0 +1,74 @@ +import { expect } from "@std/expect"; +import { it as test } from "@std/testing/bdd"; +import { logActivity } from "#test-utils/activity-log.ts"; +import { + assertAdminHtmlWithCookie, + expectHtmlResponse, + testRequiresAuth, +} from "#test-utils/assertions.ts"; +import { describeWithEnv } from "#test-utils/db.ts"; +import { createTestAttendee } from "#test-utils/db-helpers/attendees.ts"; +import { createTestListing } from "#test-utils/db-helpers/listings.ts"; +import { awaitTestRequest } from "#test-utils/mocks.ts"; +import { + adminGet, + createTestManagerSession, + setupListingAndLogin, +} from "#test-utils/session.ts"; + +describeWithEnv("admin activity log", { db: true }, () => { + testRequiresAuth("/admin/log"); + + test("shows log page when authenticated", async () => { + await createTestListing({ maxAttendees: 50, name: "Log Test" }); + await expectHtmlResponse(await adminGet("/admin/log"), 200, "Log"); + }); + + test("shows log page for manager", async () => { + const managerCookie = await createTestManagerSession(); + await assertAdminHtmlWithCookie("/admin/log", managerCookie, "Log"); + }); + + test("shows only the most recent 200 entries", async () => { + for (let index = 0; index < 201; index++) { + await logActivity(`Action ${index}`); + } + const html = await (await adminGet("/admin/log")).text(); + expect(html).toContain("Showing the most recent 200 entries"); + expect(html).toContain("Action 200"); + expect(html).toContain("Action 1"); + expect(html).not.toContain("Action 0"); + }); + + test("does not mark exactly 200 entries as truncated", async () => { + for (let index = 0; index < 200; index++) { + await logActivity(`Exact action ${index}`); + } + const html = await (await adminGet("/admin/log")).text(); + expect(html).not.toContain("Showing the most recent 200 entries"); + }); + + test("links each entry to its attendee and listing by name", async () => { + const { listing, cookie } = await setupListingAndLogin({ + maxAttendees: 50, + name: "Gala Dinner", + }); + const attendee = await createTestAttendee( + listing.id, + listing.slug, + "Ada Lovelace", + "ada@example.com", + ); + await logActivity("Balance updated", listing.id, attendee.id); + + const html = await ( + await awaitTestRequest("/admin/log", { cookie }) + ).text(); + expect(html).toContain( + `Ada Lovelace`, + ); + expect(html).toContain( + `Gala Dinner`, + ); + }); +}); diff --git a/test/features/admin/settings-listing-defaults.test.ts b/test/features/admin/settings-listing-defaults.test.ts index 7cce6d34a5..b26c2bb603 100644 --- a/test/features/admin/settings-listing-defaults.test.ts +++ b/test/features/admin/settings-listing-defaults.test.ts @@ -1,6 +1,7 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; import { parseListingDefaultsForm } from "#routes/admin/settings-listing-defaults.ts"; +import { setDemoModeForTest } from "#shared/demo/mode.ts"; import { FormParams } from "#shared/form-data.ts"; const parse = (query: string, hasLogistics = true) => @@ -58,6 +59,22 @@ describe("admin > listing defaults form parse > urls", () => { expect(parse("default_webhook_url=ftp://example.com").error).not.toBeNull(); expect(parse("default_thank_you_url=not-a-url").error).not.toBeNull(); }); + + test("ignores the webhook default in demo mode", () => { + setDemoModeForTest(true); + try { + expect( + "webhookUrl" in + ok(parse("default_webhook_url=https://example.com/hook")), + ).toBe(false); + expect( + ok(parse("default_thank_you_url=https://example.com/thanks")) + .thankYouUrl, + ).toBe("https://example.com/thanks"); + } finally { + setDemoModeForTest(false); + } + }); }); describe("admin > listing defaults form parse > bookable days", () => { @@ -81,7 +98,17 @@ describe("admin > listing defaults form parse > bookable days", () => { "default_bookable_days_enabled=1&default_bookable_days=Funday&default_bookable_days=Monday", ).error; expect(error).toContain("Invalid day: Funday"); - expect(error).toContain("Monday"); + expect(error).toContain( + "Use: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday", + ); + }); + + test("reports the first malformed day supplied", () => { + const error = parse( + "default_bookable_days_enabled=1&default_bookable_days=Monday&default_bookable_days=Funday&default_bookable_days=Someday", + ).error; + expect(error).toContain("Invalid day: Funday"); + expect(error).not.toContain("Invalid day: Someday"); }); test("rejects enabled with no valid day chosen", () => { diff --git a/test/integration/server/listings/create-validation.test.ts b/test/integration/server/listings/create-validation.test.ts index 7c16092d93..6e3777fc76 100644 --- a/test/integration/server/listings/create-validation.test.ts +++ b/test/integration/server/listings/create-validation.test.ts @@ -56,6 +56,21 @@ describeWithEnv("server listings > create validation", { db: true }, () => { expect(await getListingWithCount(1)).toBeNull(); }); + test("keeps repeated bookable days after a rejected create", async () => { + const { response } = await adminMultipartPost("/admin/listing", { + bookable_days: ["Monday", "Wednesday"], + day_price_1: "10.005", + listing_type: "daily", + max_attendees: "50", + max_quantity: "1", + name: "Bad Day Price", + }); + expect(response.status).toBe(400); + const html = await response.text(); + expect(html).toContain('value="Monday" checked'); + expect(html).toContain('value="Wednesday" checked'); + }); + test("accepts a create with a valid day price and stores it", async () => { const { response } = await adminFormPost("/admin/listing", { day_price_1: "10.00", diff --git a/test/integration/server/settings/column-order.test.ts b/test/integration/server/settings/column-order.test.ts index 621a74f7cc..c410e981af 100644 --- a/test/integration/server/settings/column-order.test.ts +++ b/test/integration/server/settings/column-order.test.ts @@ -1,6 +1,7 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; -import { settings } from "#shared/db/settings.ts"; +import { execute } from "#shared/db/client.ts"; +import { CONFIG_KEYS, settings } from "#shared/db/settings.ts"; import { expectFlashRedirect } from "#test-utils/assertions.ts"; import { describeWithEnv } from "#test-utils/db.ts"; import { adminFormPost } from "#test-utils/session.ts"; @@ -20,6 +21,10 @@ describeWithEnv("server (admin settings: column order)", { db: true }, () => { "Listing column order updated", )(response); expect(settings.listingColumnOrder).toBe("{{name}}, {{status}}"); + expect(settings.listingColumnLayout.columnKeys).toEqual([ + "name", + "status", + ]); }); test("rejects invalid column name", async () => { @@ -44,6 +49,20 @@ describeWithEnv("server (admin settings: column order)", { db: true }, () => { "Listing column order updated", )(response); expect(settings.listingColumnOrder).toBe(""); + expect(settings.listingColumnLayout.columnKeys[0]).toBe("name"); + }); + + test("rejects a malformed template loaded from settings", async () => { + await execute( + "INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", + [CONFIG_KEYS.LISTING_COLUMN_ORDER, "{{not_a_column}}"], + ); + settings.invalidateCache(); + await settings.loadKeys([CONFIG_KEYS.LISTING_COLUMN_ORDER]); + + expect(() => settings.listingColumnLayout).toThrow( + 'Unknown column "not_a_column"', + ); }); }); @@ -63,6 +82,11 @@ describeWithEnv("server (admin settings: column order)", { db: true }, () => { expect(settings.attendeeColumnOrder).toBe( "{{name}}, {{qty}}, {{ticket}}", ); + expect(settings.attendeeColumnLayout.columnKeys).toEqual([ + "name", + "qty", + "ticket", + ]); }); test("rejects invalid column name", async () => { diff --git a/test/lib/server-settings/listing-defaults.test.ts b/test/integration/server/settings/listing-defaults.test.ts similarity index 99% rename from test/lib/server-settings/listing-defaults.test.ts rename to test/integration/server/settings/listing-defaults.test.ts index dbdd9ec1f4..0d4be262b1 100644 --- a/test/lib/server-settings/listing-defaults.test.ts +++ b/test/integration/server/settings/listing-defaults.test.ts @@ -116,6 +116,9 @@ describeWithEnv("server (admin listing defaults)", { db: true }, () => { default_webhook_url: "https://example.com/hook", }); expect(response.status).toBe(302); + expect(response.headers.get("location")).toMatch( + /^\/admin\/listing-defaults\?flash=/, + ); expectFlash(response, expect.stringContaining("Listing defaults saved")); expect(settings.listingDefaults).toEqual({ hidden: true, diff --git a/test/lib/server-editor.test.ts b/test/lib/server-editor.test.ts index cc13004eab..00a0a5865b 100644 --- a/test/lib/server-editor.test.ts +++ b/test/lib/server-editor.test.ts @@ -21,6 +21,7 @@ import { createTestSitePage, } from "#test-utils/db-helpers/misc.ts"; import { testListingInput } from "#test-utils/factories.ts"; +import type { TestFormValues } from "#test-utils/form-values.ts"; import { awaitTestRequest, mockFormRequest, @@ -51,7 +52,7 @@ const postFormAs = async ( const postMultipartAs = async ( path: string, cookie: string, - data: Record, + data: TestFormValues, ): Promise => { const csrf_token = await signCsrfToken(); return handleRequest( diff --git a/test/lib/server-images/attachment-edit.test.ts b/test/lib/server-images/attachment-edit.test.ts index e58c91a157..34ac64e90d 100644 --- a/test/lib/server-images/attachment-edit.test.ts +++ b/test/lib/server-images/attachment-edit.test.ts @@ -10,6 +10,7 @@ import { runWithStorageConfig } from "#shared/storage.ts"; import { expectFlashRedirect } from "#test-utils/assertions.ts"; import { describeWithEnv } from "#test-utils/db.ts"; import { PDF_BYTES } from "#test-utils/factories.ts"; +import type { TestFormValues } from "#test-utils/form-values.ts"; import { TEST_STORAGE_ZONE } from "#test-utils/internal.ts"; import { installUrlHandler, @@ -25,18 +26,18 @@ import { expectImageErrorRedirect } from "./helpers.ts"; const editFormData = async ( listingId: number, csrfToken: string, -): Promise> => { +): Promise => { const listing = await getListingWithCount(listingId); if (!listing) throw new Error(`Listing not found: ${listingId}`); return { - bookable_days: listing.bookable_days.join(","), + bookable_days: listing.bookable_days, closes_at_date: "", closes_at_time: "", csrf_token: csrfToken, date_date: "", date_time: "", description: listing.description, - fields: listing.fields || "email", + fields: (listing.fields || "email").split(","), listing_type: listing.listing_type, location: listing.location, max_attendees: String(listing.max_attendees), diff --git a/test/lib/server-images/create.test.ts b/test/lib/server-images/create.test.ts index dd4c5a38c3..a0ee772d50 100644 --- a/test/lib/server-images/create.test.ts +++ b/test/lib/server-images/create.test.ts @@ -6,6 +6,7 @@ import type { ListingWithCount } from "#shared/types.ts"; import { expectFlashRedirect } from "#test-utils/assertions.ts"; import { describeWithEnv } from "#test-utils/db.ts"; import { PDF_BYTES } from "#test-utils/factories.ts"; +import type { TestFormValues } from "#test-utils/form-values.ts"; import { mockMultipartRequest, withStorageMock } from "#test-utils/mocks.ts"; import { testCookie, testCsrfToken } from "#test-utils/session.ts"; import { makeTestPng } from "#test-utils/test-image.ts"; @@ -14,15 +15,15 @@ import { makeTestPng } from "#test-utils/test-image.ts"; const newListingFormFields = ( csrfToken: string, name: string, -): Record => ({ - bookable_days: "Monday,Tuesday,Wednesday,Thursday,Friday", +): TestFormValues => ({ + bookable_days: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"], closes_at_date: "", closes_at_time: "", csrf_token: csrfToken, date_date: "", date_time: "", description: "", - fields: "email", + fields: ["email"], listing_type: "standard", location: "", max_attendees: "50", diff --git a/test/lib/server-listings/log-and-activity.test.ts b/test/lib/server-listings/log-and-activity.test.ts index 174c7c45e4..f3c6e53947 100644 --- a/test/lib/server-listings/log-and-activity.test.ts +++ b/test/lib/server-listings/log-and-activity.test.ts @@ -1,79 +1,13 @@ // jscpd:ignore-start import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; -import { logActivity } from "#test-utils/activity-log.ts"; -import { - assertAdminHtml, - assertAdminHtmlWithCookie, - expectHtmlResponse, - testRequiresAuth, -} from "#test-utils/assertions.ts"; +import { assertAdminHtml, testRequiresAuth } from "#test-utils/assertions.ts"; import { describeWithEnv } from "#test-utils/db.ts"; -import { createTestAttendee } from "#test-utils/db-helpers/attendees.ts"; -import { createTestListing } from "#test-utils/db-helpers/listings.ts"; -import { awaitTestRequest } from "#test-utils/mocks.ts"; -import { - adminGet, - createTestManagerSession, - setupListingAndLogin, -} from "#test-utils/session.ts"; +import { adminGet, setupListingAndLogin } from "#test-utils/session.ts"; // jscpd:ignore-end describeWithEnv("server listings > log and activity", { db: true }, () => { - describe("GET /admin/log", () => { - testRequiresAuth("/admin/log"); - - test("shows log page when authenticated", async () => { - // Create an listing to generate activity - await createTestListing({ - maxAttendees: 50, - name: "Log Test", - }); - - const response = await adminGet("/admin/log"); - await expectHtmlResponse(response, 200, "Log"); - }); - - test("shows log page for manager", async () => { - const managerCookie = await createTestManagerSession(); - await assertAdminHtmlWithCookie("/admin/log", managerCookie, "Log"); - }); - - test("shows truncation message when more than 200 entries", async () => { - // Create 201 log entries to trigger truncation - for (let i = 0; i < 201; i++) { - await logActivity(`Action ${i}`); - } - - const response = await adminGet("/admin/log"); - const html = await response.text(); - expect(html).toContain("Showing the most recent 200 entries"); - }); - - test("links each entry to its attendee and listing by name", async () => { - const { listing, cookie } = await setupListingAndLogin({ - maxAttendees: 50, - name: "Gala Dinner", - }); - const attendee = await createTestAttendee( - listing.id, - listing.slug, - "Ada Lovelace", - "ada@example.com", - ); - await logActivity("Balance updated", listing.id, attendee.id); - - const response = await awaitTestRequest("/admin/log", { cookie }); - const html = await response.text(); - expect(html).toContain( - `Ada Lovelace`, - ); - expect(html).toContain( - `Gala Dinner`, - ); - }); - }); describe("GET /admin/listing/:id/activity", () => { testRequiresAuth("/admin/listing/1/activity"); diff --git a/test/shared/column-layout.test.ts b/test/shared/column-layout.test.ts new file mode 100644 index 0000000000..7e7e57211e --- /dev/null +++ b/test/shared/column-layout.test.ts @@ -0,0 +1,118 @@ +import { expect } from "@std/expect"; +import { describe, it as test } from "@std/testing/bdd"; +import { buildDefaultTemplate, COLUMN_LAYOUTS } from "#shared/column-layout.ts"; +import { + EDITOR_LISTING_LAYOUT, + EDITOR_LISTING_TABLE_COLUMNS, + LISTING_TABLE_COLUMNS, +} from "#shared/columns/listing-columns.ts"; + +describe("column layout validation", () => { + test("derives every listing schema from the matching column definitions", () => { + expect([...COLUMN_LAYOUTS.listing.schema.options].sort()).toEqual( + Object.keys(LISTING_TABLE_COLUMNS).sort(), + ); + expect([...EDITOR_LISTING_LAYOUT.columnKeys].sort()).toEqual( + Object.keys(EDITOR_LISTING_TABLE_COLUMNS).sort(), + ); + }); + + test("returns null for valid template", () => { + expect(COLUMN_LAYOUTS.listing.validate("{{name}}, {{status}}")).toBeNull(); + }); + + test("handles wonky spacing", () => { + expect( + COLUMN_LAYOUTS.listing.validate( + "{{ name }},{{description}}, {{ status }}", + ), + ).toBeNull(); + }); + + test("rejects unknown column", () => { + const error = COLUMN_LAYOUTS.listing.validate("{{name}}, {{descritpion}}"); + expect(error).toContain("descritpion"); + expect(error).toContain("Available columns"); + }); + + test("lists the schema columns in the error message", () => { + expect(COLUMN_LAYOUTS.attendee.validate("{{bogus}}")).toBe( + `Unknown column "bogus". Available columns: ${COLUMN_LAYOUTS.attendee.schema.options.join(", ")}`, + ); + }); + + test("accepts an empty template as the default layout", () => { + expect(COLUMN_LAYOUTS.listing.validate("")).toBeNull(); + }); + + test("rejects a non-empty template with no column tags", () => { + expect(COLUMN_LAYOUTS.listing.validate("name, status")).toBe( + "Template must include at least one column", + ); + }); + + test("accepts supported filters", () => { + expect( + COLUMN_LAYOUTS.listing.validate( + '{{name}}, {{created | date: "%B"}}, {{price | currency}}', + ), + ).toBeNull(); + }); +}); + +test("keeps the attendee default column order", () => { + expect(COLUMN_LAYOUTS.attendee.defaultOrder).toEqual([ + "status", + "date", + "name", + "listings", + "email", + "phone", + "address", + "special_instructions", + "answers", + "qty", + "ticket", + "registered", + ]); +}); + +describe("column layout parsing", () => { + test("returns default order when template is empty", () => { + const { columnKeys, filters } = COLUMN_LAYOUTS.listing.parse(""); + expect(columnKeys).toEqual(COLUMN_LAYOUTS.listing.defaultOrder); + expect(filters.size).toBe(0); + }); + + test("returns unique columns in template order", () => { + const { columnKeys } = COLUMN_LAYOUTS.listing.parse( + "{{status}}, {{name}}, {{status}}", + ); + expect(columnKeys).toEqual(["status", "name"]); + }); + + test("throws for an invalid template", () => { + expect(() => COLUMN_LAYOUTS.listing.parse("{{bogus}}, {{name}}")).toThrow( + 'Unknown column "bogus"', + ); + }); + + test("extracts only supplied filter expressions", () => { + const { filters } = COLUMN_LAYOUTS.listing.parse( + '{{name}}, {{created | date: "%B %d"}}', + ); + expect(filters.get("created")).toBe('created | date: "%B %d"'); + expect(filters.has("name")).toBe(false); + }); + + test("resolves all attendee columns from the default template", () => { + const template = buildDefaultTemplate(COLUMN_LAYOUTS.attendee.defaultOrder); + expect(COLUMN_LAYOUTS.attendee.parse(template).columnKeys).toEqual( + COLUMN_LAYOUTS.attendee.defaultOrder, + ); + }); +}); + +test("buildDefaultTemplate joins column tags", () => { + expect(buildDefaultTemplate(["a", "b", "c"])).toBe("{{a}}, {{b}}, {{c}}"); +}); diff --git a/test/shared/column-order.test.ts b/test/shared/column-order.test.ts index 300a54a3fd..1af6f79ad7 100644 --- a/test/shared/column-order.test.ts +++ b/test/shared/column-order.test.ts @@ -1,165 +1,19 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { COLUMN_LAYOUTS } from "#shared/column-layout.ts"; import type { ColumnDef, ColumnGenerators } from "#shared/column-order.ts"; import { - buildDefaultTemplate, getHeaderText, renderCells, renderFilteredValue, - resolveColumnLayout, - validateColumnTemplate, } from "#shared/column-order.ts"; -import { - ATTENDEE_DEFAULT_ORDER, - ATTENDEE_TABLE_COLUMNS, -} from "#shared/columns/attendee-columns.ts"; -import { - LISTING_DEFAULT_ORDER, - LISTING_TABLE_COLUMNS, -} from "#shared/columns/listing-columns.ts"; +import { LISTING_TABLE_COLUMNS } from "#shared/columns/listing-columns.ts"; import { escapeHtml } from "#templates/layout.tsx"; import { setupTestEncryptionKey } from "#test-utils/env.ts"; import { testListingWithCount } from "#test-utils/factories.ts"; setupTestEncryptionKey(); -const VALID_LISTING_KEYS = Object.keys(LISTING_TABLE_COLUMNS); -const VALID_ATTENDEE_KEYS = Object.keys(ATTENDEE_TABLE_COLUMNS); - -describe("validateColumnTemplate", () => { - test("returns null for valid template", () => { - expect( - validateColumnTemplate("{{name}}, {{status}}", VALID_LISTING_KEYS), - ).toBeNull(); - }); - - test("handles wonky spacing", () => { - expect( - validateColumnTemplate( - "{{ name }},{{description}}, {{ status }}", - VALID_LISTING_KEYS, - ), - ).toBeNull(); - }); - - test("rejects unknown column (typo)", () => { - const error = validateColumnTemplate( - "{{name}}, {{descritpion}}", - VALID_LISTING_KEYS, - ); - expect(error).toContain("descritpion"); - expect(error).toContain("Available columns"); - }); - - test("lists available columns comma-separated in the error message", () => { - const error = validateColumnTemplate("{{bogus}}", [ - "alpha", - "beta", - "gamma", - ]); - expect(error).toBe( - 'Unknown column "bogus". Available columns: alpha, beta, gamma', - ); - }); - - test("rejects empty template", () => { - const error = validateColumnTemplate("", VALID_LISTING_KEYS); - expect(error).toBe("Template must include at least one column"); - }); - - test("accepts templates with date filter", () => { - expect( - validateColumnTemplate( - '{{name}}, {{created | date: "%B"}}', - VALID_LISTING_KEYS, - ), - ).toBeNull(); - }); - - test("accepts templates with currency filter", () => { - expect( - validateColumnTemplate( - "{{name}}, {{price | currency}}", - VALID_LISTING_KEYS, - ), - ).toBeNull(); - }); -}); - -describe("resolveColumnLayout", () => { - test("returns default order when template is empty", () => { - const { columnKeys, filters } = resolveColumnLayout( - "", - VALID_LISTING_KEYS, - LISTING_DEFAULT_ORDER, - ); - expect(columnKeys).toEqual([...LISTING_DEFAULT_ORDER]); - expect(filters.size).toBe(0); - }); - - test("returns columns in template order", () => { - const { columnKeys } = resolveColumnLayout( - "{{status}}, {{name}}", - VALID_LISTING_KEYS, - LISTING_DEFAULT_ORDER, - ); - expect(columnKeys).toEqual(["status", "name"]); - }); - - test("deduplicates repeated columns", () => { - const { columnKeys } = resolveColumnLayout( - "{{name}}, {{name}}, {{status}}", - VALID_LISTING_KEYS, - LISTING_DEFAULT_ORDER, - ); - expect(columnKeys).toEqual(["name", "status"]); - }); - - test("throws for an invalid template", () => { - expect(() => - resolveColumnLayout( - "{{bogus}}", - VALID_LISTING_KEYS, - LISTING_DEFAULT_ORDER, - ), - ).toThrow('Unknown column "bogus"'); - }); - - test("extracts filter expression for filtered column", () => { - const { filters } = resolveColumnLayout( - '{{name}}, {{created | date: "%B %d"}}', - VALID_LISTING_KEYS, - LISTING_DEFAULT_ORDER, - ); - expect(filters.get("created")).toBe('created | date: "%B %d"'); - }); - - test("does not create filter entry for unfiltered column", () => { - const { filters } = resolveColumnLayout( - '{{name}}, {{created | date: "%B %d"}}', - VALID_LISTING_KEYS, - LISTING_DEFAULT_ORDER, - ); - expect(filters.has("name")).toBe(false); - }); - - test("resolves all attendee columns from default template", () => { - const template = buildDefaultTemplate(ATTENDEE_DEFAULT_ORDER); - const { columnKeys } = resolveColumnLayout( - template, - VALID_ATTENDEE_KEYS, - ATTENDEE_DEFAULT_ORDER, - ); - expect(columnKeys).toEqual([...ATTENDEE_DEFAULT_ORDER]); - }); -}); - -describe("buildDefaultTemplate", () => { - test("joins column tags with a comma and space", () => { - expect(buildDefaultTemplate(["a", "b", "c"])).toBe("{{a}}, {{b}}, {{c}}"); - }); -}); - describe("renderFilteredValue", () => { test("applies date filter with strftime format", () => { const result = renderFilteredValue( @@ -230,16 +84,20 @@ describe("renderFilteredValue", () => { }); describe("renderCells", () => { + test("rejects a column missing from the supplied definitions", () => { + expect(() => + renderCells({}, ["missing"], {}, undefined, new Map(), escapeHtml), + ).toThrow("Unknown column: missing"); + }); + test("renders listing columns end-to-end through the full pipeline", () => { const listing = testListingWithCount({ date: "2026-06-15", name: "Jazz Night", unit_price: 0, }); - const { columnKeys, filters } = resolveColumnLayout( + const { columnKeys, filters } = COLUMN_LAYOUTS.listing.parse( "{{name}}, {{price}}, {{date}}", - VALID_LISTING_KEYS, - LISTING_DEFAULT_ORDER, ); const html = renderCells( listing, @@ -260,10 +118,8 @@ describe("renderCells", () => { date: "2026-03-15", unit_price: 2500, }); - const { columnKeys, filters } = resolveColumnLayout( + const { columnKeys, filters } = COLUMN_LAYOUTS.listing.parse( '{{date | date: "%d/%m/%Y"}}, {{created | date: "%B %Y"}}, {{price | currency}}', - VALID_LISTING_KEYS, - LISTING_DEFAULT_ORDER, ); const html = renderCells( listing, @@ -282,11 +138,8 @@ describe("renderCells", () => { const listing = testListingWithCount({ location: '', }); - const { columnKeys, filters } = resolveColumnLayout( - "{{location}}", - VALID_LISTING_KEYS, - LISTING_DEFAULT_ORDER, - ); + const { columnKeys, filters } = + COLUMN_LAYOUTS.listing.parse("{{location}}"); const html = renderCells( listing, columnKeys, diff --git a/test/shared/columns/attendee-columns.test.ts b/test/shared/columns/attendee-columns.test.ts index 43d8e2a70b..b21cc11469 100644 --- a/test/shared/columns/attendee-columns.test.ts +++ b/test/shared/columns/attendee-columns.test.ts @@ -1,7 +1,7 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { type AttendeeColumn, COLUMN_LAYOUTS } from "#shared/column-layout.ts"; import { - ATTENDEE_DEFAULT_ORDER, ATTENDEE_TABLE_COLUMNS, formatAddressInline, } from "#shared/columns/attendee-columns.ts"; @@ -85,7 +85,7 @@ const METADATA: Record = { describe("ATTENDEE_TABLE_COLUMNS metadata", () => { test("every column exposes its expected label/description/className/isHtml", () => { for (const [key, expected] of Object.entries(METADATA)) { - const col = ATTENDEE_TABLE_COLUMNS[key]!; + const col = ATTENDEE_TABLE_COLUMNS[key as AttendeeColumn]; expect(col.label).toBe(expected.label); expect(col.description).toBe(expected.description); expect(col.isHtml).toBe(expected.isHtml); @@ -102,26 +102,9 @@ describe("ATTENDEE_TABLE_COLUMNS metadata", () => { }); }); -describe("ATTENDEE_DEFAULT_ORDER", () => { - test("matches the expected default order exactly", () => { - expect(ATTENDEE_DEFAULT_ORDER).toEqual([ - "status", - "date", - "name", - "listings", - "email", - "phone", - "address", - "special_instructions", - "answers", - "qty", - "ticket", - "registered", - ]); - }); - +describe("the attendee default column order", () => { test("is a permutation of ATTENDEE_TABLE_COLUMNS' keys", () => { - expect([...ATTENDEE_DEFAULT_ORDER].sort()).toEqual( + expect([...COLUMN_LAYOUTS.attendee.defaultOrder].sort()).toEqual( Object.keys(ATTENDEE_TABLE_COLUMNS).sort(), ); }); diff --git a/test/shared/dates/pinned-values.test.ts b/test/shared/dates/pinned-values.test.ts index 8d44d26509..c885d7f830 100644 --- a/test/shared/dates/pinned-values.test.ts +++ b/test/shared/dates/pinned-values.test.ts @@ -1,7 +1,7 @@ /** * Pins exact outputs of the date helpers so small slips can't hide: every - * day and month name in a rendered label, the Monday-first day list, hour - * rounding, calendar-grid boundaries, and booked-range arithmetic. Each + * day and month name in a rendered label, hour rounding, calendar-grid + * boundaries, and booked-range arithmetic. Each * assertion here exists to fail under a specific one-token change that the * broader behaviour tests in dates.test.ts did not distinguish. */ @@ -18,7 +18,7 @@ import { startOfHour, widestDatedEntry, } from "#shared/dates.ts"; -import { DAY_NAMES, VALID_DAY_NAMES } from "#shared/day-names.ts"; +import { VALID_DAY_NAMES } from "#shared/day-names.ts"; import { testListing } from "#test-utils/factories.ts"; import { useSetting } from "#test-utils/settings.ts"; @@ -62,19 +62,6 @@ describe("dates — pinned values", () => { } }); - test("VALID_DAY_NAMES is the Monday-first rotation of DAY_NAMES", () => { - expect(VALID_DAY_NAMES).toEqual([ - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", - "Sunday", - ]); - expect(DAY_NAMES[0]).toBe("Sunday"); - }); - test("adding months clamps a month-end start to each target month's length", () => { // From 31 January, every non-leap target month clamps to its true length. const expectedDays = [28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; diff --git a/test/shared/day-names.test.ts b/test/shared/day-names.test.ts new file mode 100644 index 0000000000..29261c6ce3 --- /dev/null +++ b/test/shared/day-names.test.ts @@ -0,0 +1,23 @@ +import { expect } from "@std/expect"; +import { DAY_NAMES, VALID_DAY_NAMES } from "#shared/day-names.ts"; + +Deno.test("bookable day names rotate the date order to Monday first", () => { + expect(DAY_NAMES).toEqual([ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + ]); + expect(VALID_DAY_NAMES).toEqual([ + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday", + ]); +}); diff --git a/test/shared/db/attendees/api/errors.test.ts b/test/shared/db/attendees/api/errors.test.ts index 20f7f77327..c730f61923 100644 --- a/test/shared/db/attendees/api/errors.test.ts +++ b/test/shared/db/attendees/api/errors.test.ts @@ -148,7 +148,7 @@ describeWithEnv( const { response } = await adminFormPost( `/admin/attendees/${attendee.id}`, { - name: attendee.name, + name: "Blank", ...attendeeLineFields([ { eventId: event.id, quantity: Number("0") }, ]), diff --git a/test/shared/form-data.test.ts b/test/shared/form-data.test.ts index 8ba435dbbb..7eccdc2b77 100644 --- a/test/shared/form-data.test.ts +++ b/test/shared/form-data.test.ts @@ -81,3 +81,45 @@ describe("FormParams.getNumberArray", () => { expect(form.getNumberArray("ids")).toEqual([]); }); }); + +describe("FormParams.getRepeatedPicklist", () => { + const allowed = ["Monday", "Tuesday", "Wednesday"] as const; + const read = (query: string) => + new FormParams(query).getRepeatedPicklist("days", allowed); + + test("returns no selections when the field is absent", () => { + expect(read("")).toEqual({ ok: true, value: [] }); + }); + + test("returns the first invalid supplied token", () => { + expect(read("days=Monday&days=Funday&days=Someday")).toEqual({ + error: "Funday", + ok: false, + }); + }); + + test("returns unique values in declared order", () => { + expect(read("days=Wednesday&days=Monday&days=Wednesday")).toEqual({ + ok: true, + value: ["Monday", "Wednesday"], + }); + }); + + test("rejects empty and padded tokens", () => { + expect(read("days=")).toEqual({ error: "", ok: false }); + expect(read("days=%20Monday%20")).toEqual({ + error: " Monday ", + ok: false, + }); + }); +}); + +describe("FormParams.toRenderValues", () => { + test("joins repeated controls without changing single values", () => { + const form = new FormParams("days=Monday&name=Alice&days=Wednesday"); + expect(form.toRenderValues()).toEqual({ + days: "Monday,Wednesday", + name: "Alice", + }); + }); +}); diff --git a/test/shared/forms/definition/define-form.test.ts b/test/shared/forms/definition/define-form.test.ts index 79b31d2a45..57ed553d82 100644 --- a/test/shared/forms/definition/define-form.test.ts +++ b/test/shared/forms/definition/define-form.test.ts @@ -175,7 +175,7 @@ describe("defineForm", () => { id: "test", }); - const html = form.field("color").render("blue"); + const html = form.renderField("color", "blue"); expect(html).toContain("blue"); }); diff --git a/test/shared/forms/definition/field-schema.test.ts b/test/shared/forms/definition/field-schema.test.ts index c5353c8b99..d1958805ea 100644 --- a/test/shared/forms/definition/field-schema.test.ts +++ b/test/shared/forms/definition/field-schema.test.ts @@ -1,11 +1,28 @@ import { expect } from "@std/expect"; -import { describe, it as test } from "@std/testing/bdd"; +import { beforeAll, describe, it as test } from "@std/testing/bdd"; import { FormParams } from "#shared/form-data.ts"; import { defineForm } from "#shared/forms/definition.ts"; import type { Field } from "#shared/forms/field.ts"; import { renderField } from "#shared/forms/rendering.tsx"; +import { ensureMessageGroups } from "#shared/i18n.ts"; + +const singleActionSelect = (id: string, invalidMessage?: string) => + defineForm({ + fields: [ + { + ...(invalidMessage === undefined ? {} : { invalidMessage }), + label: "Action", + name: "action", + options: [{ label: "Pay", value: "pay" }], + type: "select", + }, + ] as const, + id, + }); describe("form field schema", () => { + beforeAll(() => ensureMessageGroups(["validation"])); + test("renders select option hints from the field schema", () => { const form = defineForm({ fields: [ @@ -50,17 +67,7 @@ describe("form field schema", () => { }); test("uses the shared invalid message when a choice has no custom message", () => { - const form = defineForm({ - fields: [ - { - label: "Action", - name: "action", - options: [{ label: "Pay", value: "pay" }], - type: "select", - }, - ] as const, - id: "default-choice-message", - }); + const form = singleActionSelect("default-choice-message"); expect(form.validate(new FormParams({ action: "refund" }))).toEqual({ error: "Action is invalid.", @@ -92,6 +99,15 @@ describe("form field schema", () => { } }); + test("normalizes an empty select value to null", () => { + const form = singleActionSelect("empty-select-value"); + + expect(form.validate(new FormParams())).toEqual({ + valid: true, + values: { action: null }, + }); + }); + test("requires options when declaring a select field", () => { const acceptField = (_field: Field): void => {}; // @ts-expect-error A select without options is not a valid Field. @@ -129,7 +145,7 @@ describe("form field schema", () => { expect(defineEmptySelect).toThrow("Action must define at least one option"); }); - test("accepts spaces in comma-separated checkbox choices", () => { + test("rejects checkbox choices submitted as one comma-separated token", () => { const form = defineForm({ fields: [ { @@ -148,8 +164,8 @@ describe("form field schema", () => { expect( form.validate(new FormParams({ days: "Monday, Wednesday" })), ).toEqual({ - valid: true, - values: { days: "Monday, Wednesday" }, + error: "Days is invalid.", + valid: false, }); }); @@ -199,6 +215,7 @@ describe("form field schema", () => { const form = defineForm({ fields: [ { label: "Name", name: "name", section: "main", type: "text" }, + { label: "Summary", name: "summary", type: "text" }, { label: "Private", name: "private", @@ -216,6 +233,7 @@ describe("form field schema", () => { expect(form.sections).toEqual(["main", "advanced"]); expect(form.section("main")).toContain('name="name"'); + expect(form.section("main")).not.toContain('name="summary"'); expect(form.section("advanced")).not.toContain('name="private"'); expect(rejectUnknownSection).toThrow("Unknown section: missing"); }); @@ -227,7 +245,7 @@ describe("form field schema", () => { }); const renderUnknownField = () => { // @ts-expect-error Field names come from the field declarations. - form.field("missing").render(); + form.renderField("missing"); }; expect(renderUnknownField).toThrow("Unknown field: missing"); @@ -239,6 +257,6 @@ describe("form field schema", () => { id: "blank-field", }); - expect(form.field("name").render()).not.toContain("value="); + expect(form.renderField("name")).not.toContain("value="); }); }); diff --git a/test/shared/forms/validation.test.ts b/test/shared/forms/validation.test.ts index c59db8a5ad..07d6251aef 100644 --- a/test/shared/forms/validation.test.ts +++ b/test/shared/forms/validation.test.ts @@ -1,8 +1,9 @@ import { expect } from "@std/expect"; -import { describe, it as test } from "@std/testing/bdd"; +import { beforeAll, describe, it as test } from "@std/testing/bdd"; import { FormParams } from "#shared/form-data.ts"; import type { Field } from "#shared/forms/field.ts"; import { validateForm } from "#shared/forms/validation.ts"; +import { ensureMessageGroups } from "#shared/i18n.ts"; const field = ( overrides: Partial & { name: string; label: string }, @@ -12,7 +13,32 @@ const requiredName: Field[] = [ field({ label: "Name", name: "name", required: true }), ]; +const dayCheckboxFields = (invalidMessage?: string): Field[] => [ + field({ + ...(invalidMessage === undefined ? {} : { invalidMessage }), + label: "Days", + name: "days", + options: [ + { label: "Monday", value: "Monday" }, + { label: "Wednesday", value: "Wednesday" }, + ], + type: "checkbox-group", + }), +]; + +const colorSelectFields = (invalidMessage?: string): Field[] => [ + field({ + ...(invalidMessage === undefined ? {} : { invalidMessage }), + label: "Color", + name: "color", + options: [{ label: "Red", value: "red" }], + type: "select", + }), +]; + describe("validateForm", () => { + beforeAll(() => ensureMessageGroups(["validation"])); + test("rejects empty required field", () => { const result = validateForm(new FormParams({ name: "" }), requiredName); expect(result.valid).toBe(false); @@ -59,6 +85,13 @@ describe("validateForm", () => { if (result.valid) expect(result.values.note).toBe(""); }); + test("returns null for an empty optional select", () => { + expect(validateForm(new FormParams(), colorSelectFields())).toEqual({ + valid: true, + values: { color: null }, + }); + }); + test("runs custom validate function and surfaces its error", () => { const fields: Field[] = [ field({ @@ -114,26 +147,125 @@ describe("validateForm", () => { expect(validateForm(new FormParams({ code: "" }), fields).valid).toBe(true); }); - test("collects checkbox-group values from multiple form entries", () => { + test("uses a field parser instead of the built-in value", () => { const fields: Field[] = [ - field({ - label: "Days", - name: "days", - options: [ - { label: "Monday", value: "Monday" }, - { label: "Wednesday", value: "Wednesday" }, - ], - type: "checkbox-group", - }), + field({ label: "Code", name: "code", parse: () => "parsed" }), ]; + expect(validateForm(new FormParams({ code: "raw" }), fields)).toEqual({ + valid: true, + values: { code: "parsed" }, + }); + }); + + test("keeps an explicitly empty required message", () => { + expect( + validateForm(new FormParams(), [ + field({ + label: "Name", + name: "name", + required: true, + requiredMessage: "", + }), + ]), + ).toEqual({ error: "", valid: false }); + }); + + test("keeps an explicitly empty invalid message", () => { + expect( + validateForm(new FormParams({ color: "blue" }), colorSelectFields("")), + ).toEqual({ error: "", valid: false }); + }); + + test("accepts a declared select value", () => { + expect( + validateForm(new FormParams({ color: "red" }), colorSelectFields()), + ).toEqual({ + valid: true, + values: { color: "red" }, + }); + }); + + test("rejects an undeclared select value with the default message", () => { + expect( + validateForm(new FormParams({ color: "blue" }), colorSelectFields()), + ).toEqual({ error: "Color is invalid.", valid: false }); + }); + + test("rejects parsers that return unusable values", () => { + for (const [name, parse] of [ + ["missing", () => null], + ["infinite", () => Number.POSITIVE_INFINITY], + ] as const) { + expect( + validateForm(new FormParams({ [name]: "value" }), [ + field({ label: name, name, parse }), + ]), + ).toEqual({ error: `${name} is invalid.`, valid: false }); + } + }); + + test("uses a default when the submitted value is empty", () => { + const fields: Field[] = [ + field({ defaultValue: "fallback", label: "Code", name: "code" }), + ]; + expect(validateForm(new FormParams(), fields)).toEqual({ + valid: true, + values: { code: "fallback" }, + }); + }); + + test("keeps a submitted value instead of its default", () => { + const fields: Field[] = [ + field({ defaultValue: "fallback", label: "Code", name: "code" }), + ]; + expect(validateForm(new FormParams({ code: "given" }), fields)).toEqual({ + valid: true, + values: { code: "given" }, + }); + }); + + test("collects checkbox-group values from multiple form entries", () => { const form = new FormParams(); form.append("days", "Monday"); form.append("days", "Wednesday"); - const result = validateForm(form, fields); + const result = validateForm(form, dayCheckboxFields()); expect(result.valid).toBe(true); if (result.valid) expect(result.values.days).toBe("Monday,Wednesday"); }); + test("normalizes checkbox-group values to option order", () => { + const form = new FormParams("days=Wednesday&days=Monday&days=Wednesday"); + + expect(validateForm(form, dayCheckboxFields())).toEqual({ + valid: true, + values: { days: "Monday,Wednesday" }, + }); + }); + + test("rejects a bad checkbox value mixed into valid selections", () => { + expect( + validateForm( + new FormParams("days=Monday&days=Funday&days=Wednesday"), + dayCheckboxFields("Choose listed days only."), + ), + ).toEqual({ error: "Choose listed days only.", valid: false }); + }); + + test("keeps an explicitly empty invalid checkbox message", () => { + expect( + validateForm(new FormParams("days=Funday"), dayCheckboxFields("")), + ).toEqual({ error: "", valid: false }); + }); + + test("keeps a custom validation error for a bad checkbox value", () => { + const fields = dayCheckboxFields(); + fields[0]!.validate = () => "Choose a valid day."; + expect(validateForm(new FormParams("days=Funday"), fields)).toEqual({ + error: "Choose a valid day.", + valid: false, + }); + }); + test("returns empty string for empty checkbox-group", () => { const fields: Field[] = [ field({ @@ -148,6 +280,32 @@ describe("validateForm", () => { if (result.valid) expect(result.values.days).toBe(""); }); + test("rejects an empty required checkbox group", () => { + const fields = dayCheckboxFields(); + fields[0]!.required = true; + expect(validateForm(new FormParams(), fields)).toEqual({ + error: "Days is required", + valid: false, + }); + }); + + test("runs checkbox-group validation on selected values", () => { + const fields = dayCheckboxFields(); + fields[0]!.validate = () => "Days cannot be combined."; + expect( + validateForm(new FormParams("days=Monday&days=Wednesday"), fields), + ).toEqual({ error: "Days cannot be combined.", valid: false }); + }); + + test("does not run checkbox-group validation without a selection", () => { + const fields = dayCheckboxFields(); + fields[0]!.validate = () => "Unexpected validation."; + expect(validateForm(new FormParams(), fields)).toEqual({ + valid: true, + values: { days: "" }, + }); + }); + test("skips file fields and returns null", () => { const fields: Field[] = [ field({ label: "Image", name: "image", type: "file" }), diff --git a/test/test-utils/db-helpers/listing-forms.ts b/test/test-utils/db-helpers/listing-forms.ts index 4023a6439b..33c7d15e1c 100644 --- a/test/test-utils/db-helpers/listing-forms.ts +++ b/test/test-utils/db-helpers/listing-forms.ts @@ -1,18 +1,22 @@ import { toMajorUnits } from "#shared/currency.ts"; import type { ListingInput } from "#shared/db/listings/table.ts"; import type { DayPrices, ListingWithCount } from "#shared/types.ts"; +import type { TestFormValues } from "#test-utils/form-values.ts"; -const bool = (v: unknown): string => (v ? "1" : ""); +const checked = (name: string, value: unknown): TestFormValues => + value ? { [name]: "1" } : {}; +const flagChoice = (value: unknown): string => (value ? "1" : ""); const optionalNumber = (v: number | null | undefined): string => v != null ? String(v) : ""; const optionalPrice = (v: number | null | undefined): string => v != null ? toMajorUnits(v) : ""; -const formatBookableDaysForForm = (days: string[]): string => days.join(","); +const repeated = (value: string): string[] => + value ? value.split(",").map((part) => part.trim()) : []; /** Serialize a DayPrices map into the form's `day_price_` fields. */ const dayPriceFormFields = ( dayPrices: DayPrices | undefined, -): Record => { +): TestFormValues => { const result: Record = {}; for (const [days, price] of Object.entries(dayPrices ?? {})) { result[`day_price_${days}`] = toMajorUnits(price); @@ -44,30 +48,28 @@ export const priceFormValue = (minorUnits: number): string => export const buildCreateListingForm = ( input: Omit, -): Record => { +): TestFormValues => { const closesAtParts = splitClosesAt(input.closesAt, null); const dateParts = splitClosesAt(input.date, null); const initialSiteMonths = input.assignBuiltSite ? (input.initialSiteMonths ?? 1) : (input.initialSiteMonths ?? 0); return { - assign_built_site: bool(input.assignBuiltSite), - bookable_alone: bool(input.bookableAlone), - bookable_days: input.bookableDays - ? formatBookableDaysForForm(input.bookableDays) - : "", - can_pay_more: bool(input.canPayMore), + ...checked("assign_built_site", input.assignBuiltSite), + ...checked("bookable_alone", input.bookableAlone), + bookable_days: input.bookableDays ?? [], + ...checked("can_pay_more", input.canPayMore), closes_at_date: closesAtParts.date, closes_at_time: closesAtParts.time, - customisable_days: bool(input.customisableDays), + ...checked("customisable_days", input.customisableDays), date_date: dateParts.date, date_time: dateParts.time, description: input.description ?? "", duration_days: optionalNumber(input.durationDays), - uses_logistics: bool(input.usesLogistics), + ...checked("uses_logistics", input.usesLogistics), ...dayPriceFormFields(input.dayPrices), - fields: input.fields ?? "email", - hidden: bool(input.hidden), + fields: repeated(input.fields ?? "email"), + ...checked("hidden", input.hidden), initial_site_months: String(initialSiteMonths), listing_type: input.listingType ?? "", location: input.location ?? "", @@ -78,11 +80,11 @@ export const buildCreateListingForm = ( minimum_days_before: optionalNumber(input.minimumDaysBefore), months_per_unit: String(input.monthsPerUnit ?? 0), name: input.name, - non_transferable: bool(input.nonTransferable), - purchase_only: bool(input.purchaseOnly), + non_transferable: flagChoice(input.nonTransferable), + ...checked("purchase_only", input.purchaseOnly), thank_you_url: input.thankYouUrl ?? "", unit_price: optionalPrice(input.unitPrice), - use_defaults: bool(input.useDefaults), + ...checked("use_defaults", input.useDefaults), webhook_url: input.webhookUrl ?? "", }; }; @@ -90,21 +92,33 @@ export const buildCreateListingForm = ( const buildUpdateBoolFields = ( updates: Partial, existing: ListingWithCount, -): Record => ({ - assign_built_site: bool( +): TestFormValues => ({ + ...checked( + "assign_built_site", pickField(updates.assignBuiltSite, existing.assign_built_site), ), - bookable_alone: bool( + ...checked( + "bookable_alone", pickField(updates.bookableAlone, existing.bookable_alone), ), - can_pay_more: bool(pickField(updates.canPayMore, existing.can_pay_more)), - hidden: bool(pickField(updates.hidden, existing.hidden)), - non_transferable: bool( + ...checked( + "can_pay_more", + pickField(updates.canPayMore, existing.can_pay_more), + ), + ...checked("hidden", pickField(updates.hidden, existing.hidden)), + non_transferable: flagChoice( pickField(updates.nonTransferable, existing.non_transferable), ), - purchase_only: bool(pickField(updates.purchaseOnly, existing.purchase_only)), - use_defaults: bool(pickField(updates.useDefaults, existing.use_defaults)), - uses_logistics: bool( + ...checked( + "purchase_only", + pickField(updates.purchaseOnly, existing.purchase_only), + ), + ...checked( + "use_defaults", + pickField(updates.useDefaults, existing.use_defaults), + ), + ...checked( + "uses_logistics", pickField(updates.usesLogistics, existing.uses_logistics), ), }); @@ -112,7 +126,7 @@ const buildUpdateBoolFields = ( const buildUpdateNumericFields = ( updates: Partial, existing: ListingWithCount, -): Record => { +): TestFormValues => { const assignsBuiltSite = pickField( updates.assignBuiltSite, existing.assign_built_site, @@ -146,12 +160,10 @@ const buildUpdateNumericFields = ( const buildUpdateStringFields = ( updates: Partial, existing: ListingWithCount, -): Record => ({ - bookable_days: formatBookableDaysForForm( - pickField(updates.bookableDays, existing.bookable_days), - ), +): TestFormValues => ({ + bookable_days: pickField(updates.bookableDays, existing.bookable_days), description: pickField(updates.description, existing.description), - fields: pickField(updates.fields, existing.fields), + fields: repeated(pickField(updates.fields, existing.fields)), listing_type: pickField(updates.listingType, existing.listing_type), location: pickField(updates.location, existing.location), name: pickField(updates.name, existing.name), @@ -163,7 +175,7 @@ const buildUpdateStringFields = ( export const buildUpdateListingForm = ( updates: Partial, existing: ListingWithCount, -): Record => { +): TestFormValues => { const closesAtParts = splitClosesAt(updates.closesAt, existing.closes_at); const dateParts = splitClosesAt(updates.date, existing.date); return { @@ -173,7 +185,8 @@ export const buildUpdateListingForm = ( ...dayPriceFormFields(updates.dayPrices ?? existing.day_prices), closes_at_date: closesAtParts.date, closes_at_time: closesAtParts.time, - customisable_days: bool( + ...checked( + "customisable_days", updates.customisableDays ?? existing.customisable_days, ), date_date: dateParts.date, diff --git a/test/test-utils/db-helpers/request.ts b/test/test-utils/db-helpers/request.ts index 8889b2dca2..d486072b5a 100644 --- a/test/test-utils/db-helpers/request.ts +++ b/test/test-utils/db-helpers/request.ts @@ -4,12 +4,8 @@ * admin create/update/delete test helper below. */ async function doAuthenticatedRequest( path: string, - formData: Record, - buildRequest: ( - path: string, - data: Record, - cookie: string, - ) => Request, + formData: TestFormValues, + buildRequest: (path: string, data: TestFormValues, cookie: string) => Request, onSuccess: () => Promise, errorContext: string, ): Promise { @@ -31,7 +27,7 @@ async function doAuthenticatedRequest( export const doAuthenticatedFormRequest = async ( path: string, - formData: Record, + formData: TestFormValues, onSuccess: () => Promise, errorContext: string, ): Promise => { @@ -47,7 +43,7 @@ export const doAuthenticatedFormRequest = async ( export const doAuthenticatedMultipartFormRequest = async ( path: string, - formData: Record, + formData: TestFormValues, onSuccess: () => Promise, errorContext: string, ): Promise => { @@ -60,3 +56,5 @@ export const doAuthenticatedMultipartFormRequest = async ( errorContext, ); }; + +import type { TestFormValues } from "#test-utils/form-values.ts"; diff --git a/test/test-utils/form-values.test.ts b/test/test-utils/form-values.test.ts new file mode 100644 index 0000000000..d624014467 --- /dev/null +++ b/test/test-utils/form-values.test.ts @@ -0,0 +1,18 @@ +import { expect } from "@std/expect"; +import { it as test } from "@std/testing/bdd"; +import { testFormParams } from "#test-utils/form-values.ts"; + +test("testFormParams appends repeated values and skips missing values", () => { + const params = testFormParams({ + absent: undefined, + empty: null, + selected: ["first", "second"], + single: "value", + }); + + expect([...params.entries()]).toEqual([ + ["selected", "first"], + ["selected", "second"], + ["single", "value"], + ]); +}); diff --git a/test/test-utils/form-values.ts b/test/test-utils/form-values.ts new file mode 100644 index 0000000000..0f7de8b438 --- /dev/null +++ b/test/test-utils/form-values.ts @@ -0,0 +1,24 @@ +import { FormParams } from "#shared/form-data.ts"; + +export type TestFormValues = Record< + string, + string | string[] | null | undefined +>; + +export const appendTestFormValues = ( + params: URLSearchParams | FormData, + data: TestFormValues = {}, +): void => { + for (const [key, values] of Object.entries(data)) { + if (values == null) continue; + for (const value of typeof values === "string" ? [values] : values) { + params.append(key, value); + } + } +}; + +export const testFormParams = (data: TestFormValues): FormParams => { + const params = new FormParams(); + appendTestFormValues(params, data); + return params; +}; diff --git a/test/test-utils/mocks.ts b/test/test-utils/mocks.ts index 8a33412a62..704aa1089a 100644 --- a/test/test-utils/mocks.ts +++ b/test/test-utils/mocks.ts @@ -10,6 +10,10 @@ import { runWithStorageConfig } from "#shared/storage.ts"; import { type EnvScope, withEnv } from "#test-utils/env.ts"; import { stubFetch } from "#test-utils/fetch-stub.ts"; import { withTempDir } from "#test-utils/files.ts"; +import { + appendTestFormValues, + type TestFormValues, +} from "#test-utils/form-values.ts"; import { TEST_STORAGE_ZONE, type TestRequestOptions, @@ -30,10 +34,12 @@ export const mockRequest = (path: string, options: RequestInit = {}): Request => export const mockFormRequest = ( path: string, - data: Record, + data: TestFormValues = {}, cookie?: string, ): Request => { - const body = new URLSearchParams(data).toString(); + const params = new URLSearchParams(); + appendTestFormValues(params, data); + const body = params.toString(); const headers: HeadersInit = { "content-type": "application/x-www-form-urlencoded", host: "localhost", @@ -73,7 +79,7 @@ export const mockAdminLoginRequest = async ( export const mockMultipartRequest = ( path: string, - data: Record, + data: TestFormValues = {}, cookie?: string, file?: { name: string; @@ -83,9 +89,7 @@ export const mockMultipartRequest = ( }, ): Request => { const formData = new FormData(); - for (const [key, value] of Object.entries(data)) { - formData.append(key, value); - } + appendTestFormValues(formData, data); if (file) { // deno-lint-ignore no-explicit-any const blob = new Blob([file.data as any], { type: file.contentType }); diff --git a/test/test-utils/session.ts b/test/test-utils/session.ts index 374e1c86ee..783c8815cc 100644 --- a/test/test-utils/session.ts +++ b/test/test-utils/session.ts @@ -11,6 +11,7 @@ import { } from "#shared/session-context.ts"; import type { Listing } from "#shared/types.ts"; import type { TestListingOverrides } from "#test-utils/factories.ts"; +import type { TestFormValues } from "#test-utils/form-values.ts"; import type { AdminTestContext } from "#test-utils/internal.ts"; import { getInternalTestSession, @@ -413,7 +414,7 @@ export const adminFormPost = async ( export const adminMultipartPost = async ( path: string, - data: Record = {}, + data: TestFormValues = {}, file?: { name: string; fieldName: string; diff --git a/test/test-utils/validation.ts b/test/test-utils/validation.ts index 3a69770470..ca17ca41e1 100644 --- a/test/test-utils/validation.ts +++ b/test/test-utils/validation.ts @@ -1,16 +1,17 @@ import { expect } from "@std/expect"; -import { FormParams } from "#shared/form-data.ts"; import type { Field } from "#shared/forms/field.ts"; import { validateForm } from "#shared/forms/validation.ts"; +import { + type TestFormValues, + testFormParams, +} from "#test-utils/form-values.ts"; -const validateFormData = ( - fields: readonly Field[], - data: Record, -) => validateForm(new FormParams(data), fields); +const validateFormData = (fields: readonly Field[], data: TestFormValues) => + validateForm(testFormParams(data), fields); export const expectValid = ( fields: readonly Field[], - data: Record, + data: TestFormValues, ): Record => { const result = validateFormData(fields, data); expect(result.valid).toBe(true); @@ -18,8 +19,10 @@ export const expectValid = ( }; export const expectInvalid = - (expectedError: string) => - (fields: readonly Field[], data: Record): void => { + ( + expectedError: string, + ): ((fields: readonly Field[], data: TestFormValues) => void) => + (fields: readonly Field[], data: TestFormValues): void => { const result = validateFormData(fields, data); expect(result.valid).toBe(false); if (!result.valid) expect(result.error).toBe(expectedError); @@ -27,7 +30,7 @@ export const expectInvalid = export const expectInvalidForm = ( fields: readonly Field[], - data: Record, + data: TestFormValues, ): void => { expect(validateFormData(fields, data).valid).toBe(false); }; diff --git a/test/ui/templates/admin/dashboard.test.ts b/test/ui/templates/admin/dashboard.test.ts index 81a32ef760..d5fd6a5462 100644 --- a/test/ui/templates/admin/dashboard.test.ts +++ b/test/ui/templates/admin/dashboard.test.ts @@ -4,6 +4,7 @@ import { NO_QUANTITY_PREFIX, QTY_PREFIX, } from "#routes/admin/attendee-form-model.ts"; +import { COLUMN_LAYOUTS } from "#shared/column-layout.ts"; import { signCsrfToken } from "#shared/csrf.ts"; import { getDb } from "#shared/db/client.ts"; import { @@ -265,7 +266,7 @@ describe("adminDashboardPage with column template filters", () => { [], undefined, null, - '{{name}}, {{created | date: "%B %Y"}}', + COLUMN_LAYOUTS.listing.parse('{{name}}, {{created | date: "%B %Y"}}'), ); expect(html).toContain("April 2026"); }); @@ -281,7 +282,7 @@ describe("adminDashboardPage with column template filters", () => { [], undefined, null, - "{{name}}, {{created}}", + COLUMN_LAYOUTS.listing.parse("{{name}}, {{created}}"), ); // Default uses toLocaleDateString — locale format, not Liquid strftime expect(html).toContain("2026"); diff --git a/test/ui/templates/admin/ledger/forms.test.ts b/test/ui/templates/admin/ledger/forms.test.ts index 49ad775185..ce54a77e72 100644 --- a/test/ui/templates/admin/ledger/forms.test.ts +++ b/test/ui/templates/admin/ledger/forms.test.ts @@ -38,7 +38,7 @@ describe("ledger entry forms", () => { type: MANUAL_ATTENDEE_WRITEOFF, }, ]; - const html = defineLedgerEntryAddForm(options).renderFields({ + const html = defineLedgerEntryAddForm(options).render({ amount: "5.00", entry_type: MANUAL_ATTENDEE_CHARGE, occurred_at: "2026-06-22T09:30", diff --git a/test/ui/templates/attendee-table/template.test.ts b/test/ui/templates/attendee-table/template.test.ts index eb3a934a6a..a7e395613e 100644 --- a/test/ui/templates/attendee-table/template.test.ts +++ b/test/ui/templates/attendee-table/template.test.ts @@ -1,5 +1,6 @@ import { expect } from "@std/expect"; import { it as test } from "@std/testing/bdd"; +import { COLUMN_LAYOUTS } from "#shared/column-layout.ts"; import { AttendeeTable } from "#templates/attendee-table.tsx"; import { testAttendee } from "#test-utils/factories.ts"; import { attendeeTableSuite, makeOpts, makeRow } from "./shared.ts"; @@ -11,28 +12,28 @@ attendeeTableSuite(() => { test("renders only specified columns in template order", () => { const html = AttendeeTable( makeOpts({ - columnTemplate: "{{name}}, {{qty}}, {{registered}}", + columnLayout: COLUMN_LAYOUTS.attendee.parse( + "{{name}}, {{qty}}, {{registered}}", + ), showCheckin: false, }), ); expect(headersOf(html)).toEqual(["Name", "Qty", "Registered"]); }); - test("throws for an invalid template loaded outside the settings form", () => { - expect(() => - AttendeeTable( - makeOpts({ - columnTemplate: "{{invalid_column}}", - }), - ), - ).toThrow('Unknown column "invalid_column"'); + test("rejects an invalid template before rendering", () => { + expect(() => COLUMN_LAYOUTS.attendee.parse("{{invalid_column}}")).toThrow( + 'Unknown column "invalid_column"', + ); }); test("hides a data-dependent template column with no data", () => { const attendee = testAttendee({ email: "" }); const html = AttendeeTable( makeOpts({ - columnTemplate: "{{name}}, {{email}}, {{qty}}", + columnLayout: COLUMN_LAYOUTS.attendee.parse( + "{{name}}, {{email}}, {{qty}}", + ), rows: [makeRow({ attendee })], showCheckin: false, }), @@ -44,7 +45,9 @@ attendeeTableSuite(() => { const attendee = testAttendee({ email: "a@b.com" }); const html = AttendeeTable( makeOpts({ - columnTemplate: "{{qty}}, {{name}}, {{email}}", + columnLayout: COLUMN_LAYOUTS.attendee.parse( + "{{qty}}, {{name}}, {{email}}", + ), rows: [makeRow({ attendee })], showCheckin: false, }), @@ -56,7 +59,9 @@ attendeeTableSuite(() => { const attendee = testAttendee({ created: "2026-04-10T14:00:00Z" }); const html = AttendeeTable( makeOpts({ - columnTemplate: '{{name}}, {{registered | date: "%B %d, %Y"}}', + columnLayout: COLUMN_LAYOUTS.attendee.parse( + '{{name}}, {{registered | date: "%B %d, %Y"}}', + ), rows: [makeRow({ attendee })], showCheckin: false, }), @@ -68,7 +73,7 @@ attendeeTableSuite(() => { const attendee = testAttendee({ created: "2026-04-10T14:00:00Z" }); const html = AttendeeTable( makeOpts({ - columnTemplate: "{{name}}, {{registered}}", + columnLayout: COLUMN_LAYOUTS.attendee.parse("{{name}}, {{registered}}"), rows: [makeRow({ attendee })], showCheckin: false, }), diff --git a/test/ui/templates/fields/listing.test.ts b/test/ui/templates/fields/listing.test.ts index bd34f2db53..024147a503 100644 --- a/test/ui/templates/fields/listing.test.ts +++ b/test/ui/templates/fields/listing.test.ts @@ -14,11 +14,10 @@ import { validateDate, } from "#templates/fields/validators.ts"; import { baseListingForm } from "#test-utils/factories.ts"; +import type { TestFormValues } from "#test-utils/form-values.ts"; import { expectInvalid, expectValid } from "#test-utils/validation.ts"; -const listingForm = ( - overrides: Record = {}, -): Record => ({ +const listingForm = (overrides: TestFormValues = {}): TestFormValues => ({ ...baseListingForm, ...overrides, }); @@ -259,16 +258,20 @@ describe("listing form contact fields setting", () => { test("rejects unknown contact field name", () => { expectInvalid("Invalid contact field: invalid")( getListingForm().fields, - listingForm({ fields: "invalid" }), + listingForm({ fields: ["invalid"] }), ); }); test("accepts known contact field values", () => { // Derived from the schema, so a new ContactField member is covered here the // moment it is added — no hand-maintained list to forget to update. - for (const value of [...CONTACT_FIELDS, "email,phone"]) { - expectValid(getListingForm().fields, listingForm({ fields: value })); + for (const value of CONTACT_FIELDS) { + expectValid(getListingForm().fields, listingForm({ fields: [value] })); } + expectValid( + getListingForm().fields, + listingForm({ fields: ["email", "phone"] }), + ); }); test("warns that attendees won't be emailed their ticket without email collection", () => { @@ -332,13 +335,20 @@ describe("listing form bookable_days", () => { test("accepts valid day names", () => { expectValid( getListingForm().fields, - listingForm({ bookable_days: "Monday,Wednesday,Friday" }), + listingForm({ bookable_days: ["Monday", "Wednesday", "Friday"] }), ); expectValid( getListingForm().fields, listingForm({ - bookable_days: - "Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday", + bookable_days: [ + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday", + ], }), ); }); @@ -346,7 +356,10 @@ describe("listing form bookable_days", () => { test("rejects invalid day name", () => { expectInvalid( "Invalid day: Funday. Use: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday", - )(getListingForm().fields, listingForm({ bookable_days: "Monday,Funday" })); + )( + getListingForm().fields, + listingForm({ bookable_days: ["Monday", "Funday"] }), + ); }); test("rejects empty-after-trimming value", () => { From 47c94517470aa0e55b7a92a436ebbed615b185e1 Mon Sep 17 00:00:00 2001 From: Stefan Date: Sun, 19 Jul 2026 22:54:05 +0100 Subject: [PATCH 08/17] Reject unsafe listing day prices --- scripts/mutation/equivalent-mutants.txt | 12 ++++----- src/features/admin/api.ts | 15 +++++++++++ src/shared/types.ts | 2 +- test/features/admin/api.test.ts | 18 +++++++++++-- .../routes/admin-api-listings-update.test.ts | 25 +++++++++++++++++++ test/shared/types/day-prices.test.ts | 4 +++ 6 files changed, 67 insertions(+), 9 deletions(-) diff --git a/scripts/mutation/equivalent-mutants.txt b/scripts/mutation/equivalent-mutants.txt index a9eeac232e..297323dbd4 100644 --- a/scripts/mutation/equivalent-mutants.txt +++ b/scripts/mutation/equivalent-mutants.txt @@ -258,12 +258,12 @@ src/shared/db/built-sites.ts:391:54 ?? → || # validated optional strings us # Admin listing API fallbacks receive only objects, arrays, positive ids, or # nullish values, so no valid request can distinguish these operators. -src/features/admin/api.ts:342:66 ?? → || # stored listing lookup returns a ListingWithCount object or null; listing objects are truthy -src/features/admin/api.ts:373:25 ?? → || # parsed group ids are an array or undefined; every array, including [], is truthy -src/features/admin/api.ts:492:30 1 → 0 # the mutation changes sentinel -1 to -0; positive listing ids match neither value -src/features/admin/api.ts:534:19 ?? → || # groupIds is an array or undefined; every array, including [], is truthy -src/features/admin/api.ts:547:43 ?? → || # an existing listing id is positive and truthy, otherwise optional access yields undefined -src/features/admin/api.ts:549:38 ?? → || # groupIds is an array or undefined; every array, including [], is truthy +src/features/admin/api.ts:357:66 ?? → || # stored listing lookup returns a ListingWithCount object or null; listing objects are truthy +src/features/admin/api.ts:388:25 ?? → || # parsed group ids are an array or undefined; every array, including [], is truthy +src/features/admin/api.ts:507:30 1 → 0 # the mutation changes sentinel -1 to -0; positive listing ids match neither value +src/features/admin/api.ts:549:19 ?? → || # groupIds is an array or undefined; every array, including [], is truthy +src/features/admin/api.ts:562:43 ?? → || # an existing listing id is positive and truthy, otherwise optional access yields undefined +src/features/admin/api.ts:564:38 ?? → || # groupIds is an array or undefined; every array, including [], is truthy # Settings registry: readOnly is optional but can only be true when present, so # `"readOnly" in accessor && accessor.readOnly` and `... || accessor.readOnly` diff --git a/src/features/admin/api.ts b/src/features/admin/api.ts index 5a7e40fcef..dc9e06f5dd 100644 --- a/src/features/admin/api.ts +++ b/src/features/admin/api.ts @@ -175,6 +175,21 @@ const API_BODY_FIELD_RULES: ApiBodyFieldRule[] = [ error: "duration_days must be a safe integer", schema: v.pipe(v.number(), v.safeInteger()), }, + { + apiKey: "day_prices", + error: "day_prices numeric values must be safe integers", + schema: v.pipe( + v.unknown(), + v.check( + (raw) => + typeof raw !== "object" || + raw === null || + Object.values(raw).every( + (price) => typeof price !== "number" || Number.isSafeInteger(price), + ), + ), + ), + }, ]; /** Reject malformed mapped values before they can reach domain or storage code. */ diff --git a/src/shared/types.ts b/src/shared/types.ts index 71a4db1b80..00fb90ffe0 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -264,7 +264,7 @@ export const parseDayPrices = (raw: unknown): DayPrices => { return Number.isInteger(days) && days >= 1 && days <= MAX_DURATION_DAYS && - Number.isInteger(price) && + Number.isSafeInteger(price) && price >= 0 ? { days, price } : null; diff --git a/test/features/admin/api.test.ts b/test/features/admin/api.test.ts index 882f392997..dd504f8246 100644 --- a/test/features/admin/api.test.ts +++ b/test/features/admin/api.test.ts @@ -47,7 +47,7 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { bookable_days: ["Monday"], closes_at: "2026-06-14T23:59:00Z", date: "2026-06-15T10:00:00Z", - day_prices: { 0: 900, 1: 1200 }, + day_prices: { 0: 900, 1: 0, 2: 1200 }, duration_days: 3, max_attendees: 10, max_price: 5000, @@ -60,7 +60,7 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { expect(result.input.bookableAlone).toBe(true); expect(result.input.bookableDays).toEqual(["Monday"]); expect(result.input.date).toBe("2026-06-15T10:00:00Z"); - expect(result.input.dayPrices).toEqual({ 1: 1200 }); + expect(result.input.dayPrices).toEqual({ 1: 0, 2: 1200 }); expect(result.input.durationDays).toBe(3); expect(result.input.maxPrice).toBe(5000); expect(result.input.slug).toBeTruthy(); @@ -99,6 +99,20 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { } }); + test("rejects unsafe day prices", async () => { + const result = await bodyToCreateInput({ + day_prices: { 1: Number.MAX_SAFE_INTEGER + 1 }, + max_attendees: 10, + name: "Unsafe Price", + }); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toBe( + "day_prices numeric values must be safe integers", + ); + } + }); + test("maps the use_defaults flag both ways and omits it when absent", async () => { // true/false both round-trip (so the API can opt in *and* out), and an // absent flag stays absent rather than defaulting to either value. diff --git a/test/integration/routes/admin-api-listings-update.test.ts b/test/integration/routes/admin-api-listings-update.test.ts index c47be6aae0..4d92f99a47 100644 --- a/test/integration/routes/admin-api-listings-update.test.ts +++ b/test/integration/routes/admin-api-listings-update.test.ts @@ -1,5 +1,6 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { getListingWithCount } from "#shared/db/listings/records.ts"; import { assertAdminHtml, assertJson, @@ -90,6 +91,30 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { ); }); + test("returns 400 without saving an unsafe day price", async () => { + const listing = await createTestListing({ + customisableDays: true, + dayPrices: { 1: 500 }, + durationDays: 2, + name: "Safe Prices", + }); + await assertJson( + apiRequest(`/api/admin/listings/${listing.id}`, { + body: { day_prices: { 1: Number.MAX_SAFE_INTEGER + 1 } }, + method: "PUT", + }), + 400, + (body) => { + expect(body.error).toBe( + "day_prices numeric values must be safe integers", + ); + }, + ); + expect((await getListingWithCount(listing.id))?.day_prices).toEqual({ + 1: 500, + }); + }); + test("rejects duplicate slug", async () => { const listing1 = await createTestListing({ name: "Listing One" }); const listing2 = await createTestListing({ name: "Listing Two" }); diff --git a/test/shared/types/day-prices.test.ts b/test/shared/types/day-prices.test.ts index b6fa827d09..948a08fac7 100644 --- a/test/shared/types/day-prices.test.ts +++ b/test/shared/types/day-prices.test.ts @@ -38,6 +38,10 @@ describe("parseDayPrices", () => { test("drops negative prices but keeps a zero (free) tier", () => { expect(parseDayPrices({ 1: -100, 2: 0 })).toEqual({ 2: 0 }); }); + + test("drops prices outside JavaScript's safe integer range", () => { + expect(parseDayPrices({ 1: Number.MAX_SAFE_INTEGER + 1 })).toEqual({}); + }); }); describe("availableDayCounts", () => { From 42ffc2ab3e018fe18b0062756cd89cc29456d2df Mon Sep 17 00:00:00 2001 From: stefan burke <83819576+stefan-burke@users.noreply.github.com> Date: Sun, 19 Jul 2026 22:09:18 +0000 Subject: [PATCH 09/17] Standardize nullable lookups and explicit required failures (#1867) * Normalize lookup and result contracts * Move changed integration tests into mapped suites * Map admin API tests to their source * Map listing API tests to their source * Add branch code line task * Keep required lookups at domain boundaries * Address lookup contract review feedback * Preserve optional provider and write-back outcomes * Keep cache hits stable during batch loads --- deno.json | 1 + scripts/diff-code-lines.ts | 11 +- scripts/precommit/git.ts | 2 +- src/features/admin/api-groups.ts | 154 +++++++++--------- src/features/admin/api-holidays.ts | 20 +-- src/features/admin/api.ts | 32 ++-- src/features/admin/attendee-logistics-tab.ts | 6 +- src/features/admin/attendees.ts | 7 +- src/features/admin/bulk-actions.ts | 7 +- src/features/admin/catalog-transfer/export.ts | 12 +- src/features/admin/catalog-transfer/import.ts | 31 ++-- src/features/admin/catalog-transfer/routes.ts | 11 +- src/features/admin/dashboard.ts | 7 +- src/features/admin/groups.ts | 25 +-- src/features/admin/ledger/names.ts | 4 +- src/features/admin/listings-edit.ts | 3 +- src/features/admin/listings-parents.ts | 5 +- src/features/admin/previous-bookings.ts | 4 +- src/features/admin/servicing.tsx | 7 +- src/features/admin/settings-password.ts | 6 +- src/features/admin/settings-statuses.ts | 10 +- src/features/api/payment-processing/cancel.ts | 1 - src/features/api/payment-processing/create.ts | 4 +- src/features/public/address-lookup.ts | 4 +- src/features/public/cart.ts | 4 +- src/features/public/site-nav.ts | 5 +- src/features/public/ticket-payment.ts | 8 +- src/features/public/ticket-submit/paths.ts | 6 +- src/shared/accounting/listing-money-totals.ts | 6 +- src/shared/accounting/queries.ts | 14 +- src/shared/address-lookup/easypostcodes.ts | 24 +-- src/shared/address-lookup/service.ts | 18 +- src/shared/address-lookup/types.ts | 7 +- src/shared/booking.ts | 4 +- src/shared/builder.ts | 9 +- src/shared/bunny-cdn.ts | 19 ++- src/shared/bunny-db.ts | 29 +--- src/shared/db/admin-features.ts | 10 +- src/shared/db/api-keys.ts | 2 +- src/shared/db/attendee-statuses.ts | 28 ++-- src/shared/db/attendees/balance.ts | 6 +- src/shared/db/attendees/capacity/checks.ts | 8 +- src/shared/db/attendees/servicing.ts | 9 +- src/shared/db/built-sites.ts | 12 +- src/shared/db/client.ts | 36 +++- src/shared/db/common-schema.ts | 1 - src/shared/db/define-id-table.ts | 4 +- src/shared/db/groups.ts | 2 +- src/shared/db/keyed-cache.ts | 71 ++++---- src/shared/db/link-table.ts | 11 +- src/shared/db/listing-overview-stats.ts | 8 +- src/shared/db/listing-parents.ts | 7 +- src/shared/db/listing-prices.ts | 54 +++--- src/shared/db/listings/aggregates.ts | 6 +- src/shared/db/listings/catalog.ts | 2 +- src/shared/db/listings/records.ts | 66 ++++---- src/shared/db/listings/table.ts | 2 +- src/shared/db/modifiers.ts | 7 +- src/shared/db/news-posts.ts | 2 +- src/shared/db/orphan-attendees.ts | 4 +- src/shared/db/questions/aggregates.ts | 5 +- src/shared/db/site-pages.ts | 6 +- src/shared/db/table.ts | 32 +++- src/shared/deno-deploy-api.ts | 52 +++--- src/shared/fetch.ts | 11 +- src/shared/ledger/types.ts | 5 - src/shared/ledger/validate.ts | 22 +-- src/shared/provider-types.ts | 29 +++- src/shared/required-value.ts | 8 + src/shared/rest/crud-api.ts | 82 +++++----- src/shared/rest/resource.ts | 25 +-- src/shared/result.ts | 46 ++++-- src/shared/site-db.ts | 7 +- src/shared/site-secrets.ts | 7 +- src/shared/site-update.ts | 9 +- src/shared/turso-api.ts | 9 +- src/shared/update.ts | 6 +- .../admin/api-groups.test.ts} | 2 +- .../admin/api-holidays.test.ts} | 4 +- .../admin/api.test.ts} | 20 +++ .../catalog-transfer/import/fields.test.ts | 14 +- .../catalog-transfer/import/packages.test.ts | 2 +- .../db/listings/queries.test.ts | 41 +++-- .../admin-api-listings-input-parsers.test.ts} | 52 +++--- .../routes/admin-api-listings-read.test.ts} | 0 .../routes/api-book-payments.test.ts} | 6 +- .../server/attendee-form-status.test.ts} | 10 +- .../server/builder.test.ts} | 4 +- .../server/built-sites-update.test.ts} | 9 +- .../server/built-sites.test.ts} | 10 ++ .../server}/catalog-transfer.test.ts | 82 +++++----- .../server}/demo.test.ts | 4 +- .../server/listings-create.test.ts} | 9 +- .../server/listings-error-pages.test.ts} | 4 +- .../server/reservation-edge-cases.test.ts} | 16 +- .../server/reservation-no-provider.test.ts} | 8 +- .../server/scheduled.test.ts} | 50 +++--- .../server/settings-statuses.test.ts} | 4 +- .../server}/site-assignment.test.ts | 2 +- test/lib/server-balance-helpers.ts | 4 +- test/lib/server-groups/tabs.test.ts | 30 +++- test/lib/server-reservation/helpers.ts | 4 +- test/lib/server-site-page-public.test.ts | 9 + .../address-lookup/easypostcodes.test.ts | 8 +- test/shared/address-lookup/service.test.ts | 6 +- test/shared/builder.test.ts | 52 +++--- test/shared/bunny-db.test.ts | 18 +- test/shared/db/attendee-statuses.test.ts | 24 +-- test/shared/db/attendees/balance.test.ts | 18 +- test/shared/db/client.test.ts | 31 ++++ test/shared/db/keyed-cache.test.ts | 75 +++++++-- test/shared/db/listing-parents.test.ts | 42 ++--- test/shared/db/orphan-attendees.test.ts | 6 +- test/shared/db/site-pages.test.ts | 9 +- test/shared/db/table.test.ts | 22 +++ test/shared/deno-deploy-api.test.ts | 20 +-- test/shared/ledger/validate.test.ts | 4 +- test/shared/required-value.test.ts | 27 +++ test/shared/rest/crud-api.test.ts | 9 +- test/shared/rest/resource.test.ts | 2 +- test/shared/result.test.ts | 74 ++++++++- test/shared/site-secrets.test.ts | 10 +- test/shared/turso-api.test.ts | 10 +- test/shared/update.test.ts | 5 +- test/test-utils/builder-mocks.ts | 26 +-- 125 files changed, 1255 insertions(+), 889 deletions(-) create mode 100644 src/shared/required-value.ts rename test/{admin-api-groups.test.ts => features/admin/api-groups.test.ts} (99%) rename test/{admin-api-holidays.test.ts => features/admin/api-holidays.test.ts} (98%) rename test/{admin-api-listings/update.test.ts => features/admin/api.test.ts} (94%) rename test/{shared => integration}/db/listings/queries.test.ts (87%) rename test/{admin-api-listings/input-parsers.test.ts => integration/routes/admin-api-listings-input-parsers.test.ts} (82%) rename test/{admin-api-listings/read.test.ts => integration/routes/admin-api-listings-read.test.ts} (100%) rename test/{routes/api/book-payments.test.ts => integration/routes/api-book-payments.test.ts} (98%) rename test/{lib/server-attendee-form/status.test.ts => integration/server/attendee-form-status.test.ts} (97%) rename test/{lib/server-builder.test.ts => integration/server/builder.test.ts} (99%) rename test/{lib/server-built-sites-update.test.ts => integration/server/built-sites-update.test.ts} (97%) rename test/{lib/server-built-sites.test.ts => integration/server/built-sites.test.ts} (98%) rename test/{lib => integration/server}/catalog-transfer.test.ts (93%) rename test/{shared => integration/server}/demo.test.ts (98%) rename test/{lib/server-listings/create.test.ts => integration/server/listings-create.test.ts} (94%) rename test/{lib/server-listings/error-pages-and-fallbacks.test.ts => integration/server/listings-error-pages.test.ts} (98%) rename test/{lib/server-reservation/edge-cases.test.ts => integration/server/reservation-edge-cases.test.ts} (94%) rename test/{lib/server-reservation/no-provider.test.ts => integration/server/reservation-no-provider.test.ts} (93%) rename test/{lib/server-scheduled.test.ts => integration/server/scheduled.test.ts} (77%) rename test/{lib/server-settings/statuses.test.ts => integration/server/settings-statuses.test.ts} (99%) rename test/{shared => integration/server}/site-assignment.test.ts (99%) create mode 100644 test/shared/required-value.test.ts diff --git a/deno.json b/deno.json index 828312a800..139ca095b7 100644 --- a/deno.json +++ b/deno.json @@ -23,6 +23,7 @@ "precommit:mutation": "deno run -A scripts/precommit-mutation.ts", "find-unused-src": "deno run --allow-read scripts/find-unused-src.ts", "line-counts": "deno run --allow-read=src,test scripts/line-counts.ts", + "diff-code-lines": "deno run --allow-env=PATH --allow-run=git scripts/diff-code-lines.ts", "unit-tests-report": "deno run --allow-read=src,test,deno.json scripts/unit-tests-report.ts", "upgrade": "deno run --allow-read --allow-write --allow-net scripts/safe-upgrade.ts", "backup": "deno run --env-file --allow-env --allow-read --allow-write --allow-net --allow-sys --allow-ffi scripts/backup.ts", diff --git a/scripts/diff-code-lines.ts b/scripts/diff-code-lines.ts index 5097bc6c48..0b0df771b8 100644 --- a/scripts/diff-code-lines.ts +++ b/scripts/diff-code-lines.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env -S deno run --allow-run +#!/usr/bin/env -S deno run --allow-env=PATH --allow-run=git /** * Count the changed lines of a branch's diff, split by area (src / test / other) * and by whether the line is real code or just an import / comment / blank. @@ -6,7 +6,7 @@ * only runs `git diff` and prints. * * Usage: - * deno run --allow-run scripts/diff-code-lines.ts [baseRef] + * deno run --allow-env=PATH --allow-run=git scripts/diff-code-lines.ts [baseRef] * * `baseRef` defaults to `origin/main`; the diff is `baseRef...HEAD` (the * branch's own changes since it forked, ignoring later commits on the base). @@ -17,7 +17,12 @@ import { runCommand } from "./precommit/git.ts"; const runGitDiff = async (base: string): Promise => { // --unified=0: only changed lines, no surrounding context to misclassify. - const result = await runCommand(["git", ...gitDiffArgs(base)]); + const path = Deno.env.get("PATH"); + if (path === undefined) throw new Error("PATH is required to run Git"); + const result = await runCommand(["git", ...gitDiffArgs(base)], { + clearEnv: true, + env: { PATH: path }, + }); if (!result.success) { throw new Error(`git diff failed: ${result.stderr}`); } diff --git a/scripts/precommit/git.ts b/scripts/precommit/git.ts index 30b3047e31..802d0962d7 100644 --- a/scripts/precommit/git.ts +++ b/scripts/precommit/git.ts @@ -9,7 +9,7 @@ export interface CommandResult { export type RunCommand = ( cmd: string[], - options?: { cwd?: string }, + options?: { clearEnv?: boolean; cwd?: string; env?: Record }, ) => Promise; /** Split a command into [executable, args], rejecting an empty command. */ diff --git a/src/features/admin/api-groups.ts b/src/features/admin/api-groups.ts index 23a3c16778..888b072153 100644 --- a/src/features/admin/api-groups.ts +++ b/src/features/admin/api-groups.ts @@ -28,13 +28,17 @@ import { bodyString, type DeleteBody, defineCrudApi, - type ItemResult, - type ParseResult, parseOptionalArray, parseUpdateName, parseUpdateSlug, requireStrings, } from "#shared/rest/crud-api.ts"; +import { + errorResult, + okResult, + parseOptionalResult, + type Result, +} from "#shared/result.ts"; import { normalizeSlug } from "#shared/slug.ts"; import { buildDayPrices, @@ -84,31 +88,29 @@ const STRIP_KEYS = ["slug_index"]; /** Parse one member's optional `day_prices` object into a {@link DayPrices} * map, failing closed on anything malformed: keys must be positive whole day * counts and values non-negative integer minor units. `undefined` when absent. */ -const parseMemberDayPrices = ( - raw: unknown, -): ItemResult => { - if (raw === undefined) return { value: undefined }; - if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { - return { error: "package_members day_prices must be an object" }; - } - const dayPrices = buildDayPrices(raw, (key, value) => { - const days = Number(key); - if (!/^\d+$/.test(key) || !Number.isInteger(days) || days < 1) { - return "package_members day_prices keys must be positive day counts"; - } - if (!Number.isInteger(value) || (value as number) < 0) { - return "package_members day_prices values must be non-negative integers"; +const parseMemberDayPrices = (raw: unknown): Result => + parseOptionalResult(raw, (value) => { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return errorResult("package_members day_prices must be an object"); } - return { days, price: value as number }; + const dayPrices = buildDayPrices(value, (key, price) => { + const days = Number(key); + if (!/^\d+$/.test(key) || !Number.isInteger(days) || days < 1) { + return "package_members day_prices keys must be positive day counts"; + } + if (!Number.isInteger(price) || (price as number) < 0) { + return "package_members day_prices values must be non-negative integers"; + } + return { days, price: price as number }; + }); + return typeof dayPrices === "string" + ? errorResult(dayPrices) + : okResult(dayPrices); }); - return typeof dayPrices === "string" - ? { error: dayPrices } - : { value: dayPrices }; -}; -const parsePackageMember = (item: unknown): ItemResult => { +const parsePackageMember = (item: unknown): Result => { if (typeof item !== "object" || item === null) { - return { error: "package_members entries must be objects" }; + return errorResult("package_members entries must be objects"); } const { day_prices, @@ -117,26 +119,24 @@ const parsePackageMember = (item: unknown): ItemResult => { quantity = 1, } = item as Record; if (!Number.isInteger(listing_id) || (listing_id as number) <= 0) { - return { error: "package_members listing_id must be a positive integer" }; + return errorResult("package_members listing_id must be a positive integer"); } if (price !== null && (!Number.isInteger(price) || (price as number) < 0)) { - return { - error: "package_members price must be a non-negative integer or null", - }; + return errorResult( + "package_members price must be a non-negative integer or null", + ); } if (!Number.isInteger(quantity) || (quantity as number) < 1) { - return { error: "package_members quantity must be a positive integer" }; + return errorResult("package_members quantity must be a positive integer"); } const dayPrices = parseMemberDayPrices(day_prices); - if ("error" in dayPrices) return dayPrices; - return { - value: { - dayPrices: dayPrices.value ?? {}, - listingId: listing_id as number, - price: price as number | null, - quantity: quantity as number, - }, - }; + if (!dayPrices.ok) return dayPrices; + return okResult({ + dayPrices: dayPrices.value ?? {}, + listingId: listing_id as number, + price: price as number | null, + quantity: quantity as number, + }); }; /** @@ -147,7 +147,7 @@ const parsePackageMember = (item: unknown): ItemResult => { */ const parsePackageMembers = ( body: Record, -): ParseResult => +): Result => parseOptionalArray( body.package_members, "package_members", @@ -243,7 +243,7 @@ export const groupApiRoutes = defineCrudApi({ toCreateInput: async (body) => { const required = requireStrings(body, ["name"]); if (!required.ok) return required; - const { name } = required.values; + const { name } = required.value; // A brand-new group has no `group_listings` rows yet, so member overrides // have nothing to attach to — `setGroupPackageMembers` would silently drop @@ -253,28 +253,23 @@ export const groupApiRoutes = defineCrudApi({ if (body.package_members !== undefined) { const members = parsePackageMembers(body); if (!members.ok) return members; - return { - error: - "package_members cannot be set on create; create the group, assign listings, then update it", - ok: false, - }; + return errorResult( + "package_members cannot be set on create; create the group, assign listings, then update it", + ); } const { slug, slugIndex } = await generateUniqueGroupSlug(); - return { - input: { - description: bodyString(body, "description", ""), - hidden: bodyBoolean(body, "hidden", false), - hidePackageListings: bodyBoolean(body, "hide_package_listings", false), - isPackage: bodyBoolean(body, "is_package", false), - maxAttendees: bodyNumber(body, "max_attendees", 0), - name, - slug, - slugIndex, - termsAndConditions: bodyString(body, "terms_and_conditions", ""), - }, - ok: true, - }; + return okResult({ + description: bodyString(body, "description", ""), + hidden: bodyBoolean(body, "hidden", false), + hidePackageListings: bodyBoolean(body, "hide_package_listings", false), + isPackage: bodyBoolean(body, "is_package", false), + maxAttendees: bodyNumber(body, "max_attendees", 0), + name, + slug, + slugIndex, + termsAndConditions: bodyString(body, "terms_and_conditions", ""), + }); }, toUpdateInput: async (body, existing) => { @@ -291,29 +286,26 @@ export const groupApiRoutes = defineCrudApi({ computeGroupSlugIndex, ); - return { - input: { - description: bodyString(body, "description", existing.description), - hidden: bodyBoolean(body, "hidden", existing.hidden), - hidePackageListings: bodyBoolean( - body, - "hide_package_listings", - existing.hide_package_listings, - ), - isPackage: bodyBoolean(body, "is_package", existing.is_package), - maxAttendees: bodyNumber(body, "max_attendees", existing.max_attendees), - name: parsed.name, - packageMembers: members.input, - slug, - slugIndex, - termsAndConditions: bodyString( - body, - "terms_and_conditions", - existing.terms_and_conditions, - ), - }, - ok: true, - }; + return okResult({ + description: bodyString(body, "description", existing.description), + hidden: bodyBoolean(body, "hidden", existing.hidden), + hidePackageListings: bodyBoolean( + body, + "hide_package_listings", + existing.hide_package_listings, + ), + isPackage: bodyBoolean(body, "is_package", existing.is_package), + maxAttendees: bodyNumber(body, "max_attendees", existing.max_attendees), + name: parsed.value, + packageMembers: members.value, + slug, + slugIndex, + termsAndConditions: bodyString( + body, + "terms_and_conditions", + existing.terms_and_conditions, + ), + }); }, validate: validateGroupWithPackage, validateDelete: soldHiddenPackageError, diff --git a/src/features/admin/api-holidays.ts b/src/features/admin/api-holidays.ts index f8f863ac0a..7053f0c0de 100644 --- a/src/features/admin/api-holidays.ts +++ b/src/features/admin/api-holidays.ts @@ -11,6 +11,7 @@ import { parseUpdateName, requireStrings, } from "#shared/rest/crud-api.ts"; +import { okResult } from "#shared/result.ts"; import type { Holiday } from "#shared/types.ts"; /** JSON body accepted by POST /api/admin/holidays */ @@ -39,23 +40,20 @@ export const holidayApiRoutes = defineCrudApi({ toCreateInput: (body) => { const required = requireStrings(body, ["name", "start_date", "end_date"]); if (!required.ok) return required; - const { end_date: endDate, name, start_date: startDate } = required.values; - return { input: { endDate, name, startDate }, ok: true }; + const { end_date: endDate, name, start_date: startDate } = required.value; + return okResult({ endDate, name, startDate }); }, toUpdateInput: (body, existing) => { const nameParsed = parseUpdateName(body, existing.name); if (!nameParsed.ok) return nameParsed; - const str = (key: string, fallback: string) => + const trimmedFieldOrFallback = (key: string, fallback: string) => body[key] != null ? String(body[key]).trim() : fallback; - return { - input: { - endDate: str("end_date", existing.end_date), - name: nameParsed.name, - startDate: str("start_date", existing.start_date), - }, - ok: true, - }; + return okResult({ + endDate: trimmedFieldOrFallback("end_date", existing.end_date), + name: nameParsed.value, + startDate: trimmedFieldOrFallback("start_date", existing.start_date), + }); }, validate: validateDateRange, }); diff --git a/src/features/admin/api.ts b/src/features/admin/api.ts index d53a45153b..bd8de9a509 100644 --- a/src/features/admin/api.ts +++ b/src/features/admin/api.ts @@ -48,11 +48,11 @@ import { bodyNumber, type DeleteBody, defineCrudApi, - type ParseResult, parseOptionalArray, parseUpdateName, withApiEntity, } from "#shared/rest/crud-api.ts"; +import { errorResult, okResult, type Result } from "#shared/result.ts"; import type { AdminListing, Listing, @@ -182,11 +182,11 @@ const parseDayPrices = (raw: unknown): Record => { * `[]`) replaces it. Fails closed: any non-positive-integer entry rejects the * whole request rather than being silently dropped, so a typo like * `["5"]` can't quietly clear a listing's groups. */ -const parseGroupIds = (raw: unknown): ParseResult => +const parseGroupIds = (raw: unknown): Result => parseOptionalArray(raw, "group_ids", (entry) => typeof entry === "number" && Number.isInteger(entry) && entry > 0 - ? { value: entry } - : { error: "group_ids must contain only positive integer ids" }, + ? okResult(entry) + : errorResult("group_ids must contain only positive integer ids"), ); /** Check whether a value matches the expected field type */ @@ -253,22 +253,16 @@ const existingToDefaults = (existing: ListingWithCount): FieldRecord => * the ids to `build` to finish producing the listing input. */ const withParsedGroupIds = ( body: Record, - build: (groupIds: number[] | undefined) => Promise>, -): Promise> => { + build: (groupIds: number[] | undefined) => Promise>, +): Promise> => { const groups = parseGroupIds(body.group_ids); - return groups.ok ? build(groups.input) : Promise.resolve(groups); + return groups.ok ? build(groups.value) : Promise.resolve(groups); }; -/** A successful listing-input parse result. */ -const okListingInput = (input: ListingInput): ParseResult => ({ - input, - ok: true, -}); - /** Convert JSON body to ListingInput for create (auto-generates slug) */ export const bodyToCreateInput = ( body: Record, -): Promise> => { +): Promise> => { if (typeof body.name !== "string" || body.name.trim() === "") { return Promise.resolve({ error: "name is required", ok: false }); } @@ -283,7 +277,7 @@ export const bodyToCreateInput = ( return withParsedGroupIds(body, async (groupIds) => { const { slug, slugIndex } = await generateUniqueListingSlug(); - return okListingInput({ + return okResult({ ...pickTypedFields(body, optionalFields), dayPrices: parseDayPrices(body.day_prices), groupIds, @@ -300,7 +294,7 @@ export const bodyToCreateInput = ( export const bodyToUpdateInput = async ( body: Record, resolved: ListingWithCount, -): Promise> => { +): Promise> => { // Merge the patch onto the listing's *stored* values, not the resolved view, // so an API update that doesn't touch a defaulted field can't bake the current // default into the row (mirrors the HTML edit path). The lookup row is @@ -317,7 +311,7 @@ export const bodyToUpdateInput = async ( existing.max_attendees, ); if (maxAttendees < 1) { - return { error: "max_attendees must be >= 1", ok: false }; + return errorResult("max_attendees must be >= 1"); } const { slug, slugIndex } = await parseUpdatedListingSlug( @@ -325,7 +319,7 @@ export const bodyToUpdateInput = async ( existing.slug, ); - return okListingInput({ + return okResult({ ...existingToDefaults(existing), ...pickTypedFields(body, optionalFields), dayPrices: @@ -339,7 +333,7 @@ export const bodyToUpdateInput = async ( groupIds: groupIds ?? existingGroupIds, maxAttendees, maxPrice: bodyNumber(body, "max_price", existing.max_price), - name: parsedName.name, + name: parsedName.value, slug, slugIndex, } as ListingInput); diff --git a/src/features/admin/attendee-logistics-tab.ts b/src/features/admin/attendee-logistics-tab.ts index 5beb3eb146..0a35132271 100644 --- a/src/features/admin/attendee-logistics-tab.ts +++ b/src/features/admin/attendee-logistics-tab.ts @@ -28,7 +28,7 @@ import { } from "#shared/db/attendees/overlap.ts"; import { getAttendeeNamesByIds } from "#shared/db/attendees/queries.ts"; import type { DayRange } from "#shared/db/capacity.ts"; -import { getListingNamesByIds } from "#shared/db/listings/records.ts"; +import { listingNames } from "#shared/db/listings/records.ts"; import { requireRequestPrivateKey } from "#shared/session-private-key.ts"; import { AttendeeLogisticsPanel } from "#templates/admin/attendee-logistics-tab.tsx"; @@ -87,14 +87,14 @@ const loadOtherAttendees = async ( unique(rows.map((row) => row.attendee_id)), await requireRequestPrivateKey(), ); - const listingNames = await getListingNamesByIds( + const namesByListing = await listingNames.byIds( unique(rows.map((row) => row.listing_id)), ); return rows.map((row: OverlappingBooking) => ({ attendeeId: row.attendee_id, endAt: row.end_at, endTime: row.end_time, - listingName: listingNames.get(row.listing_id)!, + listingName: namesByListing.get(row.listing_id)!, name: names.get(row.attendee_id)!, quantity: row.quantity, startAt: row.start_at, diff --git a/src/features/admin/attendees.ts b/src/features/admin/attendees.ts index a43102b237..8cbc12b281 100644 --- a/src/features/admin/attendees.ts +++ b/src/features/admin/attendees.ts @@ -17,7 +17,10 @@ import { hasActiveBookingLine, } from "#shared/db/attendees/queries.ts"; import { updateCheckedIn } from "#shared/db/attendees/update.ts"; -import { getListingWithCount } from "#shared/db/listings/records.ts"; +import { + getListingWithCount, + requireListingWithCount, +} from "#shared/db/listings/records.ts"; import { hasAnyPaymentReference } from "#shared/db/payment-references.ts"; import { ATTENDEE_DEMO_FIELDS, @@ -318,7 +321,7 @@ const resendEntries = async ( // rows exist, decrypt with the same key, and each names a live listing. rows.map(async (row) => ({ attendee: (await decryptAttendeeOrNull(row, pk))!, - listing: (await getListingWithCount(row.listing_id))!, + listing: await requireListingWithCount(row.listing_id), })), ); }; diff --git a/src/features/admin/bulk-actions.ts b/src/features/admin/bulk-actions.ts index 46974efb87..ba4760f2b2 100644 --- a/src/features/admin/bulk-actions.ts +++ b/src/features/admin/bulk-actions.ts @@ -59,6 +59,7 @@ import { buildDuplicateListingInput, deactivationOrphanedAddOnError, } from "#shared/listings-actions.ts"; +import { requireValue } from "#shared/required-value.ts"; import { sortListings } from "#shared/sort-listings.ts"; import type { AdminSession, Group, ListingWithCount } from "#shared/types.ts"; import { @@ -266,7 +267,11 @@ const handleDuplicateGroupPost = groupFormPost(async (group, form) => { // Resolve the freshly-inserted ids by their (unique) slug_index for the redirect // and the edge remap — two reads, not one per clone. - const newGroupId = (await getGroupBySlugIndex(slugIndex))!.id; + const duplicated = requireValue( + await getGroupBySlugIndex(slugIndex), + `Group with slug index ${slugIndex} does not exist`, + ); + const newGroupId = duplicated.id; const idBySlugIndex = new Map( (await getListingsByGroupId(newGroupId)).map((l) => [l.slug_index, l.id]), ); diff --git a/src/features/admin/catalog-transfer/export.ts b/src/features/admin/catalog-transfer/export.ts index 96ba4a1055..f5bbd1ee9f 100644 --- a/src/features/admin/catalog-transfer/export.ts +++ b/src/features/admin/catalog-transfer/export.ts @@ -22,8 +22,8 @@ import { getGroupDayPricesByGroupIds, } from "#shared/db/listing-prices.ts"; import { - getListingNamesByIds, getStoredListingWithCount, + listingNames, listingsTable, } from "#shared/db/listings/records.ts"; import { namedError } from "#shared/named-error.ts"; @@ -167,7 +167,7 @@ export const exportListing = async ( ), })); - const parentNames = await getListingNamesByIds(parentIds); + const parentNames = await listingNames.byIds(parentIds); const parents = mapNotNullish((parentId: number) => parentNames.get(parentId), )(parentIds); @@ -198,15 +198,15 @@ export const exportGroup = ( if (groupData instanceof CatalogExportError) return groupData; const rows = await getGroupPackagePrices(id); - const [listingNames, dayPrices] = await Promise.all([ - getListingNamesByIds(rows.map((r) => r.listing_id)), + const [namesByListing, dayPrices] = await Promise.all([ + listingNames.byIds(rows.map((r) => r.listing_id)), getGroupDayPrices(id), ]); - // Every package row references an existing listing (FK), and `listingNames` + // Every package row references an existing listing (FK), and `namesByListing` // covers exactly those ids, so the name lookup always resolves. const members: GroupMember[] = rows.map((row) => ({ - listing: listingNames.get(row.listing_id)!, + listing: namesByListing.get(row.listing_id)!, ...overrideFields( row.package_price, row.quantity, diff --git a/src/features/admin/catalog-transfer/import.ts b/src/features/admin/catalog-transfer/import.ts index c2f3613047..ee4b94f968 100644 --- a/src/features/admin/catalog-transfer/import.ts +++ b/src/features/admin/catalog-transfer/import.ts @@ -31,8 +31,8 @@ import { } from "#shared/db/listing-prices.ts"; import { getListingsById, - getListingsWithCountsByIds, listingsTable, + requireListingsWithCountsByIds, } from "#shared/db/listings/records.ts"; import type { ListingInput } from "#shared/db/listings/table.ts"; import { @@ -58,6 +58,7 @@ import { listingInputToEdge, validateListingInput, } from "#shared/listings-actions.ts"; +import { errorResult, okResult, type Result } from "#shared/result.ts"; import { seenBefore } from "#shared/seen-before.ts"; import { type AdminLevel, @@ -82,11 +83,13 @@ import { /** The result of an import attempt: the created entity's kind/id/name, or an * operator-facing error explaining what to fix. */ -export type ImportResult = - | { ok: true; kind: "listing" | "group"; id: number; name: string } - | { ok: false; error: string }; +type ImportedEntity = { + kind: "listing" | "group"; + id: number; + name: string; +}; -const fail = (error: string): ImportResult => ({ error, ok: false }); +const fail = (error: string): Result => errorResult(error); /** Resolve a list of names to ids within one entity kind, returning the ids or * the first reference that can't be resolved (missing or, on legacy duplicate @@ -348,7 +351,7 @@ const applyImportPolicy = ( const importListing = async ( transfer: ListingTransfer, adminLevel: AdminLevel | undefined, -): Promise => { +): Promise> => { const { groups: memberships, listing, parents } = transfer; if (await isNameTakenAnywhere(listing.name)) { return fail(nameTakenError(listing.name)); @@ -419,7 +422,7 @@ const importListing = async ( // insertStatement bypassed the table wrapper, so re-sync the derived `base` // price row from the just-written `unit_price` column (as afterCommit does). await syncListingPrices(id); - return { id, kind: "listing", name: input.name, ok: true }; + return okResult({ id, kind: "listing", name: input.name }); }; /** Every listing in a group must share both its type and its customisable-days @@ -447,7 +450,9 @@ const membersHomogeneous = ( return null; }; -const importGroup = async (transfer: GroupTransfer): Promise => { +const importGroup = async ( + transfer: GroupTransfer, +): Promise> => { const { group, members } = transfer; if (await isNameTakenAnywhere(group.name)) { return fail(nameTakenError(group.name)); @@ -461,9 +466,9 @@ const importGroup = async (transfer: GroupTransfer): Promise => { ); if ("error" in memberResolve) return fail(memberResolve.error); - const listings = await getListingsWithCountsByIds(memberResolve.ids); - // Members are few, so resolve each id against the loaded set directly (order - // preserved, missing dropped) rather than building an intermediate index. + const listings = await requireListingsWithCountsByIds(memberResolve.ids); + // Members are few, so resolve each required id against the loaded set + // directly, preserving order without building an intermediate index. const memberListings = mapNotNullish((id: number) => listings.find((l) => l.id === id), )(memberResolve.ids); @@ -507,7 +512,7 @@ const importGroup = async (transfer: GroupTransfer): Promise => { null, (tx, newId) => writeMembershipsTx(tx, withNewId(specs, "groupId", newId)), ); - return { id, kind: "group", name: input.name, ok: true }; + return okResult({ id, kind: "group", name: input.name }); }; /** @@ -521,7 +526,7 @@ const importGroup = async (transfer: GroupTransfer): Promise => { export const importCatalog = async ( blob: unknown, adminLevel?: AdminLevel, -): Promise => { +): Promise> => { const parsed = v.safeParse(CatalogTransferSchema, blob); if (!parsed.success) return fail(formatTransferIssues(parsed.issues)); return parsed.output.kind === "listing" diff --git a/src/features/admin/catalog-transfer/routes.ts b/src/features/admin/catalog-transfer/routes.ts index e4b9a01468..fc0b73c3a1 100644 --- a/src/features/admin/catalog-transfer/routes.ts +++ b/src/features/admin/catalog-transfer/routes.ts @@ -130,19 +130,20 @@ const handleImportPost: TypedRouteHandler<"POST /admin/catalog/import"> = const result = await importCatalog(parsed, session.adminLevel); if (!result.ok) return errorRedirect(IMPORT_PATH, result.error); + const imported = result.value; - if (result.kind === "listing") { - await logActivity(`Listing '${result.name}' imported`, result.id); + if (imported.kind === "listing") { + await logActivity(`Listing '${imported.name}' imported`, imported.id); return redirect( "/admin/listings", - t("catalog_transfer.imported_listing", { name: result.name }), + t("catalog_transfer.imported_listing", { name: imported.name }), true, ); } - await logActivity(`Group '${result.name}' imported`); + await logActivity(`Group '${imported.name}' imported`); return redirect( "/admin/groups", - t("catalog_transfer.imported_group", { name: result.name }), + t("catalog_transfer.imported_group", { name: imported.name }), true, ); }); diff --git a/src/features/admin/dashboard.ts b/src/features/admin/dashboard.ts index fc59de32a6..cef871f648 100644 --- a/src/features/admin/dashboard.ts +++ b/src/features/admin/dashboard.ts @@ -30,10 +30,7 @@ import { getSelectedAttributesForListings } from "#shared/db/attributes.ts"; import { getHiddenPackageMemberIds } from "#shared/db/groups.ts"; import { getActiveHolidays } from "#shared/db/holidays.ts"; import { getNonStandaloneChildIds } from "#shared/db/listing-parents.ts"; -import { - getAllListings, - getListingNamesByIds, -} from "#shared/db/listings/records.ts"; +import { getAllListings, listingNames } from "#shared/db/listings/records.ts"; import { settings } from "#shared/db/settings.ts"; import { getFlash } from "#shared/flash-context.ts"; import { @@ -222,7 +219,7 @@ const loadActivityLogRefs = async ( const listingIds = unique(compact(entries.map((e) => e.listing_id))); const [attendees, listings] = await Promise.all([ loadAttendeeLinkRefs(attendeeIds), - getListingNamesByIds(listingIds), + listingNames.byIds(listingIds), ]); return { attendees, listings }; }; diff --git a/src/features/admin/groups.ts b/src/features/admin/groups.ts index 44aaa9348b..ed155237c4 100644 --- a/src/features/admin/groups.ts +++ b/src/features/admin/groups.ts @@ -1,5 +1,6 @@ /* jscpd:ignore-start */ import { handlersFor } from "#routes/admin/handlers.ts"; + /** * Admin group management routes - accessible to owners and managers */ @@ -31,7 +32,7 @@ import { validateGroupListingType, } from "#shared/db/groups.ts"; import { clearImageUsesForItemStatement } from "#shared/db/images.ts"; -import { getListingWithCount } from "#shared/db/listings/records.ts"; +import { getListingsWithCountsByIds } from "#shared/db/listings/records.ts"; import { isNameTakenAnywhere } from "#shared/db/name-registry.ts"; import { clearItemEdgesStatement } from "#shared/db/site-page-items.ts"; import { @@ -42,7 +43,12 @@ import type { FormParams } from "#shared/form-data.ts"; import type { ResponseHandler } from "#shared/response-steps.ts"; import { defineNamedResource } from "#shared/rest/resource.ts"; import { generateUniqueSlug, normalizeSlug } from "#shared/slug.ts"; -import type { AdminSession, DayPrices, Group } from "#shared/types.ts"; +import type { + AdminSession, + DayPrices, + Group, + ListingWithCount, +} from "#shared/types.ts"; import { parseOptionalMinorUnits } from "#shared/validation/money.ts"; import { adminGroupDeletePage } from "#templates/admin/groups/delete.tsx"; import { adminGroupNewPage } from "#templates/admin/groups/form.tsx"; @@ -350,13 +356,8 @@ export const groupFormPost = ( * (see {@link isPackageableMember}). */ const validateListingTypesForGroup = async ( group: Group, - listingIds: number[], + listings: ListingWithCount[], ): Promise => { - const listings = compact( - await Promise.all( - listingIds.map((listingId) => getListingWithCount(listingId)), - ), - ); for (const listing of listings) { const typeError = await validateGroupListingType( group.id, @@ -382,13 +383,15 @@ const handleAddListingsToGroup = groupFormPost(async (group, form) => { .map(Number) .filter((n) => n > 0); if (listingIds.length > 0) { - const typeError = await validateListingTypesForGroup(group, listingIds); + const listings = compact(await getListingsWithCountsByIds(listingIds)); + const typeError = await validateListingTypesForGroup(group, listings); if (typeError) { return redirect(`/admin/groups/${group.id}`, typeError, false); } - await assignListingsToGroup(listingIds, group.id); + const existingListingIds = listings.map((listing) => listing.id); + await assignListingsToGroup(existingListingIds, group.id); await logActivity( - `${listingIds.length} listing(s) added to group '${group.name}'`, + `${existingListingIds.length} listing(s) added to group '${group.name}'`, ); } return redirect( diff --git a/src/features/admin/ledger/names.ts b/src/features/admin/ledger/names.ts index 9a9c66ccc7..4dc6c68654 100644 --- a/src/features/admin/ledger/names.ts +++ b/src/features/admin/ledger/names.ts @@ -7,7 +7,7 @@ import { REVENUE, type RowAccountType, } from "#shared/accounting/accounts.ts"; -import { getListingNamesByIds } from "#shared/db/listings/records.ts"; +import { listingNames } from "#shared/db/listings/records.ts"; import { getModifierNamesByIds } from "#shared/db/modifiers.ts"; import type { AccountRef, Transfer } from "#shared/ledger/types.ts"; import { @@ -45,7 +45,7 @@ export const loadLedgerNamesForAccounts = async ( const modifierIds = referencedAccountIds(accounts, MODIFIER); const [attendees, listings, modifiers] = await Promise.all([ loadAttendeeNames(attendeeIds), - getListingNamesByIds(listingIds), + listingNames.byIds(listingIds), getModifierNamesByIds(modifierIds), ]); return { diff --git a/src/features/admin/listings-edit.ts b/src/features/admin/listings-edit.ts index 37c5891216..6a93949fca 100644 --- a/src/features/admin/listings-edit.ts +++ b/src/features/admin/listings-edit.ts @@ -46,6 +46,7 @@ import { import { getListingWithCount, getStoredListingWithCount, + requireListingWithCount, } from "#shared/db/listings/records.ts"; import { settings } from "#shared/db/settings.ts"; import { @@ -200,7 +201,7 @@ const copyEdgesFromDuplicateSource = async ( }); } // The copy was just created in this request, so it always loads. - const newListing = (await getListingWithCount(newId))!; + const newListing = await requireListingWithCount(newId); const error = await copyDuplicatedChildEdges(newListing, childIds); return error ? t("listings_table.duplicate_children_dropped", { reason: error }) diff --git a/src/features/admin/listings-parents.ts b/src/features/admin/listings-parents.ts index 5658eeb97c..f3ae58c2ed 100644 --- a/src/features/admin/listings-parents.ts +++ b/src/features/admin/listings-parents.ts @@ -22,6 +22,7 @@ import { getAllListings, getListingsById, getListingWithCount, + requireListingWithCount, } from "#shared/db/listings/records.ts"; import { childOnlyAddOnName, @@ -293,7 +294,7 @@ const addChildrenToParent = async ( addChildIds: readonly number[], ): Promise => { // The parent always loads (it is a real listing referenced by an existing edge). - const parent = (await getListingWithCount(parentId))!; + const parent = await requireListingWithCount(parentId); const existing = await listingChildren.getIds(parentId); return copyDuplicatedChildEdges(parent, [...existing, ...addChildIds]); }; @@ -341,7 +342,7 @@ export const remapDuplicatedGroupEdges = async ( (childId) => idMap.get(childId) ?? childId, ); // `newId` is a clone just inserted in this request, so it always loads. - const newParent = (await getListingWithCount(newId))!; + const newParent = await requireListingWithCount(newId); const error = await copyDuplicatedChildEdges(newParent, remapped); if (error) errors.push(error); } diff --git a/src/features/admin/previous-bookings.ts b/src/features/admin/previous-bookings.ts index 2a74582452..5e2ce77001 100644 --- a/src/features/admin/previous-bookings.ts +++ b/src/features/admin/previous-bookings.ts @@ -10,7 +10,7 @@ import { } from "#shared/db/attendees/tokens.ts"; import { hashEmail, hashPhone } from "#shared/db/contact-preferences.ts"; import { getRecentBookingTokens } from "#shared/db/contact-tokens.ts"; -import { getListingNamesByIds } from "#shared/db/listings/records.ts"; +import { listingNames } from "#shared/db/listings/records.ts"; import { requireRequestPrivateKey } from "#shared/session-private-key.ts"; import type { Attendee } from "#shared/types.ts"; import type { PreviousBooking } from "#templates/admin/attendee-page.tsx"; @@ -99,7 +99,7 @@ export const loadPreviousBookings = async ( const [statuses, listingNameById] = await Promise.all([ attendeeStatuses.getAll(), - getListingNamesByIds(listingIdsFor(resolved)), + listingNames.byIds(listingIdsFor(resolved)), ]); const statusNameById = new Map( statuses.map((status) => [status.id, status.name]), diff --git a/src/features/admin/servicing.tsx b/src/features/admin/servicing.tsx index ec4417c577..9b5a27b13f 100644 --- a/src/features/admin/servicing.tsx +++ b/src/features/admin/servicing.tsx @@ -40,10 +40,7 @@ import { servicingHoldsListing, updateServicingEvent, } from "#shared/db/attendees/servicing.ts"; -import { - getAllListings, - getListingNamesByIds, -} from "#shared/db/listings/records.ts"; +import { getAllListings, listingNames } from "#shared/db/listings/records.ts"; import { applyDemoOverrides, SERVICING_DEMO_FIELDS, @@ -88,7 +85,7 @@ const loadEditPage = async ( getAllListings().then((all) => listingsForServicingEdit(all, event)), getServicingCosts(id), ]); - const costListingNames = await getListingNamesByIds( + const costListingNames = await listingNames.byIds( unique(map((cost: ServicingCostRecord) => cost.listingId)(costs)), ); return renderServicingPage({ diff --git a/src/features/admin/settings-password.ts b/src/features/admin/settings-password.ts index 1072049d68..eaae118dd4 100644 --- a/src/features/admin/settings-password.ts +++ b/src/features/admin/settings-password.ts @@ -11,6 +11,7 @@ import { logActivity } from "#shared/db/activityLog.ts"; import { settings } from "#shared/db/settings.ts"; import { getUserById, verifyUserPassword } from "#shared/db/users.ts"; import type { FormParams } from "#shared/form-data.ts"; +import { requireValue } from "#shared/required-value.ts"; import { ok } from "#shared/response.ts"; import { getChangePasswordForm } from "#templates/fields/admin.ts"; @@ -62,7 +63,10 @@ export const handleAdminSettingsPost = settingsRoute( } // Load current user (guaranteed to exist since session was just validated) - const user = (await getUserById(session.userId))!; + const user = requireValue( + await getUserById(session.userId), + `User ${session.userId} does not exist`, + ); const passwordHash = await verifyUserPassword( user, diff --git a/src/features/admin/settings-statuses.ts b/src/features/admin/settings-statuses.ts index 35c0459326..3473155de3 100644 --- a/src/features/admin/settings-statuses.ts +++ b/src/features/admin/settings-statuses.ts @@ -27,9 +27,9 @@ import { flatCollectionSwap } from "#shared/db/ordered-collection.ts"; import { getFlash } from "#shared/flash-context.ts"; import type { FormParams } from "#shared/form-data.ts"; import { validateReservationAmount } from "#shared/reservation-amount.ts"; -import type { ParseResult } from "#shared/rest/crud-api.ts"; import type { NamedOperations } from "#shared/rest/resource.ts"; -import { errorResult } from "#shared/result.ts"; +import type { Result } from "#shared/result.ts"; +import { errorResult, okResult } from "#shared/result.ts"; import { statusPages } from "#templates/admin/settings-statuses.tsx"; import { attendeeStatusPage } from "./attendee-status-page.ts"; @@ -40,7 +40,7 @@ const LIST_PATH = "/admin/settings/statuses"; /** Parse and validate the status form. */ const parseStatusForm = ( form: FormParams, -): ParseResult => { +): Result => { const isReservation = form.has("is_reservation"); const input = { isPaidDefault: form.has("is_paid_default"), @@ -58,7 +58,7 @@ const parseStatusForm = ( const error = isReservation ? validateReservationAmount(input.reservationAmount) : null; - return error ? { error, ok: false } : { input, ok: true }; + return error ? errorResult(error) : okResult(input); }; const SAVE_ERRORS: Record = { @@ -77,7 +77,7 @@ const DELETE_ERRORS: Record = { const saveStatus = async (id: number | null, form: FormParams) => { const parsed = parseStatusForm(form); if (!parsed.ok) return parsed; - const saved = await attendeeStatusWrites.save(id, parsed.input); + const saved = await attendeeStatusWrites.save(id, parsed.value); if (!saved.ok) return errorResult(SAVE_ERRORS[saved.error]); return { ok: true as const, row: saved.value }; }; diff --git a/src/features/api/payment-processing/cancel.ts b/src/features/api/payment-processing/cancel.ts index 6886744cb3..0d2ecb65b9 100644 --- a/src/features/api/payment-processing/cancel.ts +++ b/src/features/api/payment-processing/cancel.ts @@ -61,7 +61,6 @@ export const cancelPageResponse = async ( ): Promise => { const intent = extractIntent(session); const listingId = intent?.items[0]?.e ?? 0; - // Use getListingWithCount (not getListingWithCount) - we only need slug for the link const listing = await getListingWithCount(listingId); if (!listing) { logFailure( diff --git a/src/features/api/payment-processing/create.ts b/src/features/api/payment-processing/create.ts index da1c3be34f..7c5d9650fa 100644 --- a/src/features/api/payment-processing/create.ts +++ b/src/features/api/payment-processing/create.ts @@ -26,7 +26,7 @@ import type { } from "#shared/checkout-pricing.ts"; import { formatCurrency } from "#shared/currency.ts"; import { logActivity } from "#shared/db/activityLog.ts"; -import { getPublicStatusId } from "#shared/db/attendee-statuses.ts"; +import { requirePublicStatusId } from "#shared/db/attendee-statuses.ts"; import { attendeesApi } from "#shared/db/attendees/api.ts"; import { decryptSessionTokens, @@ -215,7 +215,7 @@ export const attendeeBaseFields = async ( paymentId: session.paymentReference, phone: intent.phone, special_instructions: intent.special_instructions, - statusId: await getPublicStatusId(), + statusId: await requirePublicStatusId(), }); export const logPromoCodeModifiers = async ( diff --git a/src/features/public/address-lookup.ts b/src/features/public/address-lookup.ts index 93ad996367..bc3bcec7f0 100644 --- a/src/features/public/address-lookup.ts +++ b/src/features/public/address-lookup.ts @@ -57,7 +57,7 @@ export const handleAddressLookupGet: TypedRouteHandler< // receive geolocation data. const staff = session && isStaffRole(session.adminLevel); return jsonResponse({ - addresses: outcome.addresses.map((match) => match.line), - ...(staff ? { matches: outcome.addresses } : {}), + addresses: outcome.value.map((match) => match.line), + ...(staff ? { matches: outcome.value } : {}), }); }; diff --git a/src/features/public/cart.ts b/src/features/public/cart.ts index 78bf97953c..089f9d8186 100644 --- a/src/features/public/cart.ts +++ b/src/features/public/cart.ts @@ -16,7 +16,7 @@ import { uniqueBy } from "#fp"; import { notFoundResponse } from "#routes/response.ts"; import type { PagePackage } from "#shared/booking/page-packages.ts"; -import { getListingsBySlugsBatch } from "#shared/db/listings/records.ts"; +import { getListingsBySlugs } from "#shared/db/listings/records.ts"; import type { Group, ListingWithCount } from "#shared/types.ts"; import { dropHiddenPackageMembers } from "./discovery.ts"; import { loadCartPackageBySlug } from "./groups.ts"; @@ -42,7 +42,7 @@ type CartItem = const resolveCartSlugs = async ( slugs: string[], ): Promise => { - const listings = await getListingsBySlugsBatch(slugs); + const listings = await getListingsBySlugs(slugs); const items: CartItem[] = []; const standaloneIds = new Set(); const packageGroupIds = new Set(); diff --git a/src/features/public/site-nav.ts b/src/features/public/site-nav.ts index 1d324ff53f..3ea5cfe96f 100644 --- a/src/features/public/site-nav.ts +++ b/src/features/public/site-nav.ts @@ -19,7 +19,7 @@ * keeps its link (its page serves with noindex). Page targets are always live. */ -import { filter, map, pipe, unique } from "#fp"; +import { compact, filter, map, pipe, unique } from "#fp"; import { getHiddenPackageMemberIds, groups } from "#shared/db/groups.ts"; import { getListingsWithCountsByIds } from "#shared/db/listings/records.ts"; import { hasNewsPosts } from "#shared/db/news-posts.ts"; @@ -54,10 +54,11 @@ const resolveTargets = async ( ): Promise => { const listingIds = leafIds(items, "listing"); const groupIds = leafIds(items, "group"); - const [referenced, allGroups] = await Promise.all([ + const [referencedRows, allGroups] = await Promise.all([ getListingsWithCountsByIds(listingIds), groups.cache.getAll(), ]); + const referenced = compact(referencedRows); const referencedGroups = allGroups.filter((group) => groupIds.includes(group.id), ); diff --git a/src/features/public/ticket-payment.ts b/src/features/public/ticket-payment.ts index bd34eb7dc1..ac45a73b41 100644 --- a/src/features/public/ticket-payment.ts +++ b/src/features/public/ticket-payment.ts @@ -38,7 +38,7 @@ import { orderBookings } from "#shared/booking-lines.ts"; import { bookingBatchPlan } from "#shared/checkout-complete.ts"; import type { PricedOrder } from "#shared/checkout-pricing.ts"; import { getBookableStartDates, isBookingRangeValid } from "#shared/dates.ts"; -import { getPublicStatusId } from "#shared/db/attendee-statuses.ts"; +import { requirePublicStatusId } from "#shared/db/attendee-statuses.ts"; import type { ChildAllocation, LineBooking, @@ -59,7 +59,7 @@ import { listingChildren, listingParents, } from "#shared/db/listing-parents.ts"; -import { getListingsBySlugsBatch } from "#shared/db/listings/records.ts"; +import { getListingsBySlugs } from "#shared/db/listings/records.ts"; import { getOptionalAddOns, hasPromoCodeModifiers, @@ -425,7 +425,7 @@ export const createFreeReservation = async ({ // back. A plain booking with neither legs nor stock has no plan, so it writes as // a single capacity-checked batch (createAttendeeAtomic) — concurrent free // submissions never contend on the one connection. - const statusId = await getPublicStatusId(); + const statusId = await requirePublicStatusId(); const input = { ...contact, bookings: finalBookings, @@ -525,7 +525,7 @@ export const withActiveListings = async ( slugs: string[], handler: ResponseHandler<[listings: TicketListing[]]>, ): Promise => { - const listings = await getListingsBySlugsBatch(slugs); + const listings = await getListingsBySlugs(slugs); const active = compact(listings).filter((e) => e.active); const activeListings = await buildTicketListingsWithGroupCapacity(active); if (activeListings.length === 0) return notFoundResponse(); diff --git a/src/features/public/ticket-submit/paths.ts b/src/features/public/ticket-submit/paths.ts index 175bf552cd..9e030974e9 100644 --- a/src/features/public/ticket-submit/paths.ts +++ b/src/features/public/ticket-submit/paths.ts @@ -13,7 +13,7 @@ import type { TicketPaymentBreakdown, } from "#shared/checkout-pricing.ts"; import { hmacHash } from "#shared/crypto/hashing.ts"; -import { getPublicDefaultStatus } from "#shared/db/attendee-statuses.ts"; +import { requirePublicDefaultStatus } from "#shared/db/attendee-statuses.ts"; import type { ChildAllocation } from "#shared/db/attendee-types.ts"; import { groupListingAnswerSets, @@ -83,8 +83,8 @@ export const handlePaidPath = async ( export const publicReservationAmount = async (): Promise< string | undefined > => { - const status = await getPublicDefaultStatus(); - return status?.is_reservation && status.reservation_amount + const status = await requirePublicDefaultStatus(); + return status.is_reservation && status.reservation_amount ? status.reservation_amount : undefined; }; diff --git a/src/shared/accounting/listing-money-totals.ts b/src/shared/accounting/listing-money-totals.ts index dd846783ac..3d563794f9 100644 --- a/src/shared/accounting/listing-money-totals.ts +++ b/src/shared/accounting/listing-money-totals.ts @@ -11,7 +11,7 @@ import { type LedgerRange, occurredAtRange, } from "#shared/accounting/range.ts"; -import { queryOne } from "#shared/db/client.ts"; +import { requireOne } from "#shared/db/client.ts"; export type ListingMoneyTotals = { externalCosts: number; @@ -68,7 +68,7 @@ export const listingMoneyTotals = async ( const r = occurredAtRange(range, "transfer.occurred_at"); // An aggregate without GROUP BY always returns one row; COALESCE supplies // zeroes when no transfers match, so the result cannot be null. - const row = (await queryOne( + const row = await requireOne( `WITH selected_listing(id) AS (VALUES ${listingIds.map(() => "(?)").join(", ")}) SELECT COUNT(*) AS transfer_count, @@ -99,7 +99,7 @@ export const listingMoneyTotals = async ( r.clause, )}`, [...listingIds.map(String), ...r.args], - ))!; + ); const grossSales = Number(row.gross_sales); const externalIncome = Number(row.external_income); const manualAdjustments = Number(row.manual_adjustments); diff --git a/src/shared/accounting/queries.ts b/src/shared/accounting/queries.ts index 36c22305c1..ae4d7c44d0 100644 --- a/src/shared/accounting/queries.ts +++ b/src/shared/accounting/queries.ts @@ -43,7 +43,7 @@ import { import { inPlaceholders, queryAll, - queryOne, + requireOne, resultRows, rowExists, type TxScope, @@ -156,13 +156,13 @@ export const transferActivityBounds = async (): Promise<{ } | null> => { // An ungrouped aggregate always yields exactly one row; MIN and MAX are NULL // together iff the table is empty. - const row = (await queryOne<{ + const row = await requireOne<{ min_ms: number | bigint | null; max_ms: number | bigint | null; }>( "SELECT MIN(occurred_at) AS min_ms, MAX(occurred_at) AS max_ms FROM transfers", [], - ))!; + ); if (row.min_ms === null || row.max_ms === null) return null; return { maxMs: Number(row.max_ms), minMs: Number(row.min_ms) }; }; @@ -204,7 +204,7 @@ export const ledgerTotals = async ( ): Promise => { const r = occurredAtRange(range); // An ungrouped aggregate always yields exactly one row. - const row = (await queryOne( + const row = await requireOne( `SELECT COALESCE(SUM(CASE WHEN kind = '${KIND.sale}' AND dest_type = '${REVENUE}' THEN amount @@ -217,7 +217,7 @@ export const ledgerTotals = async ( ${signedSumCase(`dest_type = '${FEE_INCOME}'`, `source_type = '${FEE_INCOME}'`)} AS fees FROM transfers${wherePrefixed(r.clause)}`, r.args, - ))!; + ); return { due: Number(row.due), fees: Number(row.fees), @@ -294,11 +294,11 @@ export const accountBalance = async (acct: AccountRef): Promise => { // Each predicate binds (type, id) and appears four times — both CASE arms and // both WHERE arms — so the account's pair repeats four times, in that order. const pair: InValue[] = [acct.type, acct.id]; - const row = (await queryOne<{ balance: number | bigint }>( + const row = await requireOne<{ balance: number | bigint }>( `SELECT ${signedSumCase(asDest, asSource)} AS balance` + ` FROM transfers WHERE ${asDest} OR ${asSource}`, [...pair, ...pair, ...pair, ...pair], - ))!; + ); return Number(row.balance); }; diff --git a/src/shared/address-lookup/easypostcodes.ts b/src/shared/address-lookup/easypostcodes.ts index 30c12292eb..1d80221688 100644 --- a/src/shared/address-lookup/easypostcodes.ts +++ b/src/shared/address-lookup/easypostcodes.ts @@ -9,13 +9,9 @@ import * as v from "valibot"; import { mapNotNullish } from "#fp"; -import type { ApiResult } from "#shared/fetch.ts"; import { fetchText, parseApiError } from "#shared/fetch.ts"; -import type { - AddressLookupProviderDefinition, - AddressLookupResult, - AddressMatch, -} from "./types.ts"; +import { errorResult, okResult, type Result } from "#shared/result.ts"; +import type { AddressLookupProviderDefinition, AddressMatch } from "./types.ts"; const API_BASE = "https://api.easypostcodes.com/addresses/"; @@ -87,7 +83,7 @@ export const parseEasypostcodesBody = (body: string): AddressMatch[] | null => { export const fetchEasypostcodesAddresses = async ( search: string, apiKey: string, -): Promise> => { +): Promise> => { let response: Awaited>; try { response = await fetchText( @@ -95,23 +91,17 @@ export const fetchEasypostcodesAddresses = async ( { headers: { Key: apiKey } }, ); } catch (error) { - return { - error: `EasyPostcodes lookup failed: ${String(error)}`, - ok: false, - }; + return errorResult(`EasyPostcodes lookup failed: ${String(error)}`); } // An unknown-but-well-formed postcode is a normal "no matches" outcome, not // a provider failure — return (and cache) the empty list. - if (response.status === 404) return { addresses: [], ok: true }; + if (response.status === 404) return okResult([]); if (!response.ok) return parseApiError(response, "EasyPostcodes lookup"); const addresses = parseEasypostcodesBody(response.text); if (addresses === null) { - return { - error: "EasyPostcodes lookup returned an unexpected response", - ok: false, - }; + return errorResult("EasyPostcodes lookup returned an unexpected response"); } - return { addresses, ok: true }; + return okResult(addresses); }; /** The EasyPostcodes provider definition. */ diff --git a/src/shared/address-lookup/service.ts b/src/shared/address-lookup/service.ts index ad3ee35f76..fbeaf6ba19 100644 --- a/src/shared/address-lookup/service.ts +++ b/src/shared/address-lookup/service.ts @@ -17,35 +17,31 @@ import { } from "#shared/db/address-cache.ts"; import { settings } from "#shared/db/settings.ts"; import { ErrorCode, logError } from "#shared/logger.ts"; +import { errorResult, okResult, type Result } from "#shared/result.ts"; import { ADDRESS_LOOKUP_PROVIDERS } from "./providers.ts"; import type { AddressLookupProvider, AddressMatch } from "./types.ts"; -/** What a lookup reports back to the HTTP route. */ -export type AddressLookupOutcome = - | { ok: true; addresses: AddressMatch[] } - | { ok: false; error: string }; - /** Look up the addresses for a raw search, serving from cache when fresh. */ export const lookupAddresses = async ( provider: AddressLookupProvider, rawSearch: string, -): Promise => { +): Promise> => { const definition = ADDRESS_LOOKUP_PROVIDERS[provider]; const normalised = definition.normaliseSearch(rawSearch); if (normalised === null) { - return { error: t("address_lookup.invalid_search"), ok: false }; + return errorResult(t("address_lookup.invalid_search")); } const searchIndex = await computeAddressSearchIndex(provider, normalised); const cached = await getCachedAddresses(searchIndex); - if (cached !== null) return { addresses: cached, ok: true }; + if (cached !== null) return okResult(cached); const result = await definition.fetchAddresses( normalised, settings.addressLookup.apiKey, ); if (!result.ok) { logError({ code: ErrorCode.ADDRESS_LOOKUP, detail: result.error }); - return { error: t("address_lookup.failed"), ok: false }; + return errorResult(t("address_lookup.failed")); } - await storeCachedAddresses(searchIndex, result.addresses); - return { addresses: result.addresses, ok: true }; + await storeCachedAddresses(searchIndex, result.value); + return okResult(result.value); }; diff --git a/src/shared/address-lookup/types.ts b/src/shared/address-lookup/types.ts index 31d5a928b4..2f60c7c515 100644 --- a/src/shared/address-lookup/types.ts +++ b/src/shared/address-lookup/types.ts @@ -14,7 +14,7 @@ */ import * as v from "valibot"; -import type { ApiResult } from "#shared/fetch.ts"; +import type { Result } from "#shared/result.ts"; import { guardFor } from "#shared/validation/guard.ts"; /** Schema for the stored provider setting ("none" disables lookups). */ @@ -38,9 +38,6 @@ export type AddressLookupProvider = Exclude; * latitude/longitude when it knows them ("" when it doesn't). */ export type AddressMatch = { line: string; lat: string; lng: string }; -/** A successful search: one match per address the provider found. */ -export type AddressLookupResult = { addresses: AddressMatch[] }; - /** Everything one lookup provider knows how to do. */ export type AddressLookupProviderDefinition = { /** Provider name shown in the settings picklist (a brand, not translated). */ @@ -58,5 +55,5 @@ export type AddressLookupProviderDefinition = { fetchAddresses: ( search: string, apiKey: string, - ) => Promise>; + ) => Promise>; }; diff --git a/src/shared/booking.ts b/src/shared/booking.ts index adfe33684f..55c549dcc4 100644 --- a/src/shared/booking.ts +++ b/src/shared/booking.ts @@ -9,7 +9,7 @@ import { mapBooking } from "#shared/accounting/mappers.ts"; import { postBookingLegsTx } from "#shared/checkout-complete.ts"; import { isPaymentsEnabled } from "#shared/config.ts"; -import { getPublicStatusId } from "#shared/db/attendee-statuses.ts"; +import { requirePublicStatusId } from "#shared/db/attendee-statuses.ts"; import { attendeesApi } from "#shared/db/attendees/api.ts"; import type { LedgerPoster } from "#shared/db/attendees/create.ts"; import { nowIso } from "#shared/now.ts"; @@ -134,7 +134,7 @@ export const processBooking = async ( }, ], remainingBalance, - statusId: await getPublicStatusId(), + statusId: await requirePublicStatusId(), }, // An owed booking must record its balance in the ledger at creation, since // the outstanding balance projects from it: post the booking's gross sale diff --git a/src/shared/builder.ts b/src/shared/builder.ts index bf6ca5492b..27a7ee1264 100644 --- a/src/shared/builder.ts +++ b/src/shared/builder.ts @@ -197,7 +197,10 @@ const getDbCredentials = async ( const dbResult = await builderApi.createDatabase(input.siteName, provider); if (!dbResult.ok) return dbResult; return { - credentials: { dbToken: dbResult.dbToken, dbUrl: dbResult.dbUrl }, + credentials: { + dbToken: dbResult.value.dbToken, + dbUrl: dbResult.value.dbUrl, + }, dbProvider: provider, ok: true, }; @@ -230,8 +233,8 @@ const buildSiteOnProvider = async ( dbProvider, dbToken: dbCredentials.dbToken, dbUrl: dbCredentials.dbUrl, - defaultHostname: result.defaultHostname, - hostingId: result.hostingId, + defaultHostname: result.value.defaultHostname, + hostingId: result.value.hostingId, hostingProvider, ok: true, }; diff --git a/src/shared/bunny-cdn.ts b/src/shared/bunny-cdn.ts index 10bd2e1ba4..85cb8692cf 100644 --- a/src/shared/bunny-cdn.ts +++ b/src/shared/bunny-cdn.ts @@ -15,6 +15,7 @@ import { type FetchResult, fetchText, parseApiError } from "#shared/fetch.ts"; import { ErrorCode, logDebug, logError } from "#shared/logger.ts"; import { delay } from "#shared/now.ts"; import type { HostingProviderApi } from "#shared/provider-types.ts"; +import { errorResult, okResult, type Result } from "#shared/result.ts"; const BUNNY_API_BASE = "https://api.bunny.net"; @@ -614,23 +615,20 @@ export const bunnyHostingProvider: HostingProviderApi = { } const publishResult = await bunnyCdnApi.publishEdgeScript(scriptId); if (!publishResult.ok) return publishResult; - return { defaultHostname, hostingId: String(scriptId), ok: true as const }; + return okResult({ defaultHostname, hostingId: String(scriptId) }); }, async getSecretNames(hostingId) { const result = await bunnyCdnApi.listEdgeScriptSecrets(Number(hostingId)); - return result.ok - ? { names: result.secrets.map((s) => s.Name), ok: true as const } - : result; + return result.ok ? okResult(result.secrets.map((s) => s.Name)) : result; }, async setSecrets(hostingId, secrets) { const scriptId = Number(hostingId); - if (Number.isNaN(scriptId)) - return { error: "No hostingId", ok: false as const }; + if (Number.isNaN(scriptId)) return errorResult("No hostingId"); for (const [name, value] of secrets) { const r = await bunnyCdnApi.setEdgeScriptSecret(scriptId, name, value); if (!r.ok) return r; } - return { ok: true as const }; + return okResult(undefined); }, }; @@ -672,7 +670,10 @@ export const getCdnHostname = (): Promise => /** Upload and publish new script code to a Bunny edge script (defaults to this * host's own script when `scriptId` is omitted). */ -export const deployScriptCode = ( +export const deployScriptCode = async ( code: string, scriptId?: number | string, -): Promise => bunnyCdnApi.deployScriptCode(code, scriptId); +): Promise> => { + const result = await bunnyCdnApi.deployScriptCode(code, scriptId); + return result.ok ? okResult(undefined) : errorResult(result.error); +}; diff --git a/src/shared/bunny-db.ts b/src/shared/bunny-db.ts index d8fcf65af1..3ce9cefc9b 100644 --- a/src/shared/bunny-db.ts +++ b/src/shared/bunny-db.ts @@ -9,11 +9,13 @@ import * as v from "valibot"; import { parseBunnyError } from "#shared/bunny-cdn.ts"; import { getBunnyApiKey } from "#shared/config.ts"; -import { type ApiResult, fetchText, jsonHeaders } from "#shared/fetch.ts"; +import { fetchText, jsonHeaders } from "#shared/fetch.ts"; import type { CreateDatabaseFn, DatabaseProviderApi, } from "#shared/provider-types.ts"; +import { databaseCredentialsFromResponse } from "#shared/provider-types.ts"; +import { okResult, type Result } from "#shared/result.ts"; const DB_API_BASE = "https://api.bunny.net/database"; @@ -47,16 +49,6 @@ interface GetDbResponse { }; } -interface GenerateTokenResponse { - token: string; -} - -export interface CreateDatabaseResult { - dbId: string; - dbToken: string; - dbUrl: string; -} - /** Headers for all Bunny Database API requests. */ const dbApiHeaders = (): Record => jsonHeaders({ AccessKey: getBunnyApiKey() }); @@ -72,7 +64,7 @@ const regionIds = (regions: RegionConfig[]): string[] => * change needed when Bunny adds a server. */ const getAllRegions = async (): Promise< - ApiResult<{ primaryRegions: string[]; replicaRegions: string[] }> + Result<{ primaryRegions: string[]; replicaRegions: string[] }> > => { const res = await fetchText(`${DB_API_BASE}/v1/config`, { headers: dbApiHeaders(), @@ -83,11 +75,10 @@ const getAllRegions = async (): Promise< } const config = v.parse(DbConfigResponseSchema, JSON.parse(res.text)); - return { - ok: true, + return okResult({ primaryRegions: regionIds(config.primary_regions), replicaRegions: regionIds(config.replica_regions), - }; + }); }; /** @@ -105,8 +96,8 @@ const createDatabaseImpl: CreateDatabaseFn = async (name) => { const createRes = await fetchText(`${DB_API_BASE}/v2/databases`, { body: JSON.stringify({ name, - primary_regions: regions.primaryRegions, - replicas_regions: regions.replicaRegions, + primary_regions: regions.value.primaryRegions, + replicas_regions: regions.value.replicaRegions, storage_region: STORAGE_REGION, }), headers: dbApiHeaders(), @@ -147,9 +138,7 @@ const createDatabaseImpl: CreateDatabaseFn = async (name) => { return parseBunnyError(tokenRes, "Generate database token"); } - const tokenData: GenerateTokenResponse = JSON.parse(tokenRes.text); - - return { dbId, dbToken: tokenData.token, dbUrl, ok: true }; + return databaseCredentialsFromResponse(dbId, dbUrl, tokenRes.text, "token"); }; export const bunnyDbProvider: DatabaseProviderApi = { diff --git a/src/shared/db/admin-features.ts b/src/shared/db/admin-features.ts index cd7908b004..23dcc05bd8 100644 --- a/src/shared/db/admin-features.ts +++ b/src/shared/db/admin-features.ts @@ -15,6 +15,7 @@ import { executeBatchWithResults, queryOne, queryOnePrimary, + requireOnePrimary, resultRows, type SqlStatement, } from "#shared/db/client.ts"; @@ -230,12 +231,11 @@ const saveLogisticsDisable = async ( }; const validateStoredFeatureSetting = async (): Promise => { - const row = v.parse( - StoredValueSchema, - await queryOnePrimary("SELECT value FROM settings WHERE key = ?", [ - CONFIG_KEYS.ENABLED_FEATURES, - ]), + const stored = await requireOnePrimary( + "SELECT value FROM settings WHERE key = ?", + [CONFIG_KEYS.ENABLED_FEATURES], ); + const row = v.parse(StoredValueSchema, stored); parseEnabledFeatures(row.value); }; diff --git a/src/shared/db/api-keys.ts b/src/shared/db/api-keys.ts index 6cd0635d97..5e0bcc7b03 100644 --- a/src/shared/db/api-keys.ts +++ b/src/shared/db/api-keys.ts @@ -134,7 +134,7 @@ export const getApiKeyForUser = async ( id: number, userId: number, ): Promise<{ id: number; name: string }> => { - const decrypted = await apiKeyNameProjection.queryOneOrNull( + const decrypted = await apiKeyNameProjection.queryOne( `SELECT ${apiKeyNameProjection.columnsSql()} FROM api_keys WHERE id = ? AND user_id = ?`, [id, userId], ); diff --git a/src/shared/db/attendee-statuses.ts b/src/shared/db/attendee-statuses.ts index 11da4858cd..a34f58b1d9 100644 --- a/src/shared/db/attendee-statuses.ts +++ b/src/shared/db/attendee-statuses.ts @@ -20,6 +20,7 @@ import { import type { NamedSortOrderInput } from "#shared/db/common-schema.ts"; import { defineOrderedCollection } from "#shared/db/ordered-collection.ts"; import { col, defineCachedListTable, writeTableRow } from "#shared/db/table.ts"; +import { requireValue } from "#shared/required-value.ts"; import { errorResult, okResult, type Result } from "#shared/result.ts"; /** Name of the status seeded on first run so there is always at least one. */ @@ -93,23 +94,26 @@ const findStatus = async ( export const getAttendeeStatus = (id: number): Promise => findStatus((s) => s.id === id); -/** The first status whose given default flag is set (decrypted), or null. */ -const findFlaggedStatus = +/** Get the status carrying a required default flag. */ +const getFlaggedStatus = (flag: "is_public_default" | "is_paid_default") => - (): Promise => - findStatus((s) => s[flag]); + async (): Promise => + requireValue( + await findStatus((item) => item[flag]), + `No attendee status has the required ${flag} flag`, + ); -/** The status new public bookings start in, or null if none is flagged. */ -export const getPublicDefaultStatus = findFlaggedStatus("is_public_default"); +/** The status new public bookings start in. */ +export const requirePublicDefaultStatus: () => Promise = + getFlaggedStatus("is_public_default"); /** The status an attendee moves to once a reservation balance is paid. */ -export const getPaidDefaultStatus = findFlaggedStatus("is_paid_default"); +export const requirePaidDefaultStatus: () => Promise = + getFlaggedStatus("is_paid_default"); -/** The id of the public-default status, or null if none is configured. */ -export const getPublicStatusId = async (): Promise => { - const status = await getPublicDefaultStatus(); - return status === null ? null : status.id; -}; +/** The id of the public-default status. */ +export const requirePublicStatusId = async (): Promise => + (await requirePublicDefaultStatus()).id; type DefaultRow = { is_paid_default: number; diff --git a/src/shared/db/attendees/balance.ts b/src/shared/db/attendees/balance.ts index 7ca6682784..0d9f331760 100644 --- a/src/shared/db/attendees/balance.ts +++ b/src/shared/db/attendees/balance.ts @@ -25,7 +25,7 @@ import { decrypt } from "#shared/crypto/encryption.ts"; import type { EnvKeyEncrypted } from "#shared/crypto/sealed.ts"; import { formatCurrency } from "#shared/currency.ts"; import { logActivity } from "#shared/db/activityLog.ts"; -import { getPaidDefaultStatus } from "#shared/db/attendee-statuses.ts"; +import { requirePaidDefaultStatus } from "#shared/db/attendee-statuses.ts"; import { ATTENDEE_KIND } from "#shared/db/attendees/kind.ts"; import { remainingBalanceFromLedger } from "#shared/db/attendees/select.ts"; import { @@ -203,7 +203,7 @@ export const settleAttendeeBalance = async ( return { reason: "nothing_owed", settled: false }; } - const paid = await getPaidDefaultStatus(); + const paid = await requirePaidDefaultStatus(); // The attendee's outstanding balance, projected from the ledger, used as an // atomic guard: both writes below fire only while they still owe exactly // `expectedAmount`. A concurrent settle whose payment leg already landed sees @@ -220,7 +220,7 @@ export const settleAttendeeBalance = async ( { // Lifecycle move: only reservations advance to the paid default. Other // statuses are operator-owned and stay put once their balance is cleared. - args: [paid?.id ?? null, attendeeId, expectedAmount], + args: [paid.id, attendeeId, expectedAmount], sql: `UPDATE attendees SET status_id = COALESCE(?, status_id) WHERE id = ? AND status_id IN ( diff --git a/src/shared/db/attendees/capacity/checks.ts b/src/shared/db/attendees/capacity/checks.ts index afb6e5237d..890ac8eb01 100644 --- a/src/shared/db/attendees/capacity/checks.ts +++ b/src/shared/db/attendees/capacity/checks.ts @@ -11,7 +11,7 @@ import { buildCapacityCondition, type CapacityBucket, } from "#shared/db/capacity.ts"; -import { inPlaceholders, queryAll, queryOne } from "#shared/db/client.ts"; +import { inPlaceholders, queryAll, requireOne } from "#shared/db/client.ts"; import { listingGroups } from "#shared/db/groups.ts"; import { getListingWithCount } from "#shared/db/listings/records.ts"; import { dateToStartEnd, expandDailyRange } from "./range.ts"; @@ -78,10 +78,10 @@ export const checkLinesCapacity = async ( .map((condition, index) => `(${condition.sql}) AS ok${index}`) .join(", "); const args = conditions.flatMap((condition) => condition.args); - const row = (await queryOne>( + const row = await requireOne>( `SELECT ${columns}`, args, - ))!; + ); return conditions.map((_, index) => row[`ok${index}`] === 1); }; @@ -185,6 +185,6 @@ export const checkBatchAvailabilityImpl = async ( listingGroups.idsFor(membership, item.listingId), ); const { sql, args } = buildBatchCapacitySql(listingDemand, groupDemand); - const row = (await queryOne<{ fits: number }>(sql, args))!; + const row = await requireOne<{ fits: number }>(sql, args); return row.fits === 1; }; diff --git a/src/shared/db/attendees/servicing.ts b/src/shared/db/attendees/servicing.ts index f01163c0ef..94516e18e8 100644 --- a/src/shared/db/attendees/servicing.ts +++ b/src/shared/db/attendees/servicing.ts @@ -37,9 +37,10 @@ import { inPlaceholders, queryAll, queryOne, + requireOne, withTransaction, } from "#shared/db/client.ts"; -import { getListingNamesByIds } from "#shared/db/listings/records.ts"; +import { listingNames } from "#shared/db/listings/records.ts"; import { type AttendeeAnswersBatch, getAttendeeAnswersBatch, @@ -156,7 +157,7 @@ const formatServicingCapacityError = capacityErrorFormatter({ /** The comma-joined names of the given listing ids, dropping any id whose * listing has since been deleted (a name lookup miss) rather than throwing. */ const joinedListingNames = async (ids: number[]): Promise => { - const names = await getListingNamesByIds(ids); + const names = await listingNames.byIds(ids); return ids .map((id) => names.get(id)) .filter((name): name is string => Boolean(name)) @@ -701,11 +702,11 @@ export const recordServiceCost = async ( "SELECT ?, ?, id, ?, ?, ? FROM transfers WHERE reference = ?", }); }); - const row = await queryOne<{ id: number }>( + const row = await requireOne<{ id: number }>( "SELECT id FROM transfers WHERE reference = ?", [transfer.reference], ); - return row!.id; + return row.id; }; /** The narrow transfers columns a service-cost read needs: the row's id and diff --git a/src/shared/db/built-sites.ts b/src/shared/db/built-sites.ts index 45c9a47b17..b6ce91beb0 100644 --- a/src/shared/db/built-sites.ts +++ b/src/shared/db/built-sites.ts @@ -474,12 +474,16 @@ export const builtSitesCrudTable: Table = { findAll: (): Promise => builtSites.getAll(), findById: async (id: InValue): Promise => { - // findById already decrypts via fromDb internally const row = await rawBuiltSitesTable.findById(id); if (!row) return null; return rowToBuiltSite(row); }, + findByIds: async (ids: InValue[]): Promise<(BuiltSite | null)[]> => + (await rawBuiltSitesTable.findByIds(ids)).map((row) => + row === null ? null : rowToBuiltSite(row), + ), + // findByIdPrimary is intentionally omitted: it is optional on Table (like // insertStatement/updateStatement) and only used on the transactional // afterWrite write-back path, which this façade resource never takes. @@ -499,6 +503,7 @@ export const builtSitesCrudTable: Table = { _col: K, value: BuiltSite[K], ): Promise => Promise.resolve(value), + // The CRUD adapter is a façade over the raw table — the built-site blob // is always reconstructed from BuiltSiteFormInput, so rowToInput just picks // the exposed camelCase fields off an already-decrypted BuiltSite. @@ -565,7 +570,10 @@ export const claimNextBuiltSiteForPrune = async (): Promise<{ id: number; siteUrl: string; } | null> => { - const row = await queryOne<{ id: number; site_data: EnvKeyEncrypted }>( + const row = await queryOne<{ + id: number; + site_data: EnvKeyEncrypted; + }>( `UPDATE built_sites AS builtSite SET last_pruned = ? WHERE builtSite.id = ( SELECT candidate.id FROM built_sites AS candidate diff --git a/src/shared/db/client.ts b/src/shared/db/client.ts index 1e41e712c3..02e8497d9e 100644 --- a/src/shared/db/client.ts +++ b/src/shared/db/client.ts @@ -256,6 +256,7 @@ const executeTrackedStatement: StatementRunner = (sql, args) => /** A SQL statement and its optional bound args — the shared parameters of the * single-statement query and write helpers below. */ type SqlArgs = [sql: string, args?: InValue[]]; +type SqlWithArgs = [sql: string, args: InValue[]]; /** * Run a single statement: track it for the query log / N+1 guard, then fire any @@ -295,13 +296,32 @@ const executeRead = async (...[sql, args]: SqlArgs): Promise => { return result!; }; -/** Query single row, returning null if not found */ +/** Query all rows, returning a typed array. */ +export const queryAll = async (...[sql, args]: SqlArgs): Promise => + resultRows(await executeRead(sql, args)); + +/** Query one row, or null when the query returns none. */ export const queryOne = async (...[sql, args]: SqlArgs): Promise => - firstRowOrNull(await executeRead(sql, args)); + (await queryAll(sql, args))[0] ?? null; + +const requireQueryRow = async ( + row: Promise, + sql: string, + label: string, +): Promise => { + const found = await row; + if (found === null) + throw new Error(`${label} query returned no rows: ${sql}`); + return found; +}; + +/** Query one required row and name the failed query when none exists. */ +export const requireOne = (...[sql, args]: SqlArgs): Promise => + requireQueryRow(queryOne(sql, args), sql, "Required"); /** - * Query a single row on the primary (read-your-writes), returning null if not - * found. Use this to read a row back immediately after committing its own write: + * Query an optional row on the primary (read-your-writes). Use this to read a + * row back immediately after committing its own write: * a plain {@link queryOne} runs in "read" mode, which Turso can route to a * replica lagging the just-committed write and so miss the row (returning null); * routing through {@link queryBatchPrimary} ("write" mode) always hits the @@ -316,9 +336,9 @@ export const queryOnePrimary = async ( return firstRowOrNull(result!); }; -/** Query all rows, returning a typed array */ -export const queryAll = async (...[sql, args]: SqlArgs): Promise => - resultRows(await executeRead(sql, args)); +/** Query one required row from the primary. */ +export const requireOnePrimary = (...[sql, args]: SqlWithArgs): Promise => + requireQueryRow(queryOnePrimary(sql, args), sql, "Required primary"); /** * True when the query returns at least one row. `sql` should be an existence @@ -356,7 +376,7 @@ export const queryIdColumn = async ( /** Count all rows in a table. `table` must be a trusted constant, not input. */ export const countRows = async (table: string): Promise => { // COUNT(*) always returns exactly one row, so the result is never null. - const row = await queryOne<{ n: number }>( + const row = await requireOne<{ n: number }>( `SELECT COUNT(*) AS n FROM ${table}`, [], ); diff --git a/src/shared/db/common-schema.ts b/src/shared/db/common-schema.ts index 2029bb81a1..9aee0eaa83 100644 --- a/src/shared/db/common-schema.ts +++ b/src/shared/db/common-schema.ts @@ -12,7 +12,6 @@ import { } from "#shared/db/keyed-cache.ts"; import { type ColumnDef, col, type Table } from "#shared/db/table.ts"; -export { defineIdTable } from "#shared/db/define-id-table.ts"; // Re-exported for users.ts, which caches a table-less query and so wires the // cache by hand rather than through cachedEntityTable. export { createKeyedCache, registerCache, registerTableInvalidation }; diff --git a/src/shared/db/define-id-table.ts b/src/shared/db/define-id-table.ts index 29fce435c1..8ed246c9f7 100644 --- a/src/shared/db/define-id-table.ts +++ b/src/shared/db/define-id-table.ts @@ -1,4 +1,4 @@ -import { defineTable, type TableSchema } from "#shared/db/table.ts"; +import { defineTable, type Table, type TableSchema } from "#shared/db/table.ts"; /** * Helper for tables whose primary key column is `id`. @@ -6,7 +6,7 @@ import { defineTable, type TableSchema } from "#shared/db/table.ts"; export const defineIdTable = ( name: string, schema: TableSchema, -) => +): Table => defineTable({ name, primaryKey: "id" as keyof Row & string, diff --git a/src/shared/db/groups.ts b/src/shared/db/groups.ts index f5c6b176e3..bb70a7ba84 100644 --- a/src/shared/db/groups.ts +++ b/src/shared/db/groups.ts @@ -26,10 +26,10 @@ import { } from "#shared/db/client.ts"; import { cachedEntityTable, - defineIdTable, encryptedNameSchema, idAndEncryptedSlugSchema, } from "#shared/db/common-schema.ts"; +import { defineIdTable } from "#shared/db/define-id-table.ts"; import { linkTableSide } from "#shared/db/link-table.ts"; import { listingChildren, listingParents } from "#shared/db/listing-parents.ts"; import { diff --git a/src/shared/db/keyed-cache.ts b/src/shared/db/keyed-cache.ts index 39b052e4e9..09c320b1dd 100644 --- a/src/shared/db/keyed-cache.ts +++ b/src/shared/db/keyed-cache.ts @@ -4,7 +4,7 @@ * or `username_index`), with a separate ordered view for "all rows" pages. * * Generalised from the listings cache so listings, groups and users share one - * implementation. Single-record reads (`getById` / `getByKey` / `getByKeys`) + * implementation. Record reads (`getByIds` / `getByKeys`) * fetch only the rows they need; `getAll` loads the whole set and warms the * dictionaries. Each entry carries its own expiry (`ttlMs`); a whole-list load * stamps every entry, a single-record load stamps only what it fetched. @@ -20,7 +20,7 @@ */ /* jscpd:ignore-start -- imports */ -import { lazyRef, ttlCache, unique } from "#fp"; +import { lazyRef, mapNotNullish, ttlCache, unique } from "#fp"; import type { CacheInvalidation } from "#shared/cache-registry.ts"; import { createPrimaryCacheRefill } from "#shared/db/primary-reads.ts"; import { nowMs } from "#shared/now.ts"; @@ -31,6 +31,7 @@ import { nowMs } from "#shared/now.ts"; export type KeyedCache = { getAll: () => Promise; getById: (id: number) => Promise; + getByIds: (ids: number[]) => Promise<(T | null)[]>; getByKey: (key: string) => Promise; getByKeys: (keys: string[]) => Promise<(T | null)[]>; invalidate: (cause?: CacheInvalidation) => void; @@ -46,14 +47,14 @@ export type KeyedCacheConfig = { /** Load every row, in display order. */ fetchAll: () => Promise; /** - * Load one row by id. Provide it for large tables so a by-id read fetches - * (and decrypts) only that row; omit it for small tables, where `getById` + * Load rows by id. Provide it for large tables so id reads fetch and decrypt + * only those rows; omit it for small tables, where `getByIds` * instead scans the whole-set load — fewer queries, no extra single-row SQL. */ - fetchById?: (id: number) => Promise; + fetchByIds?: (ids: number[]) => Promise; /** * Load rows by secondary key in one query (only those that exist). Provide it - * for large tables; omit it for small tables, where `getByKey`/`getByKeys` + * for large tables; omit it for small tables, where `getByKeys` * scan the whole-set load instead. */ fetchByKeys?: (keys: string[]) => Promise; @@ -66,7 +67,7 @@ export type KeyedCacheConfig = { export const createKeyedCache = ( config: KeyedCacheConfig, ): KeyedCache => { - const { idOf, keyOf, fetchAll, fetchById, fetchByKeys, ttlMs } = config; + const { idOf, keyOf, fetchAll, fetchByIds, fetchByKeys, ttlMs } = config; const now = config.now ?? nowMs; const byId = ttlCache(ttlMs, now); const byKey = ttlCache(ttlMs, now); @@ -109,41 +110,53 @@ export const createKeyedCache = ( return loadFull(); }; - const getById = async (id: number): Promise => { - const cached = byId.get(id); - if (cached) return cached; - if (!fetchById) { - await getAll(); // whole-set load warms byId - return byId.get(id) ?? null; - } - const gen = generation; - const row = await primaryRefill.fetch(() => fetchById(id)); - return row ? remember(gen, row) : null; - }; - - // Resolve a batch of secondary keys, fetching only the misses in one query, - // so a caller never loads more rows than it asked for. Small tables omit - // fetchByKeys and instead resolve against the whole-set load. - const getByKeys = async (keys: string[]): Promise<(T | null)[]> => { - if (fetchByKeys) { - const missing = unique(keys).filter((k) => !byKey.get(k)); + const resolveMany = async ( + keys: Key[], + cache: { get: (key: Key) => T | undefined }, + fetchRows: ((keys: Key[]) => Promise) | undefined, + keyOfRow: (row: T) => Key, + ): Promise<(T | null)[]> => { + const uniqueKeys = unique(keys); + const loaded = new Map( + mapNotNullish((key: Key): [Key, T] | null => { + const row = cache.get(key); + return row === undefined ? null : [key, row]; + })(uniqueKeys), + ); + if (fetchRows) { + const missing = uniqueKeys.filter((key) => !loaded.has(key)); if (missing.length > 0) { const gen = generation; - const rows = await primaryRefill.fetch(() => fetchByKeys(missing)); - for (const row of rows) remember(gen, row); + const rows = await primaryRefill.fetch(() => fetchRows(missing)); + for (const row of rows) { + loaded.set(keyOfRow(row), remember(gen, row)); + } } } else { - await getAll(); // whole-set load warms byKey + await getAll(); } - return keys.map((k) => byKey.get(k) ?? null); + return keys.map((key) => loaded.get(key) ?? cache.get(key) ?? null); }; + const getByIds = (ids: number[]): Promise<(T | null)[]> => + resolveMany(ids, byId, fetchByIds, idOf); + + const getById = async (id: number): Promise => + (await getByIds([id]))[0] ?? null; + + // Resolve a batch of secondary keys, fetching only the misses in one query, + // so a caller never loads more rows than it asked for. Small tables omit + // fetchByKeys and instead resolve against the whole-set load. + const getByKeys = (keys: string[]): Promise<(T | null)[]> => + resolveMany(keys, byKey, fetchByKeys, keyOf); + const getByKey = async (key: string): Promise => (await getByKeys([key]))[0] ?? null; return { getAll, getById, + getByIds, getByKey, getByKeys, invalidate: (cause = "manual") => { diff --git a/src/shared/db/link-table.ts b/src/shared/db/link-table.ts index abe8d7801f..28b2e93ff6 100644 --- a/src/shared/db/link-table.ts +++ b/src/shared/db/link-table.ts @@ -106,7 +106,7 @@ export const linkTableSide = ( ]; }; - return { + const linkSide: LinkTableSide = { addIdsTx: async (tx, keyId, ids) => { const deduped = dedupe(ids); if (deduped.length === 0) return; @@ -120,8 +120,12 @@ export const linkTableSide = ( SELECT ?, ${valueColumn} FROM ${table} WHERE ${keyColumn} = ?`, }); }, - getIds: (keyId) => - readIds(({ sql, args }) => queryAll<{ id: number }>(sql, args), keyId), + getIds: async (keyId) => + requiredMapValue( + await linkSide.getIdsByKeys([keyId]), + keyId, + `Missing link result for ${keyColumn} ${keyId}`, + ), getIdsByKeys: async (keyIds) => { const keys = unique([...keyIds]); const idsByKey = new Map(keys.map((id) => [id, [] as number[]])); @@ -157,4 +161,5 @@ export const linkTableSide = ( await tx.batch(replaceStatements(keyId, ids)); }, }; + return linkSide; }; diff --git a/src/shared/db/listing-overview-stats.ts b/src/shared/db/listing-overview-stats.ts index d4ebb5b4f5..da0a5547a7 100644 --- a/src/shared/db/listing-overview-stats.ts +++ b/src/shared/db/listing-overview-stats.ts @@ -33,7 +33,7 @@ import { saleLegPredicate, } from "#shared/accounting/projection-sql.ts"; import { ATTENDEE_KIND } from "#shared/db/attendees/kind.ts"; -import { queryOne } from "#shared/db/client.ts"; +import { requireOne } from "#shared/db/client.ts"; import type { Listing } from "#shared/types.ts"; import { isPaidListing } from "#shared/types.ts"; @@ -140,13 +140,13 @@ const incompleteSales = async (listingId: number): Promise => { "CAST(saleLeg.source_id AS INTEGER)", )} <= 0`; const notRefundedSale = notRefunded("CAST(saleLeg.source_id AS INTEGER)"); - const row = (await queryOne<{ incomplete_sales: number | bigint }>( + const row = await requireOne<{ incomplete_sales: number | bigint }>( `SELECT COALESCE(SUM(saleLeg.amount), 0) AS incomplete_sales FROM transfers AS saleLeg WHERE ${saleToRevenue} AND ${noPayment} AND ${noProviderReference} AND ${nothingOwed} AND ${notRefundedSale}`, [String(listingId)], - ))!; + ); return Number(row.incomplete_sales); }; @@ -165,7 +165,7 @@ export const getListingOverviewStats = async ( const paid = isPaidListing(listing); const incomplete = incompleteRowPredicate(paid); const confirmed = `NOT ${incomplete} AND listingAttendee.quantity > 0`; - const countsPromise = queryOne( + const countsPromise = requireOne( `SELECT COALESCE(SUM(CASE WHEN ${incomplete} THEN listingAttendee.quantity ELSE 0 END), 0) AS incomplete_quantity, COALESCE(SUM(CASE WHEN NOT ${incomplete} THEN listingAttendee.quantity ELSE 0 END), 0) AS complete_quantity_sum, diff --git a/src/shared/db/listing-parents.ts b/src/shared/db/listing-parents.ts index fb54c949e5..280d62129e 100644 --- a/src/shared/db/listing-parents.ts +++ b/src/shared/db/listing-parents.ts @@ -14,7 +14,7 @@ import { firstProblem, mapNotNullish, unique } from "#fp"; import { inPlaceholders, queryIdColumn } from "#shared/db/client.ts"; import { type LinkTableSide, linkTableSide } from "#shared/db/link-table.ts"; -import { getListingsWithCountsByIds } from "#shared/db/listings/records.ts"; +import { requireListingsWithCountsByIds } from "#shared/db/listings/records.ts"; import { type EdgeListing, edgeFieldError, @@ -118,14 +118,13 @@ const listingsByIdFor = async ( const linkedIds = unique( sides.flatMap((links) => [...links.values()].flat()), ); - const listings = await getListingsWithCountsByIds(linkedIds); + const listings = await requireListingsWithCountsByIds(linkedIds); return new Map(listings.map((listing) => [listing.id, listing])); }; /** Batch and hydrate one listing relationship side. Only linked listings are * loaded, and hydrated values preserve ascending relationship order. Empty keys - * and keys whose linked listings no longer exist are omitted from - * `listingsByKey`, matching the old parent/child row loaders. */ + * are omitted from `listingsByKey`; a link to a missing listing fails loudly. */ export const hydrateListingLinks = async ( side: LinkTableSide, keyIds: readonly number[], diff --git a/src/shared/db/listing-prices.ts b/src/shared/db/listing-prices.ts index f03c56e33b..b7dc1aab6b 100644 --- a/src/shared/db/listing-prices.ts +++ b/src/shared/db/listing-prices.ts @@ -34,6 +34,7 @@ import { execute, executeBatch, inPlaceholders, + queryAll, queryBatchPrimary, queryIdColumn, type TxScope, @@ -211,53 +212,42 @@ const foldGroupDayRows = ( * (the next package save's full replace then clears them for good). */ export const getGroupDayPrices = async ( groupId: number, -): Promise>> => { - const result = await execute( - `SELECT listingPrice.listing_id, listingPrice.price_id, listingPrice.unit_price - FROM listing_prices AS listingPrice - JOIN group_listings AS groupListing - ON groupListing.listing_id = listingPrice.listing_id - AND groupListing.group_id = ? - WHERE listingPrice.price_type = ? AND listingPrice.price_id LIKE ?`, - [groupId, PRICE_TYPE_GROUP_DAY, groupDayPriceId(groupId, "%")], - ); - return foldGroupDayRows(result.rows as unknown as GroupDayRow[]); -}; +): Promise>> => + (await getGroupDayPricesByGroupIds([groupId])).get(groupId)!; /** Per-day member overrides for several groups in one query (the API list - * endpoint's bulk hydration), keyed by group id. Groups without overrides are - * absent. Reads every CURRENT member's `group_day` row (the JOIN's composed + * endpoint's bulk hydration), keyed by group id. Every requested group is + * present. Reads every CURRENT member's `group_day` row (the JOIN's composed * pattern scopes each row to its own group's membership, exactly like * {@link getGroupDayPrices}) and splits by the price_id's group prefix — - * groups are few, so one SELECT beats a LIKE per group. */ + * and bounds the query to the requested groups. */ export const getGroupDayPricesByGroupIds = async ( groupIds: readonly number[], ): Promise>>> => { - if (groupIds.length === 0) return new Map(); - const wanted = new Set(groupIds); - const rows = await execute( + const groups = new Map( + [...new Set(groupIds)].map((groupId) => [ + groupId, + new Map>(), + ]), + ); + if (groups.size === 0) return groups; + const ids = [...groups.keys()]; + const rows = await queryAll( `SELECT listingPrice.listing_id, listingPrice.price_id, listingPrice.unit_price FROM listing_prices AS listingPrice JOIN group_listings AS groupListing ON groupListing.listing_id = listingPrice.listing_id AND listingPrice.price_id LIKE (groupListing.group_id || '/%') - WHERE listingPrice.price_type = ?`, - [PRICE_TYPE_GROUP_DAY], + WHERE listingPrice.price_type = ? + AND groupListing.group_id IN (${inPlaceholders(ids)})`, + [PRICE_TYPE_GROUP_DAY, ...ids], ); const groupIdOf = (row: GroupDayRow): number => Number(row.price_id.split("/")[0]); - const rowsByGroup = Map.groupBy( - (rows.rows as unknown as GroupDayRow[]).filter((row) => - wanted.has(groupIdOf(row)), - ), - groupIdOf, - ); - return new Map( - [...rowsByGroup].map(([groupId, groupRows]) => [ - groupId, - foldGroupDayRows(groupRows), - ]), - ); + for (const [groupId, groupRows] of Map.groupBy(rows, groupIdOf)) { + groups.set(groupId, foldGroupDayRows(groupRows)); + } + return groups; }; /** The delete-then-insert statements that make a listing's `base` row match diff --git a/src/shared/db/listings/aggregates.ts b/src/shared/db/listings/aggregates.ts index 56a8668232..663bf9e049 100644 --- a/src/shared/db/listings/aggregates.ts +++ b/src/shared/db/listings/aggregates.ts @@ -1,7 +1,7 @@ /** Listing aggregate inspection, correction, and rebuilding. */ import { inOwnTx, ledgerTx } from "#shared/accounting/ledger-tx.ts"; -import { execute, queryOne, resetAggregates } from "#shared/db/client.ts"; +import { execute, requireOne, resetAggregates } from "#shared/db/client.ts"; import type { AggregateRecalculation, AggregateValues, @@ -32,10 +32,10 @@ const LISTING_AGGREGATE_RECALC_SQL = `SELECT export const getListingAggregateRecalculation = async ( listing: ListingWithCount, ): Promise => { - const row = (await queryOne( + const row = await requireOne( LISTING_AGGREGATE_RECALC_SQL, [listing.id], - ))!; + ); return { booked_quantity: { current: listing.attendee_count, diff --git a/src/shared/db/listings/catalog.ts b/src/shared/db/listings/catalog.ts index 940104ec0c..40e4d56dd5 100644 --- a/src/shared/db/listings/catalog.ts +++ b/src/shared/db/listings/catalog.ts @@ -40,7 +40,7 @@ const catalogListingProjection = defineTableProjection(rawListingsTable, [ export const getListingOfferFlags = async ( id: number, ): Promise => { - const row = await listingOfferFlagsProjection.queryOneOrNull( + const row = await listingOfferFlagsProjection.queryOne( `SELECT ${listingOfferFlagsProjection.columnsSql("listing")} FROM listings AS listing WHERE listing.id = ? LIMIT 1`, [id], ); diff --git a/src/shared/db/listings/records.ts b/src/shared/db/listings/records.ts index ca1accf270..8a6c217227 100644 --- a/src/shared/db/listings/records.ts +++ b/src/shared/db/listings/records.ts @@ -17,10 +17,11 @@ import { syncListingPrices, } from "#shared/db/listing-prices.ts"; import { LISTING_AGGREGATE_WRITE_COLUMNS } from "#shared/db/migrations/schema/listing-aggregates.ts"; -import { envNameSource } from "#shared/db/query.ts"; +import { envNameSource, rowsByIds } from "#shared/db/query.ts"; import { settings } from "#shared/db/settings.ts"; import { isSlugTakenAnywhere } from "#shared/db/slug-registry.ts"; import { resolveListingDefaults } from "#shared/listing-defaults.ts"; +import { requireValue } from "#shared/required-value.ts"; import type { DayPrices, ItemImageProjection, @@ -69,10 +70,10 @@ export const decryptListingWithCount = async ( export const getStoredListingsWithCountsByIds = async ( ids: readonly number[], ): Promise => { - if (ids.length === 0) return []; - const rows = await queryAll( - `${LISTING_COUNT_SELECT} WHERE listing.id IN (${inPlaceholders(ids)})`, + const rows = await rowsByIds( [...ids], + (placeholders) => + `${LISTING_COUNT_SELECT} WHERE listing.id IN (${placeholders})`, ); return mapParallel(decryptStoredListingWithCount)(rows); }; @@ -95,22 +96,6 @@ export const queryListingsWithCounts = async ( return mapParallel(decryptListingWithCount)(rows); }; -const queryOneListingWithCount = async ( - where: string, - args: InValue[], -): Promise => - (await queryListingsWithCounts(`WHERE ${where}`, args))[0] ?? null; - -/** Read only the requested listings in one bounded query. */ -export const getListingsWithCountsByIds = ( - ids: readonly number[], -): Promise => - ids.length === 0 - ? Promise.resolve([]) - : queryListingsWithCounts(`WHERE listing.id IN (${inPlaceholders(ids)})`, [ - ...ids, - ]); - const LISTINGS_CACHE_TTL_MS = 30_000; const listingsEntity = cachedEntityTable< Listing, @@ -121,7 +106,11 @@ const listingsEntity = cachedEntityTable< rawListingsTable, { fetchAll: () => queryListingsWithCounts(), - fetchById: (id) => queryOneListingWithCount("listing.id = ?", [id]), + fetchByIds: (ids) => + queryListingsWithCounts( + `WHERE listing.id IN (${inPlaceholders(ids)})`, + ids, + ), fetchByKeys: (slugIndexes) => queryListingsWithCounts( `WHERE listing.slug_index IN (${inPlaceholders(slugIndexes)})`, @@ -210,33 +199,52 @@ export const getAllListingOptions = (): Promise => `SELECT ${listingOptionProjection.columnsSql("listing")} FROM listings AS listing ORDER BY listing.id ASC`, ); -/** Read and decrypt names only for the requested listing ids. */ -export const getListingNamesByIds = envNameSource("listings", "listing").byIds; +/** Read and decrypt listing names without loading full records. */ +export const listingNames = envNameSource("listings", "listing"); -/** Read one listing with aggregate projections from the cache. */ +/** Read required listings in input order through the shared cache path. */ +export const requireListingsWithCountsByIds = async ( + ids: number[], +): Promise => + (await listingsCache.getByIds(ids)).map((listing, index) => + requireValue(listing, `Listing not found: ${ids[index]}`), + ); + +/** Read listings in input order, retaining nulls for expected missing rows. */ +export const getListingsWithCountsByIds = ( + ids: number[], +): Promise<(ListingWithCount | null)[]> => listingsCache.getByIds(ids); + +/** Read one required listing through the shared many-listing path. */ +export const requireListingWithCount = async ( + id: number, +): Promise => + (await requireListingsWithCountsByIds([id]))[0]!; + +/** Read one listing when absence is expected. */ export const getListingWithCount = ( id: number, ): Promise => listingsCache.getById(id); -/** Read a just-written listing from the primary. */ +/** Read a just-written listing from the primary, or null if it was deleted. */ export const getListingWithCountPrimary = async ( id: number, -): Promise => { +): Promise => { const row = await queryOnePrimary( `${LISTING_COUNT_SELECT} WHERE listing.id = ?`, [id], ); - return decryptListingWithCount(row!); + return row === null ? null : decryptListingWithCount(row); }; -/** Read one listing by its plaintext slug. */ +/** Read one listing by its plaintext slug when absence is expected. */ export const getListingWithCountBySlug = async ( slug: string, ): Promise => listingsCache.getByKey(await computeSlugIndex(slug)); /** Read listings by slug in input order, retaining nulls for missing rows. */ -export const getListingsBySlugsBatch = async ( +export const getListingsBySlugs = async ( slugs: string[], ): Promise<(ListingWithCount | null)[]> => { if (slugs.length === 0) return []; diff --git a/src/shared/db/listings/table.ts b/src/shared/db/listings/table.ts index 2c5a23e67e..f5d1770c47 100644 --- a/src/shared/db/listings/table.ts +++ b/src/shared/db/listings/table.ts @@ -5,10 +5,10 @@ import { hmacHash } from "#shared/crypto/hashing.ts"; import type { BlindIndex, EnvKeyEncrypted } from "#shared/crypto/sealed.ts"; import { VALID_DAY_NAMES } from "#shared/day-names.ts"; import { - defineIdTable, encryptedNameSchema, idAndEncryptedSlugSchema, } from "#shared/db/common-schema.ts"; +import { defineIdTable } from "#shared/db/define-id-table.ts"; import { decryptTextOrEmpty } from "#shared/db/encrypted-text.ts"; import { col, defineTableProjection } from "#shared/db/table.ts"; import { decryptImageFilenameOrEmpty } from "#shared/images/broken.ts"; diff --git a/src/shared/db/modifiers.ts b/src/shared/db/modifiers.ts index e943271283..880bbe6d22 100644 --- a/src/shared/db/modifiers.ts +++ b/src/shared/db/modifiers.ts @@ -18,15 +18,16 @@ import { queryAll, queryIdColumn, queryOne, + requireOne, resetAggregates, update, } from "#shared/db/client.ts"; import { type AggregateRecalculation, type AggregateValues, - defineIdTable, idAndEncryptedNameSchema, } from "#shared/db/common-schema.ts"; +import { defineIdTable } from "#shared/db/define-id-table.ts"; import { linkTableSide } from "#shared/db/link-table.ts"; import { columnMapByIds, @@ -167,14 +168,14 @@ export type ModifierAggregateRecalculation = export const getModifierAggregateRecalculation = async ( modifier: ModifierRow, ): Promise => { - const row = (await queryOne( + const row = await requireOne( `SELECT COALESCE(SUM(quantity), 0) AS total_uses, COUNT(*) AS usage_count FROM modifier_usages WHERE modifier_id = ?`, [modifier.id], - ))!; + ); return { total_uses: { current: modifier.total_uses, recalculated: row.total_uses }, usage_count: { diff --git a/src/shared/db/news-posts.ts b/src/shared/db/news-posts.ts index 46a95013b6..50c0995b22 100644 --- a/src/shared/db/news-posts.ts +++ b/src/shared/db/news-posts.ts @@ -25,11 +25,11 @@ import { } from "#shared/db/client.ts"; // jscpd:ignore-end import { - defineIdTable, encryptedSlugSchema, idAndCreatedSchema, } from "#shared/db/common-schema.ts"; import { encryptedNameAndSeoSchema } from "#shared/db/content-columns.ts"; +import { defineIdTable } from "#shared/db/define-id-table.ts"; import { decryptTextOrEmpty } from "#shared/db/encrypted-text.ts"; import { clearImageUsesForItemStatement, diff --git a/src/shared/db/orphan-attendees.ts b/src/shared/db/orphan-attendees.ts index 55e7131d5a..1ea5418ab0 100644 --- a/src/shared/db/orphan-attendees.ts +++ b/src/shared/db/orphan-attendees.ts @@ -21,7 +21,7 @@ */ import { attendeeDependentDeleteStatements } from "#shared/db/attendees/delete.ts"; -import { executeBatchWithResults, queryOne } from "#shared/db/client.ts"; +import { executeBatchWithResults, requireOne } from "#shared/db/client.ts"; /** * Selects the ids of orphaned attendees older than the bound cut-off. Defined @@ -41,7 +41,7 @@ export const countOrphanedAttendees = async ( cutoffIso: string, ): Promise => { // COUNT(*) always returns exactly one row, so the result is never null. - const row = await queryOne<{ count: number }>( + const row = await requireOne<{ count: number }>( `SELECT COUNT(*) AS count FROM (${ORPHAN_IDS})`, [cutoffIso], ); diff --git a/src/shared/db/questions/aggregates.ts b/src/shared/db/questions/aggregates.ts index 5540cce26d..ba65e85910 100644 --- a/src/shared/db/questions/aggregates.ts +++ b/src/shared/db/questions/aggregates.ts @@ -11,6 +11,7 @@ import { execute, queryAll, queryOne, + requireOne, resetAggregates, } from "#shared/db/client.ts"; import type { @@ -52,13 +53,13 @@ export const getAnswerSelectionTotals = async ( export const getAnswerAggregateRecalculation = async ( answerId: number, ): Promise => { - const row = (await queryOne<{ current: number; recalculated: number }>( + const row = await requireOne<{ current: number; recalculated: number }>( `SELECT times_selected AS current, (SELECT COUNT(*) FROM attendee_answers WHERE answer_id = answers.id) AS recalculated FROM answers WHERE id = ?`, [answerId], - ))!; + ); return { times_selected: { current: row.current, recalculated: row.recalculated }, }; diff --git a/src/shared/db/site-pages.ts b/src/shared/db/site-pages.ts index 8b8ec02aff..6c14a8f58c 100644 --- a/src/shared/db/site-pages.ts +++ b/src/shared/db/site-pages.ts @@ -14,11 +14,9 @@ import { decrypt, encrypt } from "#shared/crypto/encryption.ts"; import { hmacHash } from "#shared/crypto/hashing.ts"; import type { BlindIndex } from "#shared/crypto/sealed.ts"; import { queryOne, type TxScope, useTransaction } from "#shared/db/client.ts"; -import { - defineIdTable, - idAndEncryptedSlugSchema, -} from "#shared/db/common-schema.ts"; +import { idAndEncryptedSlugSchema } from "#shared/db/common-schema.ts"; import { encryptedNameAndSeoSchema } from "#shared/db/content-columns.ts"; +import { defineIdTable } from "#shared/db/define-id-table.ts"; import { defineOrderedCollection } from "#shared/db/ordered-collection.ts"; import { unclaimedSiteSlugCondition, diff --git a/src/shared/db/table.ts b/src/shared/db/table.ts index d705b5b3e0..4fb523fe66 100644 --- a/src/shared/db/table.ts +++ b/src/shared/db/table.ts @@ -107,7 +107,7 @@ export interface Table { /** Find all rows */ findAll: () => Promise; - /** Find a row by primary key */ + /** Find a row by primary key, or null when it does not exist. */ findById: (id: InValue) => Promise; /** @@ -123,6 +123,9 @@ export interface Table { */ findByIdPrimary?: (id: InValue) => Promise; + /** Find rows in input order, retaining nulls for missing primary keys. */ + findByIds: (ids: InValue[]) => Promise<(Row | null)[]>; + /** Transform a row from DB (apply read transforms) */ fromDb: (row: Row) => Promise; inputKeyMap: Record; @@ -195,7 +198,7 @@ export interface TableProjection> { readonly columns: Columns; columnsSql: (alias?: string) => string; queryAll: TableProjectionQuery[]>; - queryOneOrNull: TableProjectionQuery | null>; @@ -274,7 +277,7 @@ export const defineTableProjection = < readAll( await queryAll>(sql, args), ), - queryOneOrNull: async (sql, args) => { + queryOne: async (sql, args) => { const row = await queryOne>( sql, args, @@ -397,6 +400,9 @@ export const defineTable = ( const allColumns = Object.keys(schema) as (keyof Row & string)[]; const physicalColumns = allColumns.filter((col) => !schema[col].projected); const physicalColumnsSql = physicalColumns.join(", "); + const qualifiedPhysicalColumnsSql = physicalColumns + .map((column) => `record.${column}`) + .join(", "); const inputColumns = physicalColumns.filter((col) => !schema[col].generated); const inputKeyMap = buildInputKeyMap(inputColumns); @@ -569,14 +575,27 @@ export const defineTable = ( id: InValue, ): Promise => { const row = await query( - `SELECT ${physicalColumnsSql} FROM ${name} WHERE ${primaryKey} = ?`, + `SELECT ${qualifiedPhysicalColumnsSql} FROM ${name} AS record WHERE record.${primaryKey} = ?`, [id], ); return row ? fromDb(row) : null; }; - const findById = (id: InValue): Promise => - findByIdVia(queryOne, id); + const findByIds = async (ids: InValue[]): Promise<(Row | null)[]> => { + if (ids.length === 0) return []; + const rows = await queryAll( + `SELECT ${qualifiedPhysicalColumnsSql} FROM ${name} AS record WHERE record.${primaryKey} IN (${ids.map(() => "?").join(", ")})`, + ids, + ); + const readRows = await mapParallel(fromDb)(rows); + const rowsById = new Map( + readRows.map((row) => [row[primaryKey], row] as const), + ); + return ids.map((id) => rowsById.get(id as Row[keyof Row & string]) ?? null); + }; + + const findById = async (id: InValue): Promise => + (await findByIds([id]))[0] ?? null; const findByIdPrimary = (id: InValue): Promise => findByIdVia(queryOnePrimary, id); @@ -619,6 +638,7 @@ export const defineTable = ( findAll, findById, findByIdPrimary, + findByIds, fromDb, inputKeyMap, insert, diff --git a/src/shared/deno-deploy-api.ts b/src/shared/deno-deploy-api.ts index 206a34e595..b86006073e 100644 --- a/src/shared/deno-deploy-api.ts +++ b/src/shared/deno-deploy-api.ts @@ -12,11 +12,12 @@ import { getDenoDeployToken, slugifyForProvider, } from "#shared/config.ts"; -import { type ApiResult, fetchText, parseApiError } from "#shared/fetch.ts"; +import { fetchText, parseApiError } from "#shared/fetch.ts"; import type { CreateSiteFn, HostingProviderApi, } from "#shared/provider-types.ts"; +import { errorResult, okResult, type Result } from "#shared/result.ts"; /* jscpd:ignore-end */ @@ -61,7 +62,7 @@ export const slugifyForDeno = (name: string): string => { */ const createAppImpl = async ( slug: string, -): Promise> => { +): Promise> => { const orgId = getDenoDeployOrgId(); const res = await fetchText(`${DENO_API_BASE}/apps`, { body: JSON.stringify({ orgId, slug }), @@ -72,23 +73,20 @@ const createAppImpl = async ( if (!res.ok) return parseApiError(res, "Create app"); const data: CreateAppResponse = JSON.parse(res.text); - return { appId: data.id, ok: true, slug: data.slug }; + return okResult({ appId: data.id, slug: data.slug }); }; /** Fetch the current env vars for a Deno Deploy app. */ const fetchAppEnvVars = async ( appId: string, -): Promise< - | { ok: true; envVars: Record } - | { ok: false; error: string } -> => { +): Promise>> => { const res = await fetchText( `${DENO_API_BASE}/apps/${encodeURIComponent(appId)}`, { headers: denoApiHeaders() }, ); if (!res.ok) return parseApiError(res, "Get app"); const data: GetAppResponse = JSON.parse(res.text); - return { envVars: data.env_vars ?? {}, ok: true }; + return okResult(data.env_vars ?? {}); }; /** @@ -116,7 +114,7 @@ const setEnvVarsImpl = async (appId: string, secrets: [string, string][]) => { ); if (!patchRes.ok) return parseApiError(patchRes, "Set app env vars"); - return { ok: true as const }; + return okResult(undefined); }; /** @@ -126,7 +124,7 @@ const setEnvVarsImpl = async (appId: string, secrets: [string, string][]) => { const deployCodeImpl = async ( appId: string, code: string, -): Promise> => { +): Promise> => { const res = await fetchText( `${DENO_API_BASE}/apps/${encodeURIComponent(appId)}/deployments`, { @@ -147,21 +145,19 @@ const deployCodeImpl = async ( const data: DeploymentResponse = JSON.parse(res.text); const hostname = data.domains?.[0] ?? data.hostnames?.[0]; if (!hostname) { - return { error: "Deploy code failed: no hostname in response", ok: false }; + return errorResult("Deploy code failed: no hostname in response"); } - return { hostname: `https://${hostname}`, ok: true }; + return okResult(`https://${hostname}`); }; /** * Get the names of environment variables currently set on a Deno Deploy app. * Used by the secrets backfill UI to diff against the expected set. */ -const getEnvVarNamesImpl = async ( - appId: string, -): Promise> => { +const getEnvVarNamesImpl = async (appId: string): Promise> => { const appResult = await fetchAppEnvVars(appId); if (!appResult.ok) return appResult; - return { names: Object.keys(appResult.envVars), ok: true }; + return okResult(Object.keys(appResult.value)); }; /** Stubbable API for testing */ @@ -175,20 +171,22 @@ export const denoDeployApi = { const createDenoSiteImpl: CreateSiteFn = async (name, code, secrets) => { const createResult = await denoDeployApi.createApp(slugifyForDeno(name)); if (!createResult.ok) return createResult; - const setResult = await denoDeployApi.setEnvVars(createResult.appId, secrets); + const setResult = await denoDeployApi.setEnvVars( + createResult.value.appId, + secrets, + ); if (!setResult.ok) { - return { - error: `Failed to set secrets: ${setResult.error}`, - ok: false as const, - }; + return errorResult(`Failed to set secrets: ${setResult.error}`); } - const deployResult = await denoDeployApi.deployCode(createResult.appId, code); + const deployResult = await denoDeployApi.deployCode( + createResult.value.appId, + code, + ); if (!deployResult.ok) return deployResult; - return { - defaultHostname: deployResult.hostname, - hostingId: createResult.appId, - ok: true as const, - }; + return okResult({ + defaultHostname: deployResult.value, + hostingId: createResult.value.appId, + }); }; export const denoHostingProvider: HostingProviderApi = { diff --git a/src/shared/fetch.ts b/src/shared/fetch.ts index 13796b034c..929a17c253 100644 --- a/src/shared/fetch.ts +++ b/src/shared/fetch.ts @@ -8,6 +8,7 @@ */ import { extendedBy } from "#fp"; +import { errorResult, type Result } from "#shared/result.ts"; /** A fetch result whose body has already been read to a string. */ export type FetchResult = { @@ -17,9 +18,6 @@ export type FetchResult = { headers: Headers; }; -/** Discriminated result type for external API calls. */ -export type ApiResult = ({ ok: true } & T) | { ok: false; error: string }; - /** * Headers for a JSON API request: the given auth header(s) plus a JSON * content type. Each API client supplies its own auth scheme (a bearer token, @@ -39,7 +37,7 @@ export const parseApiError = ( response: { status: number; text: string }, label: string, keys: string[] = ["message", "error"], -): { ok: false; error: string } => { +): Result & { ok: false } => { let message = response.text; try { const json = JSON.parse(response.text); @@ -52,10 +50,7 @@ export const parseApiError = ( } catch { /* use raw text */ } - return { - error: `${label} failed (${response.status}): ${message}`, - ok: false, - }; + return errorResult(`${label} failed (${response.status}): ${message}`); }; /** Fetch a URL and eagerly read the response body, preventing resource leaks. */ diff --git a/src/shared/ledger/types.ts b/src/shared/ledger/types.ts index f1633258c8..77d226ca44 100644 --- a/src/shared/ledger/types.ts +++ b/src/shared/ledger/types.ts @@ -75,8 +75,3 @@ export type LedgerError = | { readonly code: "reserved_char_in_account" } | { readonly code: "empty_reference" } | { readonly code: "empty_event_group" }; - -/** A validation result: the value, or every reason it was rejected. */ -export type Result = - | { readonly ok: true; readonly value: T } - | { readonly ok: false; readonly errors: LedgerError[] }; diff --git a/src/shared/ledger/validate.ts b/src/shared/ledger/validate.ts index 4bffa71f80..a32359ea4b 100644 --- a/src/shared/ledger/validate.ts +++ b/src/shared/ledger/validate.ts @@ -10,14 +10,10 @@ */ import { compact } from "#fp"; +import { type Result, requireSuccess } from "#shared/result.ts"; import { isInstant } from "#shared/validation/timestamp.ts"; import { ACCOUNT_KEY_SEPARATOR, sameAccount } from "./account.ts"; -import type { - AccountRef, - LedgerError, - Result, - TransferInput, -} from "./types.ts"; +import type { AccountRef, LedgerError, TransferInput } from "./types.ts"; const isEmptyAccount = (a: AccountRef): boolean => !a.type || !a.id; @@ -46,7 +42,9 @@ const hasInvalidReversesId = (t: TransferInput): boolean => * are non-empty. (Currency is not a ledger concern: a site has one currency, * fixed at setup, so every transfer shares it.) */ -export const validateTransfer = (t: TransferInput): Result => { +export const validateTransfer = ( + t: TransferInput, +): Result => { const errors: LedgerError[] = compact([ t.amount <= 0 ? ({ code: "non_positive_amount" } as const) : null, Number.isInteger(t.amount) @@ -69,7 +67,9 @@ export const validateTransfer = (t: TransferInput): Result => { t.reference ? null : ({ code: "empty_reference" } as const), t.eventGroup ? null : ({ code: "empty_event_group" } as const), ]); - return errors.length > 0 ? { errors, ok: false } : { ok: true, value: t }; + return errors.length > 0 + ? { error: errors, ok: false } + : { ok: true, value: t }; }; /** @@ -82,9 +82,5 @@ export const assertValidTransfer = ( t: TransferInput, context: string, ): void => { - const result = validateTransfer(t); - if (!result.ok) { - const codes = result.errors.map((e) => e.code).join(", "); - throw new Error(`${context}: ${codes}`); - } + requireSuccess(validateTransfer(t), context); }; diff --git a/src/shared/provider-types.ts b/src/shared/provider-types.ts index 81a615e96c..f8179ab3b5 100644 --- a/src/shared/provider-types.ts +++ b/src/shared/provider-types.ts @@ -1,4 +1,23 @@ -import type { ApiResult } from "#shared/fetch.ts"; +import { okResult, type Result } from "#shared/result.ts"; + +export interface DatabaseCredentials { + dbId: string; + dbToken: string; + dbUrl: string; +} + +export const databaseCredentialsFromResponse = ( + dbId: string, + dbUrl: string, + text: string, + tokenKey: string, +): Result => { + const token = JSON.parse(text)[tokenKey]; + if (typeof token !== "string") { + throw new Error(`Database response is missing ${tokenKey}`); + } + return okResult({ dbId, dbToken: token, dbUrl }); +}; /** Create a site on a hosting provider: deploy `code` under `name` with the * given secrets, returning the new site's id and default hostname. Declared @@ -7,16 +26,16 @@ export type CreateSiteFn = ( name: string, code: string, secrets: [string, string][], -) => Promise>; +) => Promise>; export interface HostingProviderApi { configEnvVar: string; createSite: CreateSiteFn; - getSecretNames(hostingId: string): Promise>; + getSecretNames(hostingId: string): Promise>; setSecrets( hostingId: string, secrets: [string, string][], - ): Promise>>; + ): Promise>; } /** Create a database named `name` on a database provider, returning the new @@ -24,7 +43,7 @@ export interface HostingProviderApi { * implementation shares the exact same signature. */ export type CreateDatabaseFn = ( name: string, -) => Promise>; +) => Promise>; export interface DatabaseProviderApi { createDatabase: CreateDatabaseFn; diff --git a/src/shared/required-value.ts b/src/shared/required-value.ts new file mode 100644 index 0000000000..3fbef9660b --- /dev/null +++ b/src/shared/required-value.ts @@ -0,0 +1,8 @@ +/** Return a required value or fail with its domain-specific error. */ +export const requireValue = ( + value: T | null | undefined, + message: string, +): T => { + if (value == null) throw new Error(message); + return value; +}; diff --git a/src/shared/rest/crud-api.ts b/src/shared/rest/crud-api.ts index 33d5cf56af..3f516339ed 100644 --- a/src/shared/rest/crud-api.ts +++ b/src/shared/rest/crud-api.ts @@ -19,6 +19,7 @@ /* jscpd:ignore-start */ import type { InValue } from "@libsql/client"; +import { reduce } from "#fp"; import { verifyIdentifierOrJsonError } from "#routes/admin/confirmation.ts"; import { apiErrorResponse } from "#routes/api/cors.ts"; import { ADMIN_API, type AuthPolicy, withAuth } from "#routes/auth.ts"; @@ -27,9 +28,14 @@ import type { RouteHandlerFn } from "#routes/router.ts"; import { logActivity } from "#shared/db/activityLog.ts"; import type { TxScope } from "#shared/db/client.ts"; import type { Table } from "#shared/db/table.ts"; -import type { ApiResult } from "#shared/fetch.ts"; import type { ResponseHandler } from "#shared/response-steps.ts"; import { type JoinWrite, writeEntity } from "#shared/rest/write-entity.ts"; +import { + errorResult, + okResult, + parseOptionalResult, + type Result, +} from "#shared/result.ts"; import type { AdminSession } from "#shared/types.ts"; /* jscpd:ignore-end */ @@ -49,6 +55,18 @@ const requireString = ( ? body[key].trim() : null; +/** Parse every item with one shared first-error traversal. */ +const parseEach = + (parseItem: (item: Input) => Result) => + (items: readonly Input[]): Result => + reduce((result: Result, item: Input): Result => { + if (!result.ok) return result; + const parsed = parseItem(item); + if (!parsed.ok) return parsed; + result.value.push(parsed.value); + return result; + }, okResult([]))([...items]); + /** * Read several required non-empty string fields from a JSON body in one call. * Returns the trimmed values keyed by field name, or a ready `{ ok: false }` @@ -60,14 +78,16 @@ const requireString = ( export const requireStrings = ( body: Record, keys: readonly K[], -): ApiResult<{ values: Record }> => { - const values = {} as Record; - for (const key of keys) { +): Result> => { + const parsed = parseEach((key: K): Result => { const value = requireString(body, key); - if (!value) return { error: `${key} is required`, ok: false }; - values[key] = value; - } - return { ok: true, values }; + return value + ? okResult([key, value] as const) + : errorResult(`${key} is required`); + })(keys); + return parsed.ok + ? okResult(Object.fromEntries(parsed.value) as Record) + : parsed; }; /** @@ -95,12 +115,6 @@ export const bodyBoolean = ( fallback: boolean, ): boolean => (typeof body[key] === "boolean" ? body[key] : fallback); -/** Result of parsing a JSON body into a typed input */ -export type ParseResult = ApiResult<{ input: Input }>; - -/** Outcome of parsing a single array element: a value, or a rejection reason. */ -export type ItemResult = { value: T } | { error: string }; - /** * Parse an optional JSON-array field with partial-update semantics, failing * closed. `undefined` → ok with `undefined` (caller leaves existing data @@ -111,20 +125,14 @@ export type ItemResult = { value: T } | { error: string }; export const parseOptionalArray = ( raw: unknown, label: string, - parseItem: (item: unknown) => ItemResult, -): ParseResult => { - if (raw === undefined) return { input: undefined, ok: true }; - if (!Array.isArray(raw)) { - return { error: `${label} must be an array`, ok: false }; - } - const items: T[] = []; - for (const item of raw) { - const parsed = parseItem(item); - if ("error" in parsed) return { error: parsed.error, ok: false }; - items.push(parsed.value); - } - return { input: items, ok: true }; -}; + parseItem: (item: unknown) => Result, +): Result => + parseOptionalResult(raw, (value) => { + if (!Array.isArray(value)) { + return errorResult(`${label} must be an array`); + } + return parseEach(parseItem)(value); + }); /** Result of parsing + validating: either the input or a pre-built error response */ export type ValidatedInput = @@ -136,7 +144,7 @@ export type ValidatedInput = * error response on failure. Used by route handlers to short-circuit on error. */ export const parseAndValidate = async ( - parsed: ParseResult | Promise>, + parsed: Result | Promise>, validate?: (input: Input, id?: number) => Promise, id?: number, ): Promise> => { @@ -145,10 +153,10 @@ export const parseAndValidate = async ( return { ok: false, response: apiErrorResponse(result.error) }; } if (validate) { - const error = await validate(result.input, id); + const error = await validate(result.value, id); if (error) return { ok: false, response: apiErrorResponse(error) }; } - return { input: result.input, ok: true }; + return { input: result.value, ok: true }; }; /** @@ -173,11 +181,9 @@ export const parseUpdateSlug = async ( export const parseUpdateName = ( body: Record, existing: string, -): ApiResult<{ name: string }> => { +): Result => { const name = body.name != null ? String(body.name).trim() : existing; - return name === "" - ? { error: "name cannot be empty", ok: false } - : { name, ok: true }; + return name === "" ? errorResult("name cannot be empty") : okResult(name); }; /** @@ -287,12 +293,12 @@ export interface CrudApiConfig< /** Convert JSON body to Input for create */ toCreateInput: ( body: Record, - ) => ParseResult | Promise>; + ) => Result | Promise>; /** Convert JSON body + existing row to Input for update */ toUpdateInput: ( body: Record, existing: FullRow, - ) => ParseResult | Promise>; + ) => Result | Promise>; /** Optional validation (return error message or null) */ validate?: (input: Input, id?: number) => Promise; /** Optional delete guard: a returned message blocks the deletion with a 400 @@ -484,7 +490,7 @@ export const defineCrudApi = < /** Validate raw input against config.validate, then invoke fn with the typed * result on success; returns the validation error response on failure. */ const withValidated = async ( - raw: ParseResult | Promise>, + raw: Result | Promise>, id: number | undefined, fn: ResponseHandler<[value: Input]>, ): Promise => { diff --git a/src/shared/rest/resource.ts b/src/shared/rest/resource.ts index 1f5eec4d18..2534c47f49 100644 --- a/src/shared/rest/resource.ts +++ b/src/shared/rest/resource.ts @@ -25,8 +25,9 @@ import type { FormSchema } from "#shared/forms/definition.ts"; import type { Field } from "#shared/forms/field.ts"; import type { FieldValues } from "#shared/forms/values.ts"; import { mapValidationError } from "#shared/optional-validate.ts"; -import type { AfterCommitConfig, ParseResult } from "#shared/rest/crud-api.ts"; +import type { AfterCommitConfig } from "#shared/rest/crud-api.ts"; import { writeEntity } from "#shared/rest/write-entity.ts"; +import { okResult, type Result } from "#shared/result.ts"; /* jscpd:ignore-end */ @@ -72,7 +73,7 @@ type ValidateFn = export interface Resource extends NamedOperations { readonly fields: readonly Field[]; - parseInput: (form: FormParams) => Promise>; + parseInput: (form: FormParams) => Promise>; readonly table: Table; verifyName?: (row: Row, confirmName: string) => boolean; } @@ -120,12 +121,12 @@ const validateAndParse = async ( schema: FormSchema, toInput: (values: V) => T | Promise, validateValues?: (values: V) => string | null, -): Promise> => { +): Promise> => { const validation = schema.validate(form); if (!validation.valid) return { error: validation.error, ok: false }; const valuesError = validateValues?.(validation.values); if (valuesError) return { error: valuesError, ok: false }; - return { input: await toInput(validation.values), ok: true }; + return okResult(await toInput(validation.values)); }; /** Run async validation, return error result or null */ @@ -146,13 +147,13 @@ const toUpdateResult = (row: Row | null): UpdateResult => /** Parse and validate input, returning parsed input or error */ const parseAndValidate = async ( form: FormParams, - parseInput: (form: FormParams) => Promise>, + parseInput: (form: FormParams) => Promise>, validate: ValidateFn, id?: Id, -): Promise> => { +): Promise> => { const parsed = await parseInput(form); if (!parsed.ok) return parsed; - const validationError = await runValidation(validate, parsed.input, id); + const validationError = await runValidation(validate, parsed.value, id); return validationError ?? parsed; }; @@ -178,7 +179,7 @@ export const defineResource = < ): Resource => { const { table, form: schema, toInput, nameField } = config; - const parseInput = (form: FormParams): Promise> => + const parseInput = (form: FormParams): Promise> => validateAndParse( form, schema, @@ -214,13 +215,13 @@ export const defineResource = < afterCommit: config.afterCommit, buildStatement: () => existingId === null - ? table.insertStatement!(result.input) - : table.updateStatement!(existingId, result.input), + ? table.insertStatement!(result.value) + : table.updateStatement!(existingId, result.value), existingId, joinWrites: config.afterWrite - ? [(tx, rowId) => config.afterWrite!(tx, rowId, result.input, form)] + ? [(tx, rowId) => config.afterWrite!(tx, rowId, result.value, form)] : [], - plainWrite: () => fallback(result.input), + plainWrite: () => fallback(result.value), readBack: (rowId) => table.findByIdPrimary!(rowId), }); return { ok: true, row }; diff --git a/src/shared/result.ts b/src/shared/result.ts index 7754679dc3..ed3cff7c2a 100644 --- a/src/shared/result.ts +++ b/src/shared/result.ts @@ -1,4 +1,4 @@ -/** A small success/error result for boundary parsing and action helpers. */ +/** The shared success/error contract for operations that return one value. */ export type Result = | { ok: true; value: T } | { ok: false; error: E }; @@ -13,12 +13,38 @@ export const errorResult = (error: E): { error: E; ok: false } => ({ ok: false, }); -/** Throw a failed boundary result and narrow successful results for the caller. */ -export function requireSuccess< - T extends { ok: true } | { error: string; ok: false }, ->(result: T): asserts result is Extract; -export function requireSuccess( - result: { ok: true } | { error: string; ok: false }, -): void { - if (!result.ok) throw new Error(result.error); -} +/** Parse a value when present, or return a successful undefined value. */ +export const parseOptionalResult = ( + value: unknown, + parse: (value: unknown) => Result, +): Result => + value === undefined ? okResult(undefined) : parse(value); + +const objectErrorMessage = (error: object): string | null => { + const values = error as Record; + const message = values.message ?? values.code; + return typeof message === "string" && message ? message : null; +}; + +const errorMessage = (error: unknown): string | null => { + if (typeof error === "string") return error || null; + if (error instanceof Error) return error.message || error.name; + if (Array.isArray(error)) { + const messages = error.map(errorMessage); + return messages.length > 0 && messages.every((message) => message !== null) + ? messages.join(", ") + : null; + } + return error && typeof error === "object" ? objectErrorMessage(error) : null; +}; + +/** Return a successful value, or throw the failed result's useful message. */ +export const requireSuccess = ( + result: Result, + context?: string, +): T => { + if (result.ok) return result.value; + const message = errorMessage(result.error); + if (message === null) throw new Error("Failed result is missing an error"); + throw new Error(context ? `${context}: ${message}` : message); +}; diff --git a/src/shared/site-db.ts b/src/shared/site-db.ts index 2dcc0cbd7e..ed2a1aa263 100644 --- a/src/shared/site-db.ts +++ b/src/shared/site-db.ts @@ -19,9 +19,6 @@ import type { Result } from "#shared/result.ts"; /** Credentials needed to open a read-only connection to a site's database. */ export type SiteDbCredentials = Pick; -/** Result of a read against a site database. */ -export type SiteDbResult = Result; - /** Stubbable client factory so tests can inject an in-memory database. */ export const siteDbApi = { createClient: (url: string, authToken: string): Client => @@ -41,7 +38,7 @@ export const hasSiteDbCredentials = (creds: SiteDbCredentials): boolean => export const withSiteDb = async ( creds: SiteDbCredentials, fn: (client: Client) => Promise, -): Promise> => { +): Promise> => { if (!creds.dbUrl) return { error: "No database URL for this site", ok: false }; // Close on both the success and failure paths rather than in a `finally`: @@ -68,7 +65,7 @@ export const withSiteDb = async ( export const readSiteSetting = ( creds: SiteDbCredentials, key: string, -): Promise> => +): Promise> => withSiteDb(creds, async (client) => { const result = await client.execute({ args: [key], diff --git a/src/shared/site-secrets.ts b/src/shared/site-secrets.ts index 9ad2bc7db4..9dd674e671 100644 --- a/src/shared/site-secrets.ts +++ b/src/shared/site-secrets.ts @@ -22,6 +22,7 @@ import { siteHostingAccess, } from "#shared/builder.ts"; import type { BuiltSite } from "#shared/db/built-sites.ts"; +import type { Result } from "#shared/result.ts"; import { tryStep } from "#shared/try-step.ts"; /** @@ -63,7 +64,7 @@ export type SiteSecretsView = const listSecretNames = ( site: BuiltSite, hostingId: string, -): Promise<{ ok: true; names: string[] } | { ok: false; error: string }> => +): Promise> => tryStep("Failed to list secrets", () => resolveHostingProvider(site.hostingProvider).getSecretNames(hostingId), ); @@ -90,8 +91,8 @@ const resolveSiteSecrets = async ( return { data: { hostingId: pre.hostingId, - names: listed.names, - present: new Set(listed.names), + names: listed.value, + present: new Set(listed.value), }, ok: true, }; diff --git a/src/shared/site-update.ts b/src/shared/site-update.ts index f4a720c78d..b1a506a980 100644 --- a/src/shared/site-update.ts +++ b/src/shared/site-update.ts @@ -15,11 +15,8 @@ import { logActivity } from "#shared/db/activityLog.ts"; import type { BuiltSite } from "#shared/db/built-sites.ts"; import { settings } from "#shared/db/settings.ts"; import { getEnv } from "#shared/env.ts"; -import { - hasSiteDbCredentials, - readSiteSetting, - type SiteDbResult, -} from "#shared/site-db.ts"; +import type { Result } from "#shared/result.ts"; +import { hasSiteDbCredentials, readSiteSetting } from "#shared/site-db.ts"; /* jscpd:ignore-end */ import { tryStep } from "#shared/try-step.ts"; import { @@ -77,7 +74,7 @@ export const deployAndReport = async (opts: { /** Read the version a built site recorded for itself, via its read-only keys. */ export const readSiteScriptVersion = ( site: BuiltSite, -): Promise> => +): Promise> => readSiteSetting(site, CURRENT_SCRIPT_VERSION_KEY); /** diff --git a/src/shared/turso-api.ts b/src/shared/turso-api.ts index 805b42ecf0..890288908a 100644 --- a/src/shared/turso-api.ts +++ b/src/shared/turso-api.ts @@ -18,6 +18,7 @@ import type { CreateDatabaseFn, DatabaseProviderApi, } from "#shared/provider-types.ts"; +import { databaseCredentialsFromResponse } from "#shared/provider-types.ts"; /* jscpd:ignore-end */ @@ -40,10 +41,6 @@ interface CreateTursoDbResponse { }; } -interface CreateTursoTokenResponse { - jwt: string; -} - /** Headers for all Turso API requests. */ const tursoApiHeaders = (): Record => jsonHeaders({ Authorization: `Bearer ${getTursoApiToken()}` }); @@ -93,9 +90,7 @@ const createDatabaseImpl: CreateDatabaseFn = async (name) => { ]); } - const tokenData: CreateTursoTokenResponse = JSON.parse(tokenRes.text); - - return { dbId, dbToken: tokenData.jwt, dbUrl, ok: true }; + return databaseCredentialsFromResponse(dbId, dbUrl, tokenRes.text, "jwt"); }; export const tursoDbProvider: DatabaseProviderApi = { diff --git a/src/shared/update.ts b/src/shared/update.ts index 7342e4b0cf..de3a79e4e9 100644 --- a/src/shared/update.ts +++ b/src/shared/update.ts @@ -16,7 +16,7 @@ import { } from "#shared/db/client.ts"; import { denoDeployApi } from "#shared/deno-deploy-api.ts"; import { logDebug } from "#shared/logger.ts"; -import { requireSuccess } from "#shared/result.ts"; +import { type Result, requireSuccess } from "#shared/result.ts"; /** GitHub repo URL — update here if the repo moves */ export const GITHUB_REPO = "chobbledotcom/tickets"; @@ -250,9 +250,7 @@ export const deployRelease = async ( /** Fetch, download, and deploy the latest release via `deploy`, throwing on any failure. */ const deployLatest = async ( - deploy: ( - code: string, - ) => Promise<{ ok: false; error: string } | { ok: true }>, + deploy: (code: string) => Promise>, ): Promise => { const { code, release } = await fetchAndDownloadRelease(); const result = await deploy(code); diff --git a/test/admin-api-groups.test.ts b/test/features/admin/api-groups.test.ts similarity index 99% rename from test/admin-api-groups.test.ts rename to test/features/admin/api-groups.test.ts index 263957dd68..82262b8f7c 100644 --- a/test/admin-api-groups.test.ts +++ b/test/features/admin/api-groups.test.ts @@ -187,7 +187,7 @@ describeWithEnv("Admin API - Groups", { db: true }, () => { // a transaction on the primary, the API read it back with a plain "read"-mode // `findById`, which Turso can serve from a replica lagging the commit — // returning null and crashing on `row.id`. The read-back now uses the - // primary-pinned `findByIdPrimary`. Stub the replica read (`findById`) to + // primary-pinned `findByIdPrimary`. Stub the optional replica read to // miss the row — the create must still succeed. const findByIdStub = stub(groups.table, "findById", () => Promise.resolve(null), diff --git a/test/admin-api-holidays.test.ts b/test/features/admin/api-holidays.test.ts similarity index 98% rename from test/admin-api-holidays.test.ts rename to test/features/admin/api-holidays.test.ts index 047103ae69..125cdd64a7 100644 --- a/test/admin-api-holidays.test.ts +++ b/test/features/admin/api-holidays.test.ts @@ -267,7 +267,7 @@ describeWithEnv("Admin API - Holidays", { db: true }, () => { // Holiday should still exist const row = await holidays.table.findById(holiday.id); - expect(row).toBeDefined(); + expect(row).not.toBeNull(); }); test("returns 404 for non-existent holiday", async () => { @@ -328,7 +328,7 @@ describeWithEnv("Admin API - Holidays", { db: true }, () => { ); expect(res.status).toBe(403); // The manager's delete was blocked, so the holiday still exists. - expect(await holidays.table.findById(holiday.id)).toBeDefined(); + expect(await holidays.table.findById(holiday.id)).not.toBeNull(); }); }); }); diff --git a/test/admin-api-listings/update.test.ts b/test/features/admin/api.test.ts similarity index 94% rename from test/admin-api-listings/update.test.ts rename to test/features/admin/api.test.ts index d3a67b7aeb..290cc0d65a 100644 --- a/test/admin-api-listings/update.test.ts +++ b/test/features/admin/api.test.ts @@ -1,5 +1,6 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { getDb } from "#shared/db/client.ts"; import { assertJson, expectRejectsEmptyName } from "#test-utils/assertions.ts"; import { describeWithEnv } from "#test-utils/db.ts"; import { createTestGroup } from "#test-utils/db-helpers/groups.ts"; @@ -53,6 +54,25 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { expect(response.status).toBe(404); }); + test("returns 404 when the listing vanishes during update", async () => { + const listing = await createTestListing({ name: "Vanishing listing" }); + await getDb().execute( + `CREATE TRIGGER delete_listing_during_update + AFTER UPDATE ON listings + WHEN NEW.id = ${listing.id} + BEGIN + DELETE FROM listings WHERE id = NEW.id; + END`, + ); + + const response = await apiRequest(`/api/admin/listings/${listing.id}`, { + body: { name: "Gone" }, + method: "PUT", + }); + + expect(response.status).toBe(404); + }); + test("returns 400 when name is empty string", async () => { const listing = await createTestListing({ name: "Will Empty" }); await expectRejectsEmptyName(`/api/admin/listings/${listing.id}`); diff --git a/test/features/admin/catalog-transfer/import/fields.test.ts b/test/features/admin/catalog-transfer/import/fields.test.ts index 725a2bdd36..0fd1735f91 100644 --- a/test/features/admin/catalog-transfer/import/fields.test.ts +++ b/test/features/admin/catalog-transfer/import/fields.test.ts @@ -50,8 +50,8 @@ describeWithEnv("catalog-transfer field validation", { db: true }, () => { }, version: 1, }); - requireSuccess(result); - const imported = (await getListingWithCount(result.id))!; + const importedResult = requireSuccess(result); + const imported = (await getListingWithCount(importedResult.id))!; expect(imported.closes_at).toBe("2026-06-01T12:00:00.000Z"); expect(imported.date).toBe("2026-06-02T09:00:00.000Z"); }); @@ -72,7 +72,7 @@ describeWithEnv("catalog-transfer field validation", { db: true }, () => { version: 1, }); if (!result.ok) throw new Error(result.error); - expect((await getListingWithCount(result.id))!.closes_at).toContain( + expect((await getListingWithCount(result.value.id))!.closes_at).toContain( "2026-06-01", ); }); @@ -142,7 +142,7 @@ describeWithEnv("catalog-transfer field validation", { db: true }, () => { version: 1, }); if (!result.ok) throw new Error(result.error); - expect((await getListingWithCount(result.id))!.closes_at).toBeNull(); + expect((await getListingWithCount(result.value.id))!.closes_at).toBeNull(); }); test("rejects an over-cap duration", async () => { @@ -185,8 +185,8 @@ describeWithEnv("catalog-transfer field validation", { db: true }, () => { version: 1, }); if (!result.ok) throw new Error(result.error); - expect((await getListingWithCount(result.id))!.bookable_days).toContain( - "Monday", - ); + expect( + (await getListingWithCount(result.value.id))!.bookable_days, + ).toContain("Monday"); }); }); diff --git a/test/features/admin/catalog-transfer/import/packages.test.ts b/test/features/admin/catalog-transfer/import/packages.test.ts index c163e37723..6b38576cc4 100644 --- a/test/features/admin/catalog-transfer/import/packages.test.ts +++ b/test/features/admin/catalog-transfer/import/packages.test.ts @@ -38,7 +38,7 @@ const importListingOverride = ( const importStoredListing = async (listing: Record) => { const result = await importCatalog({ kind: "listing", listing, version: 1 }); if (!result.ok) throw new Error(result.error); - const stored = await getListingWithCount(result.id); + const stored = await getListingWithCount(result.value.id); if (!stored) throw new Error("listing not found after import"); return stored; }; diff --git a/test/shared/db/listings/queries.test.ts b/test/integration/db/listings/queries.test.ts similarity index 87% rename from test/shared/db/listings/queries.test.ts rename to test/integration/db/listings/queries.test.ts index 920b1de236..1058a605f0 100644 --- a/test/shared/db/listings/queries.test.ts +++ b/test/integration/db/listings/queries.test.ts @@ -7,11 +7,13 @@ import { } from "#shared/db/listings/attendees.ts"; import { getAllListingOptions, - getListingNamesByIds, - getListingsBySlugsBatch, + getListingsBySlugs, getListingWithCount, getStoredListingsWithCountsByIds, getStoredListingWithCount, + listingNames, + requireListingsWithCountsByIds, + requireListingWithCount, } from "#shared/db/listings/records.ts"; import { enableQueryLog, @@ -128,8 +130,8 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { expect(result?.listing.income).toBe(1800); }); - test("getListingsBySlugsBatch returns empty array for empty slugs", async () => { - const result = await getListingsBySlugsBatch([]); + test("getListingsBySlugs returns empty array for empty slugs", async () => { + const result = await getListingsBySlugs([]); expect(result).toEqual([]); }); @@ -137,7 +139,7 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { expect(await getStoredListingsWithCountsByIds([])).toEqual([]); }); - test("getListingsBySlugsBatch returns listings in slug order", async () => { + test("getListingsBySlugs returns listings in slug order", async () => { const listing1 = await createTestListing({ maxAttendees: 10, name: "Batch A", @@ -149,23 +151,20 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { thankYouUrl: "https://example.com", }); - const results = await getListingsBySlugsBatch([ - listing2.slug, - listing1.slug, - ]); + const results = await getListingsBySlugs([listing2.slug, listing1.slug]); expect(results.length).toBe(2); expect(results[0]?.id).toBe(listing2.id); expect(results[1]?.id).toBe(listing1.id); }); - test("getListingsBySlugsBatch returns null for missing slugs", async () => { + test("getListingsBySlugs returns null for missing slugs", async () => { const listing = await createTestListing({ maxAttendees: 10, name: "Exists", thankYouUrl: "https://example.com", }); - const results = await getListingsBySlugsBatch([listing.slug, "missing"]); + const results = await getListingsBySlugs([listing.slug, "missing"]); expect(results.length).toBe(2); expect(results[0]).not.toBeNull(); expect(results[1]).toBeNull(); @@ -199,21 +198,21 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { expect(await getAllListingOptions()).toEqual([]); }); - test("getListingNamesByIds returns decrypted names only for the given ids", async () => { + test("listingNames.byIds returns decrypted names only for the given ids", async () => { const alpha = await createTestListing({ maxAttendees: 10, name: "Alpha", }); const beta = await createTestListing({ maxAttendees: 10, name: "Beta" }); - const names = await getListingNamesByIds([alpha.id]); + const names = await listingNames.byIds([alpha.id]); expect(names.get(alpha.id)).toBe("Alpha"); expect(names.has(beta.id)).toBe(false); }); - test("getListingNamesByIds returns an empty map for no ids", async () => { - const names = await getListingNamesByIds([]); + test("listingNames.byIds returns an empty map for no ids", async () => { + const names = await listingNames.byIds([]); expect(names.size).toBe(0); }); @@ -262,5 +261,17 @@ describeWithEnv( test("returns null for a missing listing", async () => { expect(await getStoredListingWithCount(99999)).toBeNull(); }); + + test("required listing lookup names a missing listing", async () => { + await expect(requireListingWithCount(99999)).rejects.toThrow( + "Listing not found: 99999", + ); + }); + + test("required listing batch names the first missing listing", async () => { + await expect( + requireListingsWithCountsByIds([99998, 99999]), + ).rejects.toThrow("Listing not found: 99998"); + }); }, ); diff --git a/test/admin-api-listings/input-parsers.test.ts b/test/integration/routes/admin-api-listings-input-parsers.test.ts similarity index 82% rename from test/admin-api-listings/input-parsers.test.ts rename to test/integration/routes/admin-api-listings-input-parsers.test.ts index d5779a694f..3aa2f4adf5 100644 --- a/test/admin-api-listings/input-parsers.test.ts +++ b/test/integration/routes/admin-api-listings-input-parsers.test.ts @@ -35,9 +35,9 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { expect(result.ok).toBe(true); if (result.ok) { - expect(result.input.active).toBe(false); - expect(result.input.bookableDays).toEqual(["Monday"]); - expect(result.input.slug).toBeTruthy(); + expect(result.value.active).toBe(false); + expect(result.value.bookableDays).toEqual(["Monday"]); + expect(result.value.slug).toBeTruthy(); } }); @@ -79,7 +79,7 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { if (sent !== undefined) body.use_defaults = sent; const result = await bodyToCreateInput(body); expect(result.ok).toBe(true); - if (result.ok) expect(result.input.useDefaults).toBe(expected); + if (result.ok) expect(result.value.useDefaults).toBe(expected); } }); }); @@ -119,24 +119,24 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { const result = await bodyToUpdateInput({}, existing); expect(result.ok).toBe(true); if (result.ok) { - expect(result.input.name).toBe("Existing"); - expect(result.input.description).toBe("Existing desc"); - expect(result.input.location).toBe("Old Place"); - expect(result.input.unitPrice).toBe(100); - expect(result.input.maxQuantity).toBe(2); - expect(result.input.thankYouUrl).toBe("https://old.com/thanks"); - expect(result.input.webhookUrl).toBe("https://old.com/hook"); - expect(result.input.active).toBe(true); - expect(result.input.fields).toBe("email"); - expect(result.input.closesAt).toBe("2026-01-02T00:00:00.000Z"); - expect(result.input.listingType).toBe("standard"); - expect(result.input.bookableDays).toEqual(["Monday"]); - expect(result.input.minimumDaysBefore).toBe(1); - expect(result.input.maximumDaysAfter).toBe(90); - expect(result.input.nonTransferable).toBe(false); - expect(result.input.canPayMore).toBe(false); - expect(result.input.hidden).toBe(false); - expect(result.input.maxPrice).toBe(0); + expect(result.value.name).toBe("Existing"); + expect(result.value.description).toBe("Existing desc"); + expect(result.value.location).toBe("Old Place"); + expect(result.value.unitPrice).toBe(100); + expect(result.value.maxQuantity).toBe(2); + expect(result.value.thankYouUrl).toBe("https://old.com/thanks"); + expect(result.value.webhookUrl).toBe("https://old.com/hook"); + expect(result.value.active).toBe(true); + expect(result.value.fields).toBe("email"); + expect(result.value.closesAt).toBe("2026-01-02T00:00:00.000Z"); + expect(result.value.listingType).toBe("standard"); + expect(result.value.bookableDays).toEqual(["Monday"]); + expect(result.value.minimumDaysBefore).toBe(1); + expect(result.value.maximumDaysAfter).toBe(90); + expect(result.value.nonTransferable).toBe(false); + expect(result.value.canPayMore).toBe(false); + expect(result.value.hidden).toBe(false); + expect(result.value.maxPrice).toBe(0); } }); @@ -155,7 +155,7 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { // false, so clearing the default later still restores its own value. const result = await bodyToUpdateInput({ name: "Renamed" }, resolved); expect(result.ok).toBe(true); - if (result.ok) expect(result.input.hidden).toBe(false); + if (result.ok) expect(result.value.hidden).toBe(false); }); test("preserves use_defaults when absent and toggles it when sent", async () => { @@ -167,10 +167,10 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { }); // Omitted → the flag is preserved (an unrelated PUT can't un-inherit it). const kept = await bodyToUpdateInput({}, existing); - expect(kept.ok && kept.input.useDefaults).toBe(true); + expect(kept.ok && kept.value.useDefaults).toBe(true); // Explicit false → turned off. const off = await bodyToUpdateInput({ use_defaults: false }, existing); - expect(off.ok && off.input.useDefaults).toBe(false); + expect(off.ok && off.value.useDefaults).toBe(false); }); test("preserves existing closes_at null as empty string", async () => { @@ -184,7 +184,7 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { const result = await bodyToUpdateInput({}, existing); expect(result.ok).toBe(true); if (result.ok) { - expect(result.input.closesAt).toBe(""); + expect(result.value.closesAt).toBe(""); } }); }); diff --git a/test/admin-api-listings/read.test.ts b/test/integration/routes/admin-api-listings-read.test.ts similarity index 100% rename from test/admin-api-listings/read.test.ts rename to test/integration/routes/admin-api-listings-read.test.ts diff --git a/test/routes/api/book-payments.test.ts b/test/integration/routes/api-book-payments.test.ts similarity index 98% rename from test/routes/api/book-payments.test.ts rename to test/integration/routes/api-book-payments.test.ts index 235a0b4a35..7b06581457 100644 --- a/test/routes/api/book-payments.test.ts +++ b/test/integration/routes/api-book-payments.test.ts @@ -17,7 +17,7 @@ import { describePublicApi, fetchListingBySlug, withCheckoutStub, -} from "./helpers.ts"; +} from "../../routes/api/helpers.ts"; describePublicApi(() => { describe("POST /api/listings/:slug/book", () => { @@ -71,10 +71,10 @@ describePublicApi(() => { expect(attendee?.bookings[0]?.price_paid).toBe(1000); // The booking carries the public-default status, matching the web free // path so a balance-carrying attendee is never left status-less. - const { getPublicStatusId } = await import( + const { requirePublicStatusId } = await import( "#shared/db/attendee-statuses.ts" ); - expect(attendee?.status_id).toBe(await getPublicStatusId()); + expect(attendee?.status_id).toBe(await requirePublicStatusId()); }); test("books a free listing without an owed balance when a provider is configured", async () => { diff --git a/test/lib/server-attendee-form/status.test.ts b/test/integration/server/attendee-form-status.test.ts similarity index 97% rename from test/lib/server-attendee-form/status.test.ts rename to test/integration/server/attendee-form-status.test.ts index 6f7fc7b5eb..19a6d19804 100644 --- a/test/lib/server-attendee-form/status.test.ts +++ b/test/integration/server/attendee-form-status.test.ts @@ -3,7 +3,7 @@ import { describe, it as test } from "@std/testing/bdd"; import { attendeeAccount } from "#shared/accounting/accounts.ts"; import { attendeeStatuses, - getPaidDefaultStatus, + requirePaidDefaultStatus, } from "#shared/db/attendee-statuses.ts"; import { attendeesApi } from "#shared/db/attendees/api.ts"; import { getAttendeeBalanceState } from "#shared/db/attendees/balance.ts"; @@ -102,7 +102,7 @@ describeWithEnv( // reachable from a hand-crafted POST) must not clear the attendee — it // falls back to the public default instead. const reservation = await newReservation(); // a second, non-default status - const publicDefault = await getPaidDefaultStatus(); // the seed is also public default + const publicDefault = await requirePaidDefaultStatus(); // the seed is also public default const id = await seedAttendee(reservation.id, 1500); const form = await buildAttendeeEditForm(id, { extra: { status_id: "" }, @@ -117,7 +117,7 @@ describeWithEnv( }); test("edit page warns when a paid status still owes a balance", async () => { - const paid = await getPaidDefaultStatus(); + const paid = await requirePaidDefaultStatus(); const id = await seedAttendee(paid!.id, 1500); const html = await getEdit(id); expect(html).toContain("paid status but still owes"); @@ -212,14 +212,14 @@ describeWithEnv( test("edit page pre-selects the public default when the attendee has no status", async () => { await newReservation(); // a second status, so the select is shown - const defaultStatus = await getPaidDefaultStatus(); // also the public default seed + const defaultStatus = await requirePaidDefaultStatus(); // also the public default seed const id = await seedAttendee(null, 0); // attendee has no status const html = await getEdit(id); expect(hasSelectedOption(html, String(defaultStatus!.id))).toBe(true); }); test("edit page submits the lone status as a hidden field (no dropdown)", async () => { - const only = await getPaidDefaultStatus(); // the single seeded status + const only = await requirePaidDefaultStatus(); // the single seeded status const id = await seedAttendee(only!.id, 0); const html = await getEdit(id); // No status dropdown is rendered for a single-status site... diff --git a/test/lib/server-builder.test.ts b/test/integration/server/builder.test.ts similarity index 99% rename from test/lib/server-builder.test.ts rename to test/integration/server/builder.test.ts index a88424612f..80a15467de 100644 --- a/test/lib/server-builder.test.ts +++ b/test/integration/server/builder.test.ts @@ -295,8 +295,8 @@ describeWithEnv( const site = await expectSiteCreated(response); expect(site.name).toBe("Auto DB Site"); - expect(site.dbUrl).toBe(MOCK_DB_RESULT.dbUrl); - expect(site.dbToken).toBe(MOCK_DB_RESULT.dbToken); + expect(site.dbUrl).toBe(MOCK_DB_RESULT.value.dbUrl); + expect(site.dbToken).toBe(MOCK_DB_RESULT.value.dbToken); }); }); diff --git a/test/lib/server-built-sites-update.test.ts b/test/integration/server/built-sites-update.test.ts similarity index 97% rename from test/lib/server-built-sites-update.test.ts rename to test/integration/server/built-sites-update.test.ts index f3d2830502..f82be769dd 100644 --- a/test/lib/server-built-sites-update.test.ts +++ b/test/integration/server/built-sites-update.test.ts @@ -19,7 +19,7 @@ import { type EnvScope, withEnv } from "#test-utils/env.ts"; import { type TempPath, tempDir } from "#test-utils/files.ts"; import { stubReleaseFetch } from "#test-utils/mocks.ts"; import { adminFormPost, testCookie } from "#test-utils/session.ts"; -import { useLocalStoragePath } from "./_shared-site-update.ts"; +import { useLocalStoragePath } from "../../lib/_shared-site-update.ts"; /** A built site database URL whose backups land in a site-specific folder. */ const SITE_DB_URL = "libsql://01ABC-client-site.lite.bunnydb.net"; @@ -247,13 +247,10 @@ describeWithEnv( await seedSiteBackup(SITE_DB_URL); using _fetch = stubReleaseFetch(); const deployStub = stub(denoDeployApi, "deployCode", () => - Promise.resolve({ - hostname: "https://app.deno.dev", - ok: true as const, - }), + Promise.resolve({ ok: true as const, value: "https://app.deno.dev" }), ); const getEnvVarNamesStub = stub(denoDeployApi, "getEnvVarNames", () => - Promise.resolve({ names: [], ok: true as const }), + Promise.resolve({ ok: true as const, value: [] }), ); try { const { response } = await adminFormPost( diff --git a/test/lib/server-built-sites.test.ts b/test/integration/server/built-sites.test.ts similarity index 98% rename from test/lib/server-built-sites.test.ts rename to test/integration/server/built-sites.test.ts index b4d522c440..a212388215 100644 --- a/test/lib/server-built-sites.test.ts +++ b/test/integration/server/built-sites.test.ts @@ -524,6 +524,16 @@ describeWithEnv("server (admin built sites)", builtSitesTestEnv, () => { expect(found).not.toBeNull(); }); + test("table lookups preserve missing rows", async () => { + const site = await createTestBuiltSite({ name: "Lookup Site" }); + const { builtSitesCrudTable } = await import("#shared/db/built-sites.ts"); + expect( + (await builtSitesCrudTable.findByIds([site.id, 999_999])).map( + (row) => row?.id ?? null, + ), + ).toEqual([site.id, null]); + }); + test("name confirmation is case-insensitive", async () => { const site = await createTestBuiltSite({ name: "Case Test" }); const { response } = await adminFormPost( diff --git a/test/lib/catalog-transfer.test.ts b/test/integration/server/catalog-transfer.test.ts similarity index 93% rename from test/lib/catalog-transfer.test.ts rename to test/integration/server/catalog-transfer.test.ts index 413cc776a8..0a127134ed 100644 --- a/test/lib/catalog-transfer.test.ts +++ b/test/integration/server/catalog-transfer.test.ts @@ -45,7 +45,17 @@ const importBuiltSiteListing = async (name: string): Promise => { version: 1, }); if (!result.ok) throw new Error(result.error); - return (await getListingWithCount(result.id))!.assign_built_site; + return (await getListingWithCount(result.value.id))!.assign_built_site; +}; + +const importLogisticsListing = async (name: string): Promise => { + const result = await importCatalog({ + kind: "listing", + listing: { maxAttendees: 1, name, usesLogistics: true }, + version: 1, + }); + if (!result.ok) throw new Error(result.error); + return (await getListingWithCount(result.value.id))!.uses_logistics; }; describeWithEnv("catalog-transfer", { db: true }, () => { @@ -73,20 +83,22 @@ describeWithEnv("catalog-transfer", { db: true }, () => { blob.listing.name = "Child Copy"; const result = await importCatalog(blob); expect(result).toEqual({ - id: expect.any(Number), - kind: "listing", - name: "Child Copy", ok: true, + value: { + id: expect.any(Number), + kind: "listing", + name: "Child Copy", + }, }); if (!result.ok) throw new Error("unreachable"); - const imported = (await getListingWithCount(result.id))!; + const imported = (await getListingWithCount(result.value.id))!; expect(imported.name).toBe("Child Copy"); expect(imported.unit_price).toBe(1500); // Slug is freshly minted, never copied from the source. expect(imported.slug).not.toBe(child.slug); - expect(await listingGroups.getIds(result.id)).toEqual([group.id]); - expect(await listingParents.getIds(result.id)).toEqual([parent.id]); + expect(await listingGroups.getIds(result.value.id)).toEqual([group.id]); + expect(await listingParents.getIds(result.value.id)).toEqual([parent.id]); }); test("preserves a child's bookable-alone standalone page", async () => { @@ -103,8 +115,8 @@ describeWithEnv("catalog-transfer", { db: true }, () => { blob.listing.name = "Alone Copy"; const result = await importCatalog(blob); - requireSuccess(result); - const imported = (await getListingWithCount(result.id))!; + const importedResult = requireSuccess(result); + const imported = (await getListingWithCount(importedResult.id))!; expect(imported.bookable_alone).toBe(true); }); @@ -129,7 +141,7 @@ describeWithEnv("catalog-transfer", { db: true }, () => { }); if (!created.ok) throw new Error(created.error); - const blob = unwrapExport(await exportListing(created.id)); + const blob = unwrapExport(await exportListing(created.value.id)); expect(blob.listing.useDefaults).toBe(true); // The row's own cell (false), not the resolved default (true). expect(blob.listing.hidden).toBe(false); @@ -170,13 +182,13 @@ describeWithEnv("catalog-transfer", { db: true }, () => { }); if (!result.ok) throw new Error(result.error); - const imported = (await getListingWithCount(result.id))!; + const imported = (await getListingWithCount(result.value.id))!; expect(imported.closes_at).toBe("2030-01-01T00:00:00.000Z"); // The derived listing_prices base row is re-synced from unit_price after // the transactional insert (which bypasses the table wrapper). const priceRows = await execute( "SELECT unit_price FROM listing_prices WHERE listing_id = ? AND price_type = 'base'", - [result.id], + [result.value.id], ); expect(priceRows.rows.map((r) => Number(r.unit_price))).toEqual([2500]); }); @@ -218,11 +230,11 @@ describeWithEnv("catalog-transfer", { db: true }, () => { if (!result.ok) throw new Error(result.error); const rows = await getGroupPackagePrices(group.id); - const importedRow = rows.find((r) => r.listing_id === result.id)!; + const importedRow = rows.find((r) => r.listing_id === result.value.id)!; expect(importedRow.package_price).toBe(800); expect(importedRow.quantity).toBe(3); const dayPrices = await getGroupDayPrices(group.id); - expect(dayPrices.get(result.id)).toEqual(new Map([[1, 900]])); + expect(dayPrices.get(result.value.id)).toEqual(new Map([[1, 900]])); // The existing member's overrides are untouched by the targeted insert. expect(rows.find((r) => r.listing_id === member.id)?.package_price).toBe( 800, @@ -256,24 +268,24 @@ describeWithEnv("catalog-transfer", { db: true }, () => { blob.group.name = "Combo Copy"; const result = await importCatalog(blob); if (!result.ok) throw new Error(result.error); - expect(result.kind).toBe("group"); + expect(result.value.kind).toBe("group"); - const rows = await getGroupPackagePrices(result.id); + const rows = await getGroupPackagePrices(result.value.id); expect(rows).toEqual([ { - group_id: result.id, + group_id: result.value.id, listing_id: a.id, package_price: 800, quantity: 2, }, { - group_id: result.id, + group_id: result.value.id, listing_id: b.id, package_price: null, quantity: 1, }, { - group_id: result.id, + group_id: result.value.id, listing_id: c.id, package_price: 0, quantity: 1, @@ -506,7 +518,7 @@ describeWithEnv("catalog-transfer review fixes", { db: true }, () => { "editor", ); if (!result.ok) throw new Error(result.error); - const imported = (await getListingWithCount(result.id))!; + const imported = (await getListingWithCount(result.value.id))!; expect(imported.webhook_url).toBe(""); expect(imported.use_defaults).toBe(false); }); @@ -525,7 +537,7 @@ describeWithEnv("catalog-transfer review fixes", { db: true }, () => { "owner", ); if (!result.ok) throw new Error(result.error); - const imported = (await getListingWithCount(result.id))!; + const imported = (await getListingWithCount(result.value.id))!; expect(imported.webhook_url).toBe("https://example.com/hook"); }); @@ -534,24 +546,12 @@ describeWithEnv("catalog-transfer review fixes", { db: true }, () => { }); test("clears uses-logistics when logistics is disabled", async () => { - const result = await importCatalog({ - kind: "listing", - listing: { maxAttendees: 1, name: "Logi Off", usesLogistics: true }, - version: 1, - }); - if (!result.ok) throw new Error(result.error); - expect((await getListingWithCount(result.id))!.uses_logistics).toBe(false); + expect(await importLogisticsListing("Logi Off")).toBe(false); }); test("keeps uses-logistics when logistics is enabled", async () => { settings.setForTest(featureSetting("logistics")); - const result = await importCatalog({ - kind: "listing", - listing: { maxAttendees: 1, name: "Logi On", usesLogistics: true }, - version: 1, - }); - if (!result.ok) throw new Error(result.error); - expect((await getListingWithCount(result.id))!.uses_logistics).toBe(true); + expect(await importLogisticsListing("Logi On")).toBe(true); }); test("clears package overrides for a non-package group membership", async () => { @@ -564,7 +564,7 @@ describeWithEnv("catalog-transfer review fixes", { db: true }, () => { }); if (!result.ok) throw new Error(result.error); const row = (await getGroupPackagePrices(group.id)).find( - (r) => r.listing_id === result.id, + (r) => r.listing_id === result.value.id, )!; // The override is dropped because the group isn't a package. expect(row.package_price).toBeNull(); @@ -580,7 +580,7 @@ describeWithEnv("catalog-transfer review fixes", { db: true }, () => { version: 1, }); if (!result.ok) throw new Error(result.error); - const row = (await getGroupPackagePrices(result.id))[0]!; + const row = (await getGroupPackagePrices(result.value.id))[0]!; expect(row.package_price).toBeNull(); expect(row.quantity).toBe(1); }); @@ -634,7 +634,7 @@ describeWithEnv("catalog-transfer review fixes", { db: true }, () => { version: 1, }); if (!result.ok) throw new Error(result.error); - expect((await listingParents.getIds(result.id)).length).toBe(30); + expect((await listingParents.getIds(result.value.id)).length).toBe(30); }); test("imports a listing that belongs to many groups", async () => { @@ -663,7 +663,7 @@ describeWithEnv("catalog-transfer review fixes", { db: true }, () => { version: 1, }); if (!result.ok) throw new Error(result.error); - expect((await listingGroups.getIds(result.id)).length).toBe(30); + expect((await listingGroups.getIds(result.value.id)).length).toBe(30); }); test("imports a child listing that also belongs to a regular group", async () => { @@ -680,8 +680,8 @@ describeWithEnv("catalog-transfer review fixes", { db: true }, () => { version: 1, }); if (!result.ok) throw new Error(result.error); - expect((await listingParents.getIds(result.id)).length).toBe(1); - expect((await listingGroups.getIds(result.id)).length).toBe(1); + expect((await listingParents.getIds(result.value.id)).length).toBe(1); + expect((await listingGroups.getIds(result.value.id)).length).toBe(1); }); test("hides the webhook URL from an editor export", async () => { diff --git a/test/shared/demo.test.ts b/test/integration/server/demo.test.ts similarity index 98% rename from test/shared/demo.test.ts rename to test/integration/server/demo.test.ts index 80bbea2156..f47b217bfa 100644 --- a/test/shared/demo.test.ts +++ b/test/integration/server/demo.test.ts @@ -206,9 +206,9 @@ describe("wrapResourceForDemo", () => { fields: [], loadOrNull: () => Promise.resolve({ id: 1, name: "" }), parseInput: (_form: URLSearchParams) => - Promise.resolve({ input: {}, ok: true as const }), + Promise.resolve({ ok: true as const, value: {} }), parsePartialInput: (_form: URLSearchParams) => - Promise.resolve({ input: {}, ok: true as const }), + Promise.resolve({ ok: true as const, value: {} }), table: {} as never, update: (_id: unknown, form: URLSearchParams) => { lastUpdateForm = form; diff --git a/test/lib/server-listings/create.test.ts b/test/integration/server/listings-create.test.ts similarity index 94% rename from test/lib/server-listings/create.test.ts rename to test/integration/server/listings-create.test.ts index 57ce9af87c..8e3cfb96ac 100644 --- a/test/lib/server-listings/create.test.ts +++ b/test/integration/server/listings-create.test.ts @@ -106,13 +106,8 @@ describeWithEnv("server listings > create", { db: true }, () => { }); test("still creates when the read-back replica lags the just-committed write", async () => { - // Regression: the create resource wrote the row in a transaction (on the - // primary), then read it back with a plain "read"-mode `findById`. Turso can - // route that read to a replica still lagging the commit, so it returned null - // and the handler crashed dereferencing `row.id` ("Cannot read properties of - // null (reading 'id')"). The read-back now uses `findByIdPrimary` - // (read-your-writes). Stub the replica read (`findById`) to miss the row — - // the create must still succeed because it no longer reads back that way. + // The primary read-back succeeds even while an optional replica read + // still misses the newly committed row. const findByIdStub = stub(listingsTable, "findById", () => Promise.resolve(null), ); diff --git a/test/lib/server-listings/error-pages-and-fallbacks.test.ts b/test/integration/server/listings-error-pages.test.ts similarity index 98% rename from test/lib/server-listings/error-pages-and-fallbacks.test.ts rename to test/integration/server/listings-error-pages.test.ts index 84847cb6fa..182d2c4ff3 100644 --- a/test/lib/server-listings/error-pages-and-fallbacks.test.ts +++ b/test/integration/server/listings-error-pages.test.ts @@ -215,8 +215,8 @@ describeWithEnv( }); // handleAdminListingEditPost calls getListingWithCount (raw SQL), then - // updateResource.update which calls requireExists -> table.findById. - // We spy on findById to return null, simulating the listing being deleted + // updateResource.update which checks the nullable table.findById result. + // Return null to simulate the listing being deleted // between the initial check and the update. const findByIdStub2 = stub(listingsTable, "findById", () => Promise.resolve(null), diff --git a/test/lib/server-reservation/edge-cases.test.ts b/test/integration/server/reservation-edge-cases.test.ts similarity index 94% rename from test/lib/server-reservation/edge-cases.test.ts rename to test/integration/server/reservation-edge-cases.test.ts index c956f4bc00..6065b03148 100644 --- a/test/lib/server-reservation/edge-cases.test.ts +++ b/test/integration/server/reservation-edge-cases.test.ts @@ -15,7 +15,10 @@ import { modifierUsageAmount, modifierUsageCount, } from "#test-utils/modifiers.ts"; -import { bookFreeOrder, bookPaidReservation } from "./_shared-setup.ts"; +import { + bookFreeOrder, + bookPaidReservation, +} from "../../lib/server-reservation/_shared-setup.ts"; import { createProgrammeCharge, createSave10Promo, @@ -25,7 +28,7 @@ import { setPublicReservation, setupReservationListing, stubPaidSession, -} from "./helpers.ts"; +} from "../../lib/server-reservation/helpers.ts"; describeWithEnv( "server (reservation deposit at checkout)", @@ -129,15 +132,16 @@ describeWithEnv( } }); - test("carries no deposit when no public-default status is configured", async () => { + test("fails when no public-default status is configured", async () => { const listing = await setupReservationListing(); - // Clear the public-default flag so getPublicDefaultStatus returns null. + // Clear the public-default flag so the required lookup fails. await getDb().execute( "UPDATE attendee_statuses SET is_public_default = 0", ); attendeeStatuses.invalidate(); - const captured = await captureCheckoutIntent(listing); - expect(captured?.reservationAmount).toBeUndefined(); + await expect(captureCheckoutIntent(listing)).rejects.toThrow( + "No attendee status has the required is_public_default flag", + ); }); test("charges no deposit when the amount is zero, leaving the full balance", async () => { diff --git a/test/lib/server-reservation/no-provider.test.ts b/test/integration/server/reservation-no-provider.test.ts similarity index 93% rename from test/lib/server-reservation/no-provider.test.ts rename to test/integration/server/reservation-no-provider.test.ts index 28f6ff90a6..a5f52e2502 100644 --- a/test/lib/server-reservation/no-provider.test.ts +++ b/test/integration/server/reservation-no-provider.test.ts @@ -1,6 +1,6 @@ import { expect } from "@std/expect"; import { afterEach, it as test } from "@std/testing/bdd"; -import { getPublicDefaultStatus } from "#shared/db/attendee-statuses.ts"; +import { requirePublicDefaultStatus } from "#shared/db/attendee-statuses.ts"; import { settings } from "#shared/db/settings.ts"; import { resetStripeClient } from "#shared/stripe.ts"; import { describeWithEnv } from "#test-utils/db.ts"; @@ -9,12 +9,12 @@ import { modifierUsageAmount, modifierUsageCount, } from "#test-utils/modifiers.ts"; -import { bookFreeOrder } from "./_shared-setup.ts"; +import { bookFreeOrder } from "../../lib/server-reservation/_shared-setup.ts"; import { createOptionalAddOn, latestAttendee, submitBuyerOrder, -} from "./helpers.ts"; +} from "../../lib/server-reservation/helpers.ts"; describeWithEnv( "server (booking without a payment provider)", @@ -29,7 +29,7 @@ describeWithEnv( // The seeded public-default status is the plain non-reservation // "Confirmed", so the full balance is owed regardless of any configured // reservation amount — exactly as a zero-deposit reservation behaves. - const status = await getPublicDefaultStatus(); + const status = await requirePublicDefaultStatus(); const listing = await createTestListing({ maxAttendees: 10, maxQuantity: 5, diff --git a/test/lib/server-scheduled.test.ts b/test/integration/server/scheduled.test.ts similarity index 77% rename from test/lib/server-scheduled.test.ts rename to test/integration/server/scheduled.test.ts index f2c9dcb3bb..fc7948853f 100644 --- a/test/lib/server-scheduled.test.ts +++ b/test/integration/server/scheduled.test.ts @@ -45,24 +45,28 @@ const lastPrunedOf = async (siteId: number): Promise => ) )?.last_pruned ?? ""; -describeWithEnv("server (scheduled tasks): self-prune", { db: true }, () => { - test("pinging /scheduled prunes this site", async () => { - const orphanId = await insertOldOrphan(365); +describeWithEnv( + "server (scheduled tasks): self-prune", + { db: true, env: { CAN_BUILD_SITES: undefined } }, + () => { + test("pinging /scheduled prunes this site", async () => { + const orphanId = await insertOldOrphan(365); - const response = await scheduled("GET"); + const response = await scheduled("GET"); - expect(response.status).toBe(200); - expect(await response.json()).toEqual({ ok: true, poked: null }); - // Per-request pruning (auto-purge on by default) reaped the year-old orphan. - expect(await attendeeExists(orphanId)).toBe(false); - }); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, poked: null }); + // Per-request pruning (auto-purge on by default) reaped the year-old orphan. + expect(await attendeeExists(orphanId)).toBe(false); + }); - test("needs no auth — a bare POST is accepted", async () => { - const response = await scheduled("POST"); - expect(response.status).toBe(200); - expect(await response.json()).toEqual({ ok: true, poked: null }); - }); -}); + test("needs no auth — a bare POST is accepted", async () => { + const response = await scheduled("POST"); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, poked: null }); + }); + }, +); describeWithEnv( "server (scheduled tasks): built forwarding", @@ -113,9 +117,13 @@ describeWithEnv( }, ); -describeWithEnv("server (scheduled tasks): not a builder", { db: true }, () => { - test("POST does not poke built sites when not a builder", async () => { - await insertBuiltSite("Client", "client.b-cdn.net"); - await expectPostScheduledPokesNothing(); - }); -}); +describeWithEnv( + "server (scheduled tasks): not a builder", + { db: true, env: { CAN_BUILD_SITES: undefined } }, + () => { + test("POST does not poke built sites when not a builder", async () => { + await insertBuiltSite("Client", "client.b-cdn.net"); + await expectPostScheduledPokesNothing(); + }); + }, +); diff --git a/test/lib/server-settings/statuses.test.ts b/test/integration/server/settings-statuses.test.ts similarity index 99% rename from test/lib/server-settings/statuses.test.ts rename to test/integration/server/settings-statuses.test.ts index 4b7aaf6f5f..e8fb2e50dd 100644 --- a/test/lib/server-settings/statuses.test.ts +++ b/test/integration/server/settings-statuses.test.ts @@ -5,7 +5,7 @@ import { getAllActivityLog } from "#shared/db/activityLog.ts"; import { attendeeStatuses, getAttendeeStatus, - getPublicDefaultStatus, + requirePublicDefaultStatus, } from "#shared/db/attendee-statuses.ts"; import { getDb } from "#shared/db/client.ts"; import { RESERVATION_AMOUNT_HINT } from "#shared/reservation-amount.ts"; @@ -159,7 +159,7 @@ describeWithEnv("server (admin attendee statuses)", { db: true }, () => { }); await expectFlashRedirect(PATH, "Status created")(response); - const newDefault = await getPublicDefaultStatus(); + const newDefault = await requirePublicDefaultStatus(); expect(newDefault?.name).toBe("New Default"); // The seed is no longer the public default. expect((await getAttendeeStatus(seed.id))?.is_public_default).toBe(false); diff --git a/test/shared/site-assignment.test.ts b/test/integration/server/site-assignment.test.ts similarity index 99% rename from test/shared/site-assignment.test.ts rename to test/integration/server/site-assignment.test.ts index b0609ccdda..ea08ca5ad6 100644 --- a/test/shared/site-assignment.test.ts +++ b/test/integration/server/site-assignment.test.ts @@ -722,7 +722,7 @@ describeWithEnv( body: (setStub: SetEnvVarsStub) => Promise, ): Promise => { const setStub = stub(denoDeployApi, "setEnvVars", () => - Promise.resolve({ ok: true as const }), + Promise.resolve({ ok: true as const, value: undefined }), ); try { return await body(setStub); diff --git a/test/lib/server-balance-helpers.ts b/test/lib/server-balance-helpers.ts index 643c2ff805..294e42b1be 100644 --- a/test/lib/server-balance-helpers.ts +++ b/test/lib/server-balance-helpers.ts @@ -2,7 +2,7 @@ import { expect } from "@std/expect"; import { stub } from "@std/testing/mock"; import { handleRequest } from "#routes"; import { signBalanceToken } from "#shared/balance-link.ts"; -import { getPaidDefaultStatus } from "#shared/db/attendee-statuses.ts"; +import { requirePaidDefaultStatus } from "#shared/db/attendee-statuses.ts"; import { getAttendeeBalanceState } from "#shared/db/attendees/balance.ts"; import { getDb } from "#shared/db/client.ts"; import { stripeApi } from "#shared/stripe.ts"; @@ -146,7 +146,7 @@ export const expectSettled = async ( sessionId: string, attendeeId: number, ): Promise => { - const paid = await getPaidDefaultStatus(); + const paid = await requirePaidDefaultStatus(); const response = await handleRequest( mockRequest(`/payment/success?session_id=${sessionId}`), ); diff --git a/test/lib/server-groups/tabs.test.ts b/test/lib/server-groups/tabs.test.ts index d82e53ab25..45fb839749 100644 --- a/test/lib/server-groups/tabs.test.ts +++ b/test/lib/server-groups/tabs.test.ts @@ -12,7 +12,11 @@ import { import { describeWithEnv } from "#test-utils/db.ts"; import { createTestGroup } from "#test-utils/db-helpers/groups.ts"; import { createTestListing } from "#test-utils/db-helpers/listings.ts"; -import { awaitTestRequest, mockFormRequest } from "#test-utils/mocks.ts"; +import { + awaitTestRequest, + mockFormRequest, + mockRequest, +} from "#test-utils/mocks.ts"; import { adminFormPost, adminGet, @@ -171,6 +175,30 @@ describeWithEnv( ).toBe(true); }); + test("assigns existing listings when another selection was deleted", async () => { + const group = await createTestGroup({ + name: "Stale selection group", + slug: "stale-selection-group", + }); + const listing = await createTestListing({ name: "Existing selection" }); + const body = new URLSearchParams({ csrf_token: await testCsrfToken() }); + body.append("listing_ids", String(listing.id)); + body.append("listing_ids", "999999"); + const response = await handleRequest( + mockRequest(`/admin/groups/${group.id}/add-listings`, { + body, + headers: { cookie: await testCookie() }, + method: "POST", + }), + ); + + await expectFlashRedirect( + `/admin/groups/${group.id}`, + "Listings added to group", + )(response); + expect(await listingGroups.getIds(listing.id)).toEqual([group.id]); + }); + test("handles empty selection gracefully", async () => { const group = await createTestGroup({ name: "Empty Select", diff --git a/test/lib/server-reservation/helpers.ts b/test/lib/server-reservation/helpers.ts index dcd912f24d..af1e9f420f 100644 --- a/test/lib/server-reservation/helpers.ts +++ b/test/lib/server-reservation/helpers.ts @@ -2,7 +2,7 @@ import { expect } from "@std/expect"; import { stub } from "@std/testing/mock"; import { attendeeStatuses, - getPublicDefaultStatus, + requirePublicDefaultStatus, } from "#shared/db/attendee-statuses.ts"; import { attendeesApi } from "#shared/db/attendees/api.ts"; import { getAttendeeBalanceState } from "#shared/db/attendees/balance.ts"; @@ -27,7 +27,7 @@ export const setPublicReservation = async (amount: string): Promise => { sql: "UPDATE attendee_statuses SET is_reservation = 1, reservation_amount = ? WHERE is_public_default = 1", }); attendeeStatuses.invalidate(); - const status = await getPublicDefaultStatus(); + const status = await requirePublicDefaultStatus(); return status!.id; }; diff --git a/test/lib/server-site-page-public.test.ts b/test/lib/server-site-page-public.test.ts index 9ab98f3dfa..ed330e91f4 100644 --- a/test/lib/server-site-page-public.test.ts +++ b/test/lib/server-site-page-public.test.ts @@ -278,6 +278,15 @@ describeWithEnv("server (public site pages)", { db: true }, () => { expect(html).not.toContain('href="/ticket/gg"'); }); + test("a page with a missing listing item still renders", async () => { + const page = await makePage("missing-listing-item"); + await addPageItem(page.id, "listing", 999_999); + + const html = await assertPublicHtml("/page/missing-listing-item"); + expect(html).toContain("

Page missing-listing-item

"); + expect(html).not.toContain('href="/ticket/'); + }); + test("a package group with an incomplete bundle renders dead despite a bookable member", async () => { // A package is all-or-nothing: one inactive member makes the whole bundle // unbuyable, so its /ticket/ page 404s. The nav link must be dead diff --git a/test/shared/address-lookup/easypostcodes.test.ts b/test/shared/address-lookup/easypostcodes.test.ts index a10a348c58..ea6c7e617a 100644 --- a/test/shared/address-lookup/easypostcodes.test.ts +++ b/test/shared/address-lookup/easypostcodes.test.ts @@ -114,7 +114,7 @@ describe("fetchEasypostcodesAddresses", () => { const result = await fetchEasypostcodesAddresses("SW1A 1AA", "secret-key"); - expect(result).toEqual({ addresses: [], ok: true }); + expect(result).toEqual({ ok: true, value: [] }); // includeGeo asks the API to return each address's latitude/longitude. expect(captured).toEqual({ key: "secret-key", @@ -136,18 +136,18 @@ describe("fetchEasypostcodesAddresses", () => { ); expect(await fetchEasypostcodesAddresses("SW1A 1AA", "k")).toEqual({ - addresses: [ + ok: true, + value: [ { lat: "51.503396", line: "10 Downing Street", lng: "-0.127640" }, ], - ok: true, }); }); test("treats a 404 as no matches, not a failure", async () => { using _fetch = stubFetch(new Response("Not Found", { status: 404 })); expect(await fetchEasypostcodesAddresses("ZZ99 9ZZ", "k")).toEqual({ - addresses: [], ok: true, + value: [], }); }); diff --git a/test/shared/address-lookup/service.test.ts b/test/shared/address-lookup/service.test.ts index edb72f5117..bfdbedd89e 100644 --- a/test/shared/address-lookup/service.test.ts +++ b/test/shared/address-lookup/service.test.ts @@ -57,8 +57,8 @@ describeWithEnv("address lookup service", { db: true }, () => { const outcome = await lookupAddresses("easypostcodes", "sw1a2aa"); expect(outcome).toEqual({ - addresses: [DOWNING_STREET_MATCH], ok: true, + value: [DOWNING_STREET_MATCH], }); expect(sentKey).toBe("test-api-key"); // The result was cached under the normalised search's blind index. @@ -77,8 +77,8 @@ describeWithEnv("address lookup service", { db: true }, () => { const outcome = await lookupAddresses("easypostcodes", " sw1a 2aa "); expect(outcome).toEqual({ - addresses: [{ lat: "51.5", line: "Cached Address Line", lng: "-0.1" }], ok: true, + value: [{ lat: "51.5", line: "Cached Address Line", lng: "-0.1" }], }); expect(fetchStub.calls.length).toBe(0); }); @@ -90,7 +90,7 @@ describeWithEnv("address lookup service", { db: true }, () => { const outcome = await lookupAddresses("easypostcodes", "zz999zz"); - expect(outcome).toEqual({ addresses: [], ok: true }); + expect(outcome).toEqual({ ok: true, value: [] }); expect(fetchStub.calls.length).toBe(0); }); diff --git a/test/shared/builder.test.ts b/test/shared/builder.test.ts index 1176486ba8..7c1b513dc5 100644 --- a/test/shared/builder.test.ts +++ b/test/shared/builder.test.ts @@ -3,6 +3,7 @@ import { it as test } from "@std/testing/bdd"; import { stub } from "@std/testing/mock"; import { builderApi } from "#shared/builder.ts"; import { bunnyDbProvider as bunnyDbApi } from "#shared/bunny-db.ts"; +import { okResult } from "#shared/result.ts"; import { tursoDbProvider as tursoApi } from "#shared/turso-api.ts"; import { expectBuildError, @@ -214,13 +215,13 @@ describeWithEnv( expect(createDbStub.calls[0]!.args[0]).toBe("Auto Site"); if (result.ok) { - expect(result.dbUrl).toBe(MOCK_DB_RESULT.dbUrl); - expect(result.dbToken).toBe(MOCK_DB_RESULT.dbToken); + expect(result.dbUrl).toBe(MOCK_DB_RESULT.value.dbUrl); + expect(result.dbToken).toBe(MOCK_DB_RESULT.value.dbToken); } const secretsSet = secretsFrom(secretStub); - expectSecret(secretsSet, "DB_URL", MOCK_DB_RESULT.dbUrl); - expectSecret(secretsSet, "DB_TOKEN", MOCK_DB_RESULT.dbToken); + expectSecret(secretsSet, "DB_URL", MOCK_DB_RESULT.value.dbUrl); + expectSecret(secretsSet, "DB_TOKEN", MOCK_DB_RESULT.value.dbToken); })); test("buildSite uses provided dbUrl and dbToken without calling createDatabase", () => @@ -337,17 +338,18 @@ describeWithEnv( withMocks( () => stub(tursoApi, "createDatabase", () => - Promise.resolve({ - dbId: "turso_db_123", - dbToken: "turso-token", - dbUrl: "libsql://turso.io", - ok: true as const, - }), + Promise.resolve( + okResult({ + dbId: "turso_db_123", + dbToken: "turso-token", + dbUrl: "libsql://turso.io", + }), + ), ), async (tursoStub) => { const result = await builderApi.createDatabase("My Site", "turso"); expect(result.ok).toBe(true); - if (result.ok) expect(result.dbUrl).toContain("turso.io"); + if (result.ok) expect(result.value.dbUrl).toContain("turso.io"); expect(tursoStub.calls).toHaveLength(1); }, )); @@ -356,17 +358,18 @@ describeWithEnv( withMocks( () => stub(bunnyDbApi, "createDatabase", () => - Promise.resolve({ - dbId: "bunny_db_456", - dbToken: "bunny-token", - dbUrl: "libsql://bunny.io", - ok: true as const, - }), + Promise.resolve( + okResult({ + dbId: "bunny_db_456", + dbToken: "bunny-token", + dbUrl: "libsql://bunny.io", + }), + ), ), async (bunnyStub) => { const result = await builderApi.createDatabase("My Site", "bunny"); expect(result.ok).toBe(true); - if (result.ok) expect(result.dbUrl).toContain("bunny.io"); + if (result.ok) expect(result.value.dbUrl).toContain("bunny.io"); expect(bunnyStub.calls).toHaveLength(1); }, )); @@ -376,12 +379,13 @@ describeWithEnv( () => ({ ...stubBuildSiteApis(), tursoStub: stub(tursoApi, "createDatabase", () => - Promise.resolve({ - dbId: "turso_auto", - dbToken: "turso-tok", - dbUrl: "libsql://auto.turso.io", - ok: true as const, - }), + Promise.resolve( + okResult({ + dbId: "turso_auto", + dbToken: "turso-tok", + dbUrl: "libsql://auto.turso.io", + }), + ), ), }), async ({ tursoStub }) => { diff --git a/test/shared/bunny-db.test.ts b/test/shared/bunny-db.test.ts index d217bf6de7..7b1f07666a 100644 --- a/test/shared/bunny-db.test.ts +++ b/test/shared/bunny-db.test.ts @@ -89,15 +89,27 @@ describeWithEnv("bunny-db", { env: { BUNNY_API_KEY: "test-api-key" } }, () => { expect(result.ok).toBe(true); if (result.ok) { - expect(result.dbUrl).toBe("libsql://my-site.lite.bunnydb.net"); - expect(result.dbToken).toBe("bny_token_abc"); - expect(result.dbId).toBe("db_test123"); + expect(result.value.dbUrl).toBe("libsql://my-site.lite.bunnydb.net"); + expect(result.value.dbToken).toBe("bny_token_abc"); + expect(result.value.dbId).toBe("db_test123"); } expect(fetchCalls.length).toBe(4); expect(fetchCalls[0]).toContain("/v1/config"); }); + test("createDatabase rejects a token response with no token", async () => { + using _fetch = dbCreateFetch("db_missing_token", (url) => + url.includes("/auth") + ? new Response("{}") + : getAndAuthResponse(url, "db_missing_token"), + ); + + await expect(bunnyDbApi.createDatabase("Missing token")).rejects.toThrow( + "Database response is missing token", + ); + }); + test("createDatabase sends every region Bunny reported as primaries and replicas", async () => { let createBody: unknown; diff --git a/test/shared/db/attendee-statuses.test.ts b/test/shared/db/attendee-statuses.test.ts index 02834dc6ff..80643d3007 100644 --- a/test/shared/db/attendee-statuses.test.ts +++ b/test/shared/db/attendee-statuses.test.ts @@ -8,9 +8,9 @@ import { DEFAULT_ATTENDEE_STATUS_NAME, ensureDefaultAttendeeStatus, getAttendeeStatus, - getPaidDefaultStatus, - getPublicDefaultStatus, - getPublicStatusId, + requirePaidDefaultStatus, + requirePublicDefaultStatus, + requirePublicStatusId, } from "#shared/db/attendee-statuses.ts"; import { attendeesApi } from "#shared/db/attendees/api.ts"; import { getAttendeeOrNull } from "#shared/db/attendees/queries.ts"; @@ -76,10 +76,10 @@ describeWithEnv("db > attendee statuses", { db: true }, () => { expect(seed.sort_order).toBe(0); }); - test("getPublicDefaultStatus and getPaidDefaultStatus return the seed", async () => { + test("required default status lookups return the seed", async () => { const [pub, paid] = await Promise.all([ - getPublicDefaultStatus(), - getPaidDefaultStatus(), + requirePublicDefaultStatus(), + requirePaidDefaultStatus(), ]); expect(pub?.name).toBe(DEFAULT_ATTENDEE_STATUS_NAME); expect(paid?.name).toBe(DEFAULT_ATTENDEE_STATUS_NAME); @@ -93,12 +93,14 @@ describeWithEnv("db > attendee statuses", { db: true }, () => { expect(await getAttendeeStatus(9999)).toBeNull(); }); - test("getPublicStatusId returns the default id, or null when none is set", async () => { + test("requirePublicStatusId throws when the required default is missing", async () => { const [seed] = await attendeeStatuses.getAll(); - expect(await getPublicStatusId()).toBe(seed!.id); + expect(await requirePublicStatusId()).toBe(seed!.id); await getDb().execute("UPDATE attendee_statuses SET is_public_default = 0"); attendeeStatuses.invalidate(); - expect(await getPublicStatusId()).toBeNull(); + await expect(requirePublicStatusId()).rejects.toThrow( + "No attendee status has the required is_public_default flag", + ); }); test("ensureDefaultAttendeeStatus is idempotent once a status exists", async () => { @@ -327,7 +329,7 @@ describeWithEnv("db > attendee statuses", { db: true }, () => { error: "public_default_required", ok: false, }); - expect((await getPublicDefaultStatus())?.id).toBe(candidate.id); + expect((await requirePublicDefaultStatus()).id).toBe(candidate.id); }); test("status writes fail loudly for a missing status", async () => { @@ -397,7 +399,7 @@ describeWithEnv("db > attendee statuses", { db: true }, () => { maxAttendees: 10, thankYouUrl: "https://example.com", }); - const status = await getPublicDefaultStatus(); + const status = await requirePublicDefaultStatus(); const result = await attendeesApi.createAttendeeAtomic({ bookings: [{ listingId: listing.id, pricePaid: 500, quantity: 1 }], email: "guest@example.com", diff --git a/test/shared/db/attendees/balance.test.ts b/test/shared/db/attendees/balance.test.ts index a7a72c487c..52cd949096 100644 --- a/test/shared/db/attendees/balance.test.ts +++ b/test/shared/db/attendees/balance.test.ts @@ -9,7 +9,7 @@ import { import { eventGroup, legReference } from "#shared/accounting/refs.ts"; import { attendeeStatuses, - getPaidDefaultStatus, + requirePaidDefaultStatus, } from "#shared/db/attendee-statuses.ts"; import { getAttendeeBalanceState, @@ -42,7 +42,7 @@ import { expectRefundReferences } from "#test-utils/payment-references.ts"; describeWithEnv("db > settle attendee balance", { db: true }, () => { test("clears the balance, moves to the paid status and logs it", async () => { const { attendeeId, listingId } = await createReservedAttendee(1500); - const paid = await getPaidDefaultStatus(); + const paid = await requirePaidDefaultStatus(); const settlement = settle(); const result = await settleAttendeeBalance(attendeeId, 1500, settlement); @@ -50,7 +50,7 @@ describeWithEnv("db > settle attendee balance", { db: true }, () => { const state = await getAttendeeBalanceState(attendeeId); expect(state?.remainingBalance).toBe(0); - expect(state?.statusId).toBe(paid!.id); + expect(state?.statusId).toBe(paid.id); const log = await getAttendeeActivityLog(attendeeId); expect(log).toHaveLength(1); @@ -178,15 +178,17 @@ describeWithEnv("db > settle attendee balance", { db: true }, () => { expect(state?.remainingBalance).toBe(0); }); - test("settles even when no paid-default status is configured", async () => { + test("fails when no paid-default status is configured", async () => { const { attendeeId } = await createReservedAttendee(1500); await getDb().execute("UPDATE attendee_statuses SET is_paid_default = 0"); attendeeStatuses.invalidate(); - const result = await settleAttendeeBalance(attendeeId, 1500, settle()); - expect(result.settled).toBe(true); - // No paid default: COALESCE keeps the existing status. + await expect( + settleAttendeeBalance(attendeeId, 1500, settle()), + ).rejects.toThrow( + "No attendee status has the required is_paid_default flag", + ); const state = await getAttendeeBalanceState(attendeeId); - expect(state?.remainingBalance).toBe(0); + expect(state?.remainingBalance).toBe(1500); }); test("settles an attendee that has no booking lines", async () => { diff --git a/test/shared/db/client.test.ts b/test/shared/db/client.test.ts index cc5db88a25..2890571dd7 100644 --- a/test/shared/db/client.test.ts +++ b/test/shared/db/client.test.ts @@ -13,7 +13,10 @@ import { insert, queryAll, queryBatch, + queryOne, rawSql, + requireOne, + requireOnePrimary, resetAggregates, rowExists, setDb, @@ -189,6 +192,34 @@ describeWithEnv("db > client", { db: true }, () => { } }); + test("queryOne returns null for an expected miss", async () => { + expect( + await queryOne("SELECT value FROM settings WHERE key = ?", [ + "missing-query-one-test", + ]), + ).toBeNull(); + }); + + test("requireOne throws the failed query when a required row is missing", async () => { + await expect( + requireOne("SELECT value FROM settings WHERE key = ?", [ + "missing-query-one-test", + ]), + ).rejects.toThrow( + "Required query returned no rows: SELECT value FROM settings WHERE key = ?", + ); + }); + + test("requireOnePrimary names a missing row on the primary", async () => { + await expect( + requireOnePrimary("SELECT value FROM settings WHERE key = ?", [ + "missing-primary-query-one-test", + ]), + ).rejects.toThrow( + "Required primary query returned no rows: SELECT value FROM settings WHERE key = ?", + ); + }); + test("deleteByFieldStatement builds the DELETE for one table, field and value", () => { const stmt = deleteByFieldStatement({ field: "user_id", diff --git a/test/shared/db/keyed-cache.test.ts b/test/shared/db/keyed-cache.test.ts index b01ee9e823..d17057da6c 100644 --- a/test/shared/db/keyed-cache.test.ts +++ b/test/shared/db/keyed-cache.test.ts @@ -15,15 +15,18 @@ const row = (id: number): Row => ({ id, key: `k${id}` }); * many round-trips the cache made and for which records. */ const makeFetchers = (rows: Row[]) => { const store = new Map(rows.map((r) => [r.id, r])); - const calls = { all: 0, byId: [] as number[], byKeys: [] as string[][] }; + const calls = { all: 0, byIds: [] as number[][], byKeys: [] as string[][] }; const base: Omit, "ttlMs" | "now"> = { fetchAll: () => { calls.all++; return Promise.resolve([...store.values()]); }, - fetchById: (id) => { - calls.byId.push(id); - return Promise.resolve(store.get(id) ?? null); + fetchByIds: (ids) => { + calls.byIds.push(ids); + const wanted = new Set(ids); + return Promise.resolve( + [...store.values()].filter((item) => wanted.has(item.id)), + ); }, fetchByKeys: (keys) => { calls.byKeys.push(keys); @@ -69,11 +72,11 @@ describe("db > keyed-cache", () => { }; }; - test("getById fetches once, then serves from cache within the TTL", async () => { + test("getById uses the batch loader once, then serves from cache", async () => { const { cache, calls } = build([row(1), row(2)]); expect((await cache.getById(1))?.id).toBe(1); expect((await cache.getById(1))?.id).toBe(1); - expect(calls.byId).toEqual([1]); + expect(calls.byIds).toEqual([[1]]); }); test("getById re-fetches only that record once its entry expires", async () => { @@ -81,14 +84,41 @@ describe("db > keyed-cache", () => { await cache.getById(1); clock += 1001; // past the TTL await cache.getById(1); - expect(calls.byId).toEqual([1, 1]); + expect(calls.byIds).toEqual([[1], [1]]); }); test("getById returns null for a missing record and does not cache the miss", async () => { const { cache, calls } = build([row(1)]); expect(await cache.getById(99)).toBeNull(); expect(await cache.getById(99)).toBeNull(); - expect(calls.byId).toEqual([99, 99]); + expect(calls.byIds).toEqual([[99], [99]]); + }); + + test("getByIds preserves missing and duplicate ids through one batch", async () => { + const { cache, calls } = build([row(1), row(2)]); + expect( + (await cache.getByIds([2, 99, 1, 2])).map((item) => item?.id ?? null), + ).toEqual([2, null, 1, 2]); + expect(calls.byIds).toEqual([[2, 99, 1]]); + }); + + test("getByIds keeps a cache hit that expires while misses load", async () => { + const { base } = makeFetchers([row(1), row(2)]); + const cache = createKeyedCache({ + ...base, + fetchByIds: async (ids) => { + if (ids.includes(2)) clock += 2; + return base.fetchByIds!(ids); + }, + now, + ttlMs: 1000, + }); + await cache.getById(1); + clock = 1999; + + expect( + (await cache.getByIds([1, 2])).map((item) => item?.id ?? null), + ).toEqual([1, 2]); }); test("getByKey fetches by key, then serves from cache, without loading all", async () => { @@ -125,7 +155,7 @@ describe("db > keyed-cache", () => { const { cache, calls } = buildLite([row(1), row(2)]); expect((await cache.getById(2))?.id).toBe(2); expect(await cache.getById(99)).toBeNull(); - expect(calls.byId).toEqual([]); // single-row fetcher never used + expect(calls.byIds).toEqual([]); // batch fetcher never used expect(calls.all).toBe(1); // one whole-set load, reused for both reads }); @@ -157,7 +187,7 @@ describe("db > keyed-cache", () => { await cache.getAll(); expect((await cache.getById(2))?.id).toBe(2); expect((await cache.getByKey("k1"))?.id).toBe(1); - expect(calls.byId).toEqual([]); + expect(calls.byIds).toEqual([]); expect(calls.byKeys).toEqual([]); }); @@ -175,16 +205,25 @@ describe("db > keyed-cache", () => { await cache.getById(1); // cached — no second fetch cache.invalidate(); await cache.getById(1); // re-fetched - expect(calls.byId).toEqual([1, 1]); + expect(calls.byIds).toEqual([[1], [1]]); + }); + + test("invalidate clears secondary-key entries", async () => { + const { base, store } = makeFetchers([row(1)]); + const cache = createKeyedCache({ ...base, now, ttlMs: 1000 }); + expect((await cache.getByKey("k1"))?.id).toBe(1); + store.delete(1); + cache.invalidate(); + expect(await cache.getByKey("k1")).toBeNull(); }); test("refills from primary while replicas catch up after invalidation", async () => { const reads: boolean[] = []; const cache = createKeyedCache({ fetchAll: () => Promise.resolve([]), - fetchById: (id) => { + fetchByIds: (ids) => { reads.push(mustReadFromPrimary()); - return Promise.resolve(row(id)); + return Promise.resolve(ids.map(row)); }, idOf: (item) => item.id, keyOf: (item) => item.key, @@ -212,12 +251,12 @@ describe("db > keyed-cache", () => { // A controllable fetch lets us land an invalidate() between the fetch // starting and resolving — the in-flight row predates the write, so it must // be handed back to this caller but NOT installed into the cache. - let release!: (r: Row | null) => void; + let release!: (r: Row[]) => void; const { base } = makeFetchers([]); const cache = createKeyedCache({ ...base, - fetchById: () => - new Promise((r) => { + fetchByIds: () => + new Promise((r) => { release = r; }), now, @@ -226,7 +265,7 @@ describe("db > keyed-cache", () => { const inflight = cache.getById(1); cache.invalidate(); // lands while the fetch is pending - release(row(1)); + release([row(1)]); expect((await inflight)?.id).toBe(1); // caller still gets the row expect(cache.size()).toBe(0); // but it was not cached }); @@ -256,6 +295,6 @@ describe("db > keyed-cache", () => { const cache = createKeyedCache({ ...base, ttlMs: 60_000 }); await cache.getById(1); await cache.getById(1); // well within the TTL on the real clock - expect(calls.byId).toEqual([1]); + expect(calls.byIds).toEqual([[1]]); }); }); diff --git a/test/shared/db/listing-parents.test.ts b/test/shared/db/listing-parents.test.ts index e712cde5be..ab70938c31 100644 --- a/test/shared/db/listing-parents.test.ts +++ b/test/shared/db/listing-parents.test.ts @@ -133,16 +133,14 @@ describeWithEnv("db > listing-parents", { db: true }, () => { ).toEqual([]); }); - test("drops parent edges whose listing no longer exists", async () => { + test("rejects parent edges whose listing no longer exists", async () => { const { childA } = await threeListings(); const missingParentId = childA.id + 100_000; await listingChildren.setIds(missingParentId, [childA.id]); - // The edge row exists but no parent listing does, so hydration drops it. expect(await listingParents.getIds(childA.id)).toEqual([missingParentId]); - expect( - (await hydratedListings(listingParents, [childA.id])).get(childA.id) ?? - [], - ).toEqual([]); + await expect( + hydratedListings(listingParents, [childA.id]), + ).rejects.toThrow(`Listing not found: ${missingParentId}`); }); }); @@ -251,12 +249,13 @@ describeWithEnv("db > listing-parents", { db: true }, () => { ); }); - test("omits a key when every linked listing is missing", async () => { + test("rejects a link whose listing is missing", async () => { const { parent, childA } = await threeListings(); - await listingChildren.setIds(parent.id, [childA.id + 100_000]); - expect((await hydratedListings(listingChildren, [parent.id])).size).toBe( - 0, - ); + const missingChildId = childA.id + 100_000; + await listingChildren.setIds(parent.id, [missingChildId]); + await expect( + hydratedListings(listingChildren, [parent.id]), + ).rejects.toThrow(`Listing not found: ${missingChildId}`); }); }); @@ -293,12 +292,13 @@ describeWithEnv("db > listing-parents", { db: true }, () => { expect((await hydratedListings(listingChildren, [])).size).toBe(0); }); - test("drops a child edge whose listing no longer exists", async () => { + test("rejects a child edge whose listing no longer exists", async () => { const { parent, childA } = await threeListings(); const missingChildId = childA.id + 100_000; await listingChildren.setIds(parent.id, [childA.id, missingChildId]); - const map = await hydratedListings(listingChildren, [parent.id]); - expect(map.get(parent.id)?.map((c) => c.id)).toEqual([childA.id]); + await expect( + hydratedListings(listingChildren, [parent.id]), + ).rejects.toThrow(`Listing not found: ${missingChildId}`); }); }); @@ -321,13 +321,13 @@ describeWithEnv("db > listing-parents", { db: true }, () => { expect((await hydratedListings(listingParents, [])).size).toBe(0); }); - test("drops a parent edge whose listing no longer exists", async () => { + test("rejects a parent edge whose listing no longer exists", async () => { const { parent, childA } = await threeListings(); const missingParentId = childA.id + 100_000; await linkChildToParents(childA.id, [parent.id, missingParentId]); - const map = await hydratedListings(listingParents, [childA.id]); - // The edge to the missing parent is dropped; the real parent survives. - expect(map.get(childA.id)?.map((p) => p.id)).toEqual([parent.id]); + await expect( + hydratedListings(listingParents, [childA.id]), + ).rejects.toThrow(`Listing not found: ${missingParentId}`); }); }); @@ -396,13 +396,15 @@ describeWithEnv("db > listing-parents", { db: true }, () => { ); }); - test("ignores edges whose opposite endpoint no longer exists", async () => { + test("rejects edges whose opposite endpoint no longer exists", async () => { const { childA } = await threeListings(); const missing = childA.id + 100_000; // An edge pointing at a missing child, and one pointing at a missing parent. await listingChildren.setIds(childA.id, [missing]); await listingChildren.setIds(missing, [childA.id]); - expect(await edgeIncompatibilityAfterChange(edge(childA.id))).toBeNull(); + await expect( + edgeIncompatibilityAfterChange(edge(childA.id)), + ).rejects.toThrow(`Listing not found: ${missing}`); }); }); diff --git a/test/shared/db/orphan-attendees.test.ts b/test/shared/db/orphan-attendees.test.ts index 49e4d910f9..48241b2010 100644 --- a/test/shared/db/orphan-attendees.test.ts +++ b/test/shared/db/orphan-attendees.test.ts @@ -9,7 +9,7 @@ import { assertExists } from "@std/assert"; import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; -import { getDb, insert, queryOne } from "#shared/db/client.ts"; +import { getDb, insert, queryOne, requireOne } from "#shared/db/client.ts"; import { countOrphanedAttendees, purgeOrphanedAttendees, @@ -53,7 +53,7 @@ const childCount = async ( table: string, attendeeId: number, ): Promise => { - const row = await queryOne<{ count: number }>( + const row = await requireOne<{ count: number }>( `SELECT COUNT(*) AS count FROM ${table} WHERE attendee_id = ?`, [attendeeId], ); @@ -125,7 +125,7 @@ describeWithEnv("db > orphan-attendees", { db: true }, () => { }), ); await purgeOrphanedAttendees(nowIso()); - const remaining = await queryOne<{ c: number }>( + const remaining = await requireOne<{ c: number }>( "SELECT COUNT(*) AS c FROM service_costs WHERE servicing_attendee_id = ?", [id], ); diff --git a/test/shared/db/site-pages.test.ts b/test/shared/db/site-pages.test.ts index 2585466668..42614c974b 100644 --- a/test/shared/db/site-pages.test.ts +++ b/test/shared/db/site-pages.test.ts @@ -7,10 +7,7 @@ import { getImageById, getImagesForItem, } from "#shared/db/images.ts"; -import { - getListingNamesByIds, - isSlugTaken, -} from "#shared/db/listings/records.ts"; +import { isSlugTaken, listingNames } from "#shared/db/listings/records.ts"; import { addPageItem, clearItemEdgesStatement, @@ -182,8 +179,8 @@ describeWithEnv("db > site-pages", { db: true }, () => { const listing = await createTestListing({ name: "L" }); // The id-keyed name lookup short-circuits on empty ids (no query) and // decrypts names for real ids — the projection page labels lean on. - expect((await getListingNamesByIds([])).size).toBe(0); - expect((await getListingNamesByIds([listing.id])).get(listing.id)).toBe( + expect((await listingNames.byIds([])).size).toBe(0); + expect((await listingNames.byIds([listing.id])).get(listing.id)).toBe( "L", ); }); diff --git a/test/shared/db/table.test.ts b/test/shared/db/table.test.ts index 809ac95c02..12d47ee88c 100644 --- a/test/shared/db/table.test.ts +++ b/test/shared/db/table.test.ts @@ -176,6 +176,28 @@ describeWithEnv("db > table utilities", { db: true }, () => { expect(rows.length).toBe(2); }); + test("defineTable resolves one id through the ordered many-id lookup", async () => { + const { col, defineTable } = await import("#shared/db/table.ts"); + const first = await createTestListing({ name: "First" }); + const second = await createTestListing({ name: "Second" }); + const table = buildListingsTestTable<{ name: string }>(col, defineTable); + + expect((await table.findById(second.id))?.id).toBe(second.id); + expect( + (await table.findByIds([second.id, first.id, second.id])).map( + (row) => row?.id, + ), + ).toEqual([second.id, first.id, second.id]); + }); + + test("defineTable keeps optional misses nullable", async () => { + const { col, defineTable } = await import("#shared/db/table.ts"); + const table = buildListingsTestTable<{ name: string }>(col, defineTable); + expect(await table.findById(999_999)).toBeNull(); + expect(await table.findByIdPrimary!(999_999)).toBeNull(); + expect(await table.findByIds([])).toEqual([]); + }); + test("defineTable.update with no changes returns existing row", async () => { const { col, defineTable } = await import("#shared/db/table.ts"); diff --git a/test/shared/deno-deploy-api.test.ts b/test/shared/deno-deploy-api.test.ts index 66abd3ea50..3e8547c92f 100644 --- a/test/shared/deno-deploy-api.test.ts +++ b/test/shared/deno-deploy-api.test.ts @@ -71,8 +71,8 @@ describeWithEnv("deno-deploy-api", { env: DENO_ENV }, () => { const result = await denoDeployApi.createApp("my-app"); expect(result.ok).toBe(true); if (result.ok) { - expect(result.appId).toBe("app_abc123"); - expect(result.slug).toBe("my-app"); + expect(result.value.appId).toBe("app_abc123"); + expect(result.value.slug).toBe("my-app"); } expect(captured.url).toContain("/v2/apps"); expect(captured.body).toEqual({ orgId: "test-org-id", slug: "my-app" }); @@ -153,7 +153,7 @@ describeWithEnv("deno-deploy-api", { env: DENO_ENV }, () => { ); expect(result.ok).toBe(true); if (result.ok) { - expect(result.hostname).toBe("https://my-app.deno.dev"); + expect(result.value).toBe("https://my-app.deno.dev"); } expect(captured.url).toContain("/apps/app_dc/deployments"); expect( @@ -172,7 +172,7 @@ describeWithEnv("deno-deploy-api", { env: DENO_ENV }, () => { const result = await denoDeployApi.deployCode("app_fb", "code"); expect(result.ok).toBe(true); if (result.ok) { - expect(result.hostname).toBe("https://fallback.deno.dev"); + expect(result.value).toBe("https://fallback.deno.dev"); } }); @@ -217,9 +217,9 @@ describeWithEnv("deno-deploy-api", { env: DENO_ENV }, () => { const result = await denoDeployApi.getEnvVarNames("app_gn"); expect(result.ok).toBe(true); if (result.ok) { - expect(result.names).toContain("DB_URL"); - expect(result.names).toContain("DB_TOKEN"); - expect(result.names.length).toBe(2); + expect(result.value).toContain("DB_URL"); + expect(result.value).toContain("DB_TOKEN"); + expect(result.value.length).toBe(2); } }); @@ -232,18 +232,18 @@ describeWithEnv("deno-deploy-api", { env: DENO_ENV }, () => { const result = await denoDeployApi.getEnvVarNames("app_empty"); expect(result.ok).toBe(true); if (result.ok) { - expect(result.names).toEqual([]); + expect(result.value).toEqual([]); } }); - test("getEnvVarNames returns empty array when env_vars field is absent", async () => { + test("getEnvVarNames returns empty when env_vars is omitted", async () => { using _fetch = stubFetch( new Response(JSON.stringify({ id: "app_no_ev", slug: "no-ev" })), ); const result = await denoDeployApi.getEnvVarNames("app_no_ev"); expect(result.ok).toBe(true); if (result.ok) { - expect(result.names).toEqual([]); + expect(result.value).toEqual([]); } }); diff --git a/test/shared/ledger/validate.test.ts b/test/shared/ledger/validate.test.ts index 7ffa9084f8..262a6c3ea2 100644 --- a/test/shared/ledger/validate.test.ts +++ b/test/shared/ledger/validate.test.ts @@ -89,7 +89,7 @@ describe("validateTransfer", () => { it(`rejects ${name} with ${code}`, () => { const result = validateTransfer({ ...base, ...patch }); if (result.ok) throw new Error("expected validation to fail"); - expect(result.errors).toContainEqual({ code }); + expect(result.error).toContainEqual({ code }); }); } @@ -101,7 +101,7 @@ describe("validateTransfer", () => { reference: "", }); if (result.ok) throw new Error("expected validation to fail"); - const codes = result.errors.map((e) => e.code); + const codes = result.error.map((e) => e.code); expect(codes).toContain("non_positive_amount"); expect(codes).toContain("self_transfer"); expect(codes).toContain("empty_reference"); diff --git a/test/shared/required-value.test.ts b/test/shared/required-value.test.ts new file mode 100644 index 0000000000..a9300f8f8c --- /dev/null +++ b/test/shared/required-value.test.ts @@ -0,0 +1,27 @@ +import { expect } from "@std/expect"; +import { describe, it as test } from "@std/testing/bdd"; +import { requireValue } from "#shared/required-value.ts"; + +describe("requireValue", () => { + test("returns a present value", () => { + expect(requireValue(7, "missing")).toBe(7); + }); + + test("throws the supplied message for a missing value", () => { + expect(() => requireValue(null, "Expected value is missing")).toThrow( + "Expected value is missing", + ); + }); + + test("treats undefined as missing", () => { + expect(() => requireValue(undefined, "Undefined value is missing")).toThrow( + "Undefined value is missing", + ); + }); + + test("preserves falsy present values", () => { + expect( + [0, false, ""].map((value) => requireValue(value, "missing")), + ).toEqual([0, false, ""]); + }); +}); diff --git a/test/shared/rest/crud-api.test.ts b/test/shared/rest/crud-api.test.ts index 42fdcb79bc..f3894ab110 100644 --- a/test/shared/rest/crud-api.test.ts +++ b/test/shared/rest/crud-api.test.ts @@ -2,6 +2,7 @@ import { expect } from "@std/expect"; import { beforeEach, it as test } from "@std/testing/bdd"; import type { Table } from "#shared/db/table.ts"; import { defineCrudApi } from "#shared/rest/crud-api.ts"; +import { okResult } from "#shared/result.ts"; import { describeWithEnv } from "#test-utils/db.ts"; import { createIdNameTable, @@ -20,11 +21,9 @@ const makeRoutes = (table: Table): Record => nameField: "name", singular: "Widget", table, - toCreateInput: (body) => ({ input: { name: String(body.name) }, ok: true }), - toUpdateInput: (body, existing) => ({ - input: { name: body.name != null ? String(body.name) : existing.name }, - ok: true, - }), + toCreateInput: (body) => okResult({ name: String(body.name) }), + toUpdateInput: (body, existing) => + okResult({ name: body.name != null ? String(body.name) : existing.name }), }); describeWithEnv("defineCrudApi write not-found", { db: true }, () => { diff --git a/test/shared/rest/resource.test.ts b/test/shared/rest/resource.test.ts index fafcd087b5..3714d25cc6 100644 --- a/test/shared/rest/resource.test.ts +++ b/test/shared/rest/resource.test.ts @@ -141,7 +141,7 @@ describe("rest/resource", () => { expect(result.ok).toBe(true); if (result.ok) { - expect(result.input).toEqual({ name: "Test", value: 42 }); + expect(result.value).toEqual({ name: "Test", value: 42 }); } }); diff --git a/test/shared/result.test.ts b/test/shared/result.test.ts index a4cd10b1d6..6cf82b6041 100644 --- a/test/shared/result.test.ts +++ b/test/shared/result.test.ts @@ -1,6 +1,11 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; -import { errorResult, okResult, requireSuccess } from "#shared/result.ts"; +import { + errorResult, + okResult, + parseOptionalResult, + requireSuccess, +} from "#shared/result.ts"; describe("result helpers", () => { test("creates success and error result shapes", () => { @@ -8,8 +13,25 @@ describe("result helpers", () => { expect(errorResult("Nope")).toEqual({ error: "Nope", ok: false }); }); + test("returns undefined without parsing an absent optional value", () => { + let parsed = false; + expect( + parseOptionalResult(undefined, () => { + parsed = true; + return okResult(1); + }), + ).toEqual(okResult(undefined)); + expect(parsed).toBe(false); + }); + + test("parses a present optional value", () => { + expect( + parseOptionalResult("12", (value) => okResult(Number(value))), + ).toEqual(okResult(12)); + }); + test("accepts a successful result", () => { - expect(() => requireSuccess({ ok: true })).not.toThrow(); + expect(requireSuccess(okResult(42))).toBe(42); }); test("throws the boundary error from a failed result", () => { @@ -17,4 +39,52 @@ describe("result helpers", () => { requireSuccess({ error: "Invalid setting", ok: false }), ).toThrow("Invalid setting"); }); + + test("throws typed error codes with context", () => { + expect(() => + requireSuccess( + errorResult([{ code: "empty_reference" }, { code: "self_transfer" }]), + "Post transfer", + ), + ).toThrow("Post transfer: empty_reference, self_transfer"); + }); + + test("throws one typed error code", () => { + expect(() => + requireSuccess(errorResult([{ code: "empty_reference" }])), + ).toThrow("empty_reference"); + }); + + test("does not replace an explicit empty message with a code", () => { + expect(() => + requireSuccess(errorResult({ code: "fallback", message: "" })), + ).toThrow("Failed result is missing an error"); + }); + + test("rejects an empty error message", () => { + expect(() => requireSuccess(errorResult(""))).toThrow( + "Failed result is missing an error", + ); + }); + + test("uses an Error name when its message is empty", () => { + expect(() => requireSuccess(errorResult(new TypeError()))).toThrow( + "TypeError", + ); + }); + + test("rejects an error list containing a malformed entry", () => { + expect(() => + requireSuccess(errorResult([{ code: "valid" }, null])), + ).toThrow("Failed result is missing an error"); + }); + + test("rejects a malformed failed result with a useful message", () => { + const malformed = { ok: false } as unknown as ReturnType< + typeof errorResult + >; + expect(() => requireSuccess(malformed)).toThrow( + "Failed result is missing an error", + ); + }); }); diff --git a/test/shared/site-secrets.test.ts b/test/shared/site-secrets.test.ts index a64b2a888f..a3dc92331b 100644 --- a/test/shared/site-secrets.test.ts +++ b/test/shared/site-secrets.test.ts @@ -5,6 +5,7 @@ import { collectHostSecrets } from "#shared/builder.ts"; import { bunnyCdnApi, type EdgeScriptSecret } from "#shared/bunny-cdn.ts"; import type { BuiltSite } from "#shared/db/built-sites.ts"; import { denoDeployApi } from "#shared/deno-deploy-api.ts"; +import { okResult } from "#shared/result.ts"; import { addMissingSiteSecrets, expectedSiteSecrets, @@ -43,9 +44,9 @@ const expectedNamesFor = (site: BuiltSite): string[] => type DenoSetResult = Awaited>; /** Stub denoDeployApi.getEnvVarNames (returns empty) and setEnvVars (defaults to ok). */ -const stubDenoSecrets = (setResult: DenoSetResult = { ok: true as const }) => ({ +const stubDenoSecrets = (setResult: DenoSetResult = okResult(undefined)) => ({ getStub: stub(denoDeployApi, "getEnvVarNames", () => - Promise.resolve({ names: [], ok: true as const }), + Promise.resolve(okResult([])), ), setStub: stub(denoDeployApi, "setEnvVars", () => Promise.resolve(setResult)), }); @@ -294,10 +295,7 @@ describeWithEnv( await withMocks( () => stub(denoDeployApi, "getEnvVarNames", () => - Promise.resolve({ - names: ["DB_URL", "DB_TOKEN"], - ok: true as const, - }), + Promise.resolve(okResult(["DB_URL", "DB_TOKEN"])), ), async () => { const view = await loadSiteSecretsStatus(site); diff --git a/test/shared/turso-api.test.ts b/test/shared/turso-api.test.ts index cc425bd9c9..0c7b164ebf 100644 --- a/test/shared/turso-api.test.ts +++ b/test/shared/turso-api.test.ts @@ -89,9 +89,9 @@ describeWithEnv("turso-api", { env: TURSO_ENV }, () => { expect(result.ok).toBe(true); if (result.ok) { - expect(result.dbUrl).toBe("libsql://my-site.turso.io"); - expect(result.dbToken).toBe("jwt_token"); - expect(result.dbId).toBe("db_test"); + expect(result.value.dbUrl).toBe("libsql://my-site.turso.io"); + expect(result.value.dbToken).toBe("jwt_token"); + expect(result.value.dbId).toBe("db_test"); } expect(fetchCalls.length).toBe(2); @@ -222,8 +222,8 @@ describeWithEnv("turso-api", { env: TURSO_ENV }, () => { const result = await tursoApi.createDatabase("My App"); expect(result.ok).toBe(true); if (result.ok) { - expect(result.dbUrl).toMatch(/^libsql:\/\//); - expect(result.dbUrl).toContain("my-app.turso.io"); + expect(result.value.dbUrl).toMatch(/^libsql:\/\//); + expect(result.value.dbUrl).toContain("my-app.turso.io"); } }, ); diff --git a/test/shared/update.test.ts b/test/shared/update.test.ts index 1d72800c0e..397c914a5d 100644 --- a/test/shared/update.test.ts +++ b/test/shared/update.test.ts @@ -98,10 +98,7 @@ describe("deployLatestReleaseToDeno", () => { test("fetches the latest release and deploys it to a Deno app", async () => { using _fetch = stubReleaseFetch(); const deployStub = stub(denoDeployApi, "deployCode", () => - Promise.resolve({ - hostname: "https://app.deno.dev", - ok: true as const, - }), + Promise.resolve({ ok: true as const, value: "https://app.deno.dev" }), ); try { const release = await deployLatestReleaseToDeno("app_123"); diff --git a/test/test-utils/builder-mocks.ts b/test/test-utils/builder-mocks.ts index 4988487a50..85e6c5f6ea 100644 --- a/test/test-utils/builder-mocks.ts +++ b/test/test-utils/builder-mocks.ts @@ -4,6 +4,7 @@ import { builderApi } from "#shared/builder.ts"; import { bunnyCdnApi } from "#shared/bunny-cdn.ts"; import { bunnyDbProvider } from "#shared/bunny-db.ts"; import { denoDeployApi } from "#shared/deno-deploy-api.ts"; +import { okResult } from "#shared/result.ts"; import { stubFetch } from "#test-utils/fetch-stub.ts"; import { withMocks } from "#test-utils/mocks.ts"; @@ -18,10 +19,12 @@ type DenoEnvResult = Awaited>; /** Standard auto-created-database result used across builder tests. */ export const MOCK_DB_RESULT = { - dbId: "db_auto123", - dbToken: "auto-token", - dbUrl: "libsql://auto.lite.bunnydb.net", ok: true as const, + value: { + dbId: "db_auto123", + dbToken: "auto-token", + dbUrl: "libsql://auto.lite.bunnydb.net", + }, }; interface ReleaseOptions { @@ -165,19 +168,16 @@ interface DenoBuilderMockOptions { export const stubDenoBuilderApis = (opts: DenoBuilderMockOptions = {}) => ({ createAppStub: stub(denoDeployApi, "createApp", () => Promise.resolve( - opts.createAppResult ?? { - appId: "app_abc123", - ok: true as const, - slug: "tickets-test", - }, + opts.createAppResult ?? + okResult({ + appId: "app_abc123", + slug: "tickets-test", + }), ), ), deployStub: stub(denoDeployApi, "deployCode", () => Promise.resolve( - opts.deployResult ?? { - hostname: "https://tickets-test.deno.dev", - ok: true as const, - }, + opts.deployResult ?? okResult("https://tickets-test.deno.dev"), ), ), encKeyStub: stub( @@ -187,7 +187,7 @@ export const stubDenoBuilderApis = (opts: DenoBuilderMockOptions = {}) => ({ ), fetchStub: stubBuilderFetch(opts.onOther, opts.releaseOpts), setEnvStub: stub(denoDeployApi, "setEnvVars", () => - Promise.resolve(opts.setEnvResult ?? { ok: true as const }), + Promise.resolve(opts.setEnvResult ?? okResult(undefined)), ), }); From da3dc7b211aa5055246d45e48dcce46f4421c172 Mon Sep 17 00:00:00 2001 From: Stefan Date: Sun, 19 Jul 2026 11:47:20 +0100 Subject: [PATCH 10/17] Validate structured storage values --- scripts/mutation/equivalent-mutants.txt | 16 +- src/features/admin/attendee-form-model.ts | 4 +- src/features/admin/attendees.ts | 2 +- src/features/admin/catalog-transfer/import.ts | 4 +- src/features/admin/catalog-transfer/schema.ts | 11 +- .../api/payment-processing/metadata.ts | 13 +- src/features/public/pages.ts | 4 +- src/shared/address-lookup/types.ts | 7 +- src/shared/admin-features.ts | 9 +- src/shared/booking-date-fields.ts | 8 +- src/shared/booking/model.ts | 10 +- src/shared/dates.ts | 10 +- src/shared/db/address-cache.ts | 30 ++- src/shared/db/attendees/capacity/range.ts | 4 +- src/shared/db/attendees/create.ts | 4 +- src/shared/db/attendees/pii.ts | 50 +++-- src/shared/db/attendees/servicing.ts | 6 +- src/shared/db/attendees/update.ts | 4 +- src/shared/db/built-sites.ts | 42 ++-- src/shared/db/capacity.ts | 6 +- src/shared/db/contact-preferences.ts | 26 ++- src/shared/db/groups.ts | 9 +- src/shared/db/listings/table.ts | 34 ++-- src/shared/db/processed-payments.ts | 28 ++- src/shared/db/sumup-checkouts.ts | 14 +- src/shared/db/table.ts | 57 +++++- src/shared/db/token-attempts.ts | 18 +- src/shared/email-renderer.ts | 4 +- src/shared/listing-defaults.ts | 36 ++-- src/shared/listing-parents-rules.ts | 8 +- src/shared/listings-actions.ts | 4 +- src/shared/types.ts | 53 +++-- src/shared/validation/number.ts | 50 +++-- src/shared/validation/stored-json.ts | 46 +++++ src/shared/validation/string.ts | 5 +- src/ui/templates/admin/listings/details.tsx | 4 +- .../templates/admin/listings/form-values.tsx | 4 +- src/ui/templates/tickets.tsx | 4 +- test/shared/admin-features.test.ts | 86 +++++++- test/shared/db/address-cache.test.ts | 9 + test/shared/db/attendees/pii.test.ts | 14 +- test/shared/db/built-sites.test.ts | 11 + test/shared/db/contact-preferences.test.ts | 17 ++ test/shared/db/listings/table.test.ts | 189 ++++++++++++++++-- test/shared/db/processed-payments.test.ts | 11 + test/shared/db/sumup-checkouts.test.ts | 10 + test/shared/db/table.test.ts | 39 ++++ .../cache.test.ts} | 0 .../write-row.test.ts} | 0 test/shared/db/token-attempts.test.ts | 15 +- test/shared/listing-defaults.test.ts | 31 +++ test/shared/validation/number.test.ts | 37 ++++ test/shared/validation/stored-json.test.ts | 63 ++++++ 53 files changed, 934 insertions(+), 246 deletions(-) create mode 100644 src/shared/validation/stored-json.ts rename test/shared/db/{table-cache.test.ts => table/cache.test.ts} (100%) rename test/shared/db/{table-write-row.test.ts => table/write-row.test.ts} (100%) create mode 100644 test/shared/validation/stored-json.test.ts diff --git a/scripts/mutation/equivalent-mutants.txt b/scripts/mutation/equivalent-mutants.txt index c61ed71b60..e4e37f777d 100644 --- a/scripts/mutation/equivalent-mutants.txt +++ b/scripts/mutation/equivalent-mutants.txt @@ -80,7 +80,7 @@ src/shared/checkout-ledger.ts:35:72 ?? → || # find(...)?.amount: number|und src/features/settings-bundles.ts:264:40 ?? → || # bundle is a readonly string[] or undefined; every present array, including [], is truthy src/shared/db/attendees/balance.ts:223:22 ?? → || # attendee status ids are positive integers when present, so the value is always truthy or nullish src/shared/accounting/queries.ts:162:26 || → && # transferActivityBounds: MIN(occurred_at) and MAX(occurred_at) over one table are NULL together (both iff the table is empty), so either-null and both-null coincide -src/shared/admin-features.ts:95:58 ?? → || # find(): AdminFeatureDefinition|undefined; a feature object is always truthy +src/shared/admin-features.ts:121:58 ?? → || # find(): AdminFeatureDefinition|undefined; a feature object is always truthy src/shared/db/admin-features.ts:50:10 __required_setting_condition__ → "" # the placeholder key is never stored: a failed condition always aborts on its NULL value src/shared/db/admin-features.ts:50:10 __required_setting_condition__ → "__required_setting_condition__ mutated" # same as above; no successful statement exposes this key src/shared/db/admin-features.ts:76:49 ?? → || # inUseSql: a non-empty SQL string|undefined, so only undefined reaches the fallback @@ -111,13 +111,13 @@ src/fp.ts:449:49 ?? → || # items?.length is undefined or a non-negative int # undefined, paired null checks already reject both nullish values, optional # conditions/dependencies are objects or arrays, and non-generated primary keys # are overwritten from the input-column fold in either initial-row branch. -src/shared/db/table.ts:282:17 === → == # queryOne returns StoredRow|null, never undefined -src/shared/db/table.ts:349:25 !== → != # paired checks reject both null and undefined before applying a write transform -src/shared/db/table.ts:501:24 ?: → consequent only # generated keys use the consequent; non-generated keys are overwritten by their input-column value -src/shared/db/table.ts:541:28 ?? → || # condition?.args is an array or undefined, and every array is truthy -src/shared/db/table.ts:667:59 ?? → || # dependsOn is a readonly array or undefined, and every array is truthy -src/shared/db/table.ts:694:32 ?? → || # dependsOn is a readonly array or undefined, and every array is truthy -src/shared/db/table.ts:715:6 === → == # wrapNullable constrains T to exclude undefined, so v is T|null +src/shared/db/table.ts:283:17 === → == # queryOne returns StoredRow|null, never undefined +src/shared/db/table.ts:350:25 !== → != # paired checks reject both null and undefined before applying a write transform +src/shared/db/table.ts:502:24 ?: → consequent only # generated keys use the consequent; non-generated keys are overwritten by their input-column value +src/shared/db/table.ts:542:28 ?? → || # condition?.args is an array or undefined, and every array is truthy +src/shared/db/table.ts:667:21 ?? → || # dependsOn is a readonly array or undefined, and every array is truthy +src/shared/db/table.ts:700:32 ?? → || # dependsOn is a readonly array or undefined, and every array is truthy +src/shared/db/table.ts:721:6 === → == # wrapNullable constrains T to exclude undefined, so v is T|null # Login attempt rows store an integer count. For undefined, null, zero, or any # non-zero integer, `(attempts ?? 0) + 1` and `(attempts || 0) + 1` agree. diff --git a/src/features/admin/attendee-form-model.ts b/src/features/admin/attendee-form-model.ts index c4d7fb955b..f7ff006bf7 100644 --- a/src/features/admin/attendee-form-model.ts +++ b/src/features/admin/attendee-form-model.ts @@ -30,8 +30,8 @@ import type { FormParams } from "#shared/form-data.ts"; import { START_DATE_FIELD } from "#shared/order-select.ts"; import { type ContactInfo, + clampDurationDays, type ListingWithCount, - normalizeDurationDays, } from "#shared/types.ts"; import { isIsoDate } from "#shared/validation/date.ts"; import { @@ -256,7 +256,7 @@ export const attendeeBookingsFromLines = ( /** Clamp a submitted day count to the valid range; blank defaults to 1. */ const clampDayCount = (raw: number | null): number => - normalizeDurationDays(raw ?? 1); + clampDurationDays(raw ?? 1); /** * The status an attendee resolves to: their submitted choice, or the public diff --git a/src/features/admin/attendees.ts b/src/features/admin/attendees.ts index 8cbc12b281..def4e529ae 100644 --- a/src/features/admin/attendees.ts +++ b/src/features/admin/attendees.ts @@ -210,7 +210,7 @@ const buildCreateAttendeeInput = ( const isDaily = listing.listing_type === "daily"; // Customisable daily bookings span the admin's chosen day count (a required, // options-constrained field; any odd value is clamped downstream by - // normalizeDurationDays); other daily bookings use the fixed duration. + // clampDurationDays); other daily bookings use the fixed duration. const durationDays = listing.customisable_days ? Number(values.day_count) : listing.duration_days; diff --git a/src/features/admin/catalog-transfer/import.ts b/src/features/admin/catalog-transfer/import.ts index ee4b94f968..7f658dbe0f 100644 --- a/src/features/admin/catalog-transfer/import.ts +++ b/src/features/admin/catalog-transfer/import.ts @@ -63,12 +63,12 @@ import { seenBefore } from "#shared/seen-before.ts"; import { type AdminLevel, availableDayCounts, + clampDurationDays, type DayPricedListing, type Group, type Listing, type ListingType, type ListingWithCount, - normalizeDurationDays, parseDayPrices, } from "#shared/types.ts"; import { childAddOnError } from "../listings-parents.ts"; @@ -232,7 +232,7 @@ const listingDataToInput = ( const listingToEdge = (listing: Listing): EdgeListing => ({ customisable_days: listing.customisable_days, day_prices: listing.day_prices, - duration_days: normalizeDurationDays(listing.duration_days), + duration_days: clampDurationDays(listing.duration_days), id: listing.id, listing_type: listing.listing_type, months_per_unit: listing.months_per_unit, diff --git a/src/features/admin/catalog-transfer/schema.ts b/src/features/admin/catalog-transfer/schema.ts index 7e2746113e..dfb8f97fb9 100644 --- a/src/features/admin/catalog-transfer/schema.ts +++ b/src/features/admin/catalog-transfer/schema.ts @@ -24,6 +24,7 @@ import { ListingTypeSchema, MAX_DURATION_DAYS, } from "#shared/types.ts"; +import { integerAtLeast } from "#shared/validation/number.ts"; /** * True when `value` is storable in a datetime column: empty (no value), or a @@ -88,16 +89,14 @@ export const CATALOG_TRANSFER_VERSION = 1; * so an out-of-safe-range magnitude like `1e100` — which `Number.isInteger` * accepts — is a field error here rather than being rounded or throwing a raw * error at the storage layer, matching the form's money parser. */ -const intAtLeast = (min: number) => - v.pipe(v.number(), v.safeInteger(), v.minValue(min)); /** A whole non-negative integer (counts, day windows, minor-unit prices). */ -const NonNegativeIntSchema = intAtLeast(0); +const NonNegativeIntSchema = integerAtLeast(0); /** A whole positive integer (durations, quantities). */ -const PositiveIntSchema = intAtLeast(1); +const PositiveIntSchema = integerAtLeast(1); /** A booking duration in whole days: 1..MAX_DURATION_DAYS, matching the listing * form's cap so an over-limit blob is a field error, not silently clamped. */ const DurationDaysSchema = v.pipe( - intAtLeast(1), + integerAtLeast(1), v.maxValue(MAX_DURATION_DAYS, `must be at most ${MAX_DURATION_DAYS} days`), ); /** A single valid contact-field name (email/phone/address/…). */ @@ -122,7 +121,7 @@ const FieldsSchema = v.pipe( * rather than a day that never matches an availability check. */ const BookableDaySchema = v.picklist(VALID_DAY_NAMES); /** A minor-unit price — a non-negative integer. */ -const PriceSchema = intAtLeast(0); +const PriceSchema = integerAtLeast(0); /** A required, trimmed, non-empty name reference. */ const NameRefSchema = v.pipe(v.string(), v.trim(), v.minLength(1)); /** A day-count JSON key: a positive whole number within the bookable range, so a diff --git a/src/features/api/payment-processing/metadata.ts b/src/features/api/payment-processing/metadata.ts index 6d931918d6..6cb1739291 100644 --- a/src/features/api/payment-processing/metadata.ts +++ b/src/features/api/payment-processing/metadata.ts @@ -48,6 +48,9 @@ const parseListingTextAnswerIds = jsonMetaField< Record | undefined >(undefined); +const textOrEmpty = (value: unknown): string => + typeof value === "string" ? value : ""; + /** * Parse booking items from metadata JSON. Returns null when the JSON is * unparseable, not an array, or empty. @@ -108,21 +111,21 @@ export const extractIntent = ( const siteTokenIndex = metadata.site_token_index || undefined; const thankYouUrl = metadata.thank_you_url || undefined; return { - address: metadata.address, + address: textOrEmpty(metadata.address), allocations, balanceAttendeeId, date: metadata.date || null, dayCount, - email: metadata.email, + email: textOrEmpty(metadata.email), items, listingAnswerIds, listingTextAnswerIds, modifiers: parseModifierRefs(metadata.modifiers), - name: metadata.name, - phone: metadata.phone, + name: textOrEmpty(metadata.name), + phone: textOrEmpty(metadata.phone), reservationAmount, siteTokenIndex, - special_instructions: metadata.special_instructions, + special_instructions: textOrEmpty(metadata.special_instructions), thankYouUrl, }; }; diff --git a/src/features/public/pages.ts b/src/features/public/pages.ts index cd4e2d0252..6f4f8079e6 100644 --- a/src/features/public/pages.ts +++ b/src/features/public/pages.ts @@ -30,9 +30,9 @@ import { requirePublicSite } from "#shared/public-site.ts"; import type { ResponseHandler } from "#shared/response-steps.ts"; import { loadSortedListings } from "#shared/sort-listings.ts"; import { + clampDurationDays, type GroupWithMembers, type ListingWithCount, - normalizeDurationDays, } from "#shared/types.ts"; import { parseEmail } from "#shared/validation/email.ts"; import { @@ -81,7 +81,7 @@ export const handleHome: ResponseHandler = () => * fixed daily listing books its whole duration. Mirrors * {@link getBookableStartDates}'s span. */ const cardSpanDays = (listing: ListingWithCount): number => - listing.customisable_days ? 1 : normalizeDurationDays(listing.duration_days); + listing.customisable_days ? 1 : clampDurationDays(listing.duration_days); /** The daily listings NOT bookable on `date`: outside their bookable calendar, * or without capacity for their span starting that day. One remaining query diff --git a/src/shared/address-lookup/types.ts b/src/shared/address-lookup/types.ts index 2f60c7c515..4fc2a3678e 100644 --- a/src/shared/address-lookup/types.ts +++ b/src/shared/address-lookup/types.ts @@ -36,7 +36,12 @@ export type AddressLookupProvider = Exclude; /** One matching address: its ready-to-display line, plus the provider's * latitude/longitude when it knows them ("" when it doesn't). */ -export type AddressMatch = { line: string; lat: string; lng: string }; +export const AddressMatchSchema = v.strictObject({ + lat: v.string(), + line: v.string(), + lng: v.string(), +}); +export type AddressMatch = v.InferOutput; /** Everything one lookup provider knows how to do. */ export type AddressLookupProviderDefinition = { diff --git a/src/shared/admin-features.ts b/src/shared/admin-features.ts index 57cdf831d2..95969d2074 100644 --- a/src/shared/admin-features.ts +++ b/src/shared/admin-features.ts @@ -1,4 +1,5 @@ import * as v from "valibot"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; /** * The admin features operators can choose to show. This one registry drives the @@ -81,6 +82,7 @@ const EnabledFeaturesSchema = v.pipe( "Every admin feature must have an enabled value", ), ); +const enabledFeaturesJson = defineStoredJson(EnabledFeaturesSchema); const DEFAULT_ENABLED_FEATURES = Object.freeze( Object.fromEntries(FEATURE_KEYS.map((key) => [key, false])), @@ -91,10 +93,13 @@ const DEFAULT_ENABLED_FEATURES = Object.freeze( export const parseEnabledFeatures = (value: string): EnabledFeatures => value === "" ? DEFAULT_ENABLED_FEATURES - : (v.parse(EnabledFeaturesSchema, JSON.parse(value)) as EnabledFeatures); + : (enabledFeaturesJson.read( + value, + "settings.enabled_features", + ) as EnabledFeatures); export const serializeEnabledFeatures = (features: EnabledFeatures): string => - JSON.stringify(v.parse(EnabledFeaturesSchema, features)); + enabledFeaturesJson.write(features, "settings.enabled_features"); export const setFeatureEnabled = ( features: EnabledFeatures, diff --git a/src/shared/booking-date-fields.ts b/src/shared/booking-date-fields.ts index cf8beb8c75..abb758063c 100644 --- a/src/shared/booking-date-fields.ts +++ b/src/shared/booking-date-fields.ts @@ -12,7 +12,7 @@ import { capacityDateFor } from "#shared/capacity-rules.ts"; import type { ListingWithCount } from "#shared/types.ts"; -import { normalizeDurationDays } from "#shared/types.ts"; +import { clampDurationDays } from "#shared/types.ts"; /** The listing facts the row builder reads to derive a booking's date and * duration. Narrower than the full listing so the helper stays pure over the @@ -30,7 +30,7 @@ export type BookingDateSource = Pick< * - A non-customisable `daily` listing spans its fixed `duration_days`. * - A `standard` listing spans one dateless day (no range column). * - * `dayCount` defaults to `1`, and {@link normalizeDurationDays} clamps + * `dayCount` defaults to `1`, and {@link clampDurationDays} clamps * non-finite input back to `1`, so a genuinely optional `dayCount` (a legacy * signed session without `day_count`, modelled as `undefined` on * `BookingIntent`) flows through that default unchanged — missing day count @@ -45,8 +45,8 @@ export const bookingDateFields = ( ): { date: string | null; durationDays: number } => ({ date: capacityDateFor(listing.listing_type, date), durationDays: listing.customisable_days - ? normalizeDurationDays(dayCount) + ? clampDurationDays(dayCount) : listing.listing_type === "daily" - ? normalizeDurationDays(listing.duration_days) + ? clampDurationDays(listing.duration_days) : 1, }); diff --git a/src/shared/booking/model.ts b/src/shared/booking/model.ts index 80a1cc3f3b..eb1bdff905 100644 --- a/src/shared/booking/model.ts +++ b/src/shared/booking/model.ts @@ -3,10 +3,10 @@ import { getBookableStartDates, isBookingRangeValid } from "#shared/dates.ts"; import { ascending, availableDayCounts, + clampDurationDays, dayPriceFor, type Holiday, type ListingWithCount, - normalizeDurationDays, PARENT_CHILD_GROUP_UNITS, type SharedGroupCapacity, } from "#shared/types.ts"; @@ -84,7 +84,7 @@ export const childUsesSameDays = (child: TicketListing): boolean => child.listing.customisable_days || child.listing.listing_type !== "daily" || - normalizeDurationDays(child.listing.duration_days) === days; + clampDurationDays(child.listing.duration_days) === days; /** The order's resolved date is valid for a daily child's own calendar. */ export const childDateOk = @@ -145,7 +145,7 @@ export const childDaysFromParent = ( ): T => { if (parent.customisable_days) return customisableValue; if (parent.listing_type === "daily") { - return normalizeDurationDays(parent.duration_days) as T; + return clampDurationDays(parent.duration_days) as T; } return standardValue; }; @@ -160,7 +160,7 @@ export const fixedParentDays = ( childDaysFromParent( parent, null, - normalizeDurationDays(parent.duration_days), + clampDurationDays(parent.duration_days), ); /** Keeps options that at least one child can support. */ @@ -251,7 +251,7 @@ export const dayCountsChildSupports = ( ): number[] | null => { if (child.listing.customisable_days) return availableDayCounts(child.listing); if (child.listing.listing_type === "daily") { - return [normalizeDurationDays(child.listing.duration_days)]; + return [clampDurationDays(child.listing.duration_days)]; } return null; }; diff --git a/src/shared/dates.ts b/src/shared/dates.ts index 85fa36f4cd..1cdc51b1bd 100644 --- a/src/shared/dates.ts +++ b/src/shared/dates.ts @@ -13,9 +13,9 @@ import { utcToZoned, } from "#shared/timezone.ts"; import { + clampDurationDays, type Holiday, type Listing, - normalizeDurationDays, } from "#shared/types.ts"; /** Month names for display */ @@ -181,9 +181,7 @@ export const getAvailableDates = ( durationOverride?: number, ): string[] => { const range = bookableRange(listing); - const duration = normalizeDurationDays( - durationOverride ?? listing.duration_days, - ); + const duration = clampDurationDays(durationOverride ?? listing.duration_days); return filter((d: string) => isRangeBookable(d, duration, range.bookableDays, holidays, range.end), )(dateRange(range.start, range.end)); @@ -232,7 +230,7 @@ export const isBookingRangeValid = ( if (date < range.start) return false; return isRangeBookable( date, - normalizeDurationDays(days), + clampDurationDays(days), range.bookableDays, holidays, range.end, @@ -250,7 +248,7 @@ export const getNextBookableDate = ( ): string | null => { const range = bookableRange(listing); if (range.bookableDays.length === 0) return null; - const duration = normalizeDurationDays(listing.duration_days); + const duration = clampDurationDays(listing.duration_days); let current = range.start; while (current <= range.end) { diff --git a/src/shared/db/address-cache.ts b/src/shared/db/address-cache.ts index e5b0572336..782f01a2ec 100644 --- a/src/shared/db/address-cache.ts +++ b/src/shared/db/address-cache.ts @@ -10,13 +10,18 @@ */ /* jscpd:ignore-start */ -import type { AddressMatch } from "#shared/address-lookup/types.ts"; +import * as v from "valibot"; +import { + type AddressMatch, + AddressMatchSchema, +} from "#shared/address-lookup/types.ts"; import { decrypt, encrypt } from "#shared/crypto/encryption.ts"; import { hmacHash } from "#shared/crypto/hashing.ts"; import type { BlindIndex, EnvKeyEncrypted } from "#shared/crypto/sealed.ts"; import { execute, queryOne } from "#shared/db/client.ts"; import { ADDRESS_CACHE_MS } from "#shared/limits.ts"; import { nowMs } from "#shared/now.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; /* jscpd:ignore-end */ /** @@ -32,6 +37,10 @@ export const computeAddressSearchIndex = ( const freshCutoffIso = (): string => new Date(nowMs() - ADDRESS_CACHE_MS).toISOString(); +const cachedAddressesJson = defineStoredJson( + v.union([v.array(v.string()), v.array(AddressMatchSchema)]), +); + /** Read a fresh cached result. Null on miss (absent or expired). Rows cached * before matches carried coordinates hold bare line strings; those read as a * miss too, so the next lookup re-fetches the postcode WITH coordinates and @@ -44,12 +53,15 @@ export const getCachedAddresses = async ( [searchIndex, freshCutoffIso()], ); if (!row) return null; - const entries = JSON.parse(await decrypt(row.results)) as ( - | string - | AddressMatch - )[]; - if (entries.some((entry) => typeof entry === "string")) return null; - return entries as AddressMatch[]; + const entries = cachedAddressesJson.read( + await decrypt(row.results), + `address_cache.results for ${searchIndex}`, + ); + return entries.every( + (entry): entry is AddressMatch => typeof entry !== "string", + ) + ? entries + : null; }; /** Cache a lookup result, replacing any previous row for the same search. */ @@ -62,7 +74,9 @@ export const storeCachedAddresses = async ( "ON CONFLICT(search_index) DO UPDATE SET results = excluded.results, created = excluded.created", [ searchIndex, - await encrypt(JSON.stringify(addresses)), + await encrypt( + cachedAddressesJson.write(addresses, "address_cache.results"), + ), new Date(nowMs()).toISOString(), ], ); diff --git a/src/shared/db/attendees/capacity/range.ts b/src/shared/db/attendees/capacity/range.ts index 7b1069ea6d..97de23f64e 100644 --- a/src/shared/db/attendees/capacity/range.ts +++ b/src/shared/db/attendees/capacity/range.ts @@ -1,7 +1,7 @@ import { filter, map, pipe, sumOf } from "#fp"; import { addDays } from "#shared/dates.ts"; import { dateToRange } from "#shared/db/capacity.ts"; -import { normalizeDurationDays } from "#shared/types.ts"; +import { clampDurationDays } from "#shared/types.ts"; /** Convert a nullable date to the stored half-open range. */ export const dateToStartEnd = ( @@ -18,7 +18,7 @@ export const expandDailyRange = ( date: string, durationDays: number, ): string[] => { - const duration = normalizeDurationDays(durationDays); + const duration = clampDurationDays(durationDays); return Array.from({ length: duration }, (_, i) => addDays(date, i)); }; diff --git a/src/shared/db/attendees/create.ts b/src/shared/db/attendees/create.ts index 7b224b4667..84c0f3c4a7 100644 --- a/src/shared/db/attendees/create.ts +++ b/src/shared/db/attendees/create.ts @@ -35,7 +35,7 @@ import { anyModifierSoldOut } from "#shared/db/modifier-usage.ts"; import { type Attendee, type ContactInfo, - normalizeDurationDays, + clampDurationDays, } from "#shared/types.ts"; /* jscpd:ignore-end */ @@ -74,7 +74,7 @@ const buildAttendeeResult = (input: BuildAttendeeInput): Attendee => ({ created: input.created, date: input.date, end_date: input.date - ? addDays(input.date, normalizeDurationDays(input.durationDays ?? 1)) + ? addDays(input.date, clampDurationDays(input.durationDays ?? 1)) : null, kind: input.kind, lat: "", diff --git a/src/shared/db/attendees/pii.ts b/src/shared/db/attendees/pii.ts index 1138569528..e97dba1b46 100644 --- a/src/shared/db/attendees/pii.ts +++ b/src/shared/db/attendees/pii.ts @@ -7,6 +7,7 @@ */ /* jscpd:ignore-start */ +import * as v from "valibot"; import { map } from "#fp"; import { hmacHash } from "#shared/crypto/hashing.ts"; import { @@ -24,33 +25,48 @@ import type { import { settings } from "#shared/db/settings.ts"; import { nowIso } from "#shared/now.ts"; import type { ContactInfo, PiiBlob } from "#shared/types.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; /* jscpd:ignore-end */ /** Current PII blob schema version */ export const PII_BLOB_VERSION = 1; +const PiiBlobSchema: v.GenericSchema = v.strictObject({ + a: v.string(), + e: v.string(), + la: v.optional(v.string()), + lo: v.optional(v.string()), + n: v.string(), + p: v.string(), + pi: v.string(), + s: v.string(), + t: v.string(), + v: v.optional(v.literal(PII_BLOB_VERSION), PII_BLOB_VERSION), +}); +const piiBlobJson = defineStoredJson(PiiBlobSchema); + /** Build a PII blob JSON from contact fields. An unpinned latitude/longitude * ("") is left out of the JSON so blobs without a pin stay as small as before. */ export const buildPiiBlob = (info: AttendeePii): string => - JSON.stringify({ - a: info.address, - e: info.email, - la: info.lat || undefined, - lo: info.lng || undefined, - n: info.name, - p: info.phone, - pi: info.payment_id, - s: info.special_instructions, - t: info.ticket_token, - v: PII_BLOB_VERSION, - } satisfies PiiBlob); + piiBlobJson.write( + { + a: info.address, + e: info.email, + la: info.lat || undefined, + lo: info.lng || undefined, + n: info.name, + p: info.phone, + pi: info.payment_id, + s: info.special_instructions, + t: info.ticket_token, + v: PII_BLOB_VERSION, + }, + "attendees.pii_blob", + ); /** Parse a PII blob JSON back into contact fields (defaults v to 1 for pre-versioned blobs) */ -export const parsePiiBlob = (json: string): PiiBlob => { - const blob = JSON.parse(json) as PiiBlob; - blob.v ??= PII_BLOB_VERSION; - return blob; -}; +export const parsePiiBlob = (json: string): PiiBlob => + piiBlobJson.read(json, "attendees.pii_blob"); /** Encrypt a PII blob JSON string with the public key */ export const encryptPiiBlob = ( diff --git a/src/shared/db/attendees/servicing.ts b/src/shared/db/attendees/servicing.ts index 94516e18e8..01492b0e60 100644 --- a/src/shared/db/attendees/servicing.ts +++ b/src/shared/db/attendees/servicing.ts @@ -52,7 +52,7 @@ import { import { settings } from "#shared/db/settings.ts"; import type { TransferInput } from "#shared/ledger/types.ts"; import { nowIso } from "#shared/now.ts"; -import { type Attendee, normalizeDurationDays } from "#shared/types.ts"; +import { type Attendee, clampDurationDays } from "#shared/types.ts"; /* jscpd:ignore-end */ /** An answer chosen for a service event's custom question. Only the `answerId` @@ -196,7 +196,7 @@ const saveServicingAnswers = ( const durationDaysFromRow = (row: ListingAttendeeRow): number | undefined => { if (!row.start_at || !row.end_at) return; const ms = new Date(row.end_at).getTime() - new Date(row.start_at).getTime(); - return normalizeDurationDays(Math.round(ms / 86_400_000)); + return clampDurationDays(Math.round(ms / 86_400_000)); }; const bookingFromRow = (row: ListingAttendeeRow): ListingBooking => { @@ -383,7 +383,7 @@ const desiredLines = ( ); return input.bookings.map((booking) => { const date = booking.date ?? null; - const durationDays = normalizeDurationDays(booking.durationDays ?? 1); + const durationDays = clampDurationDays(booking.durationDays ?? 1); return { ...lineKeyForInput(booking, existingBySlot), date, diff --git a/src/shared/db/attendees/update.ts b/src/shared/db/attendees/update.ts index 08e1909476..e7d02a7c2d 100644 --- a/src/shared/db/attendees/update.ts +++ b/src/shared/db/attendees/update.ts @@ -16,7 +16,7 @@ import { withTransaction, } from "#shared/db/client.ts"; import { settings } from "#shared/db/settings.ts"; -import { type ListingType, normalizeDurationDays } from "#shared/types.ts"; +import { clampDurationDays, type ListingType } from "#shared/types.ts"; /** * Set a line's check-in flag, refusing a no-quantity (quantity 0) line — it @@ -98,7 +98,7 @@ export const recomputeListingBookingRanges = async ( listingId: number, durationDays: number, ): Promise => { - const duration = normalizeDurationDays(durationDays); + const duration = clampDurationDays(durationDays); await execute( `UPDATE listing_attendees SET end_at = REPLACE(datetime(start_at, '+' || ? || ' days'), ' ', 'T') || '.000Z' diff --git a/src/shared/db/built-sites.ts b/src/shared/db/built-sites.ts index b6ce91beb0..2583d1e4e6 100644 --- a/src/shared/db/built-sites.ts +++ b/src/shared/db/built-sites.ts @@ -13,6 +13,8 @@ import type { ColumnDef, Table, TableSchema } from "#shared/db/table.ts"; import { cachedTable, col, defineTable } from "#shared/db/table.ts"; import { nowIso } from "#shared/now.ts"; import { guardFor } from "#shared/validation/guard.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; +import { OptionalStringSchema } from "#shared/validation/string.ts"; /* jscpd:ignore-end */ /** @@ -63,26 +65,20 @@ export const providerOrBunny = < provider: TProvider, ): "bunny" | TProvider => (value === provider ? provider : "bunny"); -/** Encrypted site data blob shape */ -export interface SiteDataBlob { - /** Database URL (optional, absent in older blobs) */ - d?: string; - /** Database provider (optional, defaults to "bunny" for backward compat) */ - dp?: DbProvider; - /** Hosting provider (optional, defaults to "bunny" for backward compat) */ - hp?: HostingProvider; - /** Site name */ - n: string; - /** Renewal token (optional, present when renewal access exists) */ - rt?: string; - /** Hosting ID — Bunny script ID or Deno app ID (optional, absent in older blobs) */ - s?: string; - /** Database token (optional, absent in older blobs) */ - t?: string; - /** Site URL (default hostname) */ - u: string; - v: typeof SITE_DATA_BLOB_VERSION; -} +/** Encrypted site data blob shape, including fields absent from older blobs. */ +const SiteDataBlobSchema = v.strictObject({ + d: OptionalStringSchema, + dp: v.optional(v.picklist(["bunny", "turso"])), + hp: v.optional(v.picklist(["bunny", "deno"])), + n: v.string(), + rt: OptionalStringSchema, + s: OptionalStringSchema, + t: OptionalStringSchema, + u: v.string(), + v: v.literal(SITE_DATA_BLOB_VERSION), +}); +export type SiteDataBlob = v.InferOutput; +const siteDataJson = defineStoredJson(SiteDataBlobSchema); /** Built site row as stored in the database */ export interface BuiltSiteRow { @@ -382,8 +378,8 @@ const buildSiteDataBlobFromInput = ( column.defaultValue) as string | null; return column.required || value ? [[column.blobKey, value]] : []; }), - ]) as unknown as SiteDataBlob; - return JSON.stringify(blob); + ]); + return siteDataJson.write(blob, "built_sites.site_data"); }; const blobToSiteFields = (blob: SiteDataBlob): BuiltSiteBlobFields => @@ -425,7 +421,7 @@ const toDbColumnValues = ( /** Parse a decrypted site data blob */ export const parseSiteDataBlob = (json: string): SiteDataBlob => - JSON.parse(json) as SiteDataBlob; + siteDataJson.read(json, "built_sites.site_data"); /** Convert a raw DB row (after decryption) to a BuiltSite */ const rowToBuiltSite = (row: BuiltSiteRow): BuiltSite => { diff --git a/src/shared/db/capacity.ts b/src/shared/db/capacity.ts index 56731ff72f..57031599bb 100644 --- a/src/shared/db/capacity.ts +++ b/src/shared/db/capacity.ts @@ -20,7 +20,7 @@ import type { InValue } from "@libsql/client"; import { capacityRuleTypeSql } from "#shared/capacity-rules.ts"; import { addDays } from "#shared/dates.ts"; import { joinStatements, type SqlStatement } from "#shared/db/client.ts"; -import { normalizeDurationDays } from "#shared/types.ts"; +import { clampDurationDays } from "#shared/types.ts"; /** A half-open [startAt, endAt) window of whole days, as timestamps. Also * the shape of an attendee's booked windows on the Logistics tab. */ @@ -38,7 +38,7 @@ export type DayRange = { startAt: string; endAt: string }; * to match, because SQLite TEXT comparison is byte-for-byte and tests * assert the exact stored format. */ export const dateToRange = (date: string, durationDays = 1): DayRange => { - const days = normalizeDurationDays(durationDays); + const days = clampDurationDays(durationDays); const ms = new Date(`${date}T00:00:00Z`).getTime(); const endIso = new Date(ms + days * 86_400_000).toISOString(); return { endAt: endIso, startAt: `${date}T00:00:00Z` }; @@ -293,7 +293,7 @@ export const buildCapacityCondition = ( qty, ); } - const duration = normalizeDurationDays(durationDays); + const duration = clampDurationDays(durationDays); const dayClauses = Array.from({ length: duration }, (_, i) => { const daily = buildDayCapacitySql( { diff --git a/src/shared/db/contact-preferences.ts b/src/shared/db/contact-preferences.ts index 18972e1398..0ce0ea6e84 100644 --- a/src/shared/db/contact-preferences.ts +++ b/src/shared/db/contact-preferences.ts @@ -28,6 +28,9 @@ import { ErrorCode, logError } from "#shared/logger.ts"; import { nowIso, nowMs } from "#shared/now.ts"; import { normalizePhone } from "#shared/phone.ts"; import { guardFor } from "#shared/validation/guard.ts"; +import { integerAtLeast } from "#shared/validation/number.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; +import { OptionalStringSchema } from "#shared/validation/string.ts"; /* jscpd:ignore-end */ export const ContactChannelSchema = v.picklist(["email", "sms"]); @@ -145,12 +148,14 @@ export type ContactRecordLoader = ( privateKey: CryptoKey, ) => Promise; -type StatsBlob = { - c?: number; - t?: string; - s?: string; - n?: string; -}; +const StatsBlobSchema = v.strictObject({ + c: v.optional(integerAtLeast(0)), + n: OptionalStringSchema, + s: OptionalStringSchema, + t: OptionalStringSchema, +}); +type StatsBlob = v.InferOutput; +const statsJson = defineStoredJson(StatsBlobSchema); const EMPTY_STATS: ContactStats = { adminNotes: "", @@ -164,9 +169,10 @@ const parseStats = async ( privateKey: CryptoKey, ): Promise => { if (!blob) return EMPTY_STATS; - const { c, n, s, t } = JSON.parse( + const { c, n, s, t } = statsJson.read( await decryptWithOwnerKey(blob, privateKey), - ) as StatsBlob; + "contact_preferences.stats_blob", + ); return { adminNotes: n ?? "", contactCount: c ?? 0, @@ -300,7 +306,7 @@ const saveStats = async ( args: [ hash, await encryptWithOwnerKey( - JSON.stringify(statsToBlob(stats)), + statsJson.write(statsToBlob(stats), "contact_preferences.stats_blob"), settings.publicKey, ), lastActivity, @@ -351,7 +357,7 @@ export const saveContactRecord = async ( record: ContactRecord, ): Promise => { const blob = await encryptWithOwnerKey( - JSON.stringify(statsToBlob(record)), + statsJson.write(statsToBlob(record), "contact_preferences.stats_blob"), settings.publicKey, ); await execute( diff --git a/src/shared/db/groups.ts b/src/shared/db/groups.ts index bb70a7ba84..3e0fd3f904 100644 --- a/src/shared/db/groups.ts +++ b/src/shared/db/groups.ts @@ -66,12 +66,16 @@ import type { ListingType, ListingWithCount, } from "#shared/types.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; /* jscpd:ignore-end */ /** Groups are few, so the cache loads the whole set and answers by-id / by-slug * reads from it — same isolate-level TTL as the listings cache. */ const GROUPS_CACHE_TTL_MS = 30_000; +const groupIdsJson = defineStoredJson( + v.array(v.pipe(v.number(), v.safeInteger(), v.minValue(1))), +); /** A package member's per-unit price override and fixed quantity, as parsed from * the group edit form / API. `price` is minor units (0 = no override, use the @@ -241,7 +245,10 @@ export const getListingsByGroupIds = async ( ); const listingsWithGroups: ListingGroups[] = await mapParallel( async (row: GroupListingRow): Promise => ({ - groupIds: v.parse(v.array(v.number()), JSON.parse(row.group_ids)), + groupIds: groupIdsJson.read( + row.group_ids, + `group_listings.group_ids for listing ${row.id}`, + ), member: await decryptListingWithCount(row), }), )(rows); diff --git a/src/shared/db/listings/table.ts b/src/shared/db/listings/table.ts index f5d1770c47..0e4472d6f3 100644 --- a/src/shared/db/listings/table.ts +++ b/src/shared/db/listings/table.ts @@ -1,5 +1,6 @@ /** Listing table schema and stored-value transforms. */ +import * as v from "valibot"; import { decrypt, encrypt } from "#shared/crypto/encryption.ts"; import { hmacHash } from "#shared/crypto/hashing.ts"; import type { BlindIndex, EnvKeyEncrypted } from "#shared/crypto/sealed.ts"; @@ -15,15 +16,16 @@ import { decryptImageFilenameOrEmpty } from "#shared/images/broken.ts"; import { ErrorCode, logError } from "#shared/logger.ts"; import { nowIso } from "#shared/now.ts"; import { + clampDurationDays, type DayPrices, + DayPricesSchema, type Listing, type ListingFields, type ListingType, - normalizeDurationDays, - parseDayPrices, } from "#shared/types.ts"; const DEFAULT_BOOKABLE_DAYS: string[] = [...VALID_DAY_NAMES]; +const BookableDaysSchema = v.array(v.string()); /** Listing input fields for create/update (camelCase). */ export type ListingInput = { @@ -95,9 +97,7 @@ const encryptDatetime = ( const decryptDatetime = async (value: EnvKeyEncrypted): Promise => { const decrypted = await decrypt(value); - return decrypted === "" - ? "" - : normalizeUtcDatetime(decrypted, "stored datetime"); + return normalizeUtcDatetime(decrypted, "stored datetime"); }; const writeClosesAt = (value: string | null): Promise => @@ -140,19 +140,9 @@ export const rawListingsTable = defineIdTable( attachment_name: col.encryptedText(encrypt, decrypt), attachment_url: col.encryptedText(encrypt, decrypt), bookable_alone: col.boolean(false), - bookable_days: col.converted({ + bookable_days: col.json(BookableDaysSchema, { + context: "listings.bookable_days", default: () => [...DEFAULT_BOOKABLE_DAYS], - read: (value) => { - const parsed: unknown = JSON.parse(value as string); - if ( - !Array.isArray(parsed) || - !parsed.every((day): day is string => typeof day === "string") - ) { - throw new Error("Stored bookable_days must be a JSON string array"); - } - return parsed; - }, - write: (value) => JSON.stringify(value), }), can_pay_more: col.boolean(false), closes_at: col.transform(writeClosesAt, readClosesAt), @@ -162,11 +152,13 @@ export const rawListingsTable = defineIdTable( default: () => "", ...col.encrypted(writeListingDate, decryptDatetime), }, - day_prices: col.projected((value) => - parseDayPrices(JSON.parse((value as string) ?? "{}")), - ), + day_prices: col.json(DayPricesSchema, { + context: "listings.day_prices", + projected: true, + whenMissing: () => ({}), + }), description: col.encryptedText(encrypt, decrypt), - duration_days: { default: () => 1, write: normalizeDurationDays }, + duration_days: { default: () => 1, write: clampDurationDays }, fields: col.withDefault(() => "email"), hidden: col.boolean(false), image_alt_text: col.projected(readProjectedAltText), diff --git a/src/shared/db/processed-payments.ts b/src/shared/db/processed-payments.ts index ea3e24c1de..ead91934f7 100644 --- a/src/shared/db/processed-payments.ts +++ b/src/shared/db/processed-payments.ts @@ -14,6 +14,7 @@ * - Fresh → return conflict error (still being processed) */ +import * as v from "valibot"; import { decrypt, encrypt } from "#shared/crypto/encryption.ts"; import type { EnvKeyEncrypted, @@ -23,6 +24,7 @@ import { execute, insert, queryOne } from "#shared/db/client.ts"; import { encryptPaymentReference } from "#shared/db/payment-references.ts"; import { STALE_RESERVATION_MS } from "#shared/limits.ts"; import { nowIso, nowMs } from "#shared/now.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; export { STALE_RESERVATION_MS }; @@ -68,11 +70,15 @@ export type ProcessedPayment = { * clear. Keep this shape free of any field that shouldn't round-trip through the * DB encryption key. */ -export type StoredPaymentFailure = { - error: string; - status?: number | undefined; - refunded?: boolean | undefined; -}; +const StoredPaymentFailureSchema = v.strictObject({ + error: v.string(), + refunded: v.optional(v.boolean()), + status: v.optional(v.pipe(v.number(), v.safeInteger())), +}); +export type StoredPaymentFailure = v.InferOutput< + typeof StoredPaymentFailureSchema +>; +const paymentFailureJson = defineStoredJson(StoredPaymentFailureSchema); /** Result of session reservation attempt */ export type ReserveSessionResult = @@ -249,7 +255,12 @@ export const markSessionFailed = async ( ): Promise => { await execute( `UPDATE processed_payments SET failure_data = ? WHERE payment_session_id = ? AND ${UNRESOLVED_RESERVATION}`, - [await encrypt(JSON.stringify(failure)), sessionId], + [ + await encrypt( + paymentFailureJson.write(failure, "processed_payments.failure_data"), + ), + sessionId, + ], ); }; @@ -271,7 +282,10 @@ export const parseSessionFailure = async ( ): Promise => { if (!failureData) return null; try { - return JSON.parse(await decrypt(failureData)) as StoredPaymentFailure; + return paymentFailureJson.read( + await decrypt(failureData), + "processed_payments.failure_data", + ); } catch { return CORRUPT_FAILURE; } diff --git a/src/shared/db/sumup-checkouts.ts b/src/shared/db/sumup-checkouts.ts index c1e9ef22ed..485011751a 100644 --- a/src/shared/db/sumup-checkouts.ts +++ b/src/shared/db/sumup-checkouts.ts @@ -29,6 +29,7 @@ * (30 min) and webhook retry window (2 h) have passed. */ +import * as v from "valibot"; import { decryptWithKey, encryptWithKey } from "#shared/crypto/encryption.ts"; import { hmacHash } from "#shared/crypto/hashing.ts"; import { @@ -39,6 +40,7 @@ import { import type { KeyEncrypted, WrappedKey } from "#shared/crypto/sealed.ts"; import { execute, executeUpdate, insert, queryOne } from "#shared/db/client.ts"; import { nowIso } from "#shared/now.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; type SumupCheckoutRow = { wrapped_key: WrappedKey; @@ -52,6 +54,8 @@ export type SumupCheckoutEntry = { sumupId: string; }; +const metadataJson = defineStoredJson(v.record(v.string(), v.string())); + /** Persist booking metadata for a checkout, encrypted under its reference. */ export const storeSumupCheckout = async ( reference: string, @@ -61,7 +65,10 @@ export const storeSumupCheckout = async ( const [referenceIndex, wrappedKey, ciphertext] = await Promise.all([ hmacHash(reference), wrapKeyWithToken(dataKey, reference), - encryptWithKey(JSON.stringify(metadata), dataKey), + encryptWithKey( + metadataJson.write(metadata, "sumup_checkouts.metadata"), + dataKey, + ), ]); const { sql, args } = insert("sumup_checkouts", { created_at: nowIso(), @@ -111,7 +118,10 @@ export const getSumupCheckout = async ( const dataKey = await unwrapKeyWithToken(row.wrapped_key, reference); const json = await decryptWithKey(row.metadata, dataKey); return { - metadata: JSON.parse(json) as Record, + metadata: metadataJson.read( + json, + `sumup_checkouts.metadata for ${reference}`, + ), sumupId: row.sumup_id, }; }; diff --git a/src/shared/db/table.ts b/src/shared/db/table.ts index 4fb523fe66..bf4565f6a7 100644 --- a/src/shared/db/table.ts +++ b/src/shared/db/table.ts @@ -27,6 +27,7 @@ import { } from "#shared/db/client.ts"; import { queryAndMap } from "#shared/db/query.ts"; import { requestCache } from "#shared/request-cache.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; /** * Column definition for a table @@ -739,6 +740,41 @@ const wrapNullable = (v) => v === null ? Promise.resolve(null) : Promise.resolve(fn(v)); +const storedJsonTransforms = ( + schema: TSchema, + context: string, +): { + read: (value: unknown, rowId?: unknown) => v.InferOutput; + write: (value: v.InferOutput) => string; +} => { + const json = defineStoredJson(schema); + return { + read: (value, rowId) => + json.read( + value, + `${context}${rowId === undefined ? "" : ` row ${String(rowId)}`}`, + ), + write: (value) => json.write(value, context), + }; +}; + +interface StoredJsonContext { + context: string; +} + +interface StoredJsonColumnConfig extends StoredJsonContext { + default?: () => T; +} + +interface ProjectedJsonColumnConfig extends StoredJsonContext { + projected: true; + whenMissing: () => T; +} + +type JsonColumnConfig = + | StoredJsonColumnConfig + | ProjectedJsonColumnConfig; + /** * Helper to create column definitions */ @@ -755,7 +791,7 @@ export const col = { converted: (config: { default?: () => App; write: (v: App) => InValue; - read: (raw: InValue) => App; + read: (raw: InValue, rowId?: unknown) => App; }): ColumnDef => ({ default: config.default, read: config.read as (v: App) => App, @@ -798,6 +834,25 @@ export const col = { /** Auto-generated column (like id) */ generated: (): ColumnDef => ({ generated: true }), + /** JSON column validated against one schema on every read and write. */ + json: ( + schema: TSchema, + config: JsonColumnConfig>, + ): ColumnDef> => { + const transforms = storedJsonTransforms(schema, config.context); + if ("projected" in config) { + return col.projected>((value, rowId) => + value === undefined + ? config.whenMissing() + : transforms.read(value, rowId), + ); + } + return col.converted>({ + ...(config.default ? { default: config.default } : {}), + ...transforms, + }); + }, + /** A read-only column that is NOT a physical column on the table: it is * projected into the row by the caller's SELECT (a subquery `AS `), read * back through `read`, and never written (`projected` excludes it from INSERT/ diff --git a/src/shared/db/token-attempts.ts b/src/shared/db/token-attempts.ts index 6a5aaf4dd5..bf900af29b 100644 --- a/src/shared/db/token-attempts.ts +++ b/src/shared/db/token-attempts.ts @@ -21,6 +21,7 @@ */ /* jscpd:ignore-start */ +import * as v from "valibot"; import { hmacHash } from "#shared/crypto/hashing.ts"; import { clearAttemptsFor, lockoutActive } from "#shared/db/attempt-lockout.ts"; import { execute, queryOne } from "#shared/db/client.ts"; @@ -30,6 +31,7 @@ import { TOKEN_WINDOW_MS, } from "#shared/limits.ts"; import { nowMs } from "#shared/now.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; /* jscpd:ignore-end */ @@ -39,6 +41,8 @@ type TokenAttemptRow = { window_start: number; }; +const recentTokensJson = defineStoredJson(v.array(v.string())); + const readRow = (hashedIp: string): Promise => queryOne( "SELECT recent_tokens, locked_until, window_start FROM token_attempts WHERE ip = ?", @@ -74,7 +78,12 @@ export const recordTokenFailure = async ( const windowValid = row && currentMs - row.window_start <= TOKEN_WINDOW_MS; const windowStart = windowValid ? row.window_start : currentMs; - const existing: string[] = windowValid ? JSON.parse(row.recent_tokens) : []; + const existing = windowValid + ? recentTokensJson.read( + row.recent_tokens, + `token_attempts.recent_tokens for ${hashedIp}`, + ) + : []; const merged = new Set(existing); for (const h of hashedTokens) merged.add(h); @@ -90,7 +99,12 @@ export const recordTokenFailure = async ( await execute( "INSERT OR REPLACE INTO token_attempts (ip, recent_tokens, locked_until, window_start, last_attempt) VALUES (?, ?, NULL, ?, ?)", - [hashedIp, JSON.stringify([...merged]), windowStart, currentMs], + [ + hashedIp, + recentTokensJson.write([...merged], "token_attempts.recent_tokens"), + windowStart, + currentMs, + ], ); return false; }; diff --git a/src/shared/email-renderer.ts b/src/shared/email-renderer.ts index 51ecd5c1d7..d5df27789d 100644 --- a/src/shared/email-renderer.ts +++ b/src/shared/email-renderer.ts @@ -20,10 +20,10 @@ import { createBaseLiquidEngine } from "#shared/liquid-engine.ts"; import { ErrorCode, logError } from "#shared/logger.ts"; import { type ContactInfo, + clampDurationDays, type EmailTemplateFormat, type EmailTemplateType, isPaidListing, - normalizeDurationDays, } from "#shared/types.ts"; import { DEFAULT_TEMPLATES } from "#templates/email/defaults.ts"; import type { EmailContent } from "#templates/email/shared.ts"; @@ -94,7 +94,7 @@ const toTemplateEntry = (entry: EmailEntry): TemplateEntry => { const dateRangeLabel = bookedRangeLabel( attendee.date, attendee.end_date, - normalizeDurationDays(listing.duration_days), + clampDurationDays(listing.duration_days), ); return { attendee: { diff --git a/src/shared/listing-defaults.ts b/src/shared/listing-defaults.ts index dfa32d6ded..a9ae1b76b5 100644 --- a/src/shared/listing-defaults.ts +++ b/src/shared/listing-defaults.ts @@ -15,28 +15,27 @@ * This module is pure. Form parsing/validation lives in the feature layer. */ +import * as v from "valibot"; +import { VALID_DAY_NAMES } from "#shared/day-names.ts"; import type { Listing } from "#shared/types.ts"; +import { integerAtLeast } from "#shared/validation/number.ts"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; /** * The operator-configurable defaults. A key is present only when a default is * set; an absent key means "no default — never override". */ -export type ListingDefaults = { - /** Always (`true`) / never (`false`) require logistics. */ - usesLogistics?: boolean; - /** Days of the week daily listings are bookable on. */ - bookableDays?: string[]; - /** Minimum days' notice before a daily booking. */ - minimumDaysBefore?: number; - /** Maximum days ahead a daily booking can be made. */ - maximumDaysAfter?: number; - /** Booking webhook URL. */ - webhookUrl?: string; - /** Post-purchase thank-you redirect URL. */ - thankYouUrl?: string; - /** Whether listings are hidden from public listing pages. */ - hidden?: boolean; -}; +export const ListingDefaultsSchema = v.strictObject({ + bookableDays: v.optional(v.array(v.picklist(VALID_DAY_NAMES))), + hidden: v.optional(v.boolean()), + maximumDaysAfter: v.optional(integerAtLeast(0)), + minimumDaysBefore: v.optional(integerAtLeast(0)), + thankYouUrl: v.optional(v.string()), + usesLogistics: v.optional(v.boolean()), + webhookUrl: v.optional(v.string()), +}); +export type ListingDefaults = v.InferOutput; +const listingDefaultsJson = defineStoredJson(ListingDefaultsSchema); /** How a default is stored, validated, and rendered. */ export type ListingDefaultKind = "bool" | "number" | "url" | "days"; @@ -161,9 +160,10 @@ export const resolveListingDefaults = ( */ export const parseListingDefaults = ( raw: string | undefined, -): ListingDefaults => (raw ? (JSON.parse(raw) as ListingDefaults) : {}); +): ListingDefaults => + raw ? listingDefaultsJson.read(raw, "settings.listing_defaults") : {}; /** Serialize defaults for storage. `JSON.stringify` drops every unset * (`undefined`) key, so only configured defaults are persisted. */ export const serializeListingDefaults = (defaults: ListingDefaults): string => - JSON.stringify(defaults); + listingDefaultsJson.write(defaults, "settings.listing_defaults"); diff --git a/src/shared/listing-parents-rules.ts b/src/shared/listing-parents-rules.ts index f1b259da4e..7fe5bfc6b4 100644 --- a/src/shared/listing-parents-rules.ts +++ b/src/shared/listing-parents-rules.ts @@ -13,9 +13,9 @@ import { t } from "#i18n"; import { availableDayCounts, + clampDurationDays, type DayPrices, dayPriceFor, - normalizeDurationDays, } from "#shared/types.ts"; /** The listing fields an edge-compatibility check reasons about. */ @@ -34,9 +34,7 @@ export type EdgeListing = { * non-`customisable_days` parent (a customisable parent has a *range*, via * {@link availableDayCounts}). */ const parentFixedDuration = (parent: EdgeListing): number => - parent.listing_type === "daily" - ? normalizeDurationDays(parent.duration_days) - : 1; + parent.listing_type === "daily" ? clampDurationDays(parent.duration_days) : 1; /** * Whether `child`'s booking span can match the duration it inherits from @@ -62,7 +60,7 @@ export const durationsCompatible = ( return dayPriceFor(child, parentFixedDuration(parent)) !== null; } if (child.listing_type !== "daily") return true; - const childDuration = normalizeDurationDays(child.duration_days); + const childDuration = clampDurationDays(child.duration_days); return parent.customisable_days ? availableDayCounts(parent).includes(childDuration) : childDuration === parentFixedDuration(parent); diff --git a/src/shared/listings-actions.ts b/src/shared/listings-actions.ts index 086a90a036..1fe86132af 100644 --- a/src/shared/listings-actions.ts +++ b/src/shared/listings-actions.ts @@ -50,11 +50,11 @@ import { generateUniqueSlug, normalizeSlug } from "#shared/slug.ts"; import { deleteListingAttachmentFile } from "#shared/storage.ts"; import { availableDayCounts, + clampDurationDays, type DayPricedListing, type Group, type Listing, type ListingWithCount, - normalizeDurationDays, } from "#shared/types.ts"; import { validateSafeServerFetchUrl } from "#shared/url-safety.ts"; @@ -209,7 +209,7 @@ export const dayPriceFieldsFromInput = ( ): DayPricedListing => ({ customisable_days: input.customisableDays ?? false, day_prices: input.dayPrices ?? {}, - duration_days: normalizeDurationDays(input.durationDays ?? 1), + duration_days: clampDurationDays(input.durationDays ?? 1), }); /** Project a (possibly partial) listing form input onto the edge-compatibility diff --git a/src/shared/types.ts b/src/shared/types.ts index 07a8e10b91..29a1b89b50 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -18,6 +18,7 @@ import type { ModifierTrigger, } from "#shared/price-modifier.ts"; import { guardFor } from "#shared/validation/guard.ts"; +import { boundedInteger, integerAtLeast } from "#shared/validation/number.ts"; import type { NonEmptyString } from "#shared/validation/string.ts"; /** Type guard: a non-null, non-array object (a Record shape). */ @@ -181,22 +182,27 @@ export const hasTicketQuantity = (row: { quantity: number }): boolean => export const MAX_DURATION_DAYS = 90; /** - * The single definition of "a valid booking duration": a whole number of - * days in [1, MAX_DURATION_DAYS]. Non-finite input is invalid and throws. - * - * Every read of `duration_days` and every `durationDays` parameter funnels - * through here so the clamping policy lives in exactly one place — the column - * write, the per-day capacity expansion (JS + SQL), and all display paths - * agree by construction. Idempotent, so applying it to an already-normalized - * value (e.g. a column-clamped `listing.duration_days`) is a safe no-op. + * Booking durations use one safe-integer range with two named policies. Clamp + * is for valid whole numbers outside the supported range. Reject is for + * boundaries where an out-of-range value must fail instead. Neither policy + * accepts fractions, non-finite numbers, or unsafe integers. */ -export const normalizeDurationDays = (value: number): number => { - if (!Number.isFinite(value)) { - throw new Error(`Invalid booking duration: ${String(value)}`); +const durationDays = boundedInteger(1, MAX_DURATION_DAYS); + +/** Clamp a valid whole-day count to the supported booking range. */ +export const clampDurationDays = (value: number): number => { + try { + return durationDays.clamp(value); + } catch (error) { + throw new Error(`Invalid booking duration: ${String(value)}`, { + cause: error, + }); } - return Math.max(1, Math.min(MAX_DURATION_DAYS, Math.floor(value))); }; +/** Reject any value that is not a whole day count in the supported range. */ +export const rejectDurationDays = durationDays.reject; + /** * Per-day-count ticket prices for "customisable days" listings, in minor * units, keyed by the number of days booked. e.g. `{ 1: 1000, 2: 1800 }` @@ -205,6 +211,25 @@ export const normalizeDurationDays = (value: number): number => { */ export type DayPrices = Record; +const DayPriceKeySchema = v.pipe( + v.string(), + v.regex(/^\d+$/), + v.check((value) => { + const days = Number(value); + return days >= 1 && days <= MAX_DURATION_DAYS; + }), +); +const DayPricesRecordSchema = v.record(DayPriceKeySchema, integerAtLeast(0)); + +/** Strict stored shape for per-day-count prices. */ +export const DayPricesSchema = v.pipe( + v.intersect([ + v.custom>(isRecord), + DayPricesRecordSchema, + ]), + v.transform((prices): DayPrices => prices), +); + /** * Build a {@link DayPrices} map from raw entries. `checkEntry` reads one raw * key/value pair and returns the day count and price to keep, `null` to skip @@ -266,7 +291,7 @@ export const ascending = (a: number, b: number): number => a - b; export const availableDayCounts = (listing: DayPricedListing): number[] => { if (!listing.customisable_days) return []; - const max = normalizeDurationDays(listing.duration_days); + const max = clampDurationDays(listing.duration_days); return Object.keys(listing.day_prices) .map(Number) .filter((n) => n >= 1 && n <= max) @@ -283,7 +308,7 @@ export const dayPriceFor = ( days: number, ): number | null => { if (!listing.customisable_days) return null; - const max = normalizeDurationDays(listing.duration_days); + const max = clampDurationDays(listing.duration_days); if (!Number.isInteger(days) || days < 1 || days > max) return null; return listing.day_prices[days] ?? null; }; diff --git a/src/shared/validation/number.ts b/src/shared/validation/number.ts index d7e7f7b6aa..90ff2273e0 100644 --- a/src/shared/validation/number.ts +++ b/src/shared/validation/number.ts @@ -1,5 +1,35 @@ import * as v from "valibot"; import { parseOrNull } from "./parse.ts"; +import { NonEmptyTextSchema } from "./string.ts"; + +export interface BoundedInteger { + /** Clamp valid integers to the range. Malformed numbers still throw. */ + clamp: (value: number) => number; + /** Require a valid integer inside the range. */ + reject: (value: number) => number; +} + +/** A safe whole number no lower than `minimum`. */ +export const integerAtLeast = (minimum: number) => + v.pipe(v.number(), v.safeInteger(), v.minValue(minimum)); + +/** Define explicit reject and clamp policies for one safe-integer range. */ +export const boundedInteger = ( + minimum: number, + maximum: number, +): BoundedInteger => { + const integerSchema = integerAtLeast(Number.MIN_SAFE_INTEGER); + const rangeSchema = v.pipe( + integerSchema, + v.minValue(minimum), + v.maxValue(maximum), + ); + return { + clamp: (value) => + Math.max(minimum, Math.min(maximum, v.parse(integerSchema, value))), + reject: (value) => v.parse(rangeSchema, value), + }; +}; /** * Plain decimal integer strings. The schemas accept digits only, so no signs, @@ -14,19 +44,13 @@ import { parseOrNull } from "./parse.ts"; * Mirrors the schema + parse-helper shape of validation/email.ts and * validation/date.ts as the rest of the app's validation migrates to valibot. */ -const createIntSchema = (minimum: number) => - v.pipe( - v.string(), - v.nonEmpty(), - v.digits(), - v.transform(Number), - v.minValue(minimum), - ); - -type IntSchema = ReturnType; - -const NonNegativeIntSchema = createIntSchema(0); -const PositiveIntSchema = createIntSchema(1); +const NonNegativeIntSchema = v.pipe( + NonEmptyTextSchema, + v.digits(), + v.transform(Number), +); +const PositiveIntSchema = v.pipe(NonNegativeIntSchema, v.minValue(1)); +type IntSchema = v.GenericSchema; const parseIntWithSchema = (schema: IntSchema, value: string): number | null => parseOrNull(schema, value.trim()); diff --git a/src/shared/validation/stored-json.ts b/src/shared/validation/stored-json.ts new file mode 100644 index 0000000000..7874c38dd9 --- /dev/null +++ b/src/shared/validation/stored-json.ts @@ -0,0 +1,46 @@ +import * as v from "valibot"; + +export interface StoredJson { + read: (value: unknown, context: string) => v.InferOutput; + write: (value: v.InferInput, context?: string) => string; +} + +const invalidStoredJson = ( + context: string, + detail: string, + cause: unknown, +): Error => + new Error(`Invalid stored JSON in ${context}: ${detail}`, { cause }); + +/** Define one schema-backed JSON format for both storage reads and writes. */ +export const defineStoredJson = ( + schema: TSchema, +): StoredJson => ({ + read: (value, context) => { + let parsed: unknown; + try { + parsed = JSON.parse(v.parse(v.string(), value)); + } catch (error) { + throw invalidStoredJson(context, String(error), error); + } + const result = v.safeParse(schema, parsed); + if (!result.success) { + throw invalidStoredJson( + context, + result.issues[0]!.message, + result.issues, + ); + } + return result.output; + }, + write: (value, context) => { + const result = v.safeParse(schema, value); + if (!result.success) { + throw new Error( + `Invalid value for stored JSON${context ? ` in ${context}` : ""}`, + { cause: result.issues }, + ); + } + return JSON.stringify(result.output); + }, +}); diff --git a/src/shared/validation/string.ts b/src/shared/validation/string.ts index b594af1643..86aa3026aa 100644 --- a/src/shared/validation/string.ts +++ b/src/shared/validation/string.ts @@ -9,11 +9,12 @@ import { guardFor } from "#shared/validation/guard.ts"; * only production paths into the brand are the helpers below, which validate at * the boundary and let downstream code avoid repeated empty-string checks. */ +export const NonEmptyTextSchema = v.pipe(v.string(), v.nonEmpty()); export const NonEmptyStringSchema = v.pipe( - v.string(), - v.nonEmpty(), + NonEmptyTextSchema, v.brand("NonEmptyString"), ); +export const OptionalStringSchema = v.optional(v.string()); export type NonEmptyString = v.InferOutput; type NonEmptyLiteral = T extends "" ? never : T; diff --git a/src/ui/templates/admin/listings/details.tsx b/src/ui/templates/admin/listings/details.tsx index ae1ed8107a..51cc94f42c 100644 --- a/src/ui/templates/admin/listings/details.tsx +++ b/src/ui/templates/admin/listings/details.tsx @@ -6,9 +6,9 @@ import { formatDatetimeLabel } from "#shared/dates.ts"; import type { ListingAggregateRecalculation } from "#shared/db/listings/aggregates.ts"; import { availableDayCounts, + clampDurationDays, dayPriceFor, type ListingWithCount, - normalizeDurationDays, } from "#shared/types.ts"; import { CopyableInputRow, @@ -41,7 +41,7 @@ const CustomisableDaysRow = ({ listing }: ListingRowProps): JSX.Element => { {t("listings_table.customisable_days")} {t("listings_table.visitors_choose_days", { - max_days: normalizeDurationDays(listing.duration_days), + max_days: clampDurationDays(listing.duration_days), })}{" "} {counts.length > 0 ? ( diff --git a/src/ui/templates/admin/listings/form-values.tsx b/src/ui/templates/admin/listings/form-values.tsx index b3a8c285b4..d30dd0c5df 100644 --- a/src/ui/templates/admin/listings/form-values.tsx +++ b/src/ui/templates/admin/listings/form-values.tsx @@ -19,8 +19,8 @@ import type { ListingTemplate } from "#shared/listing-templates.ts"; import { utcToLocalInput } from "#shared/timezone.ts"; import { type AdminSession, + clampDurationDays, type ListingWithCount, - normalizeDurationDays, } from "#shared/types.ts"; import { moneyPattern } from "#templates/components/price-input.tsx"; import { getListingForm } from "#templates/fields/listing.ts"; @@ -30,7 +30,7 @@ const formatDatetimeLocal = (iso: string | null): string | null => iso ? utcToLocalInput(iso, settings.timezone) : null; export const renderDayPricesFieldset = (listing?: ListingWithCount): string => { - const max = listing ? normalizeDurationDays(listing.duration_days) : 1; + const max = listing ? clampDurationDays(listing.duration_days) : 1; const prices = listing?.day_prices ?? {}; const rows = Array.from({ length: max }, (_, i) => i + 1) .map((n) => { diff --git a/src/ui/templates/tickets.tsx b/src/ui/templates/tickets.tsx index 7ac3a670ae..c8d8a1852e 100644 --- a/src/ui/templates/tickets.tsx +++ b/src/ui/templates/tickets.tsx @@ -17,7 +17,7 @@ import { namesConcealed, packagePrivacyOfDisplay, } from "#shared/package-privacy.ts"; -import { normalizeDurationDays } from "#shared/types.ts"; +import { clampDurationDays } from "#shared/types.ts"; import { headingLayoutPage } from "#templates/components/heading-layout.tsx"; import { escapeHtml } from "#templates/layout.tsx"; import { renderListingImage } from "#templates/public/shared.tsx"; @@ -77,7 +77,7 @@ const computeBookingDateLabel = (entry: TokenEntry): string => bookedRangeLabel( entry.attendee.date, entry.attendee.end_date, - normalizeDurationDays(entry.listing.duration_days), + clampDurationDays(entry.listing.duration_days), ); /** Render the "Add to: …" wallet links section, or "" when purchase-only or no diff --git a/test/shared/admin-features.test.ts b/test/shared/admin-features.test.ts index 5deca8c19f..1a9e537e82 100644 --- a/test/shared/admin-features.test.ts +++ b/test/shared/admin-features.test.ts @@ -13,15 +13,65 @@ const DEFAULT_ENABLED_FEATURES = parseEnabledFeatures(""); describe("admin features", () => { test("defines the complete feature list in display order", () => { - expect(ADMIN_FEATURES.map(({ key, slug }) => ({ key, slug }))).toEqual([ - { key: "site", slug: "site" }, - { key: "attributes", slug: "attributes" }, - { key: "questions", slug: "questions" }, - { key: "modifiers", slug: "modifiers" }, - { key: "logistics", slug: "logistics" }, - { key: "apiKeys", slug: "api-keys" }, - { key: "servicing", slug: "servicing" }, - { key: "money", slug: "money" }, + expect(ADMIN_FEATURES).toEqual([ + { + descriptionKey: "features.site.description", + inUseSql: null, + key: "site", + labelKey: "features.site.name", + slug: "site", + }, + { + descriptionKey: "features.attributes.description", + inUseSql: "EXISTS (SELECT 1 FROM attributes AS attribute)", + key: "attributes", + labelKey: "features.attributes.name", + slug: "attributes", + }, + { + descriptionKey: "features.questions.description", + inUseSql: "EXISTS (SELECT 1 FROM questions AS question)", + key: "questions", + labelKey: "features.questions.name", + slug: "questions", + }, + { + descriptionKey: "features.modifiers.description", + inUseSql: "EXISTS (SELECT 1 FROM modifiers AS modifier)", + key: "modifiers", + labelKey: "features.modifiers.name", + slug: "modifiers", + }, + { + descriptionKey: "features.logistics.description", + inUseSql: + "EXISTS (SELECT 1 FROM logistics_agents AS logisticsAgent) OR EXISTS (SELECT 1 FROM listings AS listing WHERE listing.uses_logistics = 1)", + key: "logistics", + labelKey: "features.logistics.name", + slug: "logistics", + }, + { + descriptionKey: "features.api_keys.description", + inUseSql: "EXISTS (SELECT 1 FROM api_keys AS apiKey)", + key: "apiKeys", + labelKey: "features.api_keys.name", + slug: "api-keys", + }, + { + descriptionKey: "features.servicing.description", + inUseSql: + "EXISTS (SELECT 1 FROM attendees AS attendee WHERE attendee.kind = 'servicing')", + key: "servicing", + labelKey: "features.servicing.name", + slug: "servicing", + }, + { + descriptionKey: "features.money.description", + inUseSql: null, + key: "money", + labelKey: "features.money.name", + slug: "money", + }, ]); }); @@ -99,8 +149,24 @@ describe("admin features", () => { thrown = error; } expect(thrown).toMatchObject({ - message: "Every admin feature must have an enabled value", + message: + "Invalid stored JSON in settings.enabled_features: Every admin feature must have an enabled value", }); + expect((thrown as Error).cause).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + message: "Every admin feature must have an enabled value", + }), + ]), + ); + }); + + test("names the setting when serialization rejects invalid features", () => { + expect(() => + serializeEnabledFeatures({ money: "yes" } as unknown as Parameters< + typeof serializeEnabledFeatures + >[0]), + ).toThrow(/^Invalid value for stored JSON in settings\.enabled_features$/); }); test("finds a feature by slug and returns null for an unknown slug", () => { diff --git a/test/shared/db/address-cache.test.ts b/test/shared/db/address-cache.test.ts index 893ac88346..ed6e0471cc 100644 --- a/test/shared/db/address-cache.test.ts +++ b/test/shared/db/address-cache.test.ts @@ -47,6 +47,15 @@ describeWithEnv("address cache", { db: true }, () => { expect(await getCachedAddresses(index)).toEqual([]); }); + test("rejects invalid address shapes before storing them", async () => { + const index = await computeAddressSearchIndex("easypostcodes", "BAD"); + await expect( + storeCachedAddresses(index, [ + { lat: "1", line: "Missing longitude" }, + ] as unknown as Parameters[1]), + ).rejects.toThrow("Invalid value for stored JSON in address_cache.results"); + }); + test("misses for a search that was never cached", async () => { const index = await computeAddressSearchIndex("easypostcodes", "M1 1AE"); expect(await getCachedAddresses(index)).toBeNull(); diff --git a/test/shared/db/attendees/pii.test.ts b/test/shared/db/attendees/pii.test.ts index a21dce1d4a..0b3767935d 100644 --- a/test/shared/db/attendees/pii.test.ts +++ b/test/shared/db/attendees/pii.test.ts @@ -123,9 +123,17 @@ describe("PII blob encoding", () => { expect("lo" in unpinned).toBe(false); }); - test("parsePiiBlob defaults a missing version but preserves an explicit one", () => { - expect(parsePiiBlob('{"n":"x"}').v).toBe(PII_BLOB_VERSION); - expect(parsePiiBlob('{"n":"x","v":2}').v).toBe(2); + test("parsePiiBlob defaults a missing version", () => { + const blob = JSON.parse(buildPiiBlob(samplePii)); + delete blob.v; + expect(parsePiiBlob(JSON.stringify(blob)).v).toBe(PII_BLOB_VERSION); + }); + + test("parsePiiBlob rejects an unknown version", () => { + const blob = { ...JSON.parse(buildPiiBlob(samplePii)), v: 2 }; + expect(() => parsePiiBlob(JSON.stringify(blob))).toThrow( + "Invalid stored JSON in attendees.pii_blob", + ); }); }); diff --git a/test/shared/db/built-sites.test.ts b/test/shared/db/built-sites.test.ts index f48bc1e77f..0e4dc74161 100644 --- a/test/shared/db/built-sites.test.ts +++ b/test/shared/db/built-sites.test.ts @@ -175,6 +175,17 @@ describeWithEnv("built-sites", { db: true }, () => { expect(parsed.s).toBeUndefined(); }); + test("parseSiteDataBlob rejects malformed JSON and invalid fields", () => { + expect(() => parseSiteDataBlob("{")).toThrow( + "Invalid stored JSON in built_sites.site_data", + ); + expect(() => + parseSiteDataBlob( + JSON.stringify({ hp: "unknown", n: "Site", u: "site.test", v: 1 }), + ), + ).toThrow("Invalid stored JSON in built_sites.site_data"); + }); + test("insertBuiltSite creates a row with encrypted site_data", async () => { const row = await insertBuiltSite("Alpha Site", "alpha.b-cdn.net"); expect(row.id).toBe(1); diff --git a/test/shared/db/contact-preferences.test.ts b/test/shared/db/contact-preferences.test.ts index 9ed7a9fcfc..cab527b436 100644 --- a/test/shared/db/contact-preferences.test.ts +++ b/test/shared/db/contact-preferences.test.ts @@ -248,6 +248,23 @@ describeWithEnv("contact-preferences: contact history", { db: true }, () => { }); }); + test("rejects wrong field types in an encrypted stats blob", async () => { + const pk = await getTestPrivateKey(); + const hash = await hashEmail("invalid-stats@example.com"); + const encrypted = await encryptWithOwnerKey( + JSON.stringify({ c: "2" }), + settings.publicKey, + ); + await execute( + "INSERT INTO contact_preferences (contact_hash, stats_blob) VALUES (?, ?)", + [hash, encrypted], + ); + + await expect(getContactRecord(hash, pk)).rejects.toThrow( + "Invalid stored JSON in contact_preferences.stats_blob", + ); + }); + test("getContactCountFields reads plaintext counts past a corrupt blob", async () => { const hash = await hashEmail("corrupt@example.com"); await execute( diff --git a/test/shared/db/listings/table.test.ts b/test/shared/db/listings/table.test.ts index ba0926f670..091ff7e701 100644 --- a/test/shared/db/listings/table.test.ts +++ b/test/shared/db/listings/table.test.ts @@ -1,16 +1,89 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { encrypt } from "#shared/crypto/encryption.ts"; import { getDb } from "#shared/db/client.ts"; import { getListingWithCount, listingsTable, } from "#shared/db/listings/records.ts"; -import { computeSlugIndex } from "#shared/db/listings/table.ts"; +import { + computeSlugIndex, + type ListingInput, + rawListingsTable, +} from "#shared/db/listings/table.ts"; +import type { DayPrices } from "#shared/types.ts"; import { MAX_DURATION_DAYS } from "#shared/types.ts"; import { describeWithEnv } from "#test-utils/db.ts"; +import { setupErrorSpy } from "#test-utils/error-spy.ts"; describeWithEnv("db > listings", { db: true, triggers: true }, () => { + const errors = setupErrorSpy(); + + test("applies every listing storage default", async () => { + const listing = await listingsTable.insert({ + maxAttendees: 100, + maxPrice: 10000, + name: "defaults", + slug: "storage-defaults", + slugIndex: await computeSlugIndex("storage-defaults"), + }); + const saved = await getListingWithCount(listing.id); + expect(saved).toMatchObject({ + active: true, + assign_built_site: false, + bookable_alone: false, + can_pay_more: false, + customisable_days: false, + duration_days: 1, + fields: "email", + hidden: false, + initial_site_months: 0, + listing_type: "standard", + max_price: 10000, + max_quantity: 1, + maximum_days_after: 90, + minimum_days_before: 1, + months_per_unit: 0, + non_transferable: false, + purchase_only: false, + unit_price: 0, + use_defaults: false, + uses_logistics: false, + }); + }); + + test("applies numeric defaults at the raw table boundary", async () => { + expect(rawListingsTable.schema.duration_days.default?.()).toBe(1); + const listing = await rawListingsTable.insert({ + maxAttendees: 100, + name: "raw defaults", + slug: "raw-storage-defaults", + slugIndex: await computeSlugIndex("raw-storage-defaults"), + } as ListingInput); + expect(listing.duration_days).toBe(1); + expect(listing.max_price).toBe(0); + }); + + test("names each projected image when its stored filename is broken", async () => { + const stored = await encrypt(""); + await rawListingsTable.readColumn("image_thumb_url", stored, 8); + expect(errors.lastMessage()).toContain("listing 8 thumbnail image"); + await rawListingsTable.readColumn("image_url", stored, 9); + expect(errors.lastMessage()).toContain("listing 9 image"); + }); + describe("listing date read transform", () => { + test("reads an encrypted empty stored date as empty", async () => { + expect(await rawListingsTable.readColumn("date", await encrypt(""))).toBe( + "", + ); + }); + + test("names stored datetime when a decrypted date is invalid", async () => { + await expect( + rawListingsTable.readColumn("date", await encrypt("not-a-dateZ")), + ).rejects.toThrow("stored datetime has invalid datetime: not-a-dateZ"); + }); test("returns empty string for no-date listing", async () => { const listing = await listingsTable.insert({ date: "", @@ -77,9 +150,22 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { const saved = await getListingWithCount(listing.id); expect(saved?.closes_at).toBe("2099-12-31T23:59:00.000Z"); }); + + test("names closes_at when rejecting an invalid date", async () => { + await expect( + listingsTable.insert({ + closesAt: "not-a-dateZ", + maxAttendees: 100, + maxPrice: 10000, + name: "test", + slug: "test-closes-invalid", + slugIndex: await computeSlugIndex("test-closes-invalid"), + }), + ).rejects.toThrow("closes_at has invalid datetime: not-a-dateZ"); + }); }); - describe("duration_days write clamp", () => { + describe("duration_days write validation", () => { const insertWithDuration = async (slug: string, durationDays: number) => { const listing = await listingsTable.insert({ durationDays, @@ -92,31 +178,30 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { return (await getListingWithCount(listing.id))!.duration_days; }; - test(`clamps values above MAX_DURATION_DAYS down to ${MAX_DURATION_DAYS}`, async () => { - expect(await insertWithDuration("test-dur-high", 500)).toBe( - MAX_DURATION_DAYS, - ); + test("accepts whole days within the supported range", async () => { + expect( + await insertWithDuration("test-dur-valid", MAX_DURATION_DAYS), + ).toBe(MAX_DURATION_DAYS); }); - test("clamps zero to 1", async () => { + test("clamps whole integers outside the supported range", async () => { + expect( + await insertWithDuration("test-dur-high", MAX_DURATION_DAYS + 1), + ).toBe(MAX_DURATION_DAYS); expect(await insertWithDuration("test-dur-zero", 0)).toBe(1); - }); - - test("clamps negative values to 1", async () => { expect(await insertWithDuration("test-dur-neg", -3)).toBe(1); }); - test("floors fractional values to whole days", async () => { - expect(await insertWithDuration("test-dur-frac", 2.7)).toBe(2); - }); - - test("rejects non-finite values", async () => { - await expect( - insertWithDuration("test-dur-nan", Number.NaN), - ).rejects.toThrow("Invalid booking duration: NaN"); + test("rejects fractional and non-finite values", async () => { + for (const [slug, value] of [ + ["test-dur-frac", 2.7], + ["test-dur-nan", Number.NaN], + ] as const) { + await expect(insertWithDuration(slug, value)).rejects.toThrow(); + } }); - test("clamps on update as well as insert", async () => { + test("clamps an out-of-range update", async () => { const listing = await listingsTable.insert({ maxAttendees: 100, maxPrice: 10000, @@ -124,7 +209,9 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { slug: "test-dur-upd", slugIndex: await computeSlugIndex("test-dur-upd"), }); - await listingsTable.update(listing.id, { durationDays: 1000 }); + await listingsTable.update(listing.id, { + durationDays: MAX_DURATION_DAYS + 1, + }); expect((await getListingWithCount(listing.id))!.duration_days).toBe( MAX_DURATION_DAYS, ); @@ -132,6 +219,23 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { }); describe("bookable_days read transform", () => { + test("rejects malformed JSON stored in the database", async () => { + const listing = await listingsTable.insert({ + maxAttendees: 100, + maxPrice: 10000, + name: "test-bd-json", + slug: "test-bd-json", + slugIndex: await computeSlugIndex("test-bd-json"), + }); + await getDb().execute({ + args: ["[", listing.id], + sql: "UPDATE listings SET bookable_days = ? WHERE id = ?", + }); + await expect(getListingWithCount(listing.id)).rejects.toThrow( + `Invalid stored JSON in listings.bookable_days row ${listing.id}`, + ); + }); + test("rejects non-array JSON stored in the database", async () => { const listing = await listingsTable.insert({ maxAttendees: 100, @@ -145,7 +249,7 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { sql: "UPDATE listings SET bookable_days = ? WHERE id = ?", }); await expect(getListingWithCount(listing.id)).rejects.toThrow( - "Stored bookable_days must be a JSON string array", + `Invalid stored JSON in listings.bookable_days row ${listing.id}`, ); }); @@ -162,8 +266,49 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { sql: "UPDATE listings SET bookable_days = ? WHERE id = ?", }); await expect(getListingWithCount(listing.id)).rejects.toThrow( - "Stored bookable_days must be a JSON string array", + `Invalid stored JSON in listings.bookable_days row ${listing.id}`, ); }); + + test("preserves unknown day names for catalog repair", async () => { + const listing = await listingsTable.insert({ + maxAttendees: 100, + maxPrice: 10000, + name: "test-bd-day", + slug: "test-bd-day", + slugIndex: await computeSlugIndex("test-bd-day"), + }); + await getDb().execute({ + args: ['["Monday","Funday"]', listing.id], + sql: "UPDATE listings SET bookable_days = ? WHERE id = ?", + }); + expect((await getListingWithCount(listing.id))?.bookable_days).toEqual([ + "Monday", + "Funday", + ]); + }); + }); + + describe("day_prices read transform", () => { + test("accepts a stored day-price object", async () => { + expect( + await rawListingsTable.readColumn( + "day_prices", + '{"1":100,"2":180}' as unknown as DayPrices, + ), + ).toEqual({ 1: 100, 2: 180 }); + }); + + test("rejects arrays, invalid keys, and invalid prices", async () => { + for (const stored of ["[]", '{"0":100}', '{"1":"100"}']) { + await expect( + rawListingsTable.readColumn( + "day_prices", + stored as unknown as DayPrices, + 7, + ), + ).rejects.toThrow("Invalid stored JSON in listings.day_prices row 7"); + } + }); }); }); diff --git a/test/shared/db/processed-payments.test.ts b/test/shared/db/processed-payments.test.ts index dde9cf05b5..b54adf1eee 100644 --- a/test/shared/db/processed-payments.test.ts +++ b/test/shared/db/processed-payments.test.ts @@ -1,5 +1,6 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { encrypt } from "#shared/crypto/encryption.ts"; import type { EnvKeyEncrypted } from "#shared/crypto/sealed.ts"; import { getDb, insert } from "#shared/db/client.ts"; import { @@ -171,6 +172,16 @@ describeWithEnv("db > processed payments", { db: true }, () => { expect((result?.error.length ?? 0) > 0).toBe(true); }); + test("parseSessionFailure degrades invalid JSON fields to a terminal failure", async () => { + const result = await parseSessionFailure( + await encrypt('{"error":42,"refunded":"yes"}'), + ); + expect(result).toEqual({ + error: "This payment could not be completed. Please contact support.", + status: 500, + }); + }); + test("re-throws non-unique-constraint errors", async () => { await getDb().execute("DROP TABLE processed_payments"); diff --git a/test/shared/db/sumup-checkouts.test.ts b/test/shared/db/sumup-checkouts.test.ts index caa3004b75..e4d87eae1c 100644 --- a/test/shared/db/sumup-checkouts.test.ts +++ b/test/shared/db/sumup-checkouts.test.ts @@ -57,6 +57,16 @@ describeWithEnv("db > sumup-checkouts", { db: true }, () => { expect(result).toBeNull(); }); + test("rejects non-string metadata before storing it", async () => { + await expect( + storeSumupCheckout(REFERENCE, { + quantity: 2, + } as unknown as Record), + ).rejects.toThrow( + "Invalid value for stored JSON in sumup_checkouts.metadata", + ); + }); + test("keeps rows isolated per reference", async () => { const otherReference = crypto.randomUUID(); const otherMetadata = { ...METADATA, name: "Bob Other" }; diff --git a/test/shared/db/table.test.ts b/test/shared/db/table.test.ts index 12d47ee88c..4e22b022af 100644 --- a/test/shared/db/table.test.ts +++ b/test/shared/db/table.test.ts @@ -1,5 +1,6 @@ import { expect } from "@std/expect"; import { it as test } from "@std/testing/bdd"; +import * as v from "valibot"; import type { BlindIndex } from "#shared/crypto/sealed.ts"; import { listingsTable } from "#shared/db/listings/records.ts"; import { describeWithEnv } from "#test-utils/db.ts"; @@ -87,6 +88,44 @@ describeWithEnv("db > table utilities", { db: true }, () => { expect(await def.write?.(true)).toBe(1); }); + test("col.json validates physical column reads and writes with row context", async () => { + const { col } = await import("#shared/db/table.ts"); + const def = col.json(v.array(v.string()), { + context: "records.items", + default: () => [], + }); + expect(def.default?.()).toEqual([]); + expect(await def.read?.('["one"]' as unknown as string[], 4)).toEqual([ + "one", + ]); + expect(await def.write?.(["two"])).toBe('["two"]'); + expect(() => def.read?.("[1]" as unknown as string[], 4)).toThrow( + "Invalid stored JSON in records.items row 4", + ); + expect(() => def.read?.("{}" as unknown as string[])).toThrow( + /^Invalid stored JSON in records\.items:/, + ); + const required = col.json(v.array(v.string()), { + context: "records.required_items", + }); + expect(required.default).toBeUndefined(); + expect(await required.write?.(["required"])).toBe('["required"]'); + }); + + test("col.json gives a missing projection its declared value", async () => { + const { col } = await import("#shared/db/table.ts"); + const def = col.json(v.array(v.string()), { + context: "records.items", + projected: true, + whenMissing: () => [], + }); + expect(def.projected).toBe(true); + expect(await def.read?.(undefined as unknown as string[], 4)).toEqual([]); + expect(await def.read?.('["one"]' as unknown as string[], 4)).toEqual([ + "one", + ]); + }); + test("col.transform creates column with custom transforms", async () => { const { col } = await import("#shared/db/table.ts"); const write = (v: string) => v.toUpperCase(); diff --git a/test/shared/db/table-cache.test.ts b/test/shared/db/table/cache.test.ts similarity index 100% rename from test/shared/db/table-cache.test.ts rename to test/shared/db/table/cache.test.ts diff --git a/test/shared/db/table-write-row.test.ts b/test/shared/db/table/write-row.test.ts similarity index 100% rename from test/shared/db/table-write-row.test.ts rename to test/shared/db/table/write-row.test.ts diff --git a/test/shared/db/token-attempts.test.ts b/test/shared/db/token-attempts.test.ts index c84e982bb3..68cf467880 100644 --- a/test/shared/db/token-attempts.test.ts +++ b/test/shared/db/token-attempts.test.ts @@ -10,7 +10,7 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; import { FakeTime } from "@std/testing/time"; import { hmacHash } from "#shared/crypto/hashing.ts"; -import { queryOne } from "#shared/db/client.ts"; +import { execute, queryOne } from "#shared/db/client.ts"; import { clearTokenAttempts, isTokenRateLimited, @@ -125,6 +125,19 @@ describeWithEnv("db > token-attempts", { db: true }, () => { expect(await isTokenRateLimited(ip)).toBe(false); }); + test("rejects invalid stored token arrays", async () => { + const ip = "10.0.0.12"; + const hashedIp = await hmacHash(ip); + await execute( + "INSERT INTO token_attempts (ip, recent_tokens, window_start, last_attempt) VALUES (?, ?, ?, ?)", + [hashedIp, '["valid",2]', Date.now(), Date.now()], + ); + + await expect(recordTokenFailure(ip, ["new"])).rejects.toThrow( + `Invalid stored JSON in token_attempts.recent_tokens for ${hashedIp}`, + ); + }); + test("locks when a single request supplies MAX_TOKEN_404S distinct tokens", async () => { const ip = "10.0.0.9"; const locked = await recordTokenFailure( diff --git a/test/shared/listing-defaults.test.ts b/test/shared/listing-defaults.test.ts index c91104caa4..08f3d6477b 100644 --- a/test/shared/listing-defaults.test.ts +++ b/test/shared/listing-defaults.test.ts @@ -229,6 +229,37 @@ describe("shared > listing-defaults > parse/serialize round-trip", () => { expect(parseListingDefaults(undefined)).toEqual({}); expect(parseListingDefaults("")).toEqual({}); }); + + test("rejects malformed JSON and invalid stored fields", () => { + expect(() => parseListingDefaults("{")).toThrow( + /^Invalid stored JSON in settings\.listing_defaults:/, + ); + expect(() => parseListingDefaults('{"bookableDays":["Monday",2]}')).toThrow( + "Invalid stored JSON in settings.listing_defaults", + ); + expect(() => parseListingDefaults('{"hidden":"yes"}')).toThrow( + "Invalid stored JSON in settings.listing_defaults", + ); + expect(() => parseListingDefaults('{"minimumDaysBefore":-1}')).toThrow(); + expect(() => parseListingDefaults('{"maximumDaysAfter":-1}')).toThrow(); + }); + + test("allows zero-day booking windows", () => { + expect( + parseListingDefaults( + serializeListingDefaults({ + maximumDaysAfter: 0, + minimumDaysBefore: 0, + }), + ), + ).toEqual({ maximumDaysAfter: 0, minimumDaysBefore: 0 }); + }); + + test("names the setting when serialization rejects invalid defaults", () => { + expect(() => + serializeListingDefaults({ hidden: "yes" } as unknown as ListingDefaults), + ).toThrow(/^Invalid value for stored JSON in settings\.listing_defaults$/); + }); }); describe("shared > listing-defaults > LISTING_DEFAULT_FIELDS", () => { diff --git a/test/shared/validation/number.test.ts b/test/shared/validation/number.test.ts index 1ff80a0ff4..c8c8bfe982 100644 --- a/test/shared/validation/number.test.ts +++ b/test/shared/validation/number.test.ts @@ -1,11 +1,48 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; import { + boundedInteger, parseNonNegativeInt, parsePositiveInt, parsePositiveIntId, } from "#shared/validation/number.ts"; +describe("boundedInteger", () => { + const days = boundedInteger(1, 90); + + test("reject policy accepts safe integers within the range", () => { + expect(days.reject(1)).toBe(1); + expect(days.reject(45)).toBe(45); + expect(days.reject(90)).toBe(90); + }); + + test("reject policy rejects integers outside the range", () => { + expect(() => days.reject(0)).toThrow(); + expect(() => days.reject(91)).toThrow(); + }); + + test("clamp policy clamps valid integers outside the range", () => { + expect(days.clamp(-2)).toBe(1); + expect(days.clamp(500)).toBe(90); + }); + + test("clamp policy leaves valid integers within the range unchanged", () => { + expect(days.clamp(37)).toBe(37); + }); + + test("both policies reject malformed numbers", () => { + for (const value of [ + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + Number.MAX_SAFE_INTEGER + 1, + ]) { + expect(() => days.reject(value)).toThrow(); + expect(() => days.clamp(value)).toThrow(); + } + }); +}); + describe("parsePositiveIntId", () => { test("parses plain positive integers, dropping leading zeros", () => { expect(parsePositiveIntId("5")).toBe(5); diff --git a/test/shared/validation/stored-json.test.ts b/test/shared/validation/stored-json.test.ts new file mode 100644 index 0000000000..c1059ee16f --- /dev/null +++ b/test/shared/validation/stored-json.test.ts @@ -0,0 +1,63 @@ +import { expect } from "@std/expect"; +import { describe, it as test } from "@std/testing/bdd"; +import * as v from "valibot"; +import { defineStoredJson } from "#shared/validation/stored-json.ts"; + +const entriesJson = defineStoredJson( + v.array(v.strictObject({ id: v.number(), name: v.string() })), +); + +describe("defineStoredJson", () => { + test("round-trips values that match the schema", () => { + const entries = [{ id: 1, name: "First" }]; + expect( + entriesJson.read(entriesJson.write(entries), "test.entries"), + ).toEqual(entries); + }); + + test("rejects malformed JSON with storage context", () => { + expect(() => entriesJson.read("{", "test.entries row 4")).toThrow( + "Invalid stored JSON in test.entries row 4", + ); + }); + + test("rejects the wrong top-level shape", () => { + expect(() => entriesJson.read('{"id":1}', "test.entries")).toThrow( + "Invalid stored JSON in test.entries", + ); + }); + + test("rejects wrong element types", () => { + expect(() => + entriesJson.read('[{"id":"1","name":"First"}]', "test.entries"), + ).toThrow("Invalid stored JSON in test.entries"); + }); + + test("rejects extra object fields", () => { + expect(() => + entriesJson.read( + '[{"id":1,"name":"First","extra":true}]', + "test.entries", + ), + ).toThrow("Invalid stored JSON in test.entries"); + }); + + test("validates values before writing", () => { + expect(() => + entriesJson.write([{ id: 1, name: 2 }] as unknown as Parameters< + typeof entriesJson.write + >[0]), + ).toThrow(/^Invalid value for stored JSON$/); + }); + + test("names the storage context when a write is invalid", () => { + expect(() => + entriesJson.write( + [{ id: 1, name: 2 }] as unknown as Parameters< + typeof entriesJson.write + >[0], + "test.entries", + ), + ).toThrow("Invalid value for stored JSON in test.entries"); + }); +}); From 5e6b2dbc4765c3de8d5ea92ab9ca2e3260629860 Mon Sep 17 00:00:00 2001 From: Stefan Date: Sun, 19 Jul 2026 16:22:50 +0100 Subject: [PATCH 11/17] Address structured storage review feedback --- scripts/mutation/equivalent-mutants.txt | 15 ++- src/features/admin/attendees.ts | 6 +- .../api/payment-processing/metadata.ts | 13 +-- src/shared/db/built-sites.ts | 2 +- src/shared/payment-helpers.ts | 9 +- src/shared/types.ts | 5 +- src/shared/validation/number.ts | 5 +- .../single-ticket-refunds.test.ts | 42 +------ test/shared/db/built-sites.test.ts | 82 ++++++++++++- test/shared/db/listings/table.test.ts | 10 ++ test/shared/logger/log-output.test.ts | 21 +--- .../payment-helpers/build-items.test.ts | 12 ++ test/shared/payment-helpers/dispatch.test.ts | 109 +++++++++++++++++- test/shared/payment-helpers/limits.test.ts | 10 ++ test/shared/payment-helpers/metadata.test.ts | 2 + test/shared/payments.test.ts | 18 +-- test/shared/validation/number.test.ts | 4 + test/test-utils/debug-log.ts | 17 +++ 18 files changed, 284 insertions(+), 98 deletions(-) create mode 100644 test/test-utils/debug-log.ts diff --git a/scripts/mutation/equivalent-mutants.txt b/scripts/mutation/equivalent-mutants.txt index e4e37f777d..42a44cfde6 100644 --- a/scripts/mutation/equivalent-mutants.txt +++ b/scripts/mutation/equivalent-mutants.txt @@ -249,7 +249,20 @@ src/shared/db/attendees/capacity/groups.ts:166:55 ?? → || # membership.get( src/shared/db/attendees/capacity/groups.ts:178:39 ?? → || # membership.get(): number[]|undefined — an array is always truthy # v2 signed metadata (Phase 2d). -src/shared/payment-helpers.ts:159:24 ?? → || # toBookingItems intent.allocations: ChildAllocation[]|undefined — an array is always truthy, undefined→[] either way +src/shared/payment-helpers.ts:168:24 ?? → || # toBookingItems intent.allocations: ChildAllocation[]|undefined — an array is always truthy, undefined→[] either way +src/shared/payment-helpers.ts:539:16 || → && # parsed JSON null/falsy primitives return {} in both forms; truthy primitives expose none of PACKED_KEYS and also produce {} +src/shared/payment-helpers.ts:598:40 ?? → || # metadata field length is undefined or a non-negative integer; 0 and undefined both use 0 + +# Built-site form writes cannot change assignment/renewal state, so omitted raw +# inputs preserve the same defaults/current values. Blob strings are either +# truthy or have the same falsy fallback. +src/shared/db/built-sites.ts:163:57 ?? → || # assigned IDs are positive generated IDs or null; renewal indexes are non-empty HMAC strings or null +src/shared/db/built-sites.ts:178:15 assignedAttendeeId → "" # not in BuiltSiteFormInput; inserts default null and form updates preserve the existing raw value +src/shared/db/built-sites.ts:186:15 assignedListingId → "" # not in BuiltSiteFormInput; inserts default null and form updates preserve the existing raw value +src/shared/db/built-sites.ts:194:15 readOnlyFrom → "" # not in BuiltSiteFormInput; inserts default "" and form updates preserve the existing raw value +src/shared/db/built-sites.ts:202:15 renewalTokenIndex → "" # not in BuiltSiteFormInput; inserts default null and form updates preserve the existing raw value +src/shared/db/built-sites.ts:377:71 ?? → || # blob input strings use "" as their fallback, providers are non-empty, and renewalToken uses null +src/shared/db/built-sites.ts:391:54 ?? → || # validated optional strings use "" as their fallback, providers are non-empty, and renewalToken is null or non-empty # Settings registry: readOnly is optional but can only be true when present, so # `"readOnly" in accessor && accessor.readOnly` and `... || accessor.readOnly` diff --git a/src/features/admin/attendees.ts b/src/features/admin/attendees.ts index def4e529ae..dfa44fdf3c 100644 --- a/src/features/admin/attendees.ts +++ b/src/features/admin/attendees.ts @@ -208,9 +208,9 @@ const buildCreateAttendeeInput = ( const { name, email, phone, address, special_instructions, quantity, date } = values; const isDaily = listing.listing_type === "daily"; - // Customisable daily bookings span the admin's chosen day count (a required, - // options-constrained field; any odd value is clamped downstream by - // clampDurationDays); other daily bookings use the fixed duration. + // Customisable daily bookings span the admin's chosen day count. The shared + // boundary clamps whole numbers outside its range and rejects malformed + // numbers. Other daily bookings use the fixed duration. const durationDays = listing.customisable_days ? Number(values.day_count) : listing.duration_days; diff --git a/src/features/api/payment-processing/metadata.ts b/src/features/api/payment-processing/metadata.ts index 6cb1739291..6d931918d6 100644 --- a/src/features/api/payment-processing/metadata.ts +++ b/src/features/api/payment-processing/metadata.ts @@ -48,9 +48,6 @@ const parseListingTextAnswerIds = jsonMetaField< Record | undefined >(undefined); -const textOrEmpty = (value: unknown): string => - typeof value === "string" ? value : ""; - /** * Parse booking items from metadata JSON. Returns null when the JSON is * unparseable, not an array, or empty. @@ -111,21 +108,21 @@ export const extractIntent = ( const siteTokenIndex = metadata.site_token_index || undefined; const thankYouUrl = metadata.thank_you_url || undefined; return { - address: textOrEmpty(metadata.address), + address: metadata.address, allocations, balanceAttendeeId, date: metadata.date || null, dayCount, - email: textOrEmpty(metadata.email), + email: metadata.email, items, listingAnswerIds, listingTextAnswerIds, modifiers: parseModifierRefs(metadata.modifiers), - name: textOrEmpty(metadata.name), - phone: textOrEmpty(metadata.phone), + name: metadata.name, + phone: metadata.phone, reservationAmount, siteTokenIndex, - special_instructions: textOrEmpty(metadata.special_instructions), + special_instructions: metadata.special_instructions, thankYouUrl, }; }; diff --git a/src/shared/db/built-sites.ts b/src/shared/db/built-sites.ts index 2583d1e4e6..92cef6fa91 100644 --- a/src/shared/db/built-sites.ts +++ b/src/shared/db/built-sites.ts @@ -75,7 +75,7 @@ const SiteDataBlobSchema = v.strictObject({ s: OptionalStringSchema, t: OptionalStringSchema, u: v.string(), - v: v.literal(SITE_DATA_BLOB_VERSION), + v: v.optional(v.literal(SITE_DATA_BLOB_VERSION), SITE_DATA_BLOB_VERSION), }); export type SiteDataBlob = v.InferOutput; const siteDataJson = defineStoredJson(SiteDataBlobSchema); diff --git a/src/shared/payment-helpers.ts b/src/shared/payment-helpers.ts index 51bf9aa060..5e74906a2f 100644 --- a/src/shared/payment-helpers.ts +++ b/src/shared/payment-helpers.ts @@ -3,6 +3,7 @@ * Eliminates duplication between stripe.ts/square.ts and their provider adapters. */ +import * as v from "valibot"; import { lazyRef, map } from "#fp"; import { signedEdgeFor } from "#shared/booking/signed-metadata.ts"; import type { @@ -619,13 +620,15 @@ export const enforceMetadataLimits = ( }; /** - * Validate that session metadata contains required fields (name + items). + * Validate that every metadata value is text and required fields are present. */ +const ProviderMetadataSchema = v.record(v.string(), v.string()); + export const hasRequiredSessionMetadata = ( metadata: Record | null | undefined, ): metadata is SessionMetadata => { - if (!metadata?.name) return false; - return !!metadata.items; + if (!v.is(ProviderMetadataSchema, metadata)) return false; + return !!metadata.name && !!metadata.items; }; /** diff --git a/src/shared/types.ts b/src/shared/types.ts index 29a1b89b50..709e12fc9a 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -200,9 +200,6 @@ export const clampDurationDays = (value: number): number => { } }; -/** Reject any value that is not a whole day count in the supported range. */ -export const rejectDurationDays = durationDays.reject; - /** * Per-day-count ticket prices for "customisable days" listings, in minor * units, keyed by the number of days booked. e.g. `{ 1: 1000, 2: 1800 }` @@ -213,7 +210,7 @@ export type DayPrices = Record; const DayPriceKeySchema = v.pipe( v.string(), - v.regex(/^\d+$/), + v.regex(/^[1-9]\d*$/), v.check((value) => { const days = Number(value); return days >= 1 && days <= MAX_DURATION_DAYS; diff --git a/src/shared/validation/number.ts b/src/shared/validation/number.ts index 90ff2273e0..763088cee9 100644 --- a/src/shared/validation/number.ts +++ b/src/shared/validation/number.ts @@ -10,7 +10,9 @@ export interface BoundedInteger { } /** A safe whole number no lower than `minimum`. */ -export const integerAtLeast = (minimum: number) => +export const integerAtLeast = ( + minimum: number, +): v.GenericSchema => v.pipe(v.number(), v.safeInteger(), v.minValue(minimum)); /** Define explicit reject and clamp policies for one safe-integer range. */ @@ -48,6 +50,7 @@ const NonNegativeIntSchema = v.pipe( NonEmptyTextSchema, v.digits(), v.transform(Number), + v.safeInteger(), ); const PositiveIntSchema = v.pipe(NonNegativeIntSchema, v.minValue(1)); type IntSchema = v.GenericSchema; diff --git a/test/lib/server-webhooks/single-ticket-refunds.test.ts b/test/lib/server-webhooks/single-ticket-refunds.test.ts index 9765a5dc7c..55c33a097f 100644 --- a/test/lib/server-webhooks/single-ticket-refunds.test.ts +++ b/test/lib/server-webhooks/single-ticket-refunds.test.ts @@ -18,8 +18,8 @@ import { setupStripe } from "#test-utils/settings.ts"; import { checkoutSessionEvent, expectKeptAsQuantityZeroAndRefunded, + expectWebhookIgnored, expectWebhookKeptAndRefunded, - expectWebhookProcessed, stubRefundPayment, } from "#test-utils/webhooks.ts"; @@ -134,7 +134,7 @@ describeWithEnv( } }); - test("webhook single-ticket defaults email to empty when metadata email is not a string", async () => { + test("webhook does not fulfil a session with non-text metadata", async () => { await setupStripe(); const listing = await createTestListing({ @@ -142,13 +142,13 @@ describeWithEnv( unitPrice: 1000, }); - await expectWebhookProcessed( + await expectWebhookIgnored( checkoutSessionEvent({ amountTotal: 1000, eventId: "evt_no_email_single", metadata: signedMeta( { - email: 12345 as unknown as string, // not a string -> coerced to "" by extractSessionMetadata + email: 12345 as unknown as string, items: singleItem(listing.id, 1, 1000), name: "No Email Single", }, @@ -163,39 +163,7 @@ describeWithEnv( "#shared/db/attendees/queries.ts" ); const attendees = await getAttendeesRaw(listing.id); - expect(attendees.length).toBe(1); - }); - - test("webhook multi-ticket defaults email to empty when metadata email is not a string", async () => { - await setupStripe(); - - const listing = await createTestListing({ - maxAttendees: 50, - unitPrice: 500, - }); - - await expectWebhookProcessed( - checkoutSessionEvent({ - amountTotal: 500, - eventId: "evt_no_email_multi", - metadata: signedMeta( - { - email: true as unknown as string, // not a string -> coerced to "" by extractSessionMetadata - items: JSON.stringify([{ e: listing.id, p: 500, q: 1 }]), - name: "No Email Multi", - }, - 500, - ), - paymentIntent: "pi_wh_no_email_multi", - sessionId: "cs_wh_no_email_multi", - }), - ); - - const { getAttendeesRaw } = await import( - "#shared/db/attendees/queries.ts" - ); - const attendees = await getAttendeesRaw(listing.id); - expect(attendees.length).toBe(1); + expect(attendees).toEqual([]); }); }, ); diff --git a/test/shared/db/built-sites.test.ts b/test/shared/db/built-sites.test.ts index 0e4dc74161..18af03e713 100644 --- a/test/shared/db/built-sites.test.ts +++ b/test/shared/db/built-sites.test.ts @@ -1,5 +1,6 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { getAllCacheStats } from "#shared/cache-registry.ts"; import { assignBuiltSite, builtSites, @@ -11,11 +12,13 @@ import { insertBuiltSite, isUpdateTier, parseSiteDataBlob, + providerOrBunny, siteAcceptsDeployTier, siteBaseUrl, UPDATE_TIERS, updateBuiltSiteRenewalState, } from "#shared/db/built-sites.ts"; +import { execute } from "#shared/db/client.ts"; import { describeWithEnv } from "#test-utils/db.ts"; const formBlob = async ( @@ -25,6 +28,14 @@ const formBlob = async ( return parseSiteDataBlob(values.site_data as string); }; +describe("providerOrBunny", () => { + test("keeps named providers and defaults other values to Bunny", () => { + expect(providerOrBunny("deno", "deno")).toBe("deno"); + expect(providerOrBunny("turso", "turso")).toBe("turso"); + expect(providerOrBunny("", "deno")).toBe("bunny"); + }); +}); + describe("siteBaseUrl", () => { test("prepends https:// to a bare hostname", () => { expect(siteBaseUrl("site.b-cdn.net")).toBe("https://site.b-cdn.net"); @@ -163,16 +174,27 @@ describeWithEnv("built-sites", { db: true }, () => { expect(parsed.v).toBe(1); }); - test("parseSiteDataBlob handles legacy blobs without db keys", () => { + test("parseSiteDataBlob handles legacy blobs without db keys or a version", () => { const legacyBlob = JSON.stringify({ n: "Old Site", u: "old.b-cdn.net", - v: 1, }); const parsed = parseSiteDataBlob(legacyBlob); expect(parsed.d).toBeUndefined(); expect(parsed.t).toBeUndefined(); expect(parsed.s).toBeUndefined(); + expect(parsed.v).toBe(1); + + const providers = parseSiteDataBlob( + JSON.stringify({ + dp: "turso", + hp: "deno", + n: "Provider Site", + u: "provider.b-cdn.net", + }), + ); + expect(providers.dp).toBe("turso"); + expect(providers.hp).toBe("deno"); }); test("parseSiteDataBlob rejects malformed JSON and invalid fields", () => { @@ -186,6 +208,20 @@ describeWithEnv("built-sites", { db: true }, () => { ).toThrow("Invalid stored JSON in built_sites.site_data"); }); + test("toDbValues identifies invalid site data", () => { + expect(() => + builtSitesCrudTable.toDbValues({ + assignable: false, + dbToken: "", + dbUrl: "", + hostingId: "", + hostingProvider: "invalid" as never, + name: "Invalid Provider", + siteUrl: "invalid.b-cdn.net", + }), + ).toThrow("Invalid value for stored JSON in built_sites.site_data"); + }); + test("insertBuiltSite creates a row with encrypted site_data", async () => { const row = await insertBuiltSite("Alpha Site", "alpha.b-cdn.net"); expect(row.id).toBe(1); @@ -235,9 +271,17 @@ describeWithEnv("built-sites", { db: true }, () => { }); test("getAllBuiltSites returns decrypted sites sorted by name", async () => { - await insertBuiltSite("Charlie", "charlie.b-cdn.net"); - await insertBuiltSite("Alpha", "alpha.b-cdn.net"); - await insertBuiltSite("Bravo", "bravo.b-cdn.net"); + const charlie = await insertBuiltSite("Charlie", "charlie.b-cdn.net"); + const alpha = await insertBuiltSite("Alpha", "alpha.b-cdn.net"); + const bravo = await insertBuiltSite("Bravo", "bravo.b-cdn.net"); + await execute( + `UPDATE built_sites SET created = CASE id + WHEN ? THEN '2026-01-03T00:00:00.000Z' + WHEN ? THEN '2026-01-02T00:00:00.000Z' + WHEN ? THEN '2026-01-01T00:00:00.000Z' + ELSE created END`, + [charlie.id, alpha.id, bravo.id], + ); const sites = await builtSites.getAll(); expect(sites).toHaveLength(3); @@ -299,7 +343,17 @@ describeWithEnv("built-sites", { db: true }, () => { expect(value).toBe("Test"); }); - test("inputKeyMap exposes form-facing fields", () => { + test("raw nullable columns preserve falsy stored values", async () => { + expect(await builtSites.table.readColumn("assigned_attendee_id", 0)).toBe( + 0, + ); + expect(await builtSites.table.readColumn("renewal_token_index", "")).toBe( + "", + ); + }); + + test("exposes CRUD table metadata", () => { + expect(builtSitesCrudTable.name).toBe("built_sites"); expect(builtSitesCrudTable.inputKeyMap).toEqual({ assignable: "assignable", db_provider: "dbProvider", @@ -437,10 +491,26 @@ describeWithEnv("built-sites", { db: true }, () => { test("toDbValues handles partial input with missing fields", async () => { const values = await builtSitesCrudTable.toDbValues({}); const parsed = parseSiteDataBlob(values.site_data as string); + expect(values.assignable).toBe(0); expect(parsed.n).toBe(""); expect(parsed.u).toBe(""); }); + test("legacy rows default to Bunny providers", async () => { + const row = await builtSites.table.insert({ + siteData: JSON.stringify({ n: "Legacy", u: "legacy.b-cdn.net" }), + }); + const site = await builtSitesCrudTable.findById(row.id); + expect(site!.hostingProvider).toBe("bunny"); + expect(site!.dbProvider).toBe("bunny"); + }); + + test("cache stats identify the built sites cache", () => { + expect( + getAllCacheStats().filter(({ name }) => name === "built_sites"), + ).toHaveLength(1); + }); + test("toDbValues sets assignable to 1 when true", async () => { const values = await builtSitesCrudTable.toDbValues({ assignable: true, diff --git a/test/shared/db/listings/table.test.ts b/test/shared/db/listings/table.test.ts index 091ff7e701..5bd9f79af6 100644 --- a/test/shared/db/listings/table.test.ts +++ b/test/shared/db/listings/table.test.ts @@ -310,5 +310,15 @@ describeWithEnv("db > listings", { db: true, triggers: true }, () => { ).rejects.toThrow("Invalid stored JSON in listings.day_prices row 7"); } }); + + test("rejects colliding canonical and leading-zero day keys", async () => { + await expect( + rawListingsTable.readColumn( + "day_prices", + '{"01":100,"1":200}' as unknown as DayPrices, + 7, + ), + ).rejects.toThrow("Invalid stored JSON in listings.day_prices row 7"); + }); }); }); diff --git a/test/shared/logger/log-output.test.ts b/test/shared/logger/log-output.test.ts index 3ee1f76c45..a2fed2d076 100644 --- a/test/shared/logger/log-output.test.ts +++ b/test/shared/logger/log-output.test.ts @@ -8,6 +8,7 @@ import { logRequest, setSuppressRequestLogs, } from "#shared/logger.ts"; +import { useDebugLogSpy } from "#test-utils/debug-log.ts"; import { withEnv } from "#test-utils/env.ts"; describe("logRequest", () => { @@ -74,39 +75,29 @@ describe("logRequest", () => { }); describe("logDebug", () => { - let debugSpy: Spy; - - beforeEach(() => { - setSuppressDebugLogs(false); - debugSpy = spy(console, "debug"); - }); - - afterEach(() => { - debugSpy.restore(); - setSuppressDebugLogs(null); - }); + const debugSpy = useDebugLogSpy(); test("formats message with category prefix", () => { logDebug("Setup", "Validation passed"); - expect(debugSpy.calls[0]?.args[0]).toBe("[Setup] Validation passed"); + expect(debugSpy().calls[0]?.args[0]).toBe("[Setup] Validation passed"); }); test("suppresses output when setSuppressDebugLogs(true)", () => { setSuppressDebugLogs(true); logDebug("Migration", "Step 1"); - expect(debugSpy.calls.length).toBe(0); + expect(debugSpy().calls.length).toBe(0); }); test("falls back to the TEST_SUPPRESS_DEBUG_LOGS env var when no override is set", () => { setSuppressDebugLogs(null); using _env = withEnv({ TEST_SUPPRESS_DEBUG_LOGS: "1" }); logDebug("Migration", "Step 1"); - expect(debugSpy.calls.length).toBe(0); + expect(debugSpy().calls.length).toBe(0); }); test("emits output when setSuppressDebugLogs(false)", () => { logDebug("Migration", "Step 1"); - expect(debugSpy.calls.length).toBe(1); + expect(debugSpy().calls.length).toBe(1); }); }); diff --git a/test/shared/payment-helpers/build-items.test.ts b/test/shared/payment-helpers/build-items.test.ts index dbafae0fe8..6b957b284c 100644 --- a/test/shared/payment-helpers/build-items.test.ts +++ b/test/shared/payment-helpers/build-items.test.ts @@ -3,6 +3,7 @@ import { describe, it as test } from "@std/testing/bdd"; import { priceCheckout } from "#shared/checkout-pricing.ts"; import { hmacHash } from "#shared/crypto/hashing.ts"; import { + assembleCheckoutMetadata, buildItemsMetadata, extractSessionMetadata, packMetadata, @@ -128,6 +129,17 @@ describeWithEnv( ), ).toBe(false); }); + + test("assembles Square metadata with small fields packed", async () => { + const wire = await assembleCheckoutMetadata( + "square", + intent, + priceCheckout(intent).total, + ); + + expect("phone" in wire).toBe(false); + expect(JSON.parse(wire.b!)).toMatchObject({ phone: "07700900000" }); + }); }, ); diff --git a/test/shared/payment-helpers/dispatch.test.ts b/test/shared/payment-helpers/dispatch.test.ts index 796c0ba9ca..f12fce7a5b 100644 --- a/test/shared/payment-helpers/dispatch.test.ts +++ b/test/shared/payment-helpers/dispatch.test.ts @@ -1,16 +1,23 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { spy } from "@std/testing/mock"; import { ErrorCode } from "#shared/logger.ts"; import { + cachedClientFactory, createWithClient, hasRequiredSessionMetadata, PaymentUserError, + parseWebhookPayload, safeAsync, toCheckoutResult, + validatedPaymentSession, } from "#shared/payment-helpers.ts"; -import { isPaymentStatus } from "#shared/payments.ts"; +import { isPaymentStatus, type SessionMetadata } from "#shared/payments.ts"; +import { useDebugLogSpy } from "#test-utils/debug-log.ts"; describe("payment-helpers", () => { + const debugSpy = useDebugLogSpy(); + describe("hasRequiredSessionMetadata", () => { test("returns false for null/undefined", () => { expect(hasRequiredSessionMetadata(null)).toBe(false); @@ -54,6 +61,16 @@ describe("payment-helpers", () => { }), ).toBe(true); }); + + test("returns false when a present metadata value is not text", () => { + expect( + hasRequiredSessionMetadata({ + email: 123 as unknown as string, + items: "[]", + name: "Alice", + }), + ).toBe(false); + }); }); describe("isPaymentStatus", () => { @@ -89,13 +106,72 @@ describe("payment-helpers", () => { }); test("re-throws PaymentUserError", async () => { + const error = new PaymentUserError("Bad phone"); + expect(error.name).toBe("PaymentUserError"); await expect( - safeAsync( - () => Promise.reject(new PaymentUserError("Bad phone")), - ErrorCode.PAYMENT_CHECKOUT, - ), + safeAsync(() => Promise.reject(error), ErrorCode.PAYMENT_CHECKOUT), ).rejects.toThrow("Bad phone"); }); + + test("logs unknown for a non-Error rejection", async () => { + const errorSpy = spy(console, "error"); + try { + await safeAsync( + () => Promise.reject("string error"), + ErrorCode.PAYMENT_CHECKOUT, + ); + expect(errorSpy.calls[0]?.args[0]).toBe( + '[Error] E_PAYMENT_CHECKOUT detail="unknown"', + ); + } finally { + errorSpy.restore(); + } + }); + }); + + describe("cachedClientFactory", () => { + test("logs missing configuration and the chosen creation message", async () => { + let config: string | null = null; + const cache = cachedClientFactory({ + create: (value: string) => ({ value }), + createMessage: () => "", + getConfig: () => config, + isSameConfig: (a, b) => a === b, + missingMessage: "No secret key configured", + provider: "Stripe", + }); + + expect(await cache.getClient()).toBeNull(); + config = "secret"; + expect(await cache.getClient()).toEqual({ value: "secret" }); + expect(debugSpy().calls.map((call) => call.args[0])).toEqual([ + "[Stripe] No secret key configured", + "[Stripe] ", + ]); + }); + + test("reuses and logs the cached client", async () => { + const client = { value: "secret" }; + let createCalls = 0; + const cache = cachedClientFactory({ + create: () => { + createCalls += 1; + return client; + }, + getConfig: () => "secret", + isSameConfig: (a, b) => a === b, + missingMessage: "No secret key configured", + provider: "Stripe", + }); + + expect(await cache.getClient()).toBe(client); + expect(await cache.getClient()).toBe(client); + expect(createCalls).toBe(1); + expect(debugSpy().calls.map((call) => call.args[0])).toEqual([ + "[Stripe] Creating new Stripe client", + "[Stripe] Using cached Stripe client", + ]); + }); }); describe("createWithClient", () => { @@ -159,6 +235,29 @@ describe("payment-helpers", () => { toCheckoutResult("", "https://pay.example.com", "Stripe"), ).toBeNull(); expect(toCheckoutResult("sess_1", "", "Payment")).toBeNull(); + expect(debugSpy().calls[0]?.args[0]).toBe( + "[Stripe] Checkout result missing session ID or URL", + ); + }); + }); + + test("validatedPaymentSession includes a supplied creation time", () => { + const createdAt = "2026-07-19T12:00:00.000Z"; + const session = validatedPaymentSession({ + amountTotal: 1000, + createdAt, + id: "session-1", + metadata: { items: "[]", name: "Alice" } as SessionMetadata, + paymentReference: "payment-1", + paymentStatus: "paid", }); + + expect(session.createdAt).toBe(createdAt); + }); + + test("parseWebhookPayload returns the invalid JSON error", () => { + expect(parseWebhookPayload("not JSON", ErrorCode.PAYMENT_CHECKOUT)).toEqual( + { error: "Invalid JSON payload", valid: false }, + ); }); }); diff --git a/test/shared/payment-helpers/limits.test.ts b/test/shared/payment-helpers/limits.test.ts index 2f95ca91f0..e308409be8 100644 --- a/test/shared/payment-helpers/limits.test.ts +++ b/test/shared/payment-helpers/limits.test.ts @@ -218,6 +218,12 @@ describe("payment-helpers", () => { }); describe("metadata packing codec", () => { + test("packs one balance attendee id", () => { + expect(packMetadata({ balance_attendee_id: "42" })).toEqual({ + b: '{"balance_attendee_id":"42"}', + }); + }); + test("packs the small fields into one `b` entry and drops them", () => { const packed = packMetadata({ _origin: "x", @@ -307,4 +313,8 @@ describe("payment-helpers", () => { expect(extracted.date).toBe("2026-07-01"); }); }); + + test("an absent option field fits a zero-length limit", () => { + expect(enforceMetadataLimits({}, 0)).toEqual({}); + }); }); diff --git a/test/shared/payment-helpers/metadata.test.ts b/test/shared/payment-helpers/metadata.test.ts index a62b4080f7..05a990b65c 100644 --- a/test/shared/payment-helpers/metadata.test.ts +++ b/test/shared/payment-helpers/metadata.test.ts @@ -113,6 +113,7 @@ describe("payment-helpers", () => { test("single-listing metadata survives full pipeline", () => { const metadata = buildMetadata({ address: "123 Main St", + balanceAttendeeId: 42, date: "2026-02-10", email: "alice@example.com", items: [{ e: 42, p: 0, q: 3 }], @@ -131,6 +132,7 @@ describe("payment-helpers", () => { expect(extracted.email).toBe("alice@example.com"); expect(extracted.phone).toBe("+1234567890"); expect(extracted.address).toBe("123 Main St"); + expect(extracted.balance_attendee_id).toBe("42"); expect(extracted.special_instructions).toBe("No nuts"); expect(extracted.date).toBe("2026-02-10"); expect(JSON.parse(extracted.answer_ids)).toEqual({ "42": [10, 20] }); diff --git a/test/shared/payments.test.ts b/test/shared/payments.test.ts index 1116b3e51d..c649affa8e 100644 --- a/test/shared/payments.test.ts +++ b/test/shared/payments.test.ts @@ -1,9 +1,7 @@ import { expect } from "@std/expect"; -import { afterEach, beforeEach, describe, it as test } from "@std/testing/bdd"; -import { type Spy, spy } from "@std/testing/mock"; +import { describe, it as test } from "@std/testing/bdd"; import * as v from "valibot"; import { ALL_SETTINGS_KEYS, settings } from "#shared/db/settings.ts"; -import { setSuppressDebugLogs } from "#shared/log-settings.ts"; import { type BookingItem, BookingItemsSchema, @@ -11,6 +9,7 @@ import { isPaymentStatus, } from "#shared/payments.ts"; import { describeWithEnv } from "#test-utils/db.ts"; +import { useDebugLogSpy } from "#test-utils/debug-log.ts"; /** A minimal booking line that satisfies every schema rule; spread and override * one field per case to probe a single boundary in isolation. Each line is @@ -114,18 +113,9 @@ describe("BookingItemsSchema", () => { }); describeWithEnv("getActivePaymentProvider", { db: true }, () => { - let debugSpy: Spy; + const debugSpy = useDebugLogSpy(); const debugLogged = (needle: string): boolean => - debugSpy.calls.some((call) => String(call.args[0]).includes(needle)); - - beforeEach(() => { - setSuppressDebugLogs(false); - debugSpy = spy(console, "debug"); - }); - afterEach(() => { - debugSpy.restore(); - setSuppressDebugLogs(null); - }); + debugSpy().calls.some((call) => String(call.args[0]).includes(needle)); test("returns null when no provider is configured", async () => { expect(await getActivePaymentProvider()).toBeNull(); diff --git a/test/shared/validation/number.test.ts b/test/shared/validation/number.test.ts index c8c8bfe982..a7006605b3 100644 --- a/test/shared/validation/number.test.ts +++ b/test/shared/validation/number.test.ts @@ -80,6 +80,10 @@ describe("parseNonNegativeInt", () => { expect(parseNonNegativeInt(value)).toBeNull(); } }); + + test("rejects integers above JavaScript's safe range", () => { + expect(parseNonNegativeInt(String(Number.MAX_SAFE_INTEGER + 1))).toBeNull(); + }); }); describe("parsePositiveInt", () => { diff --git a/test/test-utils/debug-log.ts b/test/test-utils/debug-log.ts new file mode 100644 index 0000000000..1da3d72404 --- /dev/null +++ b/test/test-utils/debug-log.ts @@ -0,0 +1,17 @@ +import { afterEach, beforeEach } from "@std/testing/bdd"; +import { type Spy, spy } from "@std/testing/mock"; +import { setSuppressDebugLogs } from "#shared/log-settings.ts"; + +/** Capture debug output for each test and restore global logging afterwards. */ +export const useDebugLogSpy = (): (() => Spy) => { + let debugSpy: Spy; + beforeEach(() => { + setSuppressDebugLogs(false); + debugSpy = spy(console, "debug"); + }); + afterEach(() => { + debugSpy.restore(); + setSuppressDebugLogs(null); + }); + return () => debugSpy; +}; From ff83046b5bf16f922aae2539d424a39f9a2a066b Mon Sep 17 00:00:00 2001 From: Stefan Date: Sun, 19 Jul 2026 17:24:39 +0100 Subject: [PATCH 12/17] Reject malformed listing API fields --- scripts/mutation/equivalent-mutants.txt | 9 +++ src/features/admin/api.ts | 36 +++++++++- test/features/admin/api.test.ts | 51 ++++++++++++- .../admin-api-listings-input-parsers.test.ts | 38 +++++++++- .../routes/admin-api-listings-read.test.ts | 71 +++++++++++++++++++ .../admin-api/listings/lifecycle.test.ts | 26 +++++-- 6 files changed, 220 insertions(+), 11 deletions(-) diff --git a/scripts/mutation/equivalent-mutants.txt b/scripts/mutation/equivalent-mutants.txt index 42a44cfde6..fb7d9cc712 100644 --- a/scripts/mutation/equivalent-mutants.txt +++ b/scripts/mutation/equivalent-mutants.txt @@ -264,6 +264,15 @@ src/shared/db/built-sites.ts:202:15 renewalTokenIndex → "" # not in BuiltSi src/shared/db/built-sites.ts:377:71 ?? → || # blob input strings use "" as their fallback, providers are non-empty, and renewalToken uses null src/shared/db/built-sites.ts:391:54 ?? → || # validated optional strings use "" as their fallback, providers are non-empty, and renewalToken is null or non-empty +# Admin listing API fallbacks receive only objects, arrays, positive ids, or +# nullish values, so no valid request can distinguish these operators. +src/features/admin/api.ts:342:66 ?? → || # stored listing lookup returns a ListingWithCount object or null; listing objects are truthy +src/features/admin/api.ts:373:25 ?? → || # parsed group ids are an array or undefined; every array, including [], is truthy +src/features/admin/api.ts:492:30 1 → 0 # the mutation changes sentinel -1 to -0; positive listing ids match neither value +src/features/admin/api.ts:534:19 ?? → || # groupIds is an array or undefined; every array, including [], is truthy +src/features/admin/api.ts:547:43 ?? → || # an existing listing id is positive and truthy, otherwise optional access yields undefined +src/features/admin/api.ts:549:38 ?? → || # groupIds is an array or undefined; every array, including [], is truthy + # Settings registry: readOnly is optional but can only be true when present, so # `"readOnly" in accessor && accessor.readOnly` and `... || accessor.readOnly` # make the same if-condition decision for every valid accessor. diff --git a/src/features/admin/api.ts b/src/features/admin/api.ts index bd8de9a509..324849230f 100644 --- a/src/features/admin/api.ts +++ b/src/features/admin/api.ts @@ -8,6 +8,7 @@ */ /* jscpd:ignore-start */ +import * as v from "valibot"; import { mapById, reduce } from "#fp"; import { groupApiRoutes } from "#routes/admin/api-groups.ts"; import { holidayApiRoutes } from "#routes/admin/api-holidays.ts"; @@ -157,6 +158,36 @@ const optionalFields: FieldMapping[] = [ ["bookable_alone", "bookableAlone", "boolean"], ]; +interface ApiBodyFieldRule { + apiKey: string; + error: string; + schema: v.GenericSchema; +} + +const API_BODY_FIELD_RULES: ApiBodyFieldRule[] = [ + { + apiKey: "bookable_days", + error: "bookable_days must contain only text", + schema: v.array(v.string()), + }, + { + apiKey: "duration_days", + error: "duration_days must be a safe integer", + schema: v.pipe(v.number(), v.safeInteger()), + }, +]; + +/** Reject malformed mapped values before they can reach domain or storage code. */ +const validateApiBodyFields = ( + body: Record, +): Result => { + const invalid = API_BODY_FIELD_RULES.find( + ({ apiKey, schema }) => + body[apiKey] !== undefined && !v.is(schema, body[apiKey]), + ); + return invalid ? errorResult(invalid.error) : okResult(undefined); +}; + /** * Parse a day_prices object from a JSON body into DayPrices. Keeps only * positive-integer day counts mapped to numeric prices; everything else is @@ -249,12 +280,13 @@ const existingToDefaults = (existing: ListingWithCount): FieldRecord => // Body → ListingInput converters // ============================================================================= -/** Parse the request's group ids, then either bail with the parse error or hand - * the ids to `build` to finish producing the listing input. */ +/** Validate mapped fields and group ids before building the listing input. */ const withParsedGroupIds = ( body: Record, build: (groupIds: number[] | undefined) => Promise>, ): Promise> => { + const fields = validateApiBodyFields(body); + if (!fields.ok) return Promise.resolve(fields); const groups = parseGroupIds(body.group_ids); return groups.ok ? build(groups.value) : Promise.resolve(groups); }; diff --git a/test/features/admin/api.test.ts b/test/features/admin/api.test.ts index 290cc0d65a..a0ce8fa7ff 100644 --- a/test/features/admin/api.test.ts +++ b/test/features/admin/api.test.ts @@ -1,7 +1,11 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; import { getDb } from "#shared/db/client.ts"; -import { assertJson, expectRejectsEmptyName } from "#test-utils/assertions.ts"; +import { + assertAdminHtml, + assertJson, + expectRejectsEmptyName, +} from "#test-utils/assertions.ts"; import { describeWithEnv } from "#test-utils/db.ts"; import { createTestGroup } from "#test-utils/db-helpers/groups.ts"; import { createTestListing } from "#test-utils/db-helpers/listings.ts"; @@ -78,6 +82,34 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { await expectRejectsEmptyName(`/api/admin/listings/${listing.id}`); }); + test("returns 400 for a fractional duration", async () => { + const listing = await createTestListing({ name: "Whole Days" }); + await assertJson( + apiRequest(`/api/admin/listings/${listing.id}`, { + body: { duration_days: 2.5 }, + method: "PUT", + }), + 400, + (body) => { + expect(body.error).toBe("duration_days must be a safe integer"); + }, + ); + }); + + test("returns 400 when a bookable day is not text", async () => { + const listing = await createTestListing({ name: "Named Days" }); + await assertJson( + apiRequest(`/api/admin/listings/${listing.id}`, { + body: { bookable_days: ["Monday", 2] }, + method: "PUT", + }), + 400, + (body) => { + expect(body.error).toBe("bookable_days must contain only text"); + }, + ); + }); + test("rejects duplicate slug", async () => { const listing1 = await createTestListing({ name: "Listing One" }); const listing2 = await createTestListing({ name: "Listing Two" }); @@ -109,6 +141,23 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { }, ); }); + + test("links an update to the listing activity page", async () => { + const listing = await createTestListing({ name: "Activity before" }); + + await assertJson( + apiRequest(`/api/admin/listings/${listing.id}`, { + body: { name: "Activity after" }, + method: "PUT", + }), + 200, + ); + + await assertAdminHtml( + `/admin/listing/${listing.id}/activity`, + "Listing 'Activity after' updated", + ); + }); }); describe("PUT /api/admin/listings/:listingId - comprehensive field updates", () => { diff --git a/test/integration/routes/admin-api-listings-input-parsers.test.ts b/test/integration/routes/admin-api-listings-input-parsers.test.ts index 3aa2f4adf5..d1f0de7435 100644 --- a/test/integration/routes/admin-api-listings-input-parsers.test.ts +++ b/test/integration/routes/admin-api-listings-input-parsers.test.ts @@ -15,6 +15,12 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { if (!result.ok) expect(result.error).toBe("name is required"); }); + test("returns error for a whitespace-only name", async () => { + const result = await bodyToCreateInput({ max_attendees: 10, name: " " }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toBe("name is required"); + }); + test("returns error for missing max_attendees", async () => { const result = await bodyToCreateInput({ name: "Test" }); expect(result.ok).toBe(false); @@ -23,24 +29,54 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { } }); + test("returns error when max_attendees is zero", async () => { + const result = await bodyToCreateInput({ + max_attendees: 0, + name: "Test", + }); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toBe("max_attendees is required and must be >= 1"); + } + }); + test("handles all field types correctly", async () => { const result = await bodyToCreateInput({ active: false, + bookable_alone: true, bookable_days: ["Monday"], closes_at: "2026-06-14T23:59:00Z", date: "2026-06-15T10:00:00Z", + day_prices: { 0: 900, 1: 1200 }, + duration_days: 3, max_attendees: 10, + max_price: 5000, name: "Test", }); expect(result.ok).toBe(true); if (result.ok) { expect(result.value.active).toBe(false); + expect(result.value.bookableAlone).toBe(true); expect(result.value.bookableDays).toEqual(["Monday"]); + expect(result.value.date).toBe("2026-06-15T10:00:00Z"); + expect(result.value.dayPrices).toEqual({ 1: 1200 }); + expect(result.value.durationDays).toBe(3); + expect(result.value.maxPrice).toBe(5000); expect(result.value.slug).toBeTruthy(); } }); + test("defaults max_price to zero", async () => { + const result = await bodyToCreateInput({ + max_attendees: 10, + name: "No Maximum Price", + }); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value.maxPrice).toBe(0); + }); + test("rejects a non-array group_ids", async () => { const result = await bodyToCreateInput({ group_ids: "5", @@ -48,7 +84,7 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { name: "Bad Groups", }); expect(result.ok).toBe(false); - if (!result.ok) expect(result.error).toContain("must be an array"); + if (!result.ok) expect(result.error).toBe("group_ids must be an array"); }); test("rejects group_ids with non-positive-integer entries", async () => { diff --git a/test/integration/routes/admin-api-listings-read.test.ts b/test/integration/routes/admin-api-listings-read.test.ts index db7df9d356..601ff115c5 100644 --- a/test/integration/routes/admin-api-listings-read.test.ts +++ b/test/integration/routes/admin-api-listings-read.test.ts @@ -5,6 +5,7 @@ import { assertJson } from "#test-utils/assertions.ts"; import { describeWithEnv } from "#test-utils/db.ts"; import { createTestListing } from "#test-utils/db-helpers/listings.ts"; import { mockRequest } from "#test-utils/mocks.ts"; +import { bookingPageHtml } from "#test-utils/parents.ts"; import { apiRequest, createTestApiKeyToken, @@ -63,4 +64,74 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { ); }); }); + + describe("listing child IDs", () => { + test("rejects child_listing_ids when it is not an array", async () => { + const listing = await createTestListing({ name: "Array required" }); + + await assertJson( + apiRequest(`/api/admin/listings/${listing.id}`, { + body: { child_listing_ids: "1" }, + method: "PUT", + }), + 400, + (body) => { + expect(body.error).toBe( + "child_listing_ids must be an array of listing ids", + ); + }, + ); + }); + + test("accepts listing ID 1 as a positive integer", async () => { + const listing = await createTestListing({ name: "Positive IDs" }); + + await assertJson( + apiRequest(`/api/admin/listings/${listing.id}`, { + body: { child_listing_ids: [1] }, + method: "PUT", + }), + 200, + ); + }); + + test("rejects a fractional child listing ID", async () => { + const listing = await createTestListing({ name: "Integer IDs" }); + + await assertJson( + apiRequest(`/api/admin/listings/${listing.id}`, { + body: { child_listing_ids: [1.5] }, + method: "PUT", + }), + 400, + (body) => { + expect(body.error).toBe( + "child_listing_ids must contain only positive integer listing ids", + ); + }, + ); + }); + + test("creates a parent with the first listing as its child", async () => { + const child = await createTestListing({ name: "First child" }); + let parentSlug = ""; + + await assertJson( + apiRequest("/api/admin/listings", { + body: { + child_listing_ids: [child.id], + max_attendees: 10, + name: "New parent", + }, + method: "POST", + }), + 201, + (body) => { + parentSlug = body.listing.slug; + }, + ); + + expect(await bookingPageHtml(parentSlug)).toContain("First child"); + }); + }); }); diff --git a/test/integration/server/admin-api/listings/lifecycle.test.ts b/test/integration/server/admin-api/listings/lifecycle.test.ts index db1e4a4bd4..1838da7b9b 100644 --- a/test/integration/server/admin-api/listings/lifecycle.test.ts +++ b/test/integration/server/admin-api/listings/lifecycle.test.ts @@ -5,6 +5,7 @@ import { invalidateListingsCache, listingsTable, } from "#shared/db/listings/records.ts"; +import { wasActivityLogged } from "#test-utils/activity-log.ts"; import { assertJson } from "#test-utils/assertions.ts"; import { describeWithEnv } from "#test-utils/db.ts"; import { createTestListing } from "#test-utils/db-helpers/listings.ts"; @@ -30,6 +31,11 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { invalidateListingsCache(); const deleted = await getListingWithCount(listing.id); expect(deleted).toBeNull(); + expect( + await wasActivityLogged( + "Listing 'Delete Me' deleted (0 attendee(s) removed)", + ), + ).toBe(true); }); test("rejects with wrong confirm_identifier", async () => { @@ -42,7 +48,9 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { }), 400, (body) => { - expect(body.error).toContain("Listing name does not match"); + expect(body.error).toBe( + "Listing name does not match. Please provide the exact listing name in confirm_identifier.", + ); }, ); }); @@ -70,12 +78,16 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { }); test("returns 404 for non-existent listing", async () => { - const response = await apiRequest("/api/admin/listings/99999", { - body: { confirm_identifier: "Ghost" }, - method: "DELETE", - }); - - expect(response.status).toBe(404); + await assertJson( + apiRequest("/api/admin/listings/99999", { + body: { confirm_identifier: "Ghost" }, + method: "DELETE", + }), + 404, + (body) => { + expect(body.error).toBe("Listing not found"); + }, + ); }); }); From 53daf0f3ac5966cbf175689ed0be2892d17390ce Mon Sep 17 00:00:00 2001 From: Stefan Date: Sun, 19 Jul 2026 20:37:52 +0100 Subject: [PATCH 13/17] Remove unused integer rejection policy --- src/shared/types.ts | 12 ++++---- src/shared/validation/number.ts | 25 ++++------------- test/shared/validation/number.test.ts | 32 +++++++--------------- test/ui/client/admin/order-gallery.test.ts | 17 ++++++------ 4 files changed, 29 insertions(+), 57 deletions(-) diff --git a/src/shared/types.ts b/src/shared/types.ts index 709e12fc9a..71a4db1b80 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -18,7 +18,7 @@ import type { ModifierTrigger, } from "#shared/price-modifier.ts"; import { guardFor } from "#shared/validation/guard.ts"; -import { boundedInteger, integerAtLeast } from "#shared/validation/number.ts"; +import { clampInteger, integerAtLeast } from "#shared/validation/number.ts"; import type { NonEmptyString } from "#shared/validation/string.ts"; /** Type guard: a non-null, non-array object (a Record shape). */ @@ -182,17 +182,15 @@ export const hasTicketQuantity = (row: { quantity: number }): boolean => export const MAX_DURATION_DAYS = 90; /** - * Booking durations use one safe-integer range with two named policies. Clamp - * is for valid whole numbers outside the supported range. Reject is for - * boundaries where an out-of-range value must fail instead. Neither policy - * accepts fractions, non-finite numbers, or unsafe integers. + * Booking durations clamp valid whole numbers to one safe-integer range. + * Fractions, non-finite numbers, and unsafe integers are rejected. */ -const durationDays = boundedInteger(1, MAX_DURATION_DAYS); +const clampBookingDuration = clampInteger(1, MAX_DURATION_DAYS); /** Clamp a valid whole-day count to the supported booking range. */ export const clampDurationDays = (value: number): number => { try { - return durationDays.clamp(value); + return clampBookingDuration(value); } catch (error) { throw new Error(`Invalid booking duration: ${String(value)}`, { cause: error, diff --git a/src/shared/validation/number.ts b/src/shared/validation/number.ts index 763088cee9..455a433d6d 100644 --- a/src/shared/validation/number.ts +++ b/src/shared/validation/number.ts @@ -2,35 +2,20 @@ import * as v from "valibot"; import { parseOrNull } from "./parse.ts"; import { NonEmptyTextSchema } from "./string.ts"; -export interface BoundedInteger { - /** Clamp valid integers to the range. Malformed numbers still throw. */ - clamp: (value: number) => number; - /** Require a valid integer inside the range. */ - reject: (value: number) => number; -} - /** A safe whole number no lower than `minimum`. */ export const integerAtLeast = ( minimum: number, ): v.GenericSchema => v.pipe(v.number(), v.safeInteger(), v.minValue(minimum)); -/** Define explicit reject and clamp policies for one safe-integer range. */ -export const boundedInteger = ( +/** Clamp safe whole numbers to a range. Malformed numbers still throw. */ +export const clampInteger = ( minimum: number, maximum: number, -): BoundedInteger => { +): ((value: number) => number) => { const integerSchema = integerAtLeast(Number.MIN_SAFE_INTEGER); - const rangeSchema = v.pipe( - integerSchema, - v.minValue(minimum), - v.maxValue(maximum), - ); - return { - clamp: (value) => - Math.max(minimum, Math.min(maximum, v.parse(integerSchema, value))), - reject: (value) => v.parse(rangeSchema, value), - }; + return (value) => + Math.max(minimum, Math.min(maximum, v.parse(integerSchema, value))); }; /** diff --git a/test/shared/validation/number.test.ts b/test/shared/validation/number.test.ts index a7006605b3..7b6f9df351 100644 --- a/test/shared/validation/number.test.ts +++ b/test/shared/validation/number.test.ts @@ -1,44 +1,32 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; import { - boundedInteger, + clampInteger, parseNonNegativeInt, parsePositiveInt, parsePositiveIntId, } from "#shared/validation/number.ts"; -describe("boundedInteger", () => { - const days = boundedInteger(1, 90); +describe("clampInteger", () => { + const clampDays = clampInteger(1, 90); - test("reject policy accepts safe integers within the range", () => { - expect(days.reject(1)).toBe(1); - expect(days.reject(45)).toBe(45); - expect(days.reject(90)).toBe(90); + test("clamps valid integers outside the range", () => { + expect(clampDays(-2)).toBe(1); + expect(clampDays(500)).toBe(90); }); - test("reject policy rejects integers outside the range", () => { - expect(() => days.reject(0)).toThrow(); - expect(() => days.reject(91)).toThrow(); + test("leaves valid integers within the range unchanged", () => { + expect(clampDays(37)).toBe(37); }); - test("clamp policy clamps valid integers outside the range", () => { - expect(days.clamp(-2)).toBe(1); - expect(days.clamp(500)).toBe(90); - }); - - test("clamp policy leaves valid integers within the range unchanged", () => { - expect(days.clamp(37)).toBe(37); - }); - - test("both policies reject malformed numbers", () => { + test("rejects malformed numbers", () => { for (const value of [ 1.5, Number.NaN, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1, ]) { - expect(() => days.reject(value)).toThrow(); - expect(() => days.clamp(value)).toThrow(); + expect(() => clampDays(value)).toThrow(); } }); }); diff --git a/test/ui/client/admin/order-gallery.test.ts b/test/ui/client/admin/order-gallery.test.ts index 42a2712e97..44d86b3d78 100644 --- a/test/ui/client/admin/order-gallery.test.ts +++ b/test/ui/client/admin/order-gallery.test.ts @@ -44,14 +44,6 @@ const stash = createGlobalStash(); // test on a virtual clock so settle() skips past it instantly instead of each // test genuinely sleeping 300ms. const clock: { time: FakeTime | null } = { time: null }; -beforeEach(() => { - clock.time = new FakeTime(); -}); -afterEach(() => { - clock.time?.restore(); - clock.time = null; - stash.restore(); -}); /** Install the DOM and a scripted availability endpoint, then boot the * script. `responses` are consumed one per request; when empty the endpoint @@ -122,6 +114,15 @@ const settle = async (): Promise => { }; describe("initOrderGallery", () => { + beforeEach(() => { + clock.time = new FakeTime(); + }); + afterEach(() => { + clock.time?.restore(); + clock.time = null; + stash.restore(); + }); + test("does nothing on a page without the gallery form", () => { const window = new Window({ url: "https://tickets.test/" }); window.document.body.innerHTML = "

No gallery here

"; From 812c8511f4aec3e466a5b6affe812cf8758a4270 Mon Sep 17 00:00:00 2001 From: Stefan Date: Sun, 19 Jul 2026 20:54:57 +0100 Subject: [PATCH 14/17] Enforce order gallery clock setup --- test/ui/client/admin/order-gallery.test.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/test/ui/client/admin/order-gallery.test.ts b/test/ui/client/admin/order-gallery.test.ts index 44d86b3d78..e60842e3bf 100644 --- a/test/ui/client/admin/order-gallery.test.ts +++ b/test/ui/client/admin/order-gallery.test.ts @@ -45,6 +45,11 @@ const stash = createGlobalStash(); // test genuinely sleeping 300ms. const clock: { time: FakeTime | null } = { time: null }; +const getClock = (): FakeTime => { + if (clock.time === null) throw new Error("Fake clock was not installed"); + return clock.time; +}; + /** Install the DOM and a scripted availability endpoint, then boot the * script. `responses` are consumed one per request; when empty the endpoint * answers "everything fine, no states". */ @@ -109,8 +114,8 @@ const harness = (html = GALLERY_HTML) => { * response microtasks (tickAsync flushes them BEFORE advancing, so the * fired callback's await chain needs one more round). */ const settle = async (): Promise => { - await clock.time!.tickAsync(300); - await clock.time!.runMicrotasks(); + await getClock().tickAsync(300); + await getClock().runMicrotasks(); }; describe("initOrderGallery", () => { @@ -118,7 +123,8 @@ describe("initOrderGallery", () => { clock.time = new FakeTime(); }); afterEach(() => { - clock.time?.restore(); + // beforeEach always installs the clock; teardown must fail if that changes. + getClock().restore(); clock.time = null; stash.restore(); }); From e4d7f58e38a164154597ec60467137ad9eee7776 Mon Sep 17 00:00:00 2001 From: Stefan Date: Sun, 19 Jul 2026 22:54:05 +0100 Subject: [PATCH 15/17] Reject unsafe listing day prices --- scripts/mutation/equivalent-mutants.txt | 12 ++--- src/features/admin/api.ts | 15 +++++++ src/shared/types.ts | 2 +- test/features/admin/api.test.ts | 45 ++++++++++--------- .../admin-api-listings-input-parsers.test.ts | 18 +++++++- test/shared/types/day-prices.test.ts | 4 ++ 6 files changed, 67 insertions(+), 29 deletions(-) diff --git a/scripts/mutation/equivalent-mutants.txt b/scripts/mutation/equivalent-mutants.txt index fb7d9cc712..4f30fbbd9a 100644 --- a/scripts/mutation/equivalent-mutants.txt +++ b/scripts/mutation/equivalent-mutants.txt @@ -266,12 +266,12 @@ src/shared/db/built-sites.ts:391:54 ?? → || # validated optional strings us # Admin listing API fallbacks receive only objects, arrays, positive ids, or # nullish values, so no valid request can distinguish these operators. -src/features/admin/api.ts:342:66 ?? → || # stored listing lookup returns a ListingWithCount object or null; listing objects are truthy -src/features/admin/api.ts:373:25 ?? → || # parsed group ids are an array or undefined; every array, including [], is truthy -src/features/admin/api.ts:492:30 1 → 0 # the mutation changes sentinel -1 to -0; positive listing ids match neither value -src/features/admin/api.ts:534:19 ?? → || # groupIds is an array or undefined; every array, including [], is truthy -src/features/admin/api.ts:547:43 ?? → || # an existing listing id is positive and truthy, otherwise optional access yields undefined -src/features/admin/api.ts:549:38 ?? → || # groupIds is an array or undefined; every array, including [], is truthy +src/features/admin/api.ts:357:66 ?? → || # stored listing lookup returns a ListingWithCount object or null; listing objects are truthy +src/features/admin/api.ts:388:25 ?? → || # parsed group ids are an array or undefined; every array, including [], is truthy +src/features/admin/api.ts:507:30 1 → 0 # the mutation changes sentinel -1 to -0; positive listing ids match neither value +src/features/admin/api.ts:549:19 ?? → || # groupIds is an array or undefined; every array, including [], is truthy +src/features/admin/api.ts:562:43 ?? → || # an existing listing id is positive and truthy, otherwise optional access yields undefined +src/features/admin/api.ts:564:38 ?? → || # groupIds is an array or undefined; every array, including [], is truthy # Settings registry: readOnly is optional but can only be true when present, so # `"readOnly" in accessor && accessor.readOnly` and `... || accessor.readOnly` diff --git a/src/features/admin/api.ts b/src/features/admin/api.ts index 324849230f..8d3d76089a 100644 --- a/src/features/admin/api.ts +++ b/src/features/admin/api.ts @@ -175,6 +175,21 @@ const API_BODY_FIELD_RULES: ApiBodyFieldRule[] = [ error: "duration_days must be a safe integer", schema: v.pipe(v.number(), v.safeInteger()), }, + { + apiKey: "day_prices", + error: "day_prices numeric values must be safe integers", + schema: v.pipe( + v.unknown(), + v.check( + (raw) => + typeof raw !== "object" || + raw === null || + Object.values(raw).every( + (price) => typeof price !== "number" || Number.isSafeInteger(price), + ), + ), + ), + }, ]; /** Reject malformed mapped values before they can reach domain or storage code. */ diff --git a/src/shared/types.ts b/src/shared/types.ts index 71a4db1b80..00fb90ffe0 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -264,7 +264,7 @@ export const parseDayPrices = (raw: unknown): DayPrices => { return Number.isInteger(days) && days >= 1 && days <= MAX_DURATION_DAYS && - Number.isInteger(price) && + Number.isSafeInteger(price) && price >= 0 ? { days, price } : null; diff --git a/test/features/admin/api.test.ts b/test/features/admin/api.test.ts index a0ce8fa7ff..4d92f99a47 100644 --- a/test/features/admin/api.test.ts +++ b/test/features/admin/api.test.ts @@ -1,6 +1,6 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; -import { getDb } from "#shared/db/client.ts"; +import { getListingWithCount } from "#shared/db/listings/records.ts"; import { assertAdminHtml, assertJson, @@ -58,25 +58,6 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { expect(response.status).toBe(404); }); - test("returns 404 when the listing vanishes during update", async () => { - const listing = await createTestListing({ name: "Vanishing listing" }); - await getDb().execute( - `CREATE TRIGGER delete_listing_during_update - AFTER UPDATE ON listings - WHEN NEW.id = ${listing.id} - BEGIN - DELETE FROM listings WHERE id = NEW.id; - END`, - ); - - const response = await apiRequest(`/api/admin/listings/${listing.id}`, { - body: { name: "Gone" }, - method: "PUT", - }); - - expect(response.status).toBe(404); - }); - test("returns 400 when name is empty string", async () => { const listing = await createTestListing({ name: "Will Empty" }); await expectRejectsEmptyName(`/api/admin/listings/${listing.id}`); @@ -110,6 +91,30 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { ); }); + test("returns 400 without saving an unsafe day price", async () => { + const listing = await createTestListing({ + customisableDays: true, + dayPrices: { 1: 500 }, + durationDays: 2, + name: "Safe Prices", + }); + await assertJson( + apiRequest(`/api/admin/listings/${listing.id}`, { + body: { day_prices: { 1: Number.MAX_SAFE_INTEGER + 1 } }, + method: "PUT", + }), + 400, + (body) => { + expect(body.error).toBe( + "day_prices numeric values must be safe integers", + ); + }, + ); + expect((await getListingWithCount(listing.id))?.day_prices).toEqual({ + 1: 500, + }); + }); + test("rejects duplicate slug", async () => { const listing1 = await createTestListing({ name: "Listing One" }); const listing2 = await createTestListing({ name: "Listing Two" }); diff --git a/test/integration/routes/admin-api-listings-input-parsers.test.ts b/test/integration/routes/admin-api-listings-input-parsers.test.ts index d1f0de7435..7f05d59697 100644 --- a/test/integration/routes/admin-api-listings-input-parsers.test.ts +++ b/test/integration/routes/admin-api-listings-input-parsers.test.ts @@ -47,7 +47,7 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { bookable_days: ["Monday"], closes_at: "2026-06-14T23:59:00Z", date: "2026-06-15T10:00:00Z", - day_prices: { 0: 900, 1: 1200 }, + day_prices: { 0: 900, 1: 0, 2: 1200 }, duration_days: 3, max_attendees: 10, max_price: 5000, @@ -60,7 +60,7 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { expect(result.value.bookableAlone).toBe(true); expect(result.value.bookableDays).toEqual(["Monday"]); expect(result.value.date).toBe("2026-06-15T10:00:00Z"); - expect(result.value.dayPrices).toEqual({ 1: 1200 }); + expect(result.value.dayPrices).toEqual({ 1: 0, 2: 1200 }); expect(result.value.durationDays).toBe(3); expect(result.value.maxPrice).toBe(5000); expect(result.value.slug).toBeTruthy(); @@ -99,6 +99,20 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { } }); + test("rejects unsafe day prices", async () => { + const result = await bodyToCreateInput({ + day_prices: { 1: Number.MAX_SAFE_INTEGER + 1 }, + max_attendees: 10, + name: "Unsafe Price", + }); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toBe( + "day_prices numeric values must be safe integers", + ); + } + }); + test("maps the use_defaults flag both ways and omits it when absent", async () => { // true/false both round-trip (so the API can opt in *and* out), and an // absent flag stays absent rather than defaulting to either value. diff --git a/test/shared/types/day-prices.test.ts b/test/shared/types/day-prices.test.ts index b6fa827d09..948a08fac7 100644 --- a/test/shared/types/day-prices.test.ts +++ b/test/shared/types/day-prices.test.ts @@ -38,6 +38,10 @@ describe("parseDayPrices", () => { test("drops negative prices but keeps a zero (free) tier", () => { expect(parseDayPrices({ 1: -100, 2: 0 })).toEqual({ 2: 0 }); }); + + test("drops prices outside JavaScript's safe integer range", () => { + expect(parseDayPrices({ 1: Number.MAX_SAFE_INTEGER + 1 })).toEqual({}); + }); }); describe("availableDayCounts", () => { From 389adcaf340e7d1ae6d7bdfa7824b875fbdac615 Mon Sep 17 00:00:00 2001 From: Stefan Date: Mon, 20 Jul 2026 09:48:06 +0100 Subject: [PATCH 16/17] Preserve listing update race coverage --- test/features/admin/api.test.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/test/features/admin/api.test.ts b/test/features/admin/api.test.ts index 4d92f99a47..b1a8137bc8 100644 --- a/test/features/admin/api.test.ts +++ b/test/features/admin/api.test.ts @@ -1,5 +1,6 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { getDb } from "#shared/db/client.ts"; import { getListingWithCount } from "#shared/db/listings/records.ts"; import { assertAdminHtml, @@ -58,6 +59,25 @@ describeWithEnv("Admin API - Listings", { db: true }, () => { expect(response.status).toBe(404); }); + test("returns 404 when the listing vanishes during update", async () => { + const listing = await createTestListing({ name: "Vanishing listing" }); + await getDb().execute( + `CREATE TRIGGER delete_listing_during_update + AFTER UPDATE ON listings + WHEN NEW.id = ${listing.id} + BEGIN + DELETE FROM listings WHERE id = NEW.id; + END`, + ); + + const response = await apiRequest(`/api/admin/listings/${listing.id}`, { + body: { name: "Gone" }, + method: "PUT", + }); + + expect(response.status).toBe(404); + }); + test("returns 400 when name is empty string", async () => { const listing = await createTestListing({ name: "Will Empty" }); await expectRejectsEmptyName(`/api/admin/listings/${listing.id}`); From 3c2b02fb7983fa46a5fda444be5315894e24c4fa Mon Sep 17 00:00:00 2001 From: Stefan Date: Mon, 20 Jul 2026 10:03:26 +0100 Subject: [PATCH 17/17] Redact stored validation errors --- src/shared/db/sumup-checkouts.ts | 5 +++-- src/shared/validation/stored-json.ts | 11 ++++------ test/shared/admin-features.test.ts | 12 +++-------- test/shared/db/admin-features.test.ts | 4 ++-- test/shared/db/settings/json-field.test.ts | 2 +- test/shared/db/sumup-checkouts.test.ts | 22 ++++++++++++++++++++ test/shared/validation/stored-json.test.ts | 24 +++++++++++++++++++++- 7 files changed, 58 insertions(+), 22 deletions(-) diff --git a/src/shared/db/sumup-checkouts.ts b/src/shared/db/sumup-checkouts.ts index 485011751a..a29bed30d7 100644 --- a/src/shared/db/sumup-checkouts.ts +++ b/src/shared/db/sumup-checkouts.ts @@ -110,9 +110,10 @@ export const hasSumupCheckoutId = async (sumupId: string): Promise => { export const getSumupCheckout = async ( reference: string, ): Promise => { + const referenceIndex = await hmacHash(reference); const row = await queryOne( "SELECT wrapped_key, metadata, sumup_id FROM sumup_checkouts WHERE reference_index = ?", - [await hmacHash(reference)], + [referenceIndex], ); if (!row) return null; const dataKey = await unwrapKeyWithToken(row.wrapped_key, reference); @@ -120,7 +121,7 @@ export const getSumupCheckout = async ( return { metadata: metadataJson.read( json, - `sumup_checkouts.metadata for ${reference}`, + `sumup_checkouts.metadata for reference_index ${referenceIndex}`, ), sumupId: row.sumup_id, }; diff --git a/src/shared/validation/stored-json.ts b/src/shared/validation/stored-json.ts index 7874c38dd9..14613c8a86 100644 --- a/src/shared/validation/stored-json.ts +++ b/src/shared/validation/stored-json.ts @@ -8,10 +8,12 @@ export interface StoredJson { const invalidStoredJson = ( context: string, detail: string, - cause: unknown, + cause?: unknown, ): Error => new Error(`Invalid stored JSON in ${context}: ${detail}`, { cause }); +const INVALID_SCHEMA_DETAIL = "Stored value does not match its schema"; + /** Define one schema-backed JSON format for both storage reads and writes. */ export const defineStoredJson = ( schema: TSchema, @@ -25,11 +27,7 @@ export const defineStoredJson = ( } const result = v.safeParse(schema, parsed); if (!result.success) { - throw invalidStoredJson( - context, - result.issues[0]!.message, - result.issues, - ); + throw invalidStoredJson(context, INVALID_SCHEMA_DETAIL); } return result.output; }, @@ -38,7 +36,6 @@ export const defineStoredJson = ( if (!result.success) { throw new Error( `Invalid value for stored JSON${context ? ` in ${context}` : ""}`, - { cause: result.issues }, ); } return JSON.stringify(result.output); diff --git a/test/shared/admin-features.test.ts b/test/shared/admin-features.test.ts index 1a9e537e82..ed39bca02f 100644 --- a/test/shared/admin-features.test.ts +++ b/test/shared/admin-features.test.ts @@ -141,7 +141,7 @@ describe("admin features", () => { } }); - test("explains why an incomplete setting is invalid", () => { + test("identifies an incomplete setting without retaining its value", () => { let thrown: unknown; try { parseEnabledFeatures(JSON.stringify({ money: false })); @@ -150,15 +150,9 @@ describe("admin features", () => { } expect(thrown).toMatchObject({ message: - "Invalid stored JSON in settings.enabled_features: Every admin feature must have an enabled value", + "Invalid stored JSON in settings.enabled_features: Stored value does not match its schema", }); - expect((thrown as Error).cause).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - message: "Every admin feature must have an enabled value", - }), - ]), - ); + expect((thrown as Error).cause).toBeUndefined(); }); test("names the setting when serialization rejects invalid features", () => { diff --git a/test/shared/db/admin-features.test.ts b/test/shared/db/admin-features.test.ts index 1264d5444c..7ecff64553 100644 --- a/test/shared/db/admin-features.test.ts +++ b/test/shared/db/admin-features.test.ts @@ -257,7 +257,7 @@ describeWithEnv("db > admin features", { db: true, triggers: true }, () => { ); await expect(setAdminFeatureEnabled("money", true)).rejects.toThrow( - "Every admin feature must have an enabled value", + "Stored value does not match its schema", ); }); @@ -288,7 +288,7 @@ describeWithEnv("db > admin features", { db: true, triggers: true }, () => { ); await expect(setAdminFeatureEnabled("logistics", false)).rejects.toThrow( - "Every admin feature must have an enabled value", + "Stored value does not match its schema", ); expect(await settingValue(CONFIG_KEYS.LISTING_DEFAULTS)).toBe( defaultsBefore, diff --git a/test/shared/db/settings/json-field.test.ts b/test/shared/db/settings/json-field.test.ts index 6a9a88cb90..727ab4a945 100644 --- a/test/shared/db/settings/json-field.test.ts +++ b/test/shared/db/settings/json-field.test.ts @@ -92,7 +92,7 @@ describeWithEnv("db > settings JSON fields", { db: true }, () => { await expect( writeFeatureBoolean(enabledMoneyFeatures, "$.money", true, "TRUE"), - ).rejects.toThrow("Every admin feature must have an enabled value"); + ).rejects.toThrow("Stored value does not match its schema"); }); test("rolls back the JSON change when its settings version write fails", async () => { diff --git a/test/shared/db/sumup-checkouts.test.ts b/test/shared/db/sumup-checkouts.test.ts index e4d87eae1c..77ce11fab1 100644 --- a/test/shared/db/sumup-checkouts.test.ts +++ b/test/shared/db/sumup-checkouts.test.ts @@ -9,6 +9,9 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; +import { encryptWithKey } from "#shared/crypto/encryption.ts"; +import { unwrapKeyWithToken } from "#shared/crypto/keys.ts"; +import type { WrappedKey } from "#shared/crypto/sealed.ts"; import { getDb } from "#shared/db/client.ts"; import { getSumupCheckout, @@ -17,6 +20,7 @@ import { storeSumupCheckout, } from "#shared/db/sumup-checkouts.ts"; import { describeWithEnv } from "#test-utils/db.ts"; +import { rejectedError } from "#test-utils/errors.ts"; const REFERENCE = "9c1f7a52-1b3e-4f6d-8a2c-5e9d0b4c7a31"; @@ -67,6 +71,24 @@ describeWithEnv("db > sumup-checkouts", { db: true }, () => { ); }); + test("identifies corrupt metadata without exposing its reference", async () => { + await storeSumupCheckout(REFERENCE, METADATA); + const row = await rawRow(); + const dataKey = await unwrapKeyWithToken( + row.wrapped_key as WrappedKey, + REFERENCE, + ); + const malformed = await encryptWithKey('{"email":123}', dataKey); + await getDb().execute( + "UPDATE sumup_checkouts SET metadata = ? WHERE reference_index = ?", + [malformed, row.reference_index as string], + ); + + const error = await rejectedError(getSumupCheckout(REFERENCE)); + expect(error.message).toContain(row.reference_index as string); + expect(error.message).not.toContain(REFERENCE); + }); + test("keeps rows isolated per reference", async () => { const otherReference = crypto.randomUUID(); const otherMetadata = { ...METADATA, name: "Bob Other" }; diff --git a/test/shared/validation/stored-json.test.ts b/test/shared/validation/stored-json.test.ts index c1059ee16f..32556ca605 100644 --- a/test/shared/validation/stored-json.test.ts +++ b/test/shared/validation/stored-json.test.ts @@ -2,6 +2,7 @@ import { expect } from "@std/expect"; import { describe, it as test } from "@std/testing/bdd"; import * as v from "valibot"; import { defineStoredJson } from "#shared/validation/stored-json.ts"; +import { thrownError } from "#test-utils/errors.ts"; const entriesJson = defineStoredJson( v.array(v.strictObject({ id: v.number(), name: v.string() })), @@ -23,7 +24,7 @@ describe("defineStoredJson", () => { test("rejects the wrong top-level shape", () => { expect(() => entriesJson.read('{"id":1}', "test.entries")).toThrow( - "Invalid stored JSON in test.entries", + "Invalid stored JSON in test.entries: Stored value does not match its schema", ); }); @@ -33,6 +34,18 @@ describe("defineStoredJson", () => { ).toThrow("Invalid stored JSON in test.entries"); }); + test("does not attach rejected plaintext to read errors", () => { + const secret = "private stored value"; + const error = thrownError(() => + entriesJson.read( + JSON.stringify([{ id: secret, name: "First" }]), + "test.entries", + ), + ); + expect(error.cause).toBeUndefined(); + expect(error.message).not.toContain(secret); + }); + test("rejects extra object fields", () => { expect(() => entriesJson.read( @@ -60,4 +73,13 @@ describe("defineStoredJson", () => { ), ).toThrow("Invalid value for stored JSON in test.entries"); }); + + test("does not attach rejected plaintext to write errors", () => { + const error = thrownError(() => + entriesJson.write([{ id: 1, name: 2 }] as unknown as Parameters< + typeof entriesJson.write + >[0]), + ); + expect(error.cause).toBeUndefined(); + }); });