mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 01:44:13 +00:00
fix(shared): refuse a malformed row id in every request schema
Request fields that hold a row id took z.union([z.number(), z.string()]), a bare z.string() or z.array(z.number()), so '0x5', '5e0', 1.5 and 1e20 reached the handler and from there SQL, where SQLite matches nothing, Postgres 14 and 15 refuse the cast and 16 and later read hex and underscores as a number. Two primitives join idParamSchema: rowIdInputSchema takes a safe integer or its digits and keeps the value as sent, so field types do not change; rowIdStringSchema takes digits only, for multipart fields. Both refuse with 'Invalid id'. The accommodation, assignment, reservation position, admin invite, collab reply, vacay, file and memories photo ids now use them, and every list of ids is z.array(z.number().int()). idParamSchema takes only the decimal spelling or a whole number, and the trip-journal-link and tour library ids use it. A body id spelled '0x5' is now a 400 on SQLite too.
This commit is contained in:
@@ -226,7 +226,7 @@ describe('Update reservation', () => {
|
||||
expect(res.body.reservation.end_day_id).toBe(day3.id);
|
||||
});
|
||||
|
||||
it('RESV-004d — a reservation_time on a date the calendar does not have lands on no day, on every engine', async () => {
|
||||
it('RESV-004d: a reservation_time on a date the calendar does not have lands on no day, on every engine', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id);
|
||||
await makeDay(orm, trip.id, { date: '2024-03-01' });
|
||||
@@ -317,7 +317,7 @@ describe('Update reservation', () => {
|
||||
expect(row.accommodation_id).toBeNull();
|
||||
});
|
||||
|
||||
it('L2 — POST with a hex-spelled accommodation_id stores NULL, the same as PUT', async () => {
|
||||
it('POST with a hex-spelled accommodation_id stores NULL, the same as PUT', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id);
|
||||
const day = await makeDay(orm, trip.id);
|
||||
@@ -596,12 +596,12 @@ describe('Batch update positions', () => {
|
||||
expect(res.body.success).toBe(true);
|
||||
});
|
||||
|
||||
// M4 (Plan 3d Task 7 review): `updatePositions`' `dayId` parsed with
|
||||
// `toRowId`, not the `Number()`-fallback `rowIdNum` — a hex-spelled
|
||||
// `day_id` used to coerce to a real day and reach the per-day upsert,
|
||||
// where the legacy raw-bind statement's affinity never converts a hex
|
||||
// string, so the join matched no row (a quiet no-op, not a write). Rule 21.
|
||||
it('M4 — PUT /positions with a hex-spelled day_id is the legacy quiet no-op (no day-scoped row written)', async () => {
|
||||
// M4 (Plan 3d Task 7 review): a hex-spelled `day_id` used to coerce to a
|
||||
// real day and reach the per-day upsert. It was then a quiet 200 that wrote
|
||||
// nothing; the request schema now takes only the decimal spelling of a row
|
||||
// id, so it is the 400 every body id toRowId refuses gets, and still writes
|
||||
// nothing.
|
||||
it('M4: PUT /positions with a hex-spelled day_id is a 400 and writes no day-scoped row', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id);
|
||||
const day = await makeDay(orm, trip.id, { date: '2026-01-01' });
|
||||
@@ -612,10 +612,8 @@ describe('Batch update positions', () => {
|
||||
.put(`/api/trips/${trip.id}/reservations/positions`)
|
||||
.set('Cookie', authCookie(user.id))
|
||||
.send({ positions: [{ id: resv.id, day_plan_position: 0 }], day_id: hexDayId });
|
||||
// Same success shape the legacy statement's own no-op miss returns —
|
||||
// this is not a validation error, it silently writes nothing.
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.success).toBe(true);
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body).toEqual({ error: 'day_id: Invalid id' });
|
||||
|
||||
const row = await findRow(orm, ReservationDayPositions, { reservation: resv.id });
|
||||
expect(row).toBeNull();
|
||||
|
||||
+1
-1
@@ -41,7 +41,7 @@ One folder per domain exporting Zod schemas plus inferred types (`export type X
|
||||
|
||||
The parity rule governs **existing** routes; it is not a license to mint new debt:
|
||||
|
||||
- **The contract describes the wire, not the storage engine.** New booleans are `z.boolean()` — convert SQLite 0/1 at the service boundary, never add a `z.union([z.boolean(), z.number()])`. New ids use `idSchema`/`idParamSchema`, never `number | string`. Request and response types for a field must agree.
|
||||
- **The contract describes the wire, not the storage engine.** New booleans are `z.boolean()` — convert SQLite 0/1 at the service boundary, never add a `z.union([z.boolean(), z.number()])`. New ids use `idSchema`/`idParamSchema`, never `number | string`; a field that already takes a number or its digits uses `rowIdInputSchema` (`rowIdStringSchema` for a multipart field), so a spelling the server's `toRowId` refuses ('0x5', '5e0', 1.5) is a 400 here, which the server's ROUTEID-002 requires of every field named like a row id. Request and response types for a field must agree.
|
||||
- **Use the shared primitives** instead of re-declaring bare `z.number()`/`z.string()` per domain. Narrow an existing open object rather than adding a new `z.record(...)`/passthrough body, because "any object" gives zero drift protection. `contracts:open` (`scripts/open-request-schemas.mjs`) counts the open shapes in every exported `*RequestSchema` (a loose object, a record of unknown, a `z.unknown()`/`z.any()` field or body, a `z.custom()`/`z.instanceof()`, each counted once per path it sits at) against `scripts/open-request-schemas-baseline.json`: a new request schema may hold none, an existing one no more than its entry. It reads the built `dist/`; `src/open-request-schemas.spec.ts` runs the same check over `src/` in `npm test`. After narrowing a schema, `npm run contracts:open -- --update` lowers the baseline (it never raises or adds an entry). The suffix is only a convention, so the server holds the schemas it really binds to the same count: `npm run contracts:dto-open --workspace=server` walks every `createZodDto` class, whatever its schema is called, against `server/scripts/dto-open-shapes-baseline.json`.
|
||||
- **Add a schema, add a spec** — especially for lenient parsers fed by untrusted or LLM input.
|
||||
- **Stay lean and isomorphic**: zero imports from client/server, no `node:` APIs, effectively no new runtime dependencies (the contract layer approaches `zod`-only; i18n is a separable concern — don't couple new contract code to it).
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { rowIdInputSchema } from '../common/primitives.schema';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
@@ -45,7 +47,7 @@ export const adminInviteCreateRequestSchema = z.object({
|
||||
role: z.enum(['user', 'admin']).optional(),
|
||||
// Optional trip binding (#1402): a user who registers via the link is
|
||||
// auto-added to this trip. Nullable/absent = a plain registration invite.
|
||||
trip_id: z.union([z.number().int(), z.string()]).nullable().optional(),
|
||||
trip_id: rowIdInputSchema.nullable().optional(),
|
||||
});
|
||||
export type AdminInviteCreateRequest = z.infer<typeof adminInviteCreateRequestSchema>;
|
||||
|
||||
@@ -173,7 +175,7 @@ export type AdminDefaultUserSettingsRequest = z.infer<typeof adminDefaultUserSet
|
||||
export const adminTestNotificationRequestSchema = z.object({
|
||||
event: z.string().optional(),
|
||||
scope: z.string().optional(),
|
||||
targetId: z.number().optional(),
|
||||
targetId: z.number().int().optional(),
|
||||
params: z.record(z.string(), z.unknown()).optional(),
|
||||
inApp: z.union([z.boolean(), z.record(z.string(), z.unknown())]).optional(),
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { rowIdInputSchema } from '../common/primitives.schema';
|
||||
import { assignmentPlaceSchema } from '../place/place.schema';
|
||||
import { stationKeySchema } from '../tours/tours.schema';
|
||||
|
||||
@@ -74,7 +75,7 @@ export const assignmentSchema = z.object({
|
||||
export type Assignment = z.infer<typeof assignmentSchema>;
|
||||
|
||||
export const assignmentCreateRequestSchema = z.object({
|
||||
place_id: z.union([z.number().int(), z.string()]),
|
||||
place_id: rowIdInputSchema,
|
||||
notes: z.string().nullable().optional(),
|
||||
/**
|
||||
* MDT-02: puts one stage of a multi-day tour on the day instead of the whole
|
||||
@@ -86,12 +87,12 @@ export const assignmentCreateRequestSchema = z.object({
|
||||
export type AssignmentCreateRequest = z.infer<typeof assignmentCreateRequestSchema>;
|
||||
|
||||
export const assignmentReorderRequestSchema = z.object({
|
||||
orderedIds: z.array(z.number()),
|
||||
orderedIds: z.array(z.number().int()),
|
||||
});
|
||||
export type AssignmentReorderRequest = z.infer<typeof assignmentReorderRequestSchema>;
|
||||
|
||||
export const assignmentMoveRequestSchema = z.object({
|
||||
new_day_id: z.union([z.number(), z.string()]),
|
||||
new_day_id: rowIdInputSchema,
|
||||
// The client api types this `number | null` (assignmentsApi.move) and the
|
||||
// legacy route accepted null (`orderIndex || 0`) — keep null on the wire.
|
||||
order_index: z.number().int().nullable().optional(),
|
||||
@@ -157,6 +158,6 @@ export const assignmentRouteRequestSchema = z.object({
|
||||
export type AssignmentRouteRequest = z.infer<typeof assignmentRouteRequestSchema>;
|
||||
|
||||
export const assignmentParticipantsRequestSchema = z.object({
|
||||
user_ids: z.array(z.number()),
|
||||
user_ids: z.array(z.number().int()),
|
||||
});
|
||||
export type AssignmentParticipantsRequest = z.infer<typeof assignmentParticipantsRequestSchema>;
|
||||
|
||||
@@ -159,7 +159,7 @@ export const budgetCreateItemRequestSchema = z.object({
|
||||
// server falls back to total_price with no explicit payer.
|
||||
payers: z.array(payerInputSchema).optional(),
|
||||
// Equal-split participants. When omitted, the item has no split (planning-only).
|
||||
member_ids: z.array(z.number()).optional(),
|
||||
member_ids: z.array(z.number().int()).optional(),
|
||||
members: z.array(memberInputSchema).optional(),
|
||||
persons: z.number().int().nullable().optional(),
|
||||
days: z.number().int().nullable().optional(),
|
||||
@@ -173,7 +173,7 @@ export const budgetCreateItemRequestSchema = z.object({
|
||||
// first, then creates the expense against it (#1298).
|
||||
place_id: z.number().int().optional(),
|
||||
// Receipt files to link to this expense
|
||||
receipt_file_ids: z.array(z.number()).optional(),
|
||||
receipt_file_ids: z.array(z.number().int()).optional(),
|
||||
// Rates to freeze a foreign currency with when the server has none of its own.
|
||||
fallback_fx: budgetFallbackFxSchema.optional(),
|
||||
});
|
||||
@@ -187,14 +187,14 @@ export const budgetUpdateItemRequestSchema = z.object({
|
||||
currency: z.string().nullable().optional(),
|
||||
exchange_rate: z.number().optional(),
|
||||
payers: z.array(payerInputSchema).optional(),
|
||||
member_ids: z.array(z.number()).optional(),
|
||||
member_ids: z.array(z.number().int()).optional(),
|
||||
members: z.array(memberInputSchema).optional(),
|
||||
persons: z.number().int().nullable().optional(),
|
||||
days: z.number().int().nullable().optional(),
|
||||
note: z.string().nullable().optional(),
|
||||
ticket_json: z.string().nullable().optional(),
|
||||
expense_date: z.string().nullable().optional(),
|
||||
receipt_file_ids: z.array(z.number()).optional(),
|
||||
receipt_file_ids: z.array(z.number().int()).optional(),
|
||||
// Link an existing expense to a booking or a place on the same trip (#2084);
|
||||
// null lets go of the link and keeps the expense. Omitted leaves it as is.
|
||||
reservation_id: z.number().int().positive().nullable().optional(),
|
||||
@@ -373,7 +373,7 @@ export const budgetParticipantFinalSchema = z.object({
|
||||
export type BudgetParticipantFinal = z.infer<typeof budgetParticipantFinalSchema>;
|
||||
|
||||
export const budgetUpdateMembersRequestSchema = z.object({
|
||||
user_ids: z.array(z.number()),
|
||||
user_ids: z.array(z.number().int()),
|
||||
});
|
||||
export type BudgetUpdateMembersRequest = z.infer<typeof budgetUpdateMembersRequestSchema>;
|
||||
|
||||
@@ -383,7 +383,7 @@ export const budgetToggleMemberPaidRequestSchema = z.object({
|
||||
export type BudgetToggleMemberPaidRequest = z.infer<typeof budgetToggleMemberPaidRequestSchema>;
|
||||
|
||||
export const budgetReorderItemsRequestSchema = z.object({
|
||||
orderedIds: z.array(z.number()),
|
||||
orderedIds: z.array(z.number().int()),
|
||||
});
|
||||
export type BudgetReorderItemsRequest = z.infer<typeof budgetReorderItemsRequestSchema>;
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { rowIdInputSchema } from '../common/primitives.schema';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
@@ -73,7 +75,7 @@ export type CollabLinkUpdateRequest = z.infer<typeof collabLinkUpdateRequestSche
|
||||
export const collabMessageCreateRequestSchema = z.object({
|
||||
text: z.string().max(5000).optional(),
|
||||
// Multipart fields arrive as strings; JSON chat still sends a number/null.
|
||||
reply_to: z.union([z.number().int(), z.string(), z.null()]).optional(),
|
||||
reply_to: z.union([rowIdInputSchema, z.literal(''), z.null()]).optional(),
|
||||
});
|
||||
export type CollabMessageCreateRequest = z.infer<typeof collabMessageCreateRequestSchema>;
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ export const collectionPlaceSchema = z.object({
|
||||
category: placeCategorySchema.optional(),
|
||||
tags: z.array(tagSchema.partial()).optional(),
|
||||
/** Ids of the per-collection labels assigned to this place. */
|
||||
label_ids: z.array(z.number()).optional(),
|
||||
label_ids: z.array(z.number().int()).optional(),
|
||||
// Collaborative ratings (#1435): every member's vote + the displayed aggregate.
|
||||
ratings: z.array(placeRatingVoteSchema).optional(),
|
||||
rating_avg: z.number().nullable().optional(),
|
||||
@@ -148,10 +148,10 @@ export const collectionUpdateRequestSchema = collectionCreateRequestSchema.parti
|
||||
export type CollectionUpdateRequest = z.infer<typeof collectionUpdateRequestSchema>;
|
||||
|
||||
/** Reorder the caller's lists — every visible collection id in the desired order.
|
||||
* Plain z.number() (no .min/.int) mirrors the legacy hand-rolled check the DTO
|
||||
* ratchet replaced: any array of numbers, empty included. */
|
||||
* No .min mirrors the legacy hand-rolled check the DTO ratchet replaced: any
|
||||
* array, empty included; .int() keeps a fractional id from reaching SQL. */
|
||||
export const collectionReorderRequestSchema = z.object({
|
||||
orderedIds: z.array(z.number()),
|
||||
orderedIds: z.array(z.number().int()),
|
||||
});
|
||||
export type CollectionReorderRequest = z.infer<typeof collectionReorderRequestSchema>;
|
||||
|
||||
@@ -177,7 +177,7 @@ export const collectionSavePlaceRequestSchema = z.object({
|
||||
phone: z.string().nullable().optional(),
|
||||
status: collectionStatusSchema.optional(),
|
||||
links: collectionLinksSchema.optional(),
|
||||
tag_ids: z.array(z.number()).optional(),
|
||||
tag_ids: z.array(z.number().int()).optional(),
|
||||
force: z.boolean().optional(), // "add anyway" over a dedup match
|
||||
});
|
||||
export type CollectionSavePlaceRequest = z.infer<typeof collectionSavePlaceRequestSchema>;
|
||||
@@ -195,7 +195,7 @@ export type CollectionSaveFromTripRequest = z.infer<typeof collectionSaveFromTri
|
||||
export const collectionSaveFromTripManyRequestSchema = z.object({
|
||||
collection_id: z.number().int(),
|
||||
source_trip_id: z.number().int(),
|
||||
source_place_ids: z.array(z.number()).min(1).max(1000),
|
||||
source_place_ids: z.array(z.number().int()).min(1).max(1000),
|
||||
force: z.boolean().optional(),
|
||||
});
|
||||
export type CollectionSaveFromTripManyRequest = z.infer<typeof collectionSaveFromTripManyRequestSchema>;
|
||||
@@ -218,9 +218,9 @@ export const collectionPlaceUpdateRequestSchema = z.object({
|
||||
category_id: z.number().int().nullable().optional(),
|
||||
collection_id: z.number().int().optional(), // move to another list
|
||||
links: collectionLinksSchema.optional(),
|
||||
tag_ids: z.array(z.number()).optional(),
|
||||
tag_ids: z.array(z.number().int()).optional(),
|
||||
// Replace the place's per-collection label assignments (omit to leave unchanged).
|
||||
label_ids: z.array(z.number()).optional(),
|
||||
label_ids: z.array(z.number().int()).optional(),
|
||||
// Custom thumbnail (#1136): null clears it (falls back to the auto-fetched photo).
|
||||
image_url: placeImageUrlSchema.nullable().optional(),
|
||||
// The fields saving accepts but editing did not (#2646), with the same checks, so
|
||||
@@ -242,7 +242,7 @@ export type CollectionSetStatusRequest = z.infer<typeof collectionSetStatusReque
|
||||
/** Set one status on several saved places at once — the place dialog's "mark
|
||||
* visited everywhere it is saved" (#1469). Ids are collection_places ids. */
|
||||
export const collectionSetStatusManyRequestSchema = z.object({
|
||||
ids: z.array(z.number()).min(1).max(1000),
|
||||
ids: z.array(z.number().int()).min(1).max(1000),
|
||||
status: collectionStatusSchema,
|
||||
});
|
||||
export type CollectionSetStatusManyRequest = z.infer<typeof collectionSetStatusManyRequestSchema>;
|
||||
@@ -251,7 +251,7 @@ export type CollectionSetStatusManyRequest = z.infer<typeof collectionSetStatusM
|
||||
* the lists it is saved in. Drives the planner's bulk "mark as visited" (#1469). */
|
||||
export const collectionSetStatusFromTripRequestSchema = z.object({
|
||||
trip_id: z.number().int(),
|
||||
place_ids: z.array(z.number()).min(1).max(1000),
|
||||
place_ids: z.array(z.number().int()).min(1).max(1000),
|
||||
status: collectionStatusSchema,
|
||||
});
|
||||
export type CollectionSetStatusFromTripRequest = z.infer<typeof collectionSetStatusFromTripRequestSchema>;
|
||||
@@ -264,17 +264,17 @@ export const collectionSetStatusManyResponseSchema = z.object({
|
||||
});
|
||||
export type CollectionSetStatusManyResponse = z.infer<typeof collectionSetStatusManyResponseSchema>;
|
||||
|
||||
/** Bulk-delete saved places. Plain z.number() (no .min/.int) mirrors the legacy
|
||||
* hand-rolled check the DTO ratchet replaced (same shape as placeBulkDeleteRequestSchema). */
|
||||
/** Bulk-delete saved places. No .min mirrors the legacy hand-rolled check the
|
||||
* DTO ratchet replaced (same shape as placeBulkDeleteRequestSchema). */
|
||||
export const collectionDeleteManyRequestSchema = z.object({
|
||||
ids: z.array(z.number()),
|
||||
ids: z.array(z.number().int()),
|
||||
});
|
||||
export type CollectionDeleteManyRequest = z.infer<typeof collectionDeleteManyRequestSchema>;
|
||||
|
||||
/** Copy one or many saved places INTO a trip (dedup precheck on server). */
|
||||
export const collectionCopyToTripRequestSchema = z.object({
|
||||
trip_id: z.number().int(),
|
||||
place_ids: z.array(z.number()).min(1),
|
||||
place_ids: z.array(z.number().int()).min(1),
|
||||
force: z.boolean().optional(),
|
||||
});
|
||||
export type CollectionCopyToTripRequest = z.infer<typeof collectionCopyToTripRequestSchema>;
|
||||
@@ -379,8 +379,8 @@ export type CollectionLabelUpdateRequest = z.infer<typeof collectionLabelUpdateR
|
||||
|
||||
/** Bulk add or remove one/several labels across many selected places. */
|
||||
export const collectionLabelAssignRequestSchema = z.object({
|
||||
label_ids: z.array(z.number()).min(1).max(50),
|
||||
place_ids: z.array(z.number()).min(1).max(1000),
|
||||
label_ids: z.array(z.number().int()).min(1).max(50),
|
||||
place_ids: z.array(z.number().int()).min(1).max(1000),
|
||||
});
|
||||
export type CollectionLabelAssignRequest = z.infer<typeof collectionLabelAssignRequestSchema>;
|
||||
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import { paginationQuerySchema } from './pagination.schema';
|
||||
import { idSchema, idParamSchema, nonEmptyString, isoDateTime } from './primitives.schema';
|
||||
import {
|
||||
idSchema,
|
||||
idParamSchema,
|
||||
isoDateTime,
|
||||
nonEmptyString,
|
||||
rowIdInputSchema,
|
||||
rowIdStringSchema,
|
||||
} from './primitives.schema';
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
@@ -16,6 +23,32 @@ describe('@trek/shared primitives', () => {
|
||||
expect(idParamSchema.safeParse('abc').success).toBe(false);
|
||||
});
|
||||
|
||||
it('idParamSchema takes only the decimal spelling of an id, the rule the server reads ids with', () => {
|
||||
expect(idParamSchema.parse('007')).toBe(7);
|
||||
expect(idParamSchema.parse(42)).toBe(42);
|
||||
for (const spelling of ['0x5', '5e0', '5.0', '+5', ' 5', '5 ', '1_000', '-5', '0', '', '99999999999999999999']) {
|
||||
expect(idParamSchema.safeParse(spelling).success, spelling).toBe(false);
|
||||
}
|
||||
expect(idParamSchema.safeParse(1.5).success).toBe(false);
|
||||
expect(idParamSchema.safeParse(2 ** 60).success).toBe(false);
|
||||
});
|
||||
|
||||
it('rowIdInputSchema keeps an id as sent and refuses every spelling toRowId refuses', () => {
|
||||
expect(rowIdInputSchema.parse(42)).toBe(42);
|
||||
expect(rowIdInputSchema.parse('42')).toBe('42');
|
||||
expect(rowIdInputSchema.parse('007')).toBe('007');
|
||||
for (const spelling of ['0x5', '5e0', '5.0', '+5', ' 5', '5 ', '5_0', '-5', '', 'abc', '99999999999999999999']) {
|
||||
expect(rowIdInputSchema.safeParse(spelling).success, spelling).toBe(false);
|
||||
expect(rowIdStringSchema.safeParse(spelling).success, spelling).toBe(false);
|
||||
}
|
||||
expect(rowIdInputSchema.safeParse(1.5).success).toBe(false);
|
||||
expect(rowIdInputSchema.safeParse(1e20).success).toBe(false);
|
||||
expect(rowIdStringSchema.safeParse(5).success).toBe(false);
|
||||
for (const value of ['0x5', 1.5, '99999999999999999999']) {
|
||||
expect(rowIdInputSchema.safeParse(value).error?.issues[0]?.message, String(value)).toBe('Invalid id');
|
||||
}
|
||||
});
|
||||
|
||||
it('nonEmptyString trims and rejects empty', () => {
|
||||
expect(nonEmptyString.parse(' hi ')).toBe('hi');
|
||||
expect(nonEmptyString.safeParse(' ').success).toBe(false);
|
||||
|
||||
@@ -11,9 +11,35 @@ export type Id = z.infer<typeof idSchema>;
|
||||
|
||||
/**
|
||||
* Numeric id coming from a URL param / query string. Express hands these over
|
||||
* as strings, so we coerce, then enforce a positive integer.
|
||||
* as strings, so a string must be decimal digits before it becomes a number,
|
||||
* then a positive safe integer. A plain coercion read '0x5', '5e0', '5.0',
|
||||
* '+5' and ' 5' as 5, spellings no client sends that the server's toRowId
|
||||
* refuses; this keeps the two the same rule.
|
||||
*/
|
||||
export const idParamSchema = z.coerce.number().int().positive();
|
||||
export const idParamSchema = z
|
||||
.union([z.number().int(), z.string().regex(/^\d+$/)])
|
||||
.pipe(z.coerce.number().int().positive());
|
||||
|
||||
/**
|
||||
* A row id written as text: decimal digits naming a safe integer, kept as the
|
||||
* string it arrived as (a multipart field is always text). The server reads it
|
||||
* with toRowId. '0x5', '5e0', '5.0', '+5', ' 5', '5_0' and a number past 2^53
|
||||
* are refused here: bound to SQL they match nothing on SQLite, Postgres 14 and
|
||||
* 15 refuse the cast and 16 and later read hex and underscores as a number.
|
||||
*/
|
||||
export const rowIdStringSchema = z
|
||||
.string()
|
||||
.regex(/^\d+$/, 'Invalid id')
|
||||
.refine((digits) => Number.isSafeInteger(Number(digits)), 'Invalid id');
|
||||
|
||||
/**
|
||||
* A row id in a request body: a safe integer, or its decimal digits as a
|
||||
* string from a client that sends text. Kept as sent, so a field that took
|
||||
* `number | string` keeps its type; the server reads it with toRowId. Refuses
|
||||
* the spellings rowIdStringSchema refuses, and 1.5 and 1e20, each as
|
||||
* `<field>: Invalid id`.
|
||||
*/
|
||||
export const rowIdInputSchema = z.union([z.number().int('Invalid id'), rowIdStringSchema], { error: 'Invalid id' });
|
||||
|
||||
/** Non-empty, trimmed string. */
|
||||
export const nonEmptyString = z.string().trim().min(1);
|
||||
|
||||
@@ -77,7 +77,7 @@ export type DayCreateRequest = z.infer<typeof dayCreateRequestSchema>;
|
||||
|
||||
/** Reorder whole days: the desired full sequence of this trip's day ids. */
|
||||
export const dayReorderRequestSchema = z.object({
|
||||
orderedIds: z.array(z.number()),
|
||||
orderedIds: z.array(z.number().int()),
|
||||
});
|
||||
export type DayReorderRequest = z.infer<typeof dayReorderRequestSchema>;
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { rowIdInputSchema, rowIdStringSchema } from '../common/primitives.schema';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
@@ -12,17 +14,17 @@ import { z } from 'zod';
|
||||
* bodies. The bespoke 400/403/404 controller messages pin the rest.
|
||||
*/
|
||||
|
||||
const nullableIdField = z.union([z.string(), z.number().int()]).nullable().optional();
|
||||
const nullableIdField = rowIdInputSchema.nullable().optional();
|
||||
|
||||
/**
|
||||
* Multipart text fields riding along with the upload — always strings on the
|
||||
* wire (multipart/form-data has no other type), so no numeric coercion here.
|
||||
*/
|
||||
export const fileUploadRequestSchema = z.object({
|
||||
place_id: z.string().optional(),
|
||||
place_id: rowIdStringSchema.optional(),
|
||||
description: z.string().optional(),
|
||||
reservation_id: z.string().optional(),
|
||||
budget_item_id: z.string().optional(),
|
||||
reservation_id: rowIdStringSchema.optional(),
|
||||
budget_item_id: rowIdStringSchema.optional(),
|
||||
});
|
||||
export type FileUploadRequest = z.infer<typeof fileUploadRequestSchema>;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { idSchema } from '../common/primitives.schema';
|
||||
import { idParamSchema, idSchema } from '../common/primitives.schema';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -36,7 +36,7 @@ export type TripJournalLinkMembersRequest = z.infer<typeof tripJournalLinkMember
|
||||
|
||||
/** GET …/candidates: whose access a journal would change, before it is linked. */
|
||||
export const tripJournalCandidatesQuerySchema = z.object({
|
||||
journey_id: z.coerce.number().int().positive(),
|
||||
journey_id: idParamSchema,
|
||||
});
|
||||
export type TripJournalCandidatesQuery = z.infer<typeof tripJournalCandidatesQuerySchema>;
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { rowIdInputSchema } from '../common/primitives.schema';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
@@ -25,8 +27,8 @@ const looseBoolean = z.union([z.boolean(), z.literal('true'), z.literal('false')
|
||||
|
||||
/** `Number(x) || fallback` — the client sends these as strings from query-ish forms. */
|
||||
const looseNumber = z.union([z.number(), z.string()]).optional();
|
||||
/** A row id the same loose way: a whole number, or a string the service converts. */
|
||||
const looseId = z.union([z.number().int(), z.string()]).optional();
|
||||
/** A row id: a whole number or its digits, which the controller reads with toRowId. */
|
||||
const looseId = rowIdInputSchema.optional();
|
||||
|
||||
/**
|
||||
* The UTC offset the caller means its calendar days in, in minutes east of UTC
|
||||
|
||||
@@ -110,14 +110,14 @@ export const packingCreateItemRequestSchema = z.object({
|
||||
// Three-tier sharing (#858): which list the item belongs to, and — for 'shared' —
|
||||
// the people it covers ("taken care of by you").
|
||||
visibility: packingVisibilitySchema.optional(),
|
||||
recipient_ids: z.array(z.number()).optional(),
|
||||
recipient_ids: z.array(z.number().int()).optional(),
|
||||
});
|
||||
export type PackingCreateItemRequest = z.infer<typeof packingCreateItemRequestSchema>;
|
||||
|
||||
// Re-set an item's sharing tier + the people a 'shared' item covers (#858).
|
||||
export const packingSetSharingRequestSchema = z.object({
|
||||
visibility: packingVisibilitySchema,
|
||||
recipient_ids: z.array(z.number()).optional(),
|
||||
recipient_ids: z.array(z.number().int()).optional(),
|
||||
});
|
||||
export type PackingSetSharingRequest = z.infer<typeof packingSetSharingRequestSchema>;
|
||||
|
||||
@@ -150,7 +150,7 @@ export const packingImportRequestSchema = z.object({
|
||||
export type PackingImportRequest = z.infer<typeof packingImportRequestSchema>;
|
||||
|
||||
export const packingReorderRequestSchema = z.object({
|
||||
orderedIds: z.array(z.number()),
|
||||
orderedIds: z.array(z.number().int()),
|
||||
});
|
||||
export type PackingReorderRequest = z.infer<typeof packingReorderRequestSchema>;
|
||||
|
||||
@@ -171,7 +171,7 @@ export const packingUpdateBagRequestSchema = z.object({
|
||||
export type PackingUpdateBagRequest = z.infer<typeof packingUpdateBagRequestSchema>;
|
||||
|
||||
export const packingBagMembersRequestSchema = z.object({
|
||||
user_ids: z.array(z.number()),
|
||||
user_ids: z.array(z.number().int()),
|
||||
});
|
||||
export type PackingBagMembersRequest = z.infer<typeof packingBagMembersRequestSchema>;
|
||||
|
||||
@@ -202,7 +202,7 @@ export const packingTemplatesResponseSchema = z.object({
|
||||
export type PackingTemplatesResponse = z.infer<typeof packingTemplatesResponseSchema>;
|
||||
|
||||
export const packingCategoryAssigneesRequestSchema = z.object({
|
||||
user_ids: z.array(z.number()),
|
||||
user_ids: z.array(z.number().int()),
|
||||
});
|
||||
export type PackingCategoryAssigneesRequest = z.infer<typeof packingCategoryAssigneesRequestSchema>;
|
||||
|
||||
|
||||
@@ -287,7 +287,7 @@ export const placeRatingRequestSchema = z.object({
|
||||
export type PlaceRatingRequest = z.infer<typeof placeRatingRequestSchema>;
|
||||
|
||||
export const placeBulkDeleteRequestSchema = z.object({
|
||||
ids: z.array(z.number()),
|
||||
ids: z.array(z.number().int()),
|
||||
});
|
||||
export type PlaceBulkDeleteRequest = z.infer<typeof placeBulkDeleteRequestSchema>;
|
||||
|
||||
@@ -295,7 +295,7 @@ export const placeBulkUpdateRequestSchema = z.object({
|
||||
// Deliberately unbounded: the endpoint answers an empty list with
|
||||
// `{ updated: [], count: 0 }` rather than a 400, so a `.min(1)` here would
|
||||
// change that contract once the body validates through the Zod pipe.
|
||||
ids: z.array(z.number()),
|
||||
ids: z.array(z.number().int()),
|
||||
// null clears the category ("No category"); a number sets it. Optional so the
|
||||
// field can be omitted, but the endpoint requires it to be present to act.
|
||||
category_id: z.number().int().nullable().optional(),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { rowIdInputSchema } from '../common/primitives.schema';
|
||||
import { RESERVATION_STATUSES, RESERVATION_TYPE_KEYS } from './reservation-types';
|
||||
|
||||
import { z } from 'zod';
|
||||
@@ -275,7 +276,7 @@ export type ReservationUpdateRequest = z.infer<typeof reservationUpdateRequestSc
|
||||
|
||||
/** Assign trip members/guests to a reservation (mirrors budget's PUT :id/members). */
|
||||
export const reservationTravelersRequestSchema = z.object({
|
||||
user_ids: z.array(z.number()),
|
||||
user_ids: z.array(z.number().int()),
|
||||
});
|
||||
export type ReservationTravelersRequest = z.infer<typeof reservationTravelersRequestSchema>;
|
||||
|
||||
@@ -284,14 +285,14 @@ export const reservationPositionsRequestSchema = z.object({
|
||||
// validated position items, and an absent value binds NULL (clears the
|
||||
// stored position) — pinned by the server integration suite (RESV-006).
|
||||
positions: z.array(z.object({ id: z.number().int(), day_plan_position: z.number().optional() })),
|
||||
day_id: z.union([z.number().int(), z.string()]).nullable().optional(),
|
||||
day_id: rowIdInputSchema.nullable().optional(),
|
||||
});
|
||||
export type ReservationPositionsRequest = z.infer<typeof reservationPositionsRequestSchema>;
|
||||
|
||||
export const accommodationCreateRequestSchema = z.object({
|
||||
place_id: z.union([z.number().int(), z.string()]),
|
||||
start_day_id: z.union([z.number().int(), z.string()]),
|
||||
end_day_id: z.union([z.number().int(), z.string()]),
|
||||
place_id: rowIdInputSchema,
|
||||
start_day_id: rowIdInputSchema,
|
||||
end_day_id: rowIdInputSchema,
|
||||
check_in: z.string().nullable().optional(),
|
||||
check_in_end: z.string().nullable().optional(),
|
||||
check_out: z.string().nullable().optional(),
|
||||
|
||||
@@ -37,12 +37,12 @@ export const todoUpdateItemRequestSchema = z.object({
|
||||
export type TodoUpdateItemRequest = z.infer<typeof todoUpdateItemRequestSchema>;
|
||||
|
||||
export const todoReorderRequestSchema = z.object({
|
||||
orderedIds: z.array(z.number()),
|
||||
orderedIds: z.array(z.number().int()),
|
||||
});
|
||||
export type TodoReorderRequest = z.infer<typeof todoReorderRequestSchema>;
|
||||
|
||||
export const todoCategoryAssigneesRequestSchema = z.object({
|
||||
user_ids: z.array(z.number()),
|
||||
user_ids: z.array(z.number().int()),
|
||||
});
|
||||
export type TodoCategoryAssigneesRequest = z.infer<typeof todoCategoryAssigneesRequestSchema>;
|
||||
|
||||
|
||||
@@ -34,6 +34,10 @@ describe('tour library contracts (LIB-02)', () => {
|
||||
});
|
||||
expect(tourLibraryQuerySchema.safeParse({ type: 'car' }).success).toBe(false);
|
||||
expect(tourLibraryQuerySchema.safeParse({ trip_id: '0' }).success).toBe(false);
|
||||
// A trip id is the decimal spelling or nothing, as the server's toRowId reads it.
|
||||
for (const spelling of ['0x3', '3e0', '3.0', '+3']) {
|
||||
expect(tourLibraryQuerySchema.safeParse({ trip_id: spelling }).success, spelling).toBe(false);
|
||||
}
|
||||
expect(tourLibraryQuerySchema.safeParse({ sort: 'name' }).success).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { idParamSchema } from '../common/primitives.schema';
|
||||
import { tourListItemSchema, tourTypeKeySchema } from './tours.schema';
|
||||
|
||||
import { z } from 'zod';
|
||||
@@ -18,8 +19,8 @@ export const tourLibraryQuerySchema = z
|
||||
.object({
|
||||
q: z.string().trim().max(100).optional(),
|
||||
type: tourTypeKeySchema.optional(),
|
||||
trip_id: z.coerce.number().int().positive().optional(),
|
||||
exclude_trip_id: z.coerce.number().int().positive().optional(),
|
||||
trip_id: idParamSchema.optional(),
|
||||
exclude_trip_id: idParamSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
export type TourLibraryQuery = z.infer<typeof tourLibraryQuerySchema>;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { rowIdInputSchema } from '../common/primitives.schema';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
@@ -55,12 +57,12 @@ export type VacayUpdateHolidayCalendarRequest = z.infer<typeof vacayUpdateHolida
|
||||
|
||||
export const vacaySetColorRequestSchema = z.object({
|
||||
color: z.string().optional(),
|
||||
target_user_id: z.union([z.number(), z.string()]).optional(),
|
||||
target_user_id: rowIdInputSchema.optional(),
|
||||
});
|
||||
export type VacaySetColorRequest = z.infer<typeof vacaySetColorRequestSchema>;
|
||||
|
||||
export const vacayInviteRequestSchema = z.object({
|
||||
user_id: z.union([z.number().int(), z.string()]),
|
||||
user_id: rowIdInputSchema,
|
||||
});
|
||||
export type VacayInviteRequest = z.infer<typeof vacayInviteRequestSchema>;
|
||||
|
||||
@@ -76,7 +78,7 @@ export type VacayAddYearRequest = z.infer<typeof vacayAddYearRequestSchema>;
|
||||
|
||||
export const vacayToggleEntryRequestSchema = z.object({
|
||||
date: z.string().min(1),
|
||||
target_user_id: z.union([z.number(), z.string()]).optional(),
|
||||
target_user_id: rowIdInputSchema.optional(),
|
||||
// Half vacation days (#552): 0.5 logs a half day, 1 (or omitted) a full day.
|
||||
fraction: z.union([z.literal(0.5), z.literal(1)]).optional(),
|
||||
// Leave type (#1074): 'comp' logs a flex/comp day (does not touch the
|
||||
@@ -111,14 +113,14 @@ export type VacayCompanyHolidayRequest = z.infer<typeof vacayCompanyHolidayReque
|
||||
|
||||
export const vacayUpdateStatsRequestSchema = z.object({
|
||||
vacation_days: z.number().int().optional(),
|
||||
target_user_id: z.union([z.number(), z.string()]).optional(),
|
||||
target_user_id: rowIdInputSchema.optional(),
|
||||
});
|
||||
export type VacayUpdateStatsRequest = z.infer<typeof vacayUpdateStatsRequestSchema>;
|
||||
|
||||
// Read-only calendar sharing (#444/#667): grant another user view access to
|
||||
// your vacation calendar without fusing plans.
|
||||
export const vacayShareRequestSchema = z.object({
|
||||
user_id: z.union([z.number().int(), z.string()]),
|
||||
user_id: rowIdInputSchema,
|
||||
});
|
||||
export type VacayShareRequest = z.infer<typeof vacayShareRequestSchema>;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user