feat(trips): trip invite links + optional trip binding on admin invites

Trip invite links (#1143): each trip can have one rotating invite link in its
Share panel. An existing, logged-in user who opens /join/<token> is added to
the trip as a member; an anonymous visitor is sent to the login page and
returned to the invite afterwards — there is no registration from this link.
Reading, rotating or disabling the link all require the share_manage permission.

Admin invite trip binding (#1402): the admin create-invite dialog can now bind
a registration invite to a trip. Someone who registers via that link is
auto-added to the trip as a member (password and OIDC paths), inside the same
atomic step that consumes the invite.

Adds a trip_invite_tokens table and a nullable invite_tokens.trip_id, a shared
owner-safe/idempotent add-by-id helper, the manage + join endpoints, the
JoinTripPage and Share-panel section, the admin trip picker, and the new i18n
keys across every locale. Wiki updated.

Discussion #1143
This commit is contained in:
Maurice
2026-07-02 13:07:46 +02:00
committed by Maurice
parent bfc857d246
commit 5f77fa5cca
71 changed files with 1294 additions and 19 deletions
+23
View File
@@ -3266,6 +3266,29 @@ function runMigrations(db: Database.Database): void {
() => {
try { db.exec("ALTER TABLE collection_members ADD COLUMN role TEXT NOT NULL DEFAULT 'editor'"); } catch (err) { console.warn('[migrations] Non-fatal migration step failed:', err); }
},
// Migration 153: per-trip invite links (#1143). One rotating token per trip;
// a logged-in existing user who opens the link joins the trip as a member.
// Deleting the trip drops the token (CASCADE); the creator is nulled if their
// account is removed so the link keeps working.
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS trip_invite_tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
trip_id INTEGER NOT NULL UNIQUE REFERENCES trips(id) ON DELETE CASCADE,
token TEXT UNIQUE NOT NULL,
created_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
expires_at TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_trip_invite_tokens_token ON trip_invite_tokens(token);
`);
},
// Migration 154: optional trip binding on an admin invite link (#1402). A user
// who REGISTERS via the link is auto-added to the trip. Nullable for backward
// compatibility; ON DELETE SET NULL so removing the trip just unbinds the invite.
() => {
try { db.exec('ALTER TABLE invite_tokens ADD COLUMN trip_id INTEGER REFERENCES trips(id) ON DELETE SET NULL'); } catch (err) { console.warn('[migrations] Non-fatal migration step failed:', err); }
},
];
if (currentVersion < migrations.length) {
+5 -1
View File
@@ -135,11 +135,15 @@ export class AdminController {
@Get('invites')
listInvites() { return { invites: this.admin.listInvites() }; }
// Trips an admin can optionally bind a registration invite to (#1402).
@Get('invites/trips')
listInviteTrips() { return { trips: this.admin.listTripsForInvite() }; }
@Post('invites')
@HttpCode(201)
createInvite(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) {
const result = this.admin.createInvite(user.id, body);
writeAudit({ userId: user.id, action: 'admin.invite_create', resource: String(result.inviteId), ip: getClientIp(req), details: { max_uses: result.uses, expires_in_days: result.expiresInDays } });
writeAudit({ userId: user.id, action: 'admin.invite_create', resource: String(result.inviteId), ip: getClientIp(req), details: { max_uses: result.uses, expires_in_days: result.expiresInDays, trip_id: result.tripId } });
return { invite: result.invite };
}
+1
View File
@@ -34,6 +34,7 @@ export class AdminService {
// Invites
listInvites() { return svc.listInvites(); }
listTripsForInvite() { return svc.listTripsForInvite(); }
createInvite(userId: number, body: unknown) { return svc.createInvite(userId, body as Parameters<typeof svc.createInvite>[1]); }
deleteInvite(id: string) { return svc.deleteInvite(id); }
+2 -1
View File
@@ -30,6 +30,7 @@ import { AirtrailModule } from './integrations/airtrail.module';
import { JourneyModule } from './journey/journey.module';
import { CollectionsModule } from './collections/collections.module';
import { ShareModule } from './share/share.module';
import { TripInviteModule } from './trip-invite/trip-invite.module';
import { FeedsModule } from './feeds/feeds.module';
import { SettingsModule } from './settings/settings.module';
import { BackupModule } from './backup/backup.module';
@@ -49,7 +50,7 @@ import { IdempotencyInterceptor } from './common/idempotency.interceptor';
* migrated.
*/
@Module({
imports: [DatabaseModule, WeatherModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, MapsModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, CollectionsModule, ShareModule, FeedsModule, SettingsModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, BookingImportModule],
imports: [DatabaseModule, WeatherModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, MapsModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, FeedsModule, SettingsModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, BookingImportModule],
controllers: [HealthController],
providers: [
HealthService,
@@ -0,0 +1,100 @@
import { Body, Controller, Delete, Get, HttpCode, HttpException, Param, Post, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import type { User } from '../../types';
import { TripInviteService } from './trip-invite.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { RateLimitService } from '../auth/rate-limit.service';
import { writeAudit, getClientIp } from '../../services/auditLog';
const RL_WINDOW = 15 * 60 * 1000;
/**
* /api/trips/:tripId/invite-link — manage a trip's invite link (#1143).
*
* Mirrors the public share link: trip access (404) + the 'share_manage'
* permission (403). Unlike the share link this one is not public — see
* TripInviteController for the login-required join.
*/
@Controller('api/trips/:tripId/invite-link')
@UseGuards(JwtAuthGuard)
export class TripInviteLinkController {
constructor(private readonly invites: TripInviteService) {}
private requireManage(tripId: string, user: User) {
const trip = this.invites.verifyTripAccess(tripId, user.id);
if (!trip) throw new HttpException({ error: 'Trip not found' }, 404);
if (!this.invites.canManage(trip, user)) throw new HttpException({ error: 'No permission' }, 403);
}
@Get()
get(@CurrentUser() user: User, @Param('tripId') tripId: string) {
// The token grants trip membership, so reading it needs the same
// share_manage permission as creating/rotating it — not just trip access.
this.requireManage(tripId, user);
const info = this.invites.get(tripId);
return info ? info : { token: null };
}
@Post()
create(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: { expires_in_days?: number | string | null },
@Req() req: Request,
) {
this.requireManage(tripId, user);
const days = body?.expires_in_days != null && String(body.expires_in_days).trim() !== ''
? parseInt(String(body.expires_in_days))
: null;
const info = this.invites.createOrRotate(tripId, user.id, Number.isFinite(days as number) ? days : null);
writeAudit({ userId: user.id, action: 'trip.invite_link_create', resource: tripId, ip: getClientIp(req), details: { expires_in_days: days } });
return info;
}
@Delete()
remove(@CurrentUser() user: User, @Param('tripId') tripId: string, @Req() req: Request) {
this.requireManage(tripId, user);
this.invites.remove(tripId);
writeAudit({ userId: user.id, action: 'trip.invite_link_delete', resource: tripId, ip: getClientIp(req) });
return { success: true };
}
}
/**
* /api/trip-invites/:token — resolve + accept a trip invite as an existing,
* logged-in user. JWT-guarded: an anonymous visitor is redirected to /login by
* the client (never registration). Rate-limited to blunt any token probing even
* though the tokens are 192-bit and unguessable. The join is idempotent and
* owner-safe (see joinTripAsMember).
*/
@Controller('api/trip-invites')
@UseGuards(JwtAuthGuard)
export class TripInviteController {
constructor(private readonly invites: TripInviteService, private readonly rl: RateLimitService) {}
private limit(req: Request, max: number): void {
if (!this.rl.check('trip_invite', req.ip || 'unknown', max, RL_WINDOW, Date.now())) {
throw new HttpException({ error: 'Too many attempts. Please try again later.' }, 429);
}
}
@Get(':token')
preview(@Param('token') token: string, @Req() req: Request) {
this.limit(req, 30);
const resolved = this.invites.resolve(token);
if (!resolved) throw new HttpException({ error: 'Invalid or expired invite link' }, 404);
return { trip_id: resolved.trip_id, title: resolved.title };
}
@Post(':token/accept')
@HttpCode(200)
accept(@CurrentUser() user: User, @Param('token') token: string, @Req() req: Request) {
this.limit(req, 20);
const resolved = this.invites.resolve(token);
if (!resolved) throw new HttpException({ error: 'Invalid or expired invite link' }, 404);
const result = this.invites.join(resolved.trip_id, user.id);
writeAudit({ userId: user.id, action: 'trip.invite_link_join', resource: String(resolved.trip_id), ip: getClientIp(req), details: { joined: result.joined } });
return { trip_id: resolved.trip_id, joined: result.joined };
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { TripInviteLinkController, TripInviteController } from './trip-invite.controller';
import { TripInviteService } from './trip-invite.service';
import { RateLimitService } from '../auth/rate-limit.service';
@Module({
controllers: [TripInviteLinkController, TripInviteController],
providers: [TripInviteService, RateLimitService],
})
export class TripInviteModule {}
@@ -0,0 +1,35 @@
import { Injectable } from '@nestjs/common';
import { canAccessTrip } from '../../db/database';
import { checkPermission } from '../../services/permissions';
import { joinTripAsMember } from '../../services/tripMembership';
import type { User } from '../../types';
import * as svc from '../../services/tripInviteService';
type Trip = NonNullable<ReturnType<typeof canAccessTrip>>;
/**
* Thin Nest wrapper around the trip invite-link service. Trip access and the
* 'share_manage' permission mirror the public share link exactly (the invite
* link lives next to it in the Share area).
*/
@Injectable()
export class TripInviteService {
verifyTripAccess(tripId: string, userId: number) {
return canAccessTrip(tripId, userId);
}
canManage(trip: Trip, user: User): boolean {
return checkPermission('share_manage', user.role, trip.user_id, user.id, trip.user_id !== user.id);
}
get(tripId: string) { return svc.getTripInviteLink(tripId); }
createOrRotate(tripId: string, userId: number, expiresInDays?: number | null) {
return svc.createOrRotateTripInviteLink(tripId, userId, expiresInDays ?? null);
}
remove(tripId: string) { return svc.deleteTripInviteLink(tripId); }
resolve(token: string) { return svc.resolveTripInvite(token); }
/** Join the resolved trip as the current (authenticated, non-guest) user.
* invited_by is null — they joined via a link, not a personal invite. */
join(tripId: number, userId: number) { return joinTripAsMember(tripId, userId, null); }
}
+23 -6
View File
@@ -432,14 +432,20 @@ export async function checkAndNotifyVersion(): Promise<void> {
export function listInvites() {
return db.prepare(`
SELECT i.*, u.username as created_by_name
SELECT i.*, u.username as created_by_name, t.title as trip_title
FROM invite_tokens i
JOIN users u ON i.created_by = u.id
LEFT JOIN trips t ON i.trip_id = t.id
ORDER BY i.created_at DESC
`).all();
}
export function createInvite(createdBy: number, data: { max_uses?: string | number; expires_in_days?: string | number }) {
/** Trips an admin can bind an invite to — id + title only, for the picker (#1402). */
export function listTripsForInvite() {
return db.prepare('SELECT id, title FROM trips ORDER BY title COLLATE NOCASE ASC').all();
}
export function createInvite(createdBy: number, data: { max_uses?: string | number; expires_in_days?: string | number; trip_id?: string | number | null }) {
const rawUses = parseInt(String(data.max_uses));
const uses = rawUses === 0 ? 0 : Math.min(Math.max(rawUses || 1, 1), 5);
const token = crypto.randomBytes(16).toString('hex');
@@ -447,19 +453,30 @@ export function createInvite(createdBy: number, data: { max_uses?: string | numb
? new Date(Date.now() + parseInt(String(data.expires_in_days)) * 86400000).toISOString()
: null;
// Optional trip binding: only persist a trip that actually exists, so a stale
// or forged id can never bind (and never auto-adds anyone on registration).
let tripId: number | null = null;
if (data.trip_id != null && String(data.trip_id).trim() !== '') {
const parsed = parseInt(String(data.trip_id));
if (Number.isInteger(parsed) && db.prepare('SELECT id FROM trips WHERE id = ?').get(parsed)) {
tripId = parsed;
}
}
const ins = db.prepare(
'INSERT INTO invite_tokens (token, max_uses, expires_at, created_by) VALUES (?, ?, ?, ?)'
).run(token, uses, expiresAt, createdBy);
'INSERT INTO invite_tokens (token, max_uses, expires_at, created_by, trip_id) VALUES (?, ?, ?, ?, ?)'
).run(token, uses, expiresAt, createdBy, tripId);
const inviteId = Number(ins.lastInsertRowid);
const invite = db.prepare(`
SELECT i.*, u.username as created_by_name
SELECT i.*, u.username as created_by_name, t.title as trip_title
FROM invite_tokens i
JOIN users u ON i.created_by = u.id
LEFT JOIN trips t ON i.trip_id = t.id
WHERE i.id = ?
`).get(inviteId);
return { invite, inviteId, uses, expiresInDays: data.expires_in_days ?? null };
return { invite, inviteId, uses, expiresInDays: data.expires_in_days ?? null, tripId };
}
export function deleteInvite(id: string) {
+6
View File
@@ -22,6 +22,7 @@ import { verifyJwtAndLoadUser } from '../middleware/auth';
import { User } from '../types';
import { DEMO_EMAIL_PRIMARY, isDemoEmail } from './demo';
import { avatarUrl } from './avatarUrl';
import { joinTripAsMember } from './tripMembership';
import { isPasskeyConfigured } from './webauthnConfig';
export { avatarUrl };
@@ -432,6 +433,11 @@ export function registerUser(body: {
if (!updated) {
console.warn(`[Auth] Invite token ${validInvite.token.slice(0, 8)}... exceeded max_uses due to race condition`);
}
// Trip-bound invite (#1402): auto-add the freshly registered user to the
// trip. Idempotent + owner-safe; no-ops if the bound trip was since deleted.
if (validInvite.trip_id) {
joinTripAsMember(Number(validInvite.trip_id), Number(result.lastInsertRowid), validInvite.created_by ?? null);
}
}
return {
+8 -1
View File
@@ -5,6 +5,7 @@ import { JWT_SECRET, SESSION_DURATION_SECONDS } from '../config';
import { User } from '../types';
import { decrypt_api_key } from './apiKeyCrypto';
import { resolveAuthToggles } from './authService';
import { joinTripAsMember } from './tripMembership';
// ---------------------------------------------------------------------------
// Types
@@ -473,9 +474,15 @@ export function findOrCreateUser(
).run(validInvite.id);
if (updated.changes === 0) throw inviteRaceError;
}
return db.prepare(
const ins = db.prepare(
'INSERT INTO users (username, email, password_hash, role, oidc_sub, oidc_issuer, avatar, first_seen_version, login_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)',
).run(username, email, hash, role, sub, config.issuer, picture, process.env.APP_VERSION || '0.0.0');
// Trip-bound invite (#1402): auto-add the new SSO user to the trip inside the
// same atomic step as the invite consume. Idempotent + owner-safe.
if (validInvite?.trip_id) {
joinTripAsMember(Number(validInvite.trip_id), Number(ins.lastInsertRowid), validInvite.created_by ?? null);
}
return ins;
});
const result = createUser() as { lastInsertRowid: number | bigint };
user = { id: Number(result.lastInsertRowid), username, email, role, avatar: picture } as User;
+83
View File
@@ -0,0 +1,83 @@
import { db } from '../db/database';
import crypto from 'crypto';
/**
* Per-trip invite links (#1143).
*
* A trip has at most ONE invite token (mirrors the public share link: one
* rotating token per trip). Unlike the share link, this one is NOT public —
* opening it only does something for a logged-in user with an existing account,
* who is then added to the trip as a member. Rotating or disabling the link
* immediately invalidates the old URL.
*/
export interface TripInviteInfo {
token: string;
expires_at: string | null;
created_at: string;
}
/** The current invite link for a trip, or null if none exists. */
export function getTripInviteLink(tripId: string | number): TripInviteInfo | null {
const row = db
.prepare('SELECT token, expires_at, created_at FROM trip_invite_tokens WHERE trip_id = ?')
.get(tripId) as { token: string; expires_at: string | null; created_at: string } | undefined;
return row ? { token: row.token, expires_at: row.expires_at, created_at: row.created_at } : null;
}
/**
* Create the trip's invite link, or rotate it to a fresh token (there is only
* ever one row per trip). An optional expiry (days) can bound the link's life.
*/
export function createOrRotateTripInviteLink(
tripId: string | number,
createdBy: number,
expiresInDays?: number | null,
): TripInviteInfo {
const token = crypto.randomBytes(24).toString('base64url');
const expiresAt =
expiresInDays && expiresInDays > 0
? new Date(Date.now() + expiresInDays * 86400000).toISOString()
: null;
const existing = db.prepare('SELECT id FROM trip_invite_tokens WHERE trip_id = ?').get(tripId);
if (existing) {
db.prepare(
'UPDATE trip_invite_tokens SET token = ?, expires_at = ?, created_by = ?, created_at = CURRENT_TIMESTAMP WHERE trip_id = ?',
).run(token, expiresAt, createdBy, tripId);
} else {
db.prepare(
'INSERT INTO trip_invite_tokens (trip_id, token, created_by, expires_at) VALUES (?, ?, ?, ?)',
).run(tripId, token, createdBy, expiresAt);
}
return getTripInviteLink(tripId)!;
}
/** Remove the trip's invite link entirely (disable). */
export function deleteTripInviteLink(tripId: string | number): void {
db.prepare('DELETE FROM trip_invite_tokens WHERE trip_id = ?').run(tripId);
}
/**
* Resolve an invite token to its (still-existing, unexpired) trip. Returns null
* for unknown/expired tokens. Only ever called for an authenticated user, so the
* trip title is safe to return for the join confirmation screen; an anonymous
* caller never reaches this (the endpoint is JWT-guarded).
*/
export function resolveTripInvite(token: string): { trip_id: number; title: string } | null {
const row = db
.prepare(
`SELECT t.id AS trip_id, t.title AS title, ti.expires_at AS expires_at
FROM trip_invite_tokens ti
JOIN trips t ON ti.trip_id = t.id
WHERE ti.token = ?`,
)
.get(token) as { trip_id: number; title: string; expires_at: string | null } | undefined;
if (!row) return null;
// Check expiry in JS, not SQL: expires_at is stored as an ISO-8601 string
// (…T…Z) which does not compare lexicographically against SQLite's
// space-separated datetime('now'), so a SQL `>` would keep an expired link
// alive until the end of the day. Mirrors the admin-invite validation.
if (row.expires_at && new Date(row.expires_at) < new Date()) return null;
return { trip_id: row.trip_id, title: row.title };
}
+29
View File
@@ -0,0 +1,29 @@
import { db } from '../db/database';
/**
* Add an existing user to a trip as a member, by user id.
*
* Idempotent and safe: it skips the trip owner and anyone who is already a
* member, and no-ops if the trip no longer exists. Shared by trip invite-link
* joins (#1143) and the trip-bound admin invite auto-join (#1402). The caller is
* responsible for authenticating/creating the user first, so the id always
* belongs to a real (non-guest) account.
*
* Returns whether a new membership row was actually created.
*/
export function joinTripAsMember(
tripId: number,
userId: number,
invitedBy: number | null,
): { joined: boolean; tripId: number } {
const trip = db.prepare('SELECT id, user_id FROM trips WHERE id = ?').get(tripId) as
| { id: number; user_id: number }
| undefined;
if (!trip) return { joined: false, tripId };
// The owner already has full access; never add them as a member.
if (trip.user_id === userId) return { joined: false, tripId };
const existing = db.prepare('SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?').get(tripId, userId);
if (existing) return { joined: false, tripId };
db.prepare('INSERT INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(tripId, userId, invitedBy);
return { joined: true, tripId };
}