The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(place-contrib): re-check consent inside the catch-up step and never share withdrawn history again
Maurice2ec1199490c3
diff --git a/server/src/db/repositories/PlaceContribOutbox.repository.ts b/server/src/db/repositories/PlaceContribOutbox.repository.tsindex 26d83186a..0cb25b0d3 100644--- a/server/src/db/repositories/PlaceContribOutbox.repository.ts+++ b/server/src/db/repositories/PlaceContribOutbox.repository.ts@@ -27,6 +27,7 @@ export interface PlaceTypedRow {name: string;lat: number | null;lng: number | null;+ address: string | null;osm_id: string | null;website: string | null;phone: string | null;@@ -305,6 +306,7 @@ export class PlaceContribOutboxRepository extends TrekRepository<PlaceContribOut'name','lat','lng',+ 'address','osm_id','website','phone',diff --git a/server/src/nest/place-contrib/place-contrib-backfill.service.ts b/server/src/nest/place-contrib/place-contrib-backfill.service.tsindex 73c56916d..1ff511c20 100644--- a/server/src/nest/place-contrib/place-contrib-backfill.service.ts+++ b/server/src/nest/place-contrib/place-contrib-backfill.service.ts@@ -1,13 +1,14 @@import { PlaceContribOutbox } from '../../db/entities/PlaceContribOutbox.entity';+import type { PlacesContributeBackfill } from '../../db/json-columns';import type { PlaceContribOutboxRepository, PlaceTypedRow } from '../../db/repositories/PlaceContribOutbox.repository';-import { getCountryFromCoords } from '../../utils/country-borders';+import { resolveCountryCodeSync } from '../atlas/atlas-geo';import { logInfo } from '../audit/audit-log.logger';import { inOrder } from '../common/in-order';import { valueHash } from '../common/value-hash';import { UnitOfWork } from '../database/unit-of-work';import { PlaceContribQueue } from './place-contrib-queue';import { PlaceContribSettings } from './place-contrib-settings';-import { contribKeyOf } from './place-contrib.helpers';+import { PLACE_CONTRIB_COLUMN, contribKeyOf } from './place-contrib.helpers';import type { ContribWrite } from './place-contrib.types';import { InjectRepository } from '@mikro-orm/nestjs';import { Injectable } from '@nestjs/common';@@ -18,15 +19,6 @@ const BACKFILL_PAGE = 100;/** The catch-up only adds to the queue while it holds fewer values than this, so new writes never wait behind it. */export const BACKFILL_LOW_WATER = 200;-const COLUMN = {- website: 'website',- phone: 'phone',- email: 'email',- opening_hours: 'opening_hours',- description: 'description',- image: 'image_url',-} as const satisfies Record<PlaceContribField, keyof PlaceTypedRow['place']>;-/*** The catch-up after an agreement: everything users typed into places since* the origin tracking began (TREK 5.1.0) goes out as well, not only what they@@ -70,22 +62,39 @@ export class PlaceContribBackfill {logInfo('Places contribution: the place details typed before the agreement are all queued');return 0;}- const writes = page.map((row) => typedWrite(row, fields)).filter((write) => write.values.length > 0);- await this.uow.transactional(async () => {- await inOrder(writes, (write) => this.queue.put(write, fields, now, { keepQueued: true }));- await this.store.writeBackfill({ fields, afterId: page[page.length - 1].place.id });+ // The reads above ran outside the transaction, so a withdrawal, a switch+ // off or a field change may have committed meanwhile. Only a catch-up that+ // still stands where it was read goes on, and only for fields still on:+ // what was just taken back must not be queued again.+ return this.uow.transactional(async () => {+ if (!sameBackfill(await this.store.backfill(), pending)) return 0;+ const stillActive = await this.store.activeFields();+ const live = fields.filter((field) => stillActive.includes(field));+ if (live.length === 0) return 0;+ const writes = page.map((row) => typedWrite(row, live)).filter((write) => write.values.length > 0);+ await inOrder(writes, (write) => this.queue.put(write, live, now, { keepQueued: true }));+ await this.store.writeBackfill({ fields: live, afterId: page[page.length - 1].place.id });+ return writes.length;});- return writes.length;}}+function sameBackfill(current: PlacesContributeBackfill | null, read: PlacesContributeBackfill): boolean {+ return (+ current !== null &&+ current.afterId === read.afterId &&+ current.fields.length === read.fields.length &&+ current.fields.every((field, i) => field === read.fields[i])+ );+}+/** The values of one place that are still the ones a user typed, for a place the service can key. */function typedWrite(row: PlaceTypedRow, fields: readonly PlaceContribField[]): ContribWrite {const { place } = row;const keyed = contribKeyOf(place.osm_id) !== null;const values = row.typed.flatMap(({ field, value_hash }) => {const known = fields.find((candidate) => candidate === field);- const value = known ? place[COLUMN[known]] : null;+ const value = known ? place[PLACE_CONTRIB_COLUMN[known]] : null;if (!keyed || !known || typeof value !== 'string' || value.trim() === '') return [];return valueHash(value) === value_hash ? [{ field: known, value }] : [];});@@ -95,8 +104,8 @@ function typedWrite(row: PlaceTypedRow, fields: readonly PlaceContribField[]): Cname: place.name,lat: place.lat,lng: place.lng,- country:- values.length > 0 && place.lat !== null && place.lng !== null ? getCountryFromCoords(place.lat, place.lng) : null,+ // Resolved the way a save resolves it, so a place goes out with the same country either way.+ country: values.length > 0 ? resolveCountryCodeSync(place) : null,values,dropped: [],};diff --git a/server/src/nest/place-contrib/place-contrib-sender.service.ts b/server/src/nest/place-contrib/place-contrib-sender.service.tsindex ba2719064..d75bde230 100644--- a/server/src/nest/place-contrib/place-contrib-sender.service.ts+++ b/server/src/nest/place-contrib/place-contrib-sender.service.ts@@ -23,6 +23,7 @@ import {PLACES_PER_RUN,} from './place-contrib.constants';import {+ PLACE_CONTRIB_COLUMN,UPLOADED_IMAGE_PREFIX,baseHashOf,dayOf,@@ -336,7 +337,7 @@ function staleReason(/** The column a field is stored in. */function columnOf(row: OutboxCurrentRow, field: PlaceContribField): string | null {- return field === 'image' ? row.image_url : row[field];+ return row[PLACE_CONTRIB_COLUMN[field]];}/** What the index serves for a field, in the form a queued value has; null when it serves nothing. */diff --git a/server/src/nest/place-contrib/place-contrib.helpers.ts b/server/src/nest/place-contrib/place-contrib.helpers.tsindex b619c6ea6..f3e8a374e 100644--- a/server/src/nest/place-contrib/place-contrib.helpers.ts+++ b/server/src/nest/place-contrib/place-contrib.helpers.ts@@ -17,6 +17,21 @@ const OSM_ID = /^(node|way|relation):(\d{1,15})$/;/** Where the place pictures users upload live (the places domain's `placeImageUrl`). */export const UPLOADED_IMAGE_PREFIX = '/uploads/places/';+/**+ * The places column each field is stored in. The origin hash, the catch-up+ * and the sender all read a field through this one map: a value is shared+ * only while the column's hash matches the origin, so two copies drifting+ * apart would skip a field without a word.+ */+export const PLACE_CONTRIB_COLUMN = {+ website: 'website',+ phone: 'phone',+ email: 'email',+ opening_hours: 'opening_hours',+ description: 'description',+ image: 'image_url',+} as const satisfies Record<PlaceContribField, string>;+/*** The key the service files a place under: `gers:<id>` for a place from the* TREK index, `osm:<type>/<id>` for an OpenStreetMap element. A place withoutdiff --git a/server/src/nest/place-contrib/place-contrib.service.ts b/server/src/nest/place-contrib/place-contrib.service.tsindex 599b71662..bde25f5bb 100644--- a/server/src/nest/place-contrib/place-contrib.service.ts+++ b/server/src/nest/place-contrib/place-contrib.service.ts@@ -99,7 +99,8 @@ export class PlaceContribService {if (!anyField(request.fields)) throw badRequest('Pick at least one field to share', { reason: 'no_field' });// A new agreement is a fresh start: a pause over a key or a wait the// service asked for is tried again on the next run, and what users- // typed before the agreement goes out too, caught up page by page.+ // typed before the agreement goes out too, caught up page by page,+ // withdrawn fields included, since the admin agreed to that anew.await this.uow.transactional(async () => {await this.store.writeConsent({enabled: true,@@ -177,9 +178,13 @@ export class PlaceContribService {reason: 'withdraw_all',}),);- // Everything taken back stays back: the catch-up does not send it again.+ // Everything taken back stays back: the catch-up running now ends, and a+ // field switched on later under this agreement does not catch up either.+ // Only a new agreement shares the earlier values again.const cleared = await this.uow.transactional(async () => {await this.log.insertLines(lines);+ const consent = await this.store.consent();+ await this.store.writeConsent({ ...consent, withdrawnFields: [...PLACE_CONTRIB_FIELDS] });await this.store.writeBackfill(null);return this.outbox.deleteAll();});@@ -235,17 +240,33 @@ export class PlaceContribService {if (!anyField(fields)) throw badRequest('Pick at least one field to share', { reason: 'no_field' });const removed = PLACE_CONTRIB_FIELDS.filter((field) => consent.fields[field] && !fields[field]);const added = PLACE_CONTRIB_FIELDS.filter((field) => !consent.fields[field] && fields[field]);- const catchUp = added.length > 0 && consent.includesEarlier === true;+ const withdrawn = PLACE_CONTRIB_FIELDS.filter(+ (field) => consent.withdrawnFields?.includes(field) || (opts.withdraw && removed.includes(field)),+ );+ // A field switched on catches up too, under an agreement that said so,+ // unless its earlier values were withdrawn: those stay taken back.+ const earlier = consent.includesEarlier === true ? added.filter((field) => !withdrawn.includes(field)) : [];+ const catchUp = earlier.length > 0;await this.uow.transactional(async () => {- await this.store.writeConsent({ ...consent, fields, ...opts.decided });+ await this.store.writeConsent({+ ...consent,+ fields,+ ...opts.decided,+ ...(withdrawn.length > 0 ? { withdrawnFields: withdrawn } : {}),+ });await this.outbox.deleteFields(removed);- // A field switched on catches up too, under an agreement that said so.+ const pending = await this.store.backfill();+ const pendingFields = (pending?.fields ?? []).filter((field) => !withdrawn.includes(field));// The catch-up keeps one position, so it starts over for every field it// still had to do; what went out already is answered as a duplicate.if (catchUp) {- const pending = (await this.store.backfill())?.fields ?? [];- const catchUpFields = PLACE_CONTRIB_FIELDS.filter((field) => added.includes(field) || pending.includes(field));+ const catchUpFields = PLACE_CONTRIB_FIELDS.filter(+ (field) => earlier.includes(field) || pendingFields.includes(field),+ );await this.store.writeBackfill({ fields: catchUpFields, afterId: 0 });+ } else if (pending && pendingFields.length < pending.fields.length) {+ // A field withdrawn while its catch-up was still under way leaves it.+ await this.store.writeBackfill(pendingFields.length > 0 ? { ...pending, fields: pendingFields } : null);}});if (catchUp) this.job.sendSoon();diff --git a/server/src/nest/places/place-origins.helpers.ts b/server/src/nest/places/place-origins.helpers.tsindex 6e941ff0e..03a12f738 100644--- a/server/src/nest/places/place-origins.helpers.ts+++ b/server/src/nest/places/place-origins.helpers.ts@@ -1,6 +1,7 @@import { PLACE_DETAILS_CACHE_PAYLOAD } from '../../db/json-columns';import type { CachedProviderPayload, PlaceShareableRow } from '../../db/repositories/PlaceFieldOrigin.repository';import { decodeJson } from '../../utils/json-column';+import { PLACE_CONTRIB_COLUMN } from '../place-contrib/place-contrib.helpers';import {PLACE_CONTRIB_FIELDS,normalizePlaceWebsite,@@ -28,20 +29,11 @@ export interface ProviderValue {origin: PlaceFieldOrigin;}-const COLUMN: Record<PlaceContribField, keyof PlaceShareableRow> = {- website: 'website',- phone: 'phone',- email: 'email',- opening_hours: 'opening_hours',- description: 'description',- image: 'image_url',-};-/** The place's shareable values as stored, an empty text read as none. */export function snapshotOf(row: PlaceShareableRow): OriginSnapshot {const snapshot = {} as OriginSnapshot;for (const field of PLACE_CONTRIB_FIELDS) {- const value = row[COLUMN[field]];+ const value = row[PLACE_CONTRIB_COLUMN[field]];snapshot[field] = typeof value === 'string' && value.trim() !== '' ? value : null;}return snapshot;diff --git a/server/tests/unit/nest/place-contrib/place-contrib-backfill.service.test.ts b/server/tests/unit/nest/place-contrib/place-contrib-backfill.service.test.tsindex 0ac7410c9..275535f33 100644--- a/server/tests/unit/nest/place-contrib/place-contrib-backfill.service.test.ts+++ b/server/tests/unit/nest/place-contrib/place-contrib-backfill.service.test.ts@@ -11,6 +11,7 @@ import type { AppEnv } from '../../../../src/app-config';import { PlaceContribLog } from '../../../../src/db/entities/PlaceContribLog.entity';import { PlaceContribOutbox } from '../../../../src/db/entities/PlaceContribOutbox.entity';import { PlaceFieldOrigin } from '../../../../src/db/entities/PlaceFieldOrigin.entity';+import type { PlaceContribOutboxRepository } from '../../../../src/db/repositories/PlaceContribOutbox.repository';import { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';import { servicesConfig } from '../../../../src/nest/app-config/tokens';import { valueHash } from '../../../../src/nest/common/value-hash';@@ -114,7 +115,15 @@ async function agree(fields: PlaceContribFieldSwitches = ALL): Promise<void> {/** A place with a website, whose origin is recorded as `origin` for the value given (the current one by default). */async function placeWith(- opts: { osmId?: string | null; origin?: string; typed?: string; website?: string } = {},+ opts: {+ osmId?: string | null;+ origin?: string;+ typed?: string;+ website?: string;+ lat?: number | null;+ lng?: number | null;+ address?: string;+ } = {},): Promise<number> {const website = opts.website ?? 'https://cafe-luna.de';const { user } = await makeUser(orm());@@ -123,8 +132,9 @@ async function placeWith(name: 'Café Luna',osm_id: opts.osmId === undefined ? GERS : opts.osmId,website,- lat: 54.08,- lng: 12.13,+ lat: opts.lat === undefined ? 54.08 : opts.lat,+ lng: opts.lng === undefined ? 12.13 : opts.lng,+ address: opts.address ?? null,});await insertRow(orm(), PlaceFieldOrigin, {place: id,@@ -135,6 +145,17 @@ async function placeWith(return id;}+/** Runs `meanwhile` once the step has read its page, before it queues anything. */+function betweenReadAndWrite(meanwhile: () => Promise<unknown>): void {+ const outbox = (backfill() as unknown as { outbox: PlaceContribOutboxRepository }).outbox;+ const read = outbox.typedAfter.bind(outbox);+ vi.spyOn(outbox, 'typedAfter').mockImplementationOnce(async (...args) => {+ const page = await read(...args);+ await meanwhile();+ return page;+ });+}+const queued = async () =>(await findRows(orm(), PlaceContribOutbox, {})).map((row) => ({ place: row.place_id, field: row.field }));@@ -266,4 +287,96 @@ describe('PlaceContribBackfill', () => {await service().decide(ADMIN, { action: 'decline', termsVersion: PLACE_CONTRIB_TERMS_VERSION }, NOW);expect(await store().backfill()).toBeNull();});++ it('PCB-011: a withdrawal that commits while a step reads its page brings nothing back', async () => {+ await placeWith();+ await agree();+ betweenReadAndWrite(() => service().withdrawAll(NOW));+ expect(await backfill().step(NOW)).toBe(0);+ expect(await queued()).toEqual([]);+ expect(await store().backfill()).toBeNull();+ });++ it('PCB-012: switching off while a step reads its page queues nothing, and leaves the catch-up ended', async () => {+ await placeWith();+ await agree();+ betweenReadAndWrite(() => service().decide(ADMIN, { action: 'off' }, NOW));+ expect(await backfill().step(NOW)).toBe(0);+ expect(await queued()).toEqual([]);+ expect(await store().backfill()).toBeNull();+ });++ it('PCB-013: a field switched off while a step reads its page is not queued', async () => {+ const id = await placeWith();+ await agree();+ betweenReadAndWrite(() => service().decide(ADMIN, { action: 'fields', fields: { ...ALL, website: false } }, NOW));+ expect(await backfill().step(NOW)).toBe(0);+ expect(await queued()).toEqual([]);+ expect(await store().backfill()).toEqual({+ fields: ['phone', 'email', 'opening_hours', 'description', 'image'],+ afterId: id,+ });+ });++ it('PCB-014: after withdrawing everything, switching a field off and on again does not share its history', async () => {+ await placeWith();+ await agree();+ await service().withdrawAll(NOW);+ await service().decide(ADMIN, { action: 'fields', fields: { ...ALL, website: false } }, NOW);+ await service().decide(ADMIN, { action: 'fields', fields: ALL }, NOW);+ expect(await store().backfill()).toBeNull();+ expect(await backfill().step(NOW)).toBe(0);+ expect(await queued()).toEqual([]);++ // A new agreement shares the earlier values again.+ await agree();+ expect((await store().consent()).withdrawnFields).toBeUndefined();+ expect(await backfill().step(NOW)).toBe(1);+ });++ it('PCB-015: a field withdrawn on its own does not catch up when switched on again, another field still does', async () => {+ await agree({ ...ALL, phone: false });+ await store().writeBackfill(null);+ await service().decide(+ ADMIN,+ { action: 'fields', fields: { ...ALL, phone: false, website: false }, withdraw: true },+ NOW,+ );+ expect((await store().consent()).withdrawnFields).toEqual(['website']);+ await service().decide(ADMIN, { action: 'fields', fields: ALL }, NOW);+ expect(await store().backfill()).toEqual({ fields: ['phone'], afterId: 0 });+ });++ it('PCB-016: a field withdrawn while its catch-up is under way leaves the catch-up', async () => {+ await agree();+ await store().writeBackfill({ fields: ['website', 'email'], afterId: 7 });+ await service().decide(ADMIN, { action: 'fields', fields: { ...ALL, website: false }, withdraw: true }, NOW);+ expect(await store().backfill()).toEqual({ fields: ['email'], afterId: 7 });++ await service().decide(+ ADMIN,+ { action: 'fields', fields: { ...ALL, website: false, email: false }, withdraw: true },+ NOW,+ );+ expect(await store().backfill()).toBeNull();+ });++ it('PCB-017: sending that stops being possible while a step reads its page queues nothing, and the catch-up waits', async () => {+ await placeWith();+ await agree();+ betweenReadAndWrite(async () => client.hasKey.mockReturnValue(false));+ expect(await backfill().step(NOW)).toBe(0);+ expect(await queued()).toEqual([]);+ expect(await store().backfill()).toEqual({+ fields: ['website', 'phone', 'email', 'opening_hours', 'description', 'image'],+ afterId: 0,+ });+ });++ it('PCB-018: the country comes from the address when the coordinates do not give one, as on a save', async () => {+ await placeWith({ lat: null, lng: null, address: 'Lange Straße 1, 18055 Rostock, Germany' });+ await agree();+ expect(await backfill().step(NOW)).toBe(1);+ expect((await findRows(orm(), PlaceContribOutbox, {})).map((row) => row.country)).toEqual(['DE']);+ });});diff --git a/server/tests/unit/nest/place-contrib/place-contrib.service.test.ts b/server/tests/unit/nest/place-contrib/place-contrib.service.test.tsindex 14d273422..ca6f24c96 100644--- a/server/tests/unit/nest/place-contrib/place-contrib.service.test.ts+++ b/server/tests/unit/nest/place-contrib/place-contrib.service.test.ts@@ -273,6 +273,7 @@ describe('the admin state and the decisions', () => {expect((await findRows(orm(), PlaceContribOutbox, {})).map((row) => row.field)).toEqual(['website']);expect(client.withdraw).toHaveBeenCalledWith({ field: 'phone' });expect(await store().activeFields()).not.toContain('phone');+ expect((await store().consent()).withdrawnFields).toEqual(['phone']);});it('PCS-017: changing the switches needs a standing agreement', async () => {@@ -428,6 +429,7 @@ describe('withdrawAll and the log', () => {body: { error: 'The TREK Places API did not confirm the withdrawal', reason: 'TimeoutError' },});expect(await countRows(orm(), PlaceContribOutbox)).toBe(1);+ expect((await store().consent()).withdrawnFields).toBeUndefined();});it('PCS-042: the log pages newest first and filters by result and field', async () => {@@ -456,6 +458,17 @@ describe('withdrawAll and the log', () => {expect((await service().logPage({ page: 1, perPage: 50, result: 'accepted' })).total).toBe(0);expect((await service().state(ADMIN, NOW)).counts.withheld).toBe(2);});++ it('PCS-043: a confirmed withdrawal keeps the agreement but marks every field withdrawn', async () => {+ await agree();+ await service().withdrawAll(NOW);+ expect(await store().consent()).toMatchObject({+ enabled: true,+ decision: 'agreed',+ includesEarlier: true,+ withdrawnFields: ['website', 'phone', 'email', 'opening_hours', 'description', 'image'],+ });+ });});function outboxRow(placeId: number, field: string) {diff --git a/shared/src/place/place-contrib.schema.ts b/shared/src/place/place-contrib.schema.tsindex cf5c2257f..bac65b498 100644--- a/shared/src/place/place-contrib.schema.ts+++ b/shared/src/place/place-contrib.schema.ts@@ -114,6 +114,13 @@ export const placeContribConsentSchema = z.object({* later catch up too. Absent on an agreement from 5.1.0.*/includesEarlier: z.boolean().optional(),+ /**+ * The fields an admin withdrew under this agreement (all of them after+ * "withdraw everything"). Switching one of them on again shares what users+ * type from then on, not the history taken back; a new agreement clears it.+ * Absent until something was withdrawn.+ */+ withdrawnFields: z.array(placeContribFieldSchema).optional(),});export type PlaceContribConsent = z.infer<typeof placeContribConsentSchema>;