feat: six community requests — import dedup, accommodations in the feed, OAuth refresh race, visited-from-trip, journal jumps, phone packing rows (#1915)

* fix(places): match imports on the provider id so renamed places are not duplicated

Re-importing a Google Maps list duplicated every place the user had renamed.
buildDedupSet only ever collected names and, for unnamed places, coordinates,
and isPlaceDuplicate returns on the name before it reaches the coordinate
fallback, so a renamed place was findable by neither. The ids were stored all
along, and even backfilled onto matched places, they were simply never read.

Match on google_place_id / google_ftid / osm_id first, keeping name and
coordinates in their old roles below it. Widening the coordinate check instead
would have merged the restaurant and the bar in the same building.

The collection copy carried a hand-mirrored port of the same predicate; it now
uses the shared helpers and gets the fix with them.

Closes #1550

* feat(calendar): put accommodations into the subscribed feed as all-day stays

A hotel keeps its dates on the linked stay, not on the reservation: the booking
form writes reservation_time = NULL for type 'hotel', and day_accommodations
carries start day, end day and the check-in/out clock. The feed only ever read
the reservation, so a stay showed up once on the arrival day at best, and not at
all when it came from the booking form.

Join the stay in and emit the reservation as an all-day range over every night,
which also keeps it correct when days are reordered later — the dates now come
from the day rows rather than from the copy stamped at creation time. Check-in
and check-out become their own timed events when the stay records a clock,
because an all-day event cannot carry the time you actually need reminding of.
The check-in window, when set, becomes that event's DTEND.

Closes #1586

* fix(oauth): treat a concurrent refresh as a race, not as a stolen token

Refresh rotation is a race by construction. Several MCP clients share one
refresh token, both post it within the same second, and the loser was read as a
replay: chain revoked, MCP sessions torn down, browser window asking to log in
again. That is the daily re-authentication people were seeing, not a short
lifetime — access tokens last an hour and refresh tokens roll for thirty days.

A revoked refresh token now only counts as a replay once it is outside a
30-second grace window, and only when the rotation that revoked it left a
successor still alive. Inside the window the caller gets its own pair branched
off the same parent, so both clients walk away with a working token. Explicit
revocation leaves no live successor and a chain killed by a real replay has none
either, so neither can slip through the window.

Closes #1007

* feat(collections): mark a place visited from the trip it belongs to

A place saved in several lists had to be opened in each of them to say you had
been there, which is the wrong way round: you find out you have been somewhere
while looking at the trip, not while browsing the library.

The save picker now shows each list's own status and cycles it in place, with one
action for "visited, wherever this is saved". The planner's selection bar and the
mobile bulk toolbar carry the same thing for a whole selection — select all, one
tap, done. Matching happens on the server with the signals findMembership already
uses plus the source link a place saved from this trip carries, so a copy renamed
inside a list is still found. Lists you may only read are skipped rather than
refused; a shared list you cannot edit should not stop you marking your own.

Closes #1469

* feat(journey): jump to the top or back to the last entry in a long journal

Everything that adds to a journal sits at the top — the entry button, the
gallery upload — and where you left off sits at the bottom, so adding one photo
to a long journey meant scrolling the whole way twice.

Two buttons float over the middle of the feed, clear of the Add Entry column on
one side and the reorder arrows on the other, each appearing only when there is
more than a screenful to travel in that direction. They live in a zero-height
sticky box so they take no layout space and never push the timeline around.
While in the header, the status pill also picks up the height of the round
buttons beside it.

Closes #1088

* fix(packing): give the item name the row back on phones

An item name had roughly a third of the row to itself: a spelled-out sharing
sentence, an empty weight column and two round action buttons took the rest, so
anything longer than a word was cut off.

Sharing is now the icon it always was next to a label rather than a sentence in
the layout, an unset weight prints nothing instead of a dash, and edit/delete
sit behind one overflow button that opens the same inline menu the bag picker
already uses. The to-do list needed none of this — it wraps its chips onto a
second line already.

Closes #1525

* docs(wiki): cover the six community changes

- Calendar feeds: accommodations as an all-day range plus check-in/check-out
- Collections: setting the visited status from a trip, and how places are matched
- Journey: the jump buttons on a long journal
- Packing: what the phone row keeps and what moved behind the overflow button
- Places: re-importing a list no longer duplicates renamed places
- MCP setup: the rotation race no longer ends an OAuth session

* test(collections): assert the stored status instead of a private method

tests/ sits outside the build tsconfig, so reaching into getPlaceById only
showed up in the dedicated typecheck step. Reading the row is the better
assertion anyway — it pins what was persisted, not what a getter returns.
This commit is contained in:
Maurice
2026-08-12 17:43:22 +02:00
committed by GitHub
parent 813b9886b3
commit df3edac7b9
82 changed files with 1721 additions and 105 deletions
+35
View File
@@ -291,6 +291,41 @@ describe('Collections e2e (real auth guard + real service + temp SQLite)', () =>
expect(imported.body.skipped.map((s: { name: string }) => s.name)).toEqual(['Musée Rodin']);
});
// ── bulk visited (#1469) ─────────────────────────────────────────────────
it('COLLECTIONS-E2E-073: a trip selection can be marked visited in every list holding it', async () => {
const paris = (await request(server).post('/api/addons/collections').set('Cookie', sessionCookie(ownerId)).send({ name: 'Paris' })).body;
const museums = (await request(server).post('/api/addons/collections').set('Cookie', sessionCookie(ownerId)).send({ name: 'Museums' })).body;
const trip = createTrip(db as never, ownerId);
const louvre = createPlace(db as never, trip.id, { name: 'Louvre', lat: 48.8606, lng: 2.3376 });
for (const col of [paris, museums]) {
await request(server).post('/api/addons/collections/places/from-trip')
.set('Cookie', sessionCookie(ownerId)).send({ collection_id: col.id, source_trip_id: trip.id, source_place_id: louvre.id });
}
const res = await request(server).post('/api/addons/collections/places/status-from-trip')
.set('Cookie', sessionCookie(ownerId)).send({ trip_id: trip.id, place_ids: [louvre.id], status: 'visited' });
expect(res.status).toBe(200);
expect(res.body).toEqual({ updated: 2, places: 1 });
// …and the dialog's per-list view now says so.
const membership = await request(server).get('/api/addons/collections/membership')
.query({ lat: 48.8606, lng: 2.3376 }).set('Cookie', sessionCookie(ownerId));
expect(membership.body.lists.map((l: { status: string }) => l.status)).toEqual(['visited', 'visited']);
});
it('COLLECTIONS-E2E-074: status-many refuses a list the caller may only read', async () => {
const col = (await request(server).post('/api/addons/collections').set('Cookie', sessionCookie(ownerId)).send({ name: 'Shared' })).body;
await request(server).post('/api/addons/collections/invite').set('Cookie', sessionCookie(ownerId)).send({ collection_id: col.id, user_id: otherId, role: 'viewer' });
await request(server).post('/api/addons/collections/invite/accept').set('Cookie', sessionCookie(otherId)).send({ collection_id: col.id });
const place = (await request(server).post('/api/addons/collections/places')
.set('Cookie', sessionCookie(ownerId)).send({ collection_id: col.id, name: 'Louvre' })).body.place;
const res = await request(server).post('/api/addons/collections/places/status-many')
.set('Cookie', sessionCookie(otherId)).send({ ids: [place.id], status: 'visited' });
expect(res.status).toBe(403);
});
it('COLLECTIONS-E2E-072: a trip the caller cannot see is a 404, and so is a foreign list', async () => {
const col = (await request(server).post('/api/addons/collections').set('Cookie', sessionCookie(ownerId)).send({ name: 'Private' })).body;
const foreignTrip = createTrip(db as never, otherId);
+53
View File
@@ -1303,6 +1303,17 @@ describe('M7 — Cookie-only auth on privileged OAuth endpoints', () => {
});
describe('C3 — Refresh token replay detection', () => {
/**
* Push a rotation out of the concurrency grace window (#1007) so a replay
* below still describes theft — a token used minutes later — rather than two
* clients refreshing at the same moment.
*/
function agePastGrace(rawRefreshToken: string) {
const hash = crypto.createHash('sha256').update(rawRefreshToken).digest('hex');
const old = new Date(Date.now() - 5 * 60 * 1000).toISOString().replace('T', ' ').slice(0, 19);
testDb.prepare('UPDATE oauth_tokens SET revoked_at = ? WHERE refresh_token_hash = ?').run(old, hash);
}
it('OAUTH-SEC-012 — replaying a rotated (old) refresh token returns invalid_grant', async () => {
const { user } = createUser(testDb);
const r = createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
@@ -1340,6 +1351,7 @@ describe('C3 — Refresh token replay detection', () => {
expect(t2.status).toBe(200);
// Replay the original (now rotated/revoked) refresh token — must be rejected
agePastGrace(originalRefreshToken);
const t3 = await request(app).post('/oauth/token').send({
grant_type: 'refresh_token',
client_id: r.client!.client_id,
@@ -1350,6 +1362,46 @@ describe('C3 — Refresh token replay detection', () => {
expect(t3.body.error).toBe('invalid_grant');
});
it('OAUTH-SEC-012b — two clients refreshing the same token at once both keep working (#1007)', async () => {
const { user } = createUser(testDb);
const r = createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { verifier, challenge } = makePkce();
const code = createAuthCode({
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
const t1 = await request(app).post('/oauth/token').send({
grant_type: 'authorization_code',
client_id: r.client!.client_id,
client_secret: r.client!.client_secret,
code,
redirect_uri: 'https://app.example.com/cb',
code_verifier: verifier,
});
const shared = t1.body.refresh_token;
const refresh = () => request(app).post('/oauth/token').send({
grant_type: 'refresh_token',
client_id: r.client!.client_id,
client_secret: r.client!.client_secret,
refresh_token: shared,
});
// The second MCP session posts the token its sibling has just spent.
const first = await refresh();
const second = await refresh();
expect(first.status).toBe(200);
expect(second.status).toBe(200);
expect(second.body.refresh_token).not.toBe(first.body.refresh_token);
});
it('OAUTH-SEC-013 — replaying old token also invalidates the new chain', async () => {
const { user } = createUser(testDb);
const r = createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
@@ -1385,6 +1437,7 @@ describe('C3 — Refresh token replay detection', () => {
const newRefreshToken = t2.body.refresh_token;
// Replay original — triggers chain revocation
agePastGrace(originalRefreshToken);
await request(app).post('/oauth/token').send({
grant_type: 'refresh_token',
client_id: r.client!.client_id,
@@ -669,6 +669,143 @@ describe('exportICS', () => {
});
});
// ── Accommodations in the feed (#1586) ───────────────────────────────────────
describe('accommodations', () => {
/** A stay with its linked hotel reservation, the shape createAccommodation writes. */
const createStay = (
tripId: number,
opts: {
start: string | null;
end?: string | null;
check_in?: string | null;
check_in_end?: string | null;
check_out?: string | null;
title?: string;
withReservation?: boolean;
lat?: number;
lng?: number;
},
) => {
const place = createPlace(testDb, tripId, {
name: opts.title ?? 'Hotel Bellevue',
lat: opts.lat ?? 48.8566,
lng: opts.lng ?? 2.3522,
});
testDb.prepare('UPDATE places SET address = ? WHERE id = ?').run('1 Rue de Rivoli', place.id);
const startDay = createDay(testDb, tripId, { date: opts.start ?? undefined });
const endDay = opts.end === undefined
? startDay
: createDay(testDb, tripId, { date: opts.end ?? undefined });
const stayId = testDb.prepare(`
INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_in_end, check_out)
VALUES (?, ?, ?, ?, ?, ?, ?)
`).run(
tripId, place.id, startDay.id, endDay.id,
opts.check_in ?? null, opts.check_in_end ?? null, opts.check_out ?? null,
).lastInsertRowid as number;
if (opts.withReservation !== false) {
testDb.prepare(`
INSERT INTO reservations (trip_id, day_id, title, reservation_time, status, type, accommodation_id)
VALUES (?, ?, ?, ?, 'confirmed', 'hotel', ?)
`).run(tripId, startDay.id, opts.title ?? 'Hotel Bellevue', opts.start, String(stayId));
}
return { stayId, placeId: place.id };
};
it('CAL-025: a stay covers every night as one all-day event, not just the arrival day', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Paris' });
createStay(trip.id, { start: '2026-07-07', end: '2026-07-12' });
const { ics } = svc.exportICS(trip.id);
// DTEND is exclusive, so the day after checkout.
expect(ics).toContain('DTSTART;VALUE=DATE:20260707\r\nDTEND;VALUE=DATE:20260713');
expect(ics).toContain('SUMMARY:Hotel Bellevue');
});
it('CAL-026: check-in and check-out become their own timed events in the stay zone', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Paris' });
createStay(trip.id, {
start: '2026-07-07', end: '2026-07-12',
check_in: '15:00', check_in_end: '22:00', check_out: '11:00',
});
const { ics } = svc.exportICS(trip.id);
expect(ics).toContain('SUMMARY:Check-in: Hotel Bellevue');
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260707T150000');
expect(ics).toContain('DTEND;TZID=Europe/Paris:20260707T220000');
expect(ics).toContain('SUMMARY:Check-out: Hotel Bellevue');
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260712T110000');
expect(ics).toContain('LOCATION:1 Rue de Rivoli');
expect(ics).toContain('BEGIN:VTIMEZONE\r\nTZID:Europe/Paris');
});
it('CAL-027: a stay without times emits the all-day range and nothing else', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Paris' });
createStay(trip.id, { start: '2026-07-07', end: '2026-07-12' });
const { ics } = svc.exportICS(trip.id);
expect(ics).not.toContain('Check-in');
expect(ics).not.toContain('Check-out');
});
it('CAL-028: a stay whose end day lost its date falls back to the arrival day', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Paris' });
createStay(trip.id, { start: '2026-07-07', end: null, check_out: '11:00' });
const { ics } = svc.exportICS(trip.id);
expect(ics).toContain('DTSTART;VALUE=DATE:20260707\r\nDTEND;VALUE=DATE:20260708');
expect(ics).toContain('SUMMARY:Check-out: Hotel Bellevue');
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20260707T110000');
});
it('CAL-029: a stay with no reservation still contributes its check-in event', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Paris' });
createStay(trip.id, { start: '2026-07-07', end: '2026-07-09', check_in: '15:00', withReservation: false });
const { ics } = svc.exportICS(trip.id);
expect(ics).toContain('SUMMARY:Check-in: Hotel Bellevue');
// No stay event without a reservation to carry it — the accommodation itself
// has no title, notes or confirmation of its own to show.
expect(ics).not.toContain('DTEND;VALUE=DATE:20260710');
});
it('CAL-030: a hotel reservation without a stay keeps its old single-day event', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Paris' });
const reservation = createReservation(testDb, trip.id, { title: 'Airbnb', type: 'hotel' });
testDb.prepare('UPDATE reservations SET reservation_time=? WHERE id=?').run('2026-07-07', reservation.id);
const { ics } = svc.exportICS(trip.id);
expect(ics).toContain('DTSTART;VALUE=DATE:20260707');
expect(ics).not.toContain('DTEND;VALUE=DATE');
});
it('CAL-031: a dateless stay is skipped instead of emitting a broken event', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Someday' });
createStay(trip.id, { start: null, end: null, check_in: '15:00', check_out: '11:00' });
const { ics } = svc.exportICS(trip.id);
expect(ics).not.toContain('Check-in');
expect(ics).not.toContain('Check-out');
expect(ics).not.toContain('DTSTART;VALUE=DATE:');
});
});
describe('folded quirk branches', () => {
it('TRIP-SVC-048: exportICS renders untimed/notes all-day summaries, multi-leg routes, endpoint routes and train/location fields', () => {
const { user } = createUser(testDb);
@@ -853,3 +853,109 @@ describe('atomic bulk writes (post-fold quirk fixes)', () => {
expect(broadcastToUser).toHaveBeenCalledWith(u.id, expect.objectContaining({ type: 'collections:updated' }), 'sock-2');
});
});
// ── Bulk "visited" from a trip (#1469) ───────────────────────────────────────
/** The stored status of a saved place, read straight off the row. */
function statusOf(placeId: number): string {
return (testDb.prepare('SELECT status FROM collection_places WHERE id = ?').get(placeId) as { status: string }).status;
}
describe('bulk status', () => {
it('COLLECTIONS-SVC-093: setStatusMany writes one status across lists and counts only real changes', () => {
const u = createUser(testDb).user;
const a = svc.createCollection(u.id, { name: 'A' });
const b = svc.createCollection(u.id, { name: 'B' });
const pa = svc.savePlace(u.id, { collection_id: a.id, name: 'Louvre' }).place!;
const pb = svc.savePlace(u.id, { collection_id: b.id, name: 'Louvre' }).place!;
svc.setStatus(u.id, pb.id, 'visited');
// pb is already visited, so only pa is a change.
expect(svc.setStatusMany(u.id, [pa.id, pb.id], 'visited')).toEqual({ updated: 1 });
expect(statusOf(pa.id)).toBe('visited');
expect(svc.setStatusMany(u.id, [pa.id, pb.id], 'visited')).toEqual({ updated: 0 });
});
it('COLLECTIONS-SVC-094: setStatusMany is all-or-nothing — a read-only list stops the batch', () => {
const owner = createUser(testDb).user;
const viewer = createUser(testDb).user;
const mine = svc.createCollection(viewer.id, { name: 'Mine' });
const readonly = svc.createCollection(owner.id, { name: 'Shared' });
addMember(readonly.id, viewer.id, 'viewer');
const p1 = svc.savePlace(viewer.id, { collection_id: mine.id, name: 'Louvre' }).place!;
const p2 = svc.savePlace(owner.id, { collection_id: readonly.id, name: 'Louvre' }).place!;
expect(() => svc.setStatusMany(viewer.id, [p1.id, p2.id], 'visited')).toThrow('You have read-only access to this list');
expect(statusOf(p1.id)).toBe('idea');
});
it('COLLECTIONS-SVC-095: setStatusFromTrip marks every saved copy of the selected trip places', () => {
const u = createUser(testDb).user;
createCategory(testDb);
const trip = createTrip(testDb, u.id);
const louvre = createPlace(testDb, trip.id, { name: 'Louvre', lat: 48.8606, lng: 2.3376 });
const orsay = createPlace(testDb, trip.id, { name: 'Orsay', lat: 48.86, lng: 2.3266 });
const a = svc.createCollection(u.id, { name: 'Paris' });
const b = svc.createCollection(u.id, { name: 'Museums' });
svc.saveFromTripPlace(u.id, a.id, trip.id, louvre.id);
svc.saveFromTripPlace(u.id, b.id, trip.id, louvre.id);
svc.saveFromTripPlace(u.id, a.id, trip.id, orsay.id);
expect(svc.setStatusFromTrip(u.id, trip.id, [louvre.id], 'visited')).toEqual({ updated: 2, places: 1 });
const statuses = testDb.prepare('SELECT status FROM collection_places ORDER BY id').all() as { status: string }[];
expect(statuses.map(s => s.status)).toEqual(['visited', 'visited', 'idea']);
});
it('COLLECTIONS-SVC-096: a place renamed in the list is still found by its source link', () => {
const u = createUser(testDb).user;
createCategory(testDb);
const trip = createTrip(testDb, u.id);
const place = createPlace(testDb, trip.id, { name: 'Trattoria da Enzo', lat: 41.88, lng: 12.47 });
const col = svc.createCollection(u.id, { name: 'Rome' });
const saved = svc.saveFromTripPlace(u.id, col.id, trip.id, place.id).place!;
// Renamed on both sides, and moved far enough that coordinates cannot match.
svc.updatePlace(u.id, saved.id, { name: 'Dinner spot', lat: 45, lng: 9 });
testDb.prepare('UPDATE places SET name = ? WHERE id = ?').run('Enzo', place.id);
expect(svc.setStatusFromTrip(u.id, trip.id, [place.id], 'visited')).toEqual({ updated: 1, places: 1 });
});
it('COLLECTIONS-SVC-097: a trip the caller cannot see is a 404, and unsaved places are a no-op', () => {
const u = createUser(testDb).user;
const stranger = createUser(testDb).user;
createCategory(testDb);
const trip = createTrip(testDb, u.id);
const place = createPlace(testDb, trip.id, { name: 'Louvre' });
expect(() => svc.setStatusFromTrip(stranger.id, trip.id, [place.id], 'visited')).toThrow('Trip not found');
expect(svc.setStatusFromTrip(u.id, trip.id, [place.id], 'visited')).toEqual({ updated: 0, places: 0 });
});
it('COLLECTIONS-SVC-098: lists the caller may only read are skipped, not refused', () => {
const owner = createUser(testDb).user;
const viewer = createUser(testDb).user;
createCategory(testDb);
const trip = createTrip(testDb, viewer.id);
const place = createPlace(testDb, trip.id, { name: 'Louvre', lat: 48.8606, lng: 2.3376 });
const readonly = svc.createCollection(owner.id, { name: 'Shared' });
addMember(readonly.id, viewer.id, 'viewer');
const theirs = svc.savePlace(owner.id, { collection_id: readonly.id, name: 'Louvre', lat: 48.8606, lng: 2.3376 }).place!;
expect(svc.setStatusFromTrip(viewer.id, trip.id, [place.id], 'visited')).toEqual({ updated: 0, places: 0 });
expect(statusOf(theirs.id)).toBe('idea');
});
it('COLLECTIONS-SVC-099: findMembership reports the per-list status and edit right', () => {
const owner = createUser(testDb).user;
const viewer = createUser(testDb).user;
const readonly = svc.createCollection(owner.id, { name: 'Shared' });
addMember(readonly.id, viewer.id, 'viewer');
const saved = svc.savePlace(owner.id, { collection_id: readonly.id, name: 'Louvre', google_place_id: 'gp-9' }).place!;
svc.setStatus(owner.id, saved.id, 'visited');
expect(svc.findMembership(viewer.id, { google_place_id: 'gp-9' }).lists).toEqual([
{ collection_id: readonly.id, name: 'Shared', place_id: saved.id, status: 'visited', can_edit: false },
]);
expect(svc.findMembership(owner.id, { google_place_id: 'gp-9' }).lists[0].can_edit).toBe(true);
});
});
+97 -1
View File
@@ -812,6 +812,17 @@ describe('getUserByAccessToken — includes clientId (C2)', () => {
// C3 — Refresh token replay detection and chain revocation
// ---------------------------------------------------------------------------
/**
* Push a token's rotation out of the concurrency grace window (#1007), so the
* replay cases below still describe theft — a token used minutes later — rather
* than two clients racing.
*/
function agePastGrace(rawRefreshToken: string) {
const hash = crypto.createHash('sha256').update(rawRefreshToken).digest('hex');
const old = new Date(Date.now() - 5 * 60 * 1000).toISOString().replace('T', ' ').slice(0, 19);
testDb.prepare('UPDATE oauth_tokens SET revoked_at = ? WHERE refresh_token_hash = ?').run(old, hash);
}
describe('refreshTokens — replay detection (C3)', () => {
it('replaying a revoked refresh token returns invalid_grant', () => {
const { user } = createUser(testDb);
@@ -825,7 +836,9 @@ describe('refreshTokens — replay detection (C3)', () => {
expect(rotateResult.error).toBeUndefined();
const { refresh_token: secondRefresh } = rotateResult.tokens!;
// Replay the FIRST (now revoked) refresh token
// Replay the FIRST (now revoked) refresh token, long enough after the
// rotation that it cannot be a concurrent refresh.
agePastGrace(firstRefresh);
const callsBefore = vi.mocked(revokeUserSessionsForClient).mock.calls.length;
const replayResult = refreshTokens(firstRefresh, clientId, rawSecret);
expect(replayResult.error).toBe('invalid_grant');
@@ -847,6 +860,7 @@ describe('refreshTokens — replay detection (C3)', () => {
const { access_token: access2, refresh_token: second } = r1.tokens!;
// Replay first (revoked) refresh token → chain revoke
agePastGrace(first);
refreshTokens(first, clientId, rawSecret);
// The rotated access token should also be dead now
@@ -873,6 +887,7 @@ describe('refreshTokens — replay detection (C3)', () => {
const { refresh_token: third } = r2.tokens!;
// Replay the first revoked token → revokes chain containing first+second+third
agePastGrace(first);
refreshTokens(first, clientId, rawSecret);
// third should now be revoked too (it's in the same chain)
@@ -881,6 +896,87 @@ describe('refreshTokens — replay detection (C3)', () => {
});
});
// ---------------------------------------------------------------------------
// #1007 — Concurrent rotation is not a replay
// ---------------------------------------------------------------------------
describe('refreshTokens — concurrent rotation grace (#1007)', () => {
const setup = () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
return {
user,
clientId: created.client!.client_id as string,
rawSecret: created.client!.client_secret as string,
};
};
it('OAUTH-GRACE-001: two clients refreshing the same token both get tokens', () => {
const { user, clientId, rawSecret } = setup();
const { refresh_token: shared } = issueTokens(clientId, user.id, ['trips:read']);
const first = refreshTokens(shared, clientId, rawSecret);
const callsBefore = vi.mocked(revokeUserSessionsForClient).mock.calls.length;
const second = refreshTokens(shared, clientId, rawSecret);
expect(first.error).toBeUndefined();
expect(second.error).toBeUndefined();
expect(second.tokens!.refresh_token).not.toBe(first.tokens!.refresh_token);
// The whole point: no chain revocation, no torn-down MCP sessions, no login window.
expect(vi.mocked(revokeUserSessionsForClient).mock.calls.length).toBe(callsBefore);
expect(getUserByAccessToken(first.tokens!.access_token)).not.toBeNull();
expect(getUserByAccessToken(second.tokens!.access_token)).not.toBeNull();
});
it('OAUTH-GRACE-002: both successors keep working afterwards', () => {
const { user, clientId, rawSecret } = setup();
const { refresh_token: shared } = issueTokens(clientId, user.id, ['trips:read']);
const a = refreshTokens(shared, clientId, rawSecret).tokens!;
const b = refreshTokens(shared, clientId, rawSecret).tokens!;
expect(refreshTokens(a.refresh_token, clientId, rawSecret).error).toBeUndefined();
expect(refreshTokens(b.refresh_token, clientId, rawSecret).error).toBeUndefined();
});
it('OAUTH-GRACE-003: the same token replayed after the window is still theft', () => {
const { user, clientId, rawSecret } = setup();
const { refresh_token: shared } = issueTokens(clientId, user.id, ['trips:read']);
const rotated = refreshTokens(shared, clientId, rawSecret).tokens!;
agePastGrace(shared);
const replay = refreshTokens(shared, clientId, rawSecret);
expect(replay.error).toBe('invalid_grant');
expect(refreshTokens(rotated.refresh_token, clientId, rawSecret).error).toBe('invalid_grant');
});
it('OAUTH-GRACE-004: a token revoked by logout is not re-opened by the window', () => {
const { user, clientId, rawSecret } = setup();
const { refresh_token: shared } = issueTokens(clientId, user.id, ['trips:read']);
// Explicit revocation leaves no successor, so there is nothing to be
// concurrent with — the grace must not resurrect it.
revokeToken(shared, clientId, user.id);
const result = refreshTokens(shared, clientId, rawSecret);
expect(result.error).toBe('invalid_grant');
});
it('OAUTH-GRACE-005: a chain killed by a real replay stays dead inside the window', () => {
const { user, clientId, rawSecret } = setup();
const { refresh_token: first } = issueTokens(clientId, user.id, ['trips:read']);
const second = refreshTokens(first, clientId, rawSecret).tokens!;
// Real theft: the first token turns up again once the window has passed.
agePastGrace(first);
expect(refreshTokens(first, clientId, rawSecret).error).toBe('invalid_grant');
// The successor was revoked with the chain, so presenting it now must not
// find a live child and slip through as "concurrent".
expect(refreshTokens(second.refresh_token, clientId, rawSecret).error).toBe('invalid_grant');
});
});
// ---------------------------------------------------------------------------
// H1 — PKCE code_challenge / code_verifier format validation
// ---------------------------------------------------------------------------
+41 -1
View File
@@ -21,6 +21,7 @@ import {
COORD_DEDUP_TOLERANCE,
googleMapsFeatureIdFromItem,
googleMapsHexId,
externalIdsOf,
isPlaceDuplicate,
KMZ_DECOMPRESSED_SIZE_LIMIT,
mapWithConcurrency,
@@ -78,7 +79,7 @@ describe('unpackKmzToKml', () => {
// ── Import dedup predicates ───────────────────────────────────────────────────
const emptyDedup = (): DedupSet => ({ names: new Set(), coords: [] });
const emptyDedup = (): DedupSet => ({ names: new Set(), coords: [], externalIds: new Set() });
describe('isPlaceDuplicate / trackInsertedInDedupSet', () => {
it('matches a named place case- and whitespace-insensitively', () => {
@@ -107,6 +108,45 @@ describe('isPlaceDuplicate / trackInsertedInDedupSet', () => {
it('a candidate with neither a name nor coordinates is never a duplicate', () => {
expect(isPlaceDuplicate({ name: null, lat: null, lng: null }, emptyDedup())).toBe(false);
});
// #1550 — the reported bug: rename an imported place, re-import the list, get a twin.
it('recognises a renamed place by its provider id', () => {
const dedup = emptyDedup();
trackInsertedInDedupSet({ name: 'Trattoria da Enzo', lat: 41.88, lng: 12.47, google_ftid: '0x1:0x2' }, dedup);
// The user renamed it in TREK; the list still calls it what Google calls it.
dedup.names.delete('trattoria da enzo');
dedup.names.add('dinner tuesday');
expect(isPlaceDuplicate({ name: 'Trattoria da Enzo', lat: 41.88, lng: 12.47, google_ftid: '0x1:0x2' }, dedup)).toBe(true);
});
it('matches on any of the three id columns, and ignores blank ones', () => {
const dedup = emptyDedup();
trackInsertedInDedupSet({ name: 'A', lat: null, lng: null, google_place_id: 'ChIJ_a' }, dedup);
trackInsertedInDedupSet({ name: 'B', lat: null, lng: null, osm_id: 'node/42' }, dedup);
expect(isPlaceDuplicate({ name: 'renamed', lat: null, lng: null, google_place_id: 'ChIJ_a' }, dedup)).toBe(true);
expect(isPlaceDuplicate({ name: 'renamed', lat: null, lng: null, osm_id: 'node/42' }, dedup)).toBe(true);
expect(isPlaceDuplicate({ name: 'renamed', lat: null, lng: null, google_ftid: ' ' }, dedup)).toBe(false);
});
it('keeps two different places in the same building apart', () => {
const dedup = emptyDedup();
// Identical coordinates, different ids: the restaurant and the bar downstairs.
trackInsertedInDedupSet({ name: 'Rooftop Bar', lat: 52.52, lng: 13.405, google_ftid: '0xaa:0xbb' }, dedup);
expect(isPlaceDuplicate({ name: 'Ground Floor Diner', lat: 52.52, lng: 13.405, google_ftid: '0xcc:0xdd' }, dedup)).toBe(false);
});
it('leaves id-less imports on their old behaviour', () => {
const dedup = emptyDedup();
trackInsertedInDedupSet({ name: 'Colosseum', lat: 41.89, lng: 12.49 }, dedup);
expect(dedup.externalIds.size).toBe(0);
expect(isPlaceDuplicate({ name: 'colosseum', lat: null, lng: null }, dedup)).toBe(true);
expect(isPlaceDuplicate({ name: 'Colosseum renamed', lat: 41.89, lng: 12.49 }, dedup)).toBe(false);
});
it('externalIdsOf trims and drops empties', () => {
expect(externalIdsOf({ google_place_id: ' ChIJ ', google_ftid: '', osm_id: null })).toEqual(['ChIJ']);
expect(externalIdsOf({})).toEqual([]);
});
});
// ── Google Maps feature ids ───────────────────────────────────────────────────
@@ -665,6 +665,58 @@ describe('importGoogleList', () => {
expect(row.google_ftid).toBe('0x882bf179e806d471:0x8591dde29c821a93');
});
it('PLACE-SVC-028d — a renamed place is not re-imported as a twin (#1550)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const listPayload = [
[null, null, null, null, 'My Test List', null, null, null, [
[null, [null, null, null, null, '878 Weber St N', [null, null, 43.5118527, -80.5542617], ['-8634542354666695567', '-8822026229683971437']], "St. Jacobs Farmers' Market"],
]],
];
const respond = () => vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => 'prefix\n' + JSON.stringify(listPayload),
}));
const url = 'https://www.google.com/maps/placelists/list/ABC123DEF456';
respond();
const first = await svc.importGoogleList(String(trip.id), url) as any;
expect(first.places).toHaveLength(1);
// What the reporter does: rename it to something they can actually read, and
// move it far enough that the coordinate fallback would not save us either.
testDb.prepare('UPDATE places SET name = ?, lat = ?, lng = ? WHERE id = ?')
.run('Saturday market', 43.6, -80.6, first.places[0].id);
respond();
const second = await svc.importGoogleList(String(trip.id), url) as any;
expect(second.places).toHaveLength(0);
expect(second.skipped).toBe(1);
expect(testDb.prepare('SELECT COUNT(*) c FROM places WHERE trip_id = ?').get(trip.id)).toEqual({ c: 1 });
});
it('PLACE-SVC-028e — two places at the same coordinates still both import', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// A bar and a diner in one building: same spot, different feature ids.
const listPayload = [
[null, null, null, null, 'One Building', null, null, null, [
[null, [null, null, null, null, 'Same street 1', [null, null, 52.52, 13.405], ['1', '2']], 'Rooftop Bar'],
[null, [null, null, null, null, 'Same street 1', [null, null, 52.52, 13.405], ['3', '4']], 'Ground Floor Diner'],
]],
];
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => 'prefix\n' + JSON.stringify(listPayload),
}));
const result = await svc.importGoogleList(String(trip.id), 'https://www.google.com/maps/placelists/list/ABC123DEF456') as any;
expect(result.places).toHaveLength(2);
expect(result.skipped).toBe(0);
});
it('PLACE-SVC-029 — returns error when list items array is empty', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);