refactor(atlas, school-holidays, settings): async DB-touching methods; transactions through UnitOfWork

This commit is contained in:
jubnl
2026-09-21 21:23:10 +02:00
parent f6c17938c3
commit 953e2526bb
55 changed files with 812 additions and 768 deletions
+1 -1
View File
@@ -101,7 +101,7 @@ export async function buildApp(): Promise<INestApplication> {
// engines go through the same door — the second one answers the avoidance questions
// the first cannot, and is blocked just as silently when the policy leaves it out.
const settings = app.get(SettingsService, { strict: false });
const defaults = settings?.getAdminUserDefaults();
const defaults = await settings?.getAdminUserDefaults();
const asUrl = (value: unknown) => (typeof value === 'string' ? value : null);
applyGlobalMiddleware(instance, {
http,
+4 -4
View File
@@ -239,15 +239,15 @@ export class AddonsService {
* personal key gets Google while every other member silently gets Transitous
* — the #1939 shape, one layer up.
*/
private googleKeySource(userId: number): ApiKeySource | null {
return resolveApiKey(this.dbs, 'maps_api_key', userId, readEnv().maps.placesApiKey).source;
private async googleKeySource(userId: number): Promise<ApiKeySource | null> {
return (await resolveApiKey(this.dbs, 'maps_api_key', userId, readEnv().maps.placesApiKey)).source;
}
async getTransitProvider(userId = 0) {
return { provider: await readTransitProvider(this.dbs), googleKeySource: this.googleKeySource(userId) };
return { provider: await readTransitProvider(this.dbs), googleKeySource: await this.googleKeySource(userId) };
}
async updateTransitProvider(provider: TransitProvider, userId = 0) {
return { provider: await writeTransitProvider(this.dbs, provider), googleKeySource: this.googleKeySource(userId) };
return { provider: await writeTransitProvider(this.dbs, provider), googleKeySource: await this.googleKeySource(userId) };
}
}
+21 -21
View File
@@ -43,13 +43,13 @@ export class AtlasController {
constructor(private readonly atlas: AtlasService) {}
@Get('stats')
stats(@CurrentUser() user: User) {
async stats(@CurrentUser() user: User) {
return this.atlas.stats(user.id);
}
@Get('regions')
@Header('Cache-Control', 'no-cache, no-store')
regions(@CurrentUser() user: User) {
async regions(@CurrentUser() user: User) {
return this.atlas.visitedRegions(user.id);
}
@@ -106,47 +106,47 @@ export class AtlasController {
}
@Get('country/:code')
countryPlaces(@CurrentUser() user: User, @Param('code') code: string) {
async countryPlaces(@CurrentUser() user: User, @Param('code') code: string) {
return this.atlas.countryPlaces(user.id, code.toUpperCase());
}
@Post('country/:code/mark')
@HttpCode(200)
markCountry(@CurrentUser() user: User, @Param('code') code: string): { success: boolean } {
this.atlas.markCountry(user.id, code.toUpperCase());
async markCountry(@CurrentUser() user: User, @Param('code') code: string): Promise<{ success: boolean }> {
await this.atlas.markCountry(user.id, code.toUpperCase());
return { success: true };
}
@Delete('country/:code/mark')
unmarkCountry(@CurrentUser() user: User, @Param('code') code: string): { success: boolean } {
this.atlas.unmarkCountry(user.id, code.toUpperCase());
async unmarkCountry(@CurrentUser() user: User, @Param('code') code: string): Promise<{ success: boolean }> {
await this.atlas.unmarkCountry(user.id, code.toUpperCase());
return { success: true };
}
@Post('region/:code/mark')
@HttpCode(200)
markRegion(
async markRegion(
@CurrentUser() user: User,
@Param('code') code: string,
@Body() body: AtlasMarkRegionDto,
): { success: boolean } {
this.atlas.markRegion(user.id, code.toUpperCase(), body.name, body.country_code.toUpperCase());
): Promise<{ success: boolean }> {
await this.atlas.markRegion(user.id, code.toUpperCase(), body.name, body.country_code.toUpperCase());
return { success: true };
}
@Delete('region/:code/mark')
unmarkRegion(@CurrentUser() user: User, @Param('code') code: string): { success: boolean } {
this.atlas.unmarkRegion(user.id, code.toUpperCase());
async unmarkRegion(@CurrentUser() user: User, @Param('code') code: string): Promise<{ success: boolean }> {
await this.atlas.unmarkRegion(user.id, code.toUpperCase());
return { success: true };
}
@Get('bucket-list')
bucketList(@CurrentUser() user: User) {
return { items: this.atlas.bucketList(user.id) };
async bucketList(@CurrentUser() user: User) {
return { items: await this.atlas.bucketList(user.id) };
}
@Post('bucket-list')
createBucketItem(@CurrentUser() user: User, @Body() body: AtlasCreateBucketItemDto): { item: unknown } {
async createBucketItem(@CurrentUser() user: User, @Body() body: AtlasCreateBucketItemDto): Promise<{ item: unknown }> {
// The schema's min(1) admits whitespace-only names — this trim guard keeps
// the legacy 400 for those (missing/empty names 400 in the pipe envelope).
if (!body.name?.trim()) {
@@ -154,7 +154,7 @@ export class AtlasController {
}
const { name, lat, lng, country_code, notes, target_date } = body;
try {
return { item: this.atlas.createBucketItem(user.id, { name, lat, lng, country_code, notes, target_date }) };
return { item: await this.atlas.createBucketItem(user.id, { name, lat, lng, country_code, notes, target_date }) };
} catch (err) {
// #1898: the same wish twice is a conflict, not a server error. Bespoke
// { error } body like the neighbouring 400/404s.
@@ -166,15 +166,15 @@ export class AtlasController {
}
@Put('bucket-list/:id')
updateBucketItem(
async updateBucketItem(
@CurrentUser() user: User,
@Param('id') id: string,
@Body() body: AtlasUpdateBucketItemDto,
): { item: unknown } {
): Promise<{ item: unknown }> {
const { name, notes, lat, lng, country_code, target_date } = body;
let item: unknown;
try {
item = this.atlas.updateBucketItem(user.id, id, { name, notes, lat, lng, country_code, target_date });
item = await this.atlas.updateBucketItem(user.id, id, { name, notes, lat, lng, country_code, target_date });
} catch (err) {
// #1898: editing a wish onto an existing one conflicts the same way a
// duplicate create does.
@@ -190,8 +190,8 @@ export class AtlasController {
}
@Delete('bucket-list/:id')
deleteBucketItem(@CurrentUser() user: User, @Param('id') id: string): { success: boolean } {
if (!this.atlas.deleteBucketItem(user.id, id)) {
async deleteBucketItem(@CurrentUser() user: User, @Param('id') id: string): Promise<{ success: boolean }> {
if (!(await this.atlas.deleteBucketItem(user.id, id))) {
throw new HttpException({ error: 'Item not found' }, 404);
}
return { success: true };
+12 -12
View File
@@ -88,7 +88,7 @@ export class AtlasMcp {
) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
try {
const item = this.atlas.createBucketItem(ctx.userId, { name, lat, lng, country_code, notes, target_date });
const item = await this.atlas.createBucketItem(ctx.userId, { name, lat, lng, country_code, notes, target_date });
return ok({ item });
} catch (err) {
if (err instanceof BucketItemExistsError) return bucketDuplicateResult();
@@ -108,7 +108,7 @@ export class AtlasMcp {
})
async deleteBucketListItem({ itemId }: { itemId: number }, ctx: McpContext) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
const deleted = this.atlas.deleteBucketItem(ctx.userId, itemId);
const deleted = await this.atlas.deleteBucketItem(ctx.userId, itemId);
if (!deleted) return { content: [{ type: 'text' as const, text: 'Bucket list item not found.' }], isError: true };
return ok({ success: true });
}
@@ -127,7 +127,7 @@ export class AtlasMcp {
})
async markCountryVisited({ country_code }: { country_code: string }, ctx: McpContext) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
this.atlas.markCountry(ctx.userId, country_code.toUpperCase());
await this.atlas.markCountry(ctx.userId, country_code.toUpperCase());
return ok({ success: true, country_code: country_code.toUpperCase() });
}
@@ -143,7 +143,7 @@ export class AtlasMcp {
})
async unmarkCountryVisited({ country_code }: { country_code: string }, ctx: McpContext) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
this.atlas.unmarkCountry(ctx.userId, country_code.toUpperCase());
await this.atlas.unmarkCountry(ctx.userId, country_code.toUpperCase());
return ok({ success: true, country_code: country_code.toUpperCase() });
}
@@ -169,7 +169,7 @@ export class AtlasMcp {
// figures the passport card is actually asked for (GET /api/auth/travel-stats)
// were unreachable here. Its coords array is one entry per place, which is
// rendering data rather than an answer, hence the opt-in.
const { coords, ...travel } = this.atlas.getTravelStats(ctx.userId);
const { coords, ...travel } = await this.atlas.getTravelStats(ctx.userId);
return ok({ stats, travel: include_coords ? { ...travel, coords } : travel });
}
@@ -231,8 +231,8 @@ export class AtlasMcp {
// (the legacy registrar passed them through verbatim, so a lowercase mark
// created a row REST's uppercased unmark could never hit).
const upperRegion = regionCode.toUpperCase();
this.atlas.markRegion(ctx.userId, upperRegion, regionName, countryCode.toUpperCase());
const row = this.atlas.listManuallyVisitedRegions(ctx.userId).find((r) => r.region_code === upperRegion);
await this.atlas.markRegion(ctx.userId, upperRegion, regionName, countryCode.toUpperCase());
const row = (await this.atlas.listManuallyVisitedRegions(ctx.userId)).find((r) => r.region_code === upperRegion);
// Echo in the client-facing shape ({ code, name, ... }) rather than raw DB columns.
const region = row
? { code: row.region_code, name: row.region_name, country_code: row.country_code, manuallyMarked: true }
@@ -253,7 +253,7 @@ export class AtlasMcp {
async unmarkRegionVisited({ regionCode }: { regionCode: string }, ctx: McpContext) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
// Post-fold quirk fix: uppercase, matching the REST controller.
this.atlas.unmarkRegion(ctx.userId, regionCode.toUpperCase());
await this.atlas.unmarkRegion(ctx.userId, regionCode.toUpperCase());
return ok({ success: true });
}
@@ -270,7 +270,7 @@ export class AtlasMcp {
async getCountryAtlasPlaces({ countryCode }: { countryCode: string }, ctx: McpContext) {
// Post-fold quirk fix: uppercase, matching the REST controller (the legacy
// registrar passed 'fr' through and matched nothing).
const result = this.atlas.countryPlaces(ctx.userId, countryCode.toUpperCase());
const result = await this.atlas.countryPlaces(ctx.userId, countryCode.toUpperCase());
return ok(result);
}
@@ -305,7 +305,7 @@ export class AtlasMcp {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
let item: unknown;
try {
item = this.atlas.updateBucketItem(ctx.userId, itemId, { name, notes, lat, lng, country_code, target_date });
item = await this.atlas.updateBucketItem(ctx.userId, itemId, { name, notes, lat, lng, country_code, target_date });
} catch (err) {
if (err instanceof BucketItemExistsError) return bucketDuplicateResult();
throw err;
@@ -327,7 +327,7 @@ export class AtlasMcp {
access: { group: 'atlas', mode: 'read' },
})
async bucketListResource(uri: URL, ctx: McpContext) {
const items = this.atlas.bucketList(ctx.userId);
const items = await this.atlas.bucketList(ctx.userId);
return jsonContent(uri.href, items);
}
@@ -340,7 +340,7 @@ export class AtlasMcp {
access: { group: 'atlas', mode: 'read' },
})
async visitedCountriesResource(uri: URL, ctx: McpContext) {
const countries = this.atlas.listVisitedCountries(ctx.userId);
const countries = await this.atlas.listVisitedCountries(ctx.userId);
return jsonContent(uri.href, countries);
}
+9 -9
View File
@@ -27,8 +27,8 @@ export class AtlasRpc {
const userId = this.requireAtlasUser(ctx, 'reads');
await this.requireAtlasAddon();
return {
countries: this.atlas.listVisitedCountries(userId),
regions: this.atlas.listManuallyVisitedRegions(userId),
countries: await this.atlas.listVisitedCountries(userId),
regions: await this.atlas.listManuallyVisitedRegions(userId),
};
}
@@ -36,7 +36,7 @@ export class AtlasRpc {
async bucketList(_params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
const userId = this.requireAtlasUser(ctx, 'reads');
await this.requireAtlasAddon();
return this.atlas.bucketList(userId) as unknown[];
return (await this.atlas.bucketList(userId)) as unknown[];
}
@PluginMethod('atlas.markCountry', { permission: 'db:write:atlas' })
@@ -44,7 +44,7 @@ export class AtlasRpc {
const userId = this.requireAtlasUser(ctx, 'writes');
const code = this.code(params.code, 'code');
await this.requireAtlasAddon();
this.atlas.markCountry(userId, code);
await this.atlas.markCountry(userId, code);
return { visited: true };
}
@@ -53,7 +53,7 @@ export class AtlasRpc {
const userId = this.requireAtlasUser(ctx, 'writes');
const code = this.code(params.code, 'code');
await this.requireAtlasAddon();
this.atlas.unmarkCountry(userId, code);
await this.atlas.unmarkCountry(userId, code);
return { visited: false };
}
@@ -67,7 +67,7 @@ export class AtlasRpc {
const regionCode = this.code(params.regionCode, 'regionCode');
const countryCode = this.code(params.countryCode, 'countryCode');
await this.requireAtlasAddon();
this.atlas.markRegion(userId, regionCode, regionName, countryCode);
await this.atlas.markRegion(userId, regionCode, regionName, countryCode);
return { visited: true };
}
@@ -76,7 +76,7 @@ export class AtlasRpc {
const userId = this.requireAtlasUser(ctx, 'writes');
const regionCode = this.code(params.regionCode, 'regionCode');
await this.requireAtlasAddon();
this.atlas.unmarkRegion(userId, regionCode);
await this.atlas.unmarkRegion(userId, regionCode);
return { visited: false };
}
@@ -87,7 +87,7 @@ export class AtlasRpc {
if (typeof input.name !== 'string' || input.name.trim() === '') throw new BadParams('bucket item name is required');
await this.requireAtlasAddon();
try {
return this.atlas.createBucketItem(userId, input as never);
return await this.atlas.createBucketItem(userId, input as never);
} catch (err) {
// #1898: a repeated wish is the caller's mistake, not ours. Without this the
// plugin sees a generic internal error and cannot tell the two apart.
@@ -101,7 +101,7 @@ export class AtlasRpc {
const userId = this.requireAtlasUser(ctx, 'writes');
const itemId = num(params.itemId, 'itemId');
await this.requireAtlasAddon();
if (!this.atlas.deleteBucketItem(userId, itemId)) {
if (!(await this.atlas.deleteBucketItem(userId, itemId))) {
throw new ForbiddenResource(`no bucket item ${itemId} for this user`);
}
return { deleted: true };
+51 -47
View File
@@ -3,6 +3,7 @@ import { CONTINENT_MAP, strongerVisitStatus, todayUtc, tripVisitStatus, VisitSta
import type { AtlasLocateResponse } from '@trek/shared';
import { Trip, Place } from '../../types';
import { DatabaseService } from '../database/database.service';
import { UnitOfWork } from '../database/unit-of-work';
import {
getCountryFromCoords,
getCountryGeoGz,
@@ -109,11 +110,14 @@ function markedSource(row: { source?: string | null } | undefined): string | nul
*/
@Injectable()
export class AtlasService {
constructor(private readonly db: DatabaseService) {}
constructor(
private readonly db: DatabaseService,
private readonly uow: UnitOfWork,
) {}
// ── Shared query: all trips the user owns or is a member of ───────────────
private getUserTrips(userId: number): Trip[] {
private async getUserTrips(userId: number): Promise<Trip[]> {
return this.db
.prepare(
`
@@ -126,7 +130,7 @@ export class AtlasService {
.all(userId, userId, userId) as Trip[];
}
private getPlacesForTrips(tripIds: number[]): Place[] {
private async getPlacesForTrips(tripIds: number[]): Promise<Place[]> {
if (tripIds.length === 0) return [];
const placeholders = tripIds.map(() => '?').join(',');
return this.db.prepare(`SELECT * FROM places WHERE trip_id IN (${placeholders})`).all(...tripIds) as Place[];
@@ -143,7 +147,7 @@ export class AtlasService {
// ── Country resolution (batch DB cache + sync fallback + background geocoding) ──
private resolvePlaceCountries(places: Place[]): Map<number, string> {
private async resolvePlaceCountries(places: Place[]): Promise<Map<number, string>> {
const out = new Map<number, string>();
const geoPlaces = places.filter((p) => p.lat && p.lng);
const placeIds = geoPlaces.map((p) => p.id);
@@ -204,11 +208,11 @@ export class AtlasService {
// ── Stats ─────────────────────────────────────────────────────────────────
async stats(userId: number) {
const trips = this.getUserTrips(userId);
const trips = await this.getUserTrips(userId);
const tripIds = trips.map((t) => t.id);
if (tripIds.length === 0) {
const hiddenOnly = this.getHiddenCountries(userId);
const hiddenOnly = await this.getHiddenCountries(userId);
const manualCountries = this.db
.prepare('SELECT country_code FROM visited_countries WHERE user_id = ?')
.all(userId) as {
@@ -224,7 +228,7 @@ export class AtlasService {
};
}
const places = this.getPlacesForTrips(tripIds);
const places = await this.getPlacesForTrips(tripIds);
const now = todayUtc();
const tripStatus = this.tripStatusMap(trips, now);
@@ -234,7 +238,7 @@ export class AtlasService {
tripIds: Set<number>;
status: VisitStatus;
}
const placeCountries = this.resolvePlaceCountries(places);
const placeCountries = await this.resolvePlaceCountries(places);
const countrySet = new Map<string, CountryEntry>();
for (const place of places) {
const code = placeCountries.get(place.id);
@@ -302,7 +306,7 @@ export class AtlasService {
// Countries the user explicitly removed. Only the zero-count passes below are
// suppressed — a country with real places isn't removable in the UI anyway, and once
// the user adds a place there the tombstone should stop mattering (#1490).
const hidden = this.getHiddenCountries(userId);
const hidden = await this.getHiddenCountries(userId);
// Merge manually marked countries
const manualCountries = this.db
@@ -489,8 +493,8 @@ export class AtlasService {
// ── Country places ────────────────────────────────────────────────────────
countryPlaces(userId: number, code: string) {
const trips = this.getUserTrips(userId);
async countryPlaces(userId: number, code: string) {
const trips = await this.getUserTrips(userId);
const tripIds = trips.map((t) => t.id);
if (tripIds.length === 0) {
// Post-fold quirk fix: the legacy early return hardcoded manually_marked
@@ -508,7 +512,7 @@ export class AtlasService {
};
}
const places = this.getPlacesForTrips(tripIds);
const places = await this.getPlacesForTrips(tripIds);
const matchingPlaces: {
id: number;
@@ -565,14 +569,14 @@ export class AtlasService {
// ── Mark / unmark country ─────────────────────────────────────────────────
listVisitedCountries(userId: number): { country_code: string; created_at: string; source: string }[] {
async listVisitedCountries(userId: number): Promise<{ country_code: string; created_at: string; source: string }[]> {
return this.db
.prepare('SELECT country_code, created_at, source FROM visited_countries WHERE user_id = ? ORDER BY created_at DESC')
.all(userId) as { country_code: string; created_at: string; source: string }[];
}
/** Countries the user explicitly removed, which stats() must not re-derive (#1490). */
getHiddenCountries(userId: number): Set<string> {
async getHiddenCountries(userId: number): Promise<Set<string>> {
const rows = this.db.prepare('SELECT country_code FROM hidden_countries WHERE user_id = ?').all(userId) as {
country_code: string;
}[];
@@ -589,8 +593,8 @@ export class AtlasService {
* Returns whether this actually added the country, so a caller reporting
* "3 countries added" is not counting the ones that were already there.
*/
markCountry(userId: number, code: string, source: 'manual' | 'dawarich' = 'manual'): boolean {
return this.db.transaction(() => {
async markCountry(userId: number, code: string, source: 'manual' | 'dawarich' = 'manual'): Promise<boolean> {
return this.uow.transactional(async () => {
const inserted = this.db
.prepare('INSERT OR IGNORE INTO visited_countries (user_id, country_code, source) VALUES (?, ?, ?)')
.run(userId, code, source).changes > 0;
@@ -600,8 +604,8 @@ export class AtlasService {
});
}
unmarkCountry(userId: number, code: string): void {
this.db.transaction(() => {
async unmarkCountry(userId: number, code: string): Promise<void> {
await this.uow.transactional(async () => {
this.db.prepare('DELETE FROM visited_countries WHERE user_id = ? AND country_code = ?').run(userId, code);
this.db.prepare('DELETE FROM visited_regions WHERE user_id = ? AND country_code = ?').run(userId, code);
// A country derived from a place or a transport endpoint has no visited_countries row,
@@ -613,7 +617,7 @@ export class AtlasService {
// ── Mark / unmark region ──────────────────────────────────────────────────
listManuallyVisitedRegions(userId: number): { region_code: string; region_name: string; country_code: string }[] {
async listManuallyVisitedRegions(userId: number): Promise<{ region_code: string; region_name: string; country_code: string }[]> {
return this.db
.prepare(
'SELECT region_code, region_name, country_code FROM visited_regions WHERE user_id = ? ORDER BY created_at DESC',
@@ -622,15 +626,15 @@ export class AtlasService {
}
/** Regions the user explicitly removed, which visitedRegions() must not re-derive. */
getHiddenRegions(userId: number): Set<string> {
async getHiddenRegions(userId: number): Promise<Set<string>> {
const rows = this.db.prepare('SELECT region_code FROM hidden_regions WHERE user_id = ?').all(userId) as {
region_code: string;
}[];
return new Set(rows.map((r) => r.region_code));
}
markRegion(userId: number, code: string, name: string, countryCode: string): void {
this.db.transaction(() => {
async markRegion(userId: number, code: string, name: string, countryCode: string): Promise<void> {
await this.uow.transactional(async () => {
this.db
.prepare(
'INSERT OR IGNORE INTO visited_regions (user_id, region_code, region_name, country_code) VALUES (?, ?, ?, ?)',
@@ -651,9 +655,9 @@ export class AtlasService {
// True when the given country still has at least one region that would show as visited —
// derived from place_regions or manually marked — after excluding the given user's hidden
// regions. Used to decide whether removing a region should cascade into hiding the country.
private hasVisibleRegionForCountry(userId: number, countryCode: string, hidden: Set<string>): boolean {
const tripIds = this.getUserTrips(userId).map((t) => t.id);
const placeIds = this.getPlacesForTrips(tripIds)
private async hasVisibleRegionForCountry(userId: number, countryCode: string, hidden: Set<string>): Promise<boolean> {
const tripIds = (await this.getUserTrips(userId)).map((t) => t.id);
const placeIds = (await this.getPlacesForTrips(tripIds))
.filter((p) => p.lat && p.lng)
.map((p) => p.id);
const placeRegionCodes =
@@ -674,10 +678,10 @@ export class AtlasService {
return [...placeRegionCodes, ...manualRegionCodes].some((code) => !hidden.has(code));
}
unmarkRegion(userId: number, code: string): void {
async unmarkRegion(userId: number, code: string): Promise<void> {
// One transaction across the delete, the tombstone and the country cascade —
// better-sqlite3 turns the nested unmarkCountry() transaction into a savepoint.
this.db.transaction(() => {
// MikroORM turns the nested unmarkCountry() transaction into a savepoint.
await this.uow.transactional(async () => {
const region = this.db
.prepare('SELECT country_code FROM visited_regions WHERE user_id = ? AND region_code = ?')
.get(userId, code) as { country_code: string } | undefined;
@@ -695,9 +699,9 @@ export class AtlasService {
// If that was the country's last visible region, hide the country too — otherwise it
// keeps showing "visited" on the world map with nothing left to drill into.
const hidden = this.getHiddenRegions(userId);
if (!this.hasVisibleRegionForCountry(userId, countryCode, hidden)) {
this.unmarkCountry(userId, countryCode);
const hidden = await this.getHiddenRegions(userId);
if (!(await this.hasVisibleRegionForCountry(userId, countryCode, hidden))) {
await this.unmarkCountry(userId, countryCode);
}
}
});
@@ -711,9 +715,9 @@ export class AtlasService {
{ code: string; name: string; placeCount: number; status: VisitStatus; manuallyMarked?: boolean }[]
>;
}> {
const trips = this.getUserTrips(userId);
const trips = await this.getUserTrips(userId);
const tripIds = trips.map((t) => t.id);
const places = this.getPlacesForTrips(tripIds);
const places = await this.getPlacesForTrips(tripIds);
// Regions carry the same status as their country, otherwise zooming into a merely
// planned country would reveal regions painted as visited (#1048).
@@ -787,7 +791,7 @@ export class AtlasService {
}
// Merge manually marked regions
const manualRegions = this.listManuallyVisitedRegions(userId);
const manualRegions = await this.listManuallyVisitedRegions(userId);
for (const r of manualRegions) {
if (!result[r.country_code]) result[r.country_code] = [];
const existing = result[r.country_code].find((x) => x.code === r.region_code);
@@ -807,7 +811,7 @@ export class AtlasService {
// Suppress regions the user explicitly removed, same as stats() does for countries
// via getHiddenCountries (#1490) — otherwise a region derived fresh from place_regions
// (or a manual mark) on every request could never actually be dismissed.
const hidden = this.getHiddenRegions(userId);
const hidden = await this.getHiddenRegions(userId);
if (hidden.size > 0) {
for (const country of Object.keys(result)) {
result[country] = result[country].filter((r) => !hidden.has(r.code));
@@ -850,7 +854,7 @@ export class AtlasService {
// ── Bucket list CRUD ──────────────────────────────────────────────────────
bucketList(userId: number) {
async bucketList(userId: number) {
return this.db.prepare('SELECT * FROM bucket_list WHERE user_id = ? ORDER BY created_at DESC').all(userId);
}
@@ -864,7 +868,7 @@ export class AtlasService {
* "no coordinates" instead of the NULL-is-never-equal SQLite default.
* `lower()` is ASCII-only in SQLite, which is what the client mirrors.
*/
private findDuplicateBucketItem(userId: number, key: BucketIdentity, excludeId?: number): { id: number } | undefined {
private async findDuplicateBucketItem(userId: number, key: BucketIdentity, excludeId?: number): Promise<{ id: number } | undefined> {
return this.db
.prepare(
`SELECT id FROM bucket_list
@@ -882,7 +886,7 @@ export class AtlasService {
| undefined;
}
createBucketItem(userId: number, data: CreateBucketData) {
async createBucketItem(userId: number, data: CreateBucketData) {
const identity: BucketIdentity = {
name: data.name.trim(),
lat: data.lat ?? null,
@@ -892,7 +896,7 @@ export class AtlasService {
};
// #1898: the same wish must not stack up. A different target date (or a
// different place under the same name) is a different wish and still lands.
if (this.findDuplicateBucketItem(userId, identity)) throw new BucketItemExistsError();
if (await this.findDuplicateBucketItem(userId, identity)) throw new BucketItemExistsError();
const result = this.db
.prepare(
'INSERT INTO bucket_list (user_id, name, lat, lng, country_code, notes, target_date) VALUES (?, ?, ?, ?, ?, ?, ?)',
@@ -909,7 +913,7 @@ export class AtlasService {
return this.db.prepare('SELECT * FROM bucket_list WHERE id = ?').get(result.lastInsertRowid);
}
updateBucketItem(userId: number, itemId: string | number, data: UpdateBucketData) {
async updateBucketItem(userId: number, itemId: string | number, data: UpdateBucketData) {
const item = this.db.prepare('SELECT * FROM bucket_list WHERE id = ? AND user_id = ?').get(itemId, userId) as
| (BucketIdentity & { id: number })
| undefined;
@@ -924,7 +928,7 @@ export class AtlasService {
country_code: data.country_code !== undefined ? blankToNull(data.country_code) : blankToNull(item.country_code),
target_date: data.target_date !== undefined ? blankToNull(data.target_date) : blankToNull(item.target_date),
};
if (this.findDuplicateBucketItem(userId, next, item.id)) throw new BucketItemExistsError();
if (await this.findDuplicateBucketItem(userId, next, item.id)) throw new BucketItemExistsError();
// Post-fold quirk fixes: the value bindings use `?? null` (the legacy
// `|| null` wrote NULL for lat/lng 0 and empty-string notes), and the
// UPDATE + re-select are user-scoped (defense-in-depth; the ownership
@@ -959,7 +963,7 @@ export class AtlasService {
return this.db.prepare('SELECT * FROM bucket_list WHERE id = ? AND user_id = ?').get(itemId, userId);
}
deleteBucketItem(userId: number, itemId: string | number): boolean {
async deleteBucketItem(userId: number, itemId: string | number): Promise<boolean> {
const item = this.db.prepare('SELECT * FROM bucket_list WHERE id = ? AND user_id = ?').get(itemId, userId);
if (!item) return false;
// Post-fold quirk fix: user-scoped DELETE (defense-in-depth, see updateBucketItem).
@@ -1000,7 +1004,7 @@ export class AtlasService {
* much to spend on a label. An unresolved trip reports an empty list, which the
* caller renders as "no country" rather than as a wrong one.
*/
lastTrip(userId: number): { title: string; start_date: string | null; end_date: string | null; countries: string[] } | null {
async lastTrip(userId: number): Promise<{ title: string; start_date: string | null; end_date: string | null; countries: string[] } | null> {
const trip = this.db.get<{ id: number; title: string; start_date: string | null; end_date: string | null }>(`
SELECT t.id, t.title, t.start_date, t.end_date
FROM trips t
@@ -1030,7 +1034,7 @@ export class AtlasService {
};
}
getTravelStats(userId: number) {
async getTravelStats(userId: number) {
// The resolved region rides along so cityFromAddress can tell the city apart from
// the region sitting right above it in the same address (#1115).
const places = this.db.all<{ address: string | null; lat: number | null; lng: number | null; region_name: string | null }>(`
@@ -1131,7 +1135,7 @@ export class AtlasService {
// Countries the user removed in Atlas stay removed on the dashboard too, so the
// passport card and the Atlas map agree (#1490).
for (const code of this.getHiddenCountries(userId)) countryCodes.delete(code.toUpperCase());
for (const code of await this.getHiddenCountries(userId)) countryCodes.delete(code.toUpperCase());
return {
countries: [...countryCodes],
@@ -1140,7 +1144,7 @@ export class AtlasService {
totalTrips: tripStats?.trips || 0,
totalDays: tripStats?.days || 0,
totalPlaces: places.length,
totalDistanceKm: this.flightDistanceKm(userId),
totalDistanceKm: await this.flightDistanceKm(userId),
};
}
@@ -1170,7 +1174,7 @@ export class AtlasService {
(NOT EXISTS (SELECT 1 FROM reservation_travelers rt WHERE rt.reservation_id = r.id)
OR EXISTS (SELECT 1 FROM reservation_travelers rt WHERE rt.reservation_id = r.id AND rt.user_id = ?))`;
private flightDistanceKm(userId: number): number {
private async flightDistanceKm(userId: number): Promise<number> {
const rows = this.db.all<{ reservation_id: number; lat: number; lng: number }>(`
SELECT re.reservation_id, re.lat, re.lng
FROM reservation_endpoints re
@@ -46,13 +46,13 @@ export class PublicStatsController {
) {}
@Get('stats')
stats(@Req() req: Request): PublicApiStats {
async stats(@Req() req: Request): Promise<PublicApiStats> {
enforcePublicApiRateLimit(this.rl, req);
requireScope(req, 'stats');
const userId = requireUserId(req);
const travel = this.atlas.getTravelStats(userId);
const last = this.atlas.lastTrip(userId);
const travel = await this.atlas.getTravelStats(userId);
const last = await this.atlas.lastTrip(userId);
// Counts, not the arrays behind them. A consumer that wants the members asks
// /api/v1/trips; this endpoint exists for the one that wants a number.
@@ -28,7 +28,7 @@ export class TravelStatsController {
constructor(private readonly atlas: AtlasService) {}
@Get('travel-stats')
travelStats(@CurrentUser() user: User) {
async travelStats(@CurrentUser() user: User) {
return this.atlas.getTravelStats(user.id);
}
}
+5 -5
View File
@@ -160,21 +160,21 @@ export class AuthController {
async mapsKey(@CurrentUser() user: User, @Body() body: MapsKeyUpdateDto, @Req() req: Request) {
// changedKeys is for the audit line, not for the client: destructured off so
// the response body stays what it always was.
const { changedKeys = [], ...result } = this.profile.updateMapsKey(user.id, body.maps_api_key);
const { changedKeys = [], ...result } = await this.profile.updateMapsKey(user.id, body.maps_api_key);
await this.auditApiKeys(user.id, changedKeys, req);
return result;
}
@Put('me/api-keys')
async apiKeys(@CurrentUser() user: User, @Body() body: ApiKeysUpdateDto, @Req() req: Request) {
const { changedKeys = [], ...result } = this.profile.updateApiKeys(user.id, body);
const { changedKeys = [], ...result } = await this.profile.updateApiKeys(user.id, body);
await this.auditApiKeys(user.id, changedKeys, req);
return result;
}
@Put('me/settings')
async updateSettings(@CurrentUser() user: User, @Body() body: SettingsUpdateDto, @Req() req: Request) {
const result = this.profile.updateSettings(user.id, body);
const result = await this.profile.updateSettings(user.id, body);
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
@@ -183,8 +183,8 @@ export class AuthController {
}
@Get('me/settings')
getSettings(@CurrentUser() user: User) {
const result = this.profile.getSettings(user.id);
async getSettings(@CurrentUser() user: User) {
const result = await this.profile.getSettings(user.id);
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
+2 -2
View File
@@ -267,11 +267,11 @@ export class AuthService {
// nor hide them from a member who does have one (#1939). Unauthenticated the
// question is only about the instance, which is the first two steps of the
// chain; id 0 matches no row.
const hasGoogleKey = !!resolveApiKey(this.db, 'maps_api_key', authenticatedUser?.id ?? 0, readEnv().maps.placesApiKey).key;
const hasGoogleKey = !!(await resolveApiKey(this.db, 'maps_api_key', authenticatedUser?.id ?? 0, readEnv().maps.placesApiKey)).key;
// The same question for Amap, asked the same way. The client needs both to
// tell "search is unavailable" from "search runs on OpenStreetMap", and to
// know whether the provider the admin selected actually has a credential.
const hasAmapKey = !!resolveApiKey(this.db, 'amap_api_key', authenticatedUser?.id ?? 0, readEnv().maps.amapApiKey).key;
const hasAmapKey = !!(await resolveApiKey(this.db, 'amap_api_key', authenticatedUser?.id ?? 0, readEnv().maps.amapApiKey)).key;
const placesProviderRow = this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'places_provider'")?.value;
const placesProvider = isPlacesProviderChoice(placesProviderRow) ? placesProviderRow : 'auto';
const oidcDisplayName = readEnv().oidc.displayName ||
+35 -28
View File
@@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import { readEnv, getAppUrl } from '../../app-config';
import { DatabaseService } from '../database/database.service';
import { UnitOfWork } from '../database/unit-of-work';
import { StorageService } from '../storage/storage.service';
import { decrypt_api_key, maybe_encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { avatarUrl } from '../common/avatarUrl';
@@ -35,6 +36,7 @@ export class UserProfileService {
constructor(
private readonly db: DatabaseService,
private readonly storage: StorageService,
private readonly uow: UnitOfWork,
) {}
/**
@@ -66,13 +68,13 @@ export class UserProfileService {
* value, because that is what the panel shows them and what the search uses;
* their own column only speaks when no instance value has been set yet.
*/
private storedKeyPlaintext(
private async storedKeyPlaintext(
name: 'maps_api_key' | 'openweather_api_key' | 'unsplash_api_key' | 'amap_api_key',
current: Pick<User, 'maps_api_key' | 'openweather_api_key' | 'unsplash_api_key' | 'amap_api_key'> | undefined,
isAdmin: boolean,
): string {
): Promise<string> {
if (isAdmin && (INSTANCE_API_KEY_NAMES as readonly string[]).includes(name)) {
const instance = readInstanceApiKey(this.db, name as InstanceApiKeyName);
const instance = await readInstanceApiKey(this.db, name as InstanceApiKeyName);
if (instance !== null) return instance;
}
return decrypt_api_key(current?.[name]) ?? '';
@@ -89,16 +91,21 @@ export class UserProfileService {
* `skipped` are the names a managed install refuses to write — auditing them
* would claim a change that never happened.
*/
private changedKeyNames(
private async changedKeyNames(
body: Record<string, unknown>,
current: Pick<User, 'maps_api_key' | 'openweather_api_key' | 'unsplash_api_key' | 'amap_api_key'> | undefined,
isAdmin: boolean,
skipped: string[] = [],
): string[] {
): Promise<string[]> {
const norm = (v: unknown) => String(v ?? '').trim();
return (['maps_api_key', 'openweather_api_key', 'unsplash_api_key', 'amap_api_key'] as const).filter(
(name) => body[name] !== undefined && !skipped.includes(name) && norm(body[name]) !== norm(this.storedKeyPlaintext(name, current, isAdmin))
);
// An explicit loop rather than `.filter`: storedKeyPlaintext reads the
// instance row and a filter predicate cannot await. Same order, same names.
const changed: string[] = [];
for (const name of ['maps_api_key', 'openweather_api_key', 'unsplash_api_key', 'amap_api_key'] as const) {
if (body[name] === undefined || skipped.includes(name)) continue;
if (norm(body[name]) !== norm(await this.storedKeyPlaintext(name, current, isAdmin))) changed.push(name);
}
return changed;
}
/**
@@ -109,40 +116,40 @@ export class UserProfileService {
* member the instance credential. A non-admin keeps writing their own column,
* which is still the last step of the resolver.
*/
private mirrorInstanceKeys(body: Record<string, unknown>, isAdmin: boolean): void {
private async mirrorInstanceKeys(body: Record<string, unknown>, isAdmin: boolean): Promise<void> {
if (!isAdmin) return;
for (const name of INSTANCE_API_KEY_NAMES) {
if (body[name] !== undefined) writeInstanceApiKey(this.db, name, body[name]);
if (body[name] !== undefined) await writeInstanceApiKey(this.db, name, body[name]);
}
}
updateMapsKey(userId: number, key: unknown) {
async updateMapsKey(userId: number, key: unknown) {
const maps_api_key = key as string | null | undefined;
if (this.managed) {
return { success: true, maps_api_key: null, managed_keys: ['maps_api_key'], changedKeys: [] };
}
const current = this.currentKeys(userId);
const isAdmin = current?.role === 'admin';
const changedKeys = this.changedKeyNames({ maps_api_key }, current, isAdmin);
this.db.transaction(() => {
const changedKeys = await this.changedKeyNames({ maps_api_key }, current, isAdmin);
await this.uow.transactional(async () => {
this.db.run(
'UPDATE users SET maps_api_key = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
maybe_encrypt_api_key(maps_api_key), userId
);
this.mirrorInstanceKeys({ maps_api_key }, isAdmin);
await this.mirrorInstanceKeys({ maps_api_key }, isAdmin);
});
return { success: true, maps_api_key: mask_stored_api_key(maps_api_key), changedKeys };
}
updateApiKeys(userId: number, rawBody: unknown) {
async updateApiKeys(userId: number, rawBody: unknown) {
const body = rawBody as { maps_api_key?: string; openweather_api_key?: string; unsplash_api_key?: string; amap_api_key?: string };
const { blocked } = splitManagedKeys(body, this.managed);
for (const key of blocked) delete body[key as keyof typeof body];
const current = this.currentKeys(userId);
const isAdmin = current?.role === 'admin';
const changedKeys = this.changedKeyNames(body, current, isAdmin, blocked);
const changedKeys = await this.changedKeyNames(body, current, isAdmin, blocked);
this.db.transaction(() => {
await this.uow.transactional(async () => {
// `?? null` instead of the former non-null assertions: a user row deleted
// mid-request must degrade to a 0-row UPDATE, not a TypeError/500.
this.db.run(
@@ -153,7 +160,7 @@ export class UserProfileService {
body.amap_api_key !== undefined ? maybe_encrypt_api_key(body.amap_api_key) : current?.amap_api_key ?? null,
userId
);
this.mirrorInstanceKeys(body, isAdmin);
await this.mirrorInstanceKeys(body, isAdmin);
});
const updated = this.db.get<Pick<User, 'id' | 'username' | 'email' | 'role' | 'maps_api_key' | 'openweather_api_key' | 'unsplash_api_key' | 'amap_api_key' | 'avatar' | 'mfa_enabled'>>(
@@ -170,10 +177,10 @@ export class UserProfileService {
};
}
updateSettings(
async updateSettings(
userId: number,
rawBody: unknown
): { error?: string; status?: number; success?: boolean; user?: Record<string, unknown>; changedKeys?: string[] } {
): Promise<{ error?: string; status?: number; success?: boolean; user?: Record<string, unknown>; changedKeys?: string[] }> {
const body = rawBody as { maps_api_key?: string; openweather_api_key?: string; unsplash_api_key?: string; amap_api_key?: string; username?: string; email?: string };
const { maps_api_key, openweather_api_key, unsplash_api_key, amap_api_key, username, email } = body;
@@ -217,14 +224,14 @@ export class UserProfileService {
// the same row decides whether the two instance-wide names travel with it.
const current = this.currentKeys(userId);
const isAdmin = current?.role === 'admin';
const changedKeys = keyLocked ? [] : this.changedKeyNames(body, current, isAdmin, blocked);
const changedKeys = keyLocked ? [] : await this.changedKeyNames(body, current, isAdmin, blocked);
if (updates.length > 0) {
updates.push('updated_at = CURRENT_TIMESTAMP');
params.push(userId);
this.db.transaction(() => {
await this.uow.transactional(async () => {
this.db.run(`UPDATE users SET ${updates.join(', ')} WHERE id = ?`, ...params);
if (!keyLocked) this.mirrorInstanceKeys(body, isAdmin);
if (!keyLocked) await this.mirrorInstanceKeys(body, isAdmin);
});
}
@@ -242,7 +249,7 @@ export class UserProfileService {
};
}
getSettings(userId: number): { error?: string; status?: number; settings?: Record<string, unknown> } {
async getSettings(userId: number): Promise<{ error?: string; status?: number; settings?: Record<string, unknown> }> {
const user = this.db.get<Pick<User, 'role' | 'maps_api_key' | 'openweather_api_key' | 'unsplash_api_key' | 'amap_api_key'>>(
'SELECT role, maps_api_key, openweather_api_key, unsplash_api_key, amap_api_key FROM users WHERE id = ?',
userId
@@ -272,10 +279,10 @@ export class UserProfileService {
// instance value exists — on that install it is what the resolver picks too.
return {
settings: {
maps_api_key: readInstanceApiKey(this.db, 'maps_api_key') ?? decrypt_api_key(user.maps_api_key),
maps_api_key: (await readInstanceApiKey(this.db, 'maps_api_key')) ?? decrypt_api_key(user.maps_api_key),
openweather_api_key: decrypt_api_key(user.openweather_api_key),
unsplash_api_key: readInstanceApiKey(this.db, 'unsplash_api_key') ?? decrypt_api_key(user.unsplash_api_key),
amap_api_key: readInstanceApiKey(this.db, 'amap_api_key') ?? decrypt_api_key(user.amap_api_key),
unsplash_api_key: (await readInstanceApiKey(this.db, 'unsplash_api_key')) ?? decrypt_api_key(user.unsplash_api_key),
amap_api_key: (await readInstanceApiKey(this.db, 'amap_api_key')) ?? decrypt_api_key(user.amap_api_key),
},
};
}
@@ -349,7 +356,7 @@ export class UserProfileService {
// The key a search would actually use, not the one in this admin's column:
// testing a value nothing resolves to is how "the panel says the key is
// fine" and "every search 403s" coexisted (#1939).
const { key: maps_api_key } = resolveApiKey(this.db, 'maps_api_key', userId, readEnv().maps.placesApiKey);
const { key: maps_api_key } = await resolveApiKey(this.db, 'maps_api_key', userId, readEnv().maps.placesApiKey);
if (maps_api_key) {
try {
// Same Referer as maps.service googleFetch — without it, keys with an
@@ -627,15 +627,15 @@ export class DawarichSuggestionsService {
* `INSERT OR IGNORE` underneath means a country already marked by hand keeps
* its own provenance — confirming it again does not relabel it as imported.
*/
acceptAtlasCountries(userId: number, codes: string[]): number {
async acceptAtlasCountries(userId: number, codes: string[]): Promise<number> {
let marked = 0;
this.db.transaction(() => {
await this.uow.transactional(async () => {
for (const raw of codes) {
const code = raw.trim().toUpperCase();
if (!/^[A-Z]{2}$/.test(code)) continue;
// Counted only when it was actually added: "3 countries added" must not
// include ones that were already on the map.
if (this.atlas.markCountry(userId, code, 'dawarich')) marked++;
if (await this.atlas.markCountry(userId, code, 'dawarich')) marked++;
}
});
return marked;
@@ -195,8 +195,8 @@ export class DawarichController {
@Post('atlas/accept')
@HttpCode(200)
acceptAtlasCountries(@CurrentUser() user: User, @Body() body: DawarichAtlasAcceptDto) {
return { marked: this.suggestions.acceptAtlasCountries(user.id, body.countryCodes) };
async acceptAtlasCountries(@CurrentUser() user: User, @Body() body: DawarichAtlasAcceptDto) {
return { marked: await this.suggestions.acceptAtlasCountries(user.id, body.countryCodes) };
}
// ── Track overlay ──────────────────────────────────────────────────────────
@@ -33,8 +33,8 @@ export class JourneyPublicController {
) {}
@Get(':token')
get(@Param('token') token: string) {
const data = this.journey.getPublicJourney(token);
async get(@Param('token') token: string) {
const data = await this.journey.getPublicJourney(token);
if (!data) {
throw new HttpException({ error: 'Not found' }, 404);
}
@@ -154,7 +154,7 @@ export class JourneyShareService {
return { ownerId: photo.owner_id || photo.journey_owner_id };
}
getPublicJourney(token: string) {
async getPublicJourney(token: string) {
const row = this.db.prepare('SELECT * FROM journey_share_tokens WHERE token = ?').get(token) as any;
if (!row) return null;
@@ -247,7 +247,7 @@ export class JourneyShareService {
// instance default and the managed-instance key in that order; carto_api_key is
// encrypted at rest but deliberately unmasked, since it is useless until it
// reaches a browser.
const ownerCartoKey = this.settings.getUserSettings(journey.user_id)['carto_api_key'];
const ownerCartoKey = (await this.settings.getUserSettings(journey.user_id))['carto_api_key'];
const cartoApiKey = typeof ownerCartoKey === 'string' ? ownerCartoKey.trim() : '';
return {
+1 -1
View File
@@ -94,7 +94,7 @@ export class JourneyService {
uploadToImmich(userId: number, relativePath: string, originalName: string) { return this.immich.uploadToImmich(userId, relativePath, originalName); }
// Public (share-token) access — no auth, validated by token.
getPublicJourney(token: string) { return this.share.getPublicJourney(token); }
async getPublicJourney(token: string) { return this.share.getPublicJourney(token); }
validateShareTokenForPhoto(token: string, photoId: number) { return this.share.validateShareTokenForPhoto(token, photoId); }
validateShareTokenForAsset(token: string, assetId: string) { return this.share.validateShareTokenForAsset(token, assetId); }
streamPhoto(res: Response, ownerId: number, photoId: number, kind: 'thumbnail' | 'original') { return this.photoResolver.streamPhoto(res, ownerId, photoId, kind); }
@@ -30,7 +30,7 @@ export class LlmConfigResolver {
*/
async resolve(userId: number): Promise<ResolvedLlmConfig | null> {
if (!(await this.addons.isAddonEnabled(ADDON_IDS.LLM_PARSING))) return null;
return this.readInstanceConfig() ?? this.readUserConfig(userId);
return this.readInstanceConfig() ?? (await this.readUserConfig(userId));
}
private readInstanceConfig(): ResolvedLlmConfig | null {
@@ -57,8 +57,8 @@ export class LlmConfigResolver {
};
}
private readUserConfig(userId: number): ResolvedLlmConfig | null {
const settings = this.settings.getUserSettings(userId);
private async readUserConfig(userId: number): Promise<ResolvedLlmConfig | null> {
const settings = await this.settings.getUserSettings(userId);
const provider = asProvider(settings.llm_provider);
const model = typeof settings.llm_model === 'string' ? settings.llm_model.trim() : '';
if (!provider || !model) return null;
@@ -72,7 +72,7 @@ export class LlmConfigResolver {
// an admin's own row. This is the choke point every consumer passes
// (booking import and the plugin RPC surface), and the only place that also
// catches values already sitting in the db.
const endpoints = this.settings.getAdminUserDefaults();
const endpoints = await this.settings.getAdminUserDefaults();
// 'local' is an endpoint choice too ("some address I name"), so without an
// admin-set local endpoint there is no config at all, never a silent
// redirect to a different provider.
@@ -82,7 +82,7 @@ export class LlmConfigResolver {
? endpoints.llm_base_url.trim()
: undefined;
const apiKey = this.settings.getDecryptedUserSetting(userId, 'llm_api_key') ?? undefined;
const apiKey = (await this.settings.getDecryptedUserSetting(userId, 'llm_api_key')) ?? undefined;
return {
provider,
model,
+18 -18
View File
@@ -1001,16 +1001,16 @@ export class MapsService {
* everybody else got the lowest-id admin's and a 403 from Google. The source
* is returned so a provider error can say which of the three was used.
*/
resolveMapsKey(userId: number): { key: string | null; source: ApiKeySource | null } {
async resolveMapsKey(userId: number): Promise<{ key: string | null; source: ApiKeySource | null }> {
return resolveApiKey(this.database, 'maps_api_key', userId, readEnv().maps.placesApiKey);
}
getMapsKey(userId: number): string | null {
return this.resolveMapsKey(userId).key;
async getMapsKey(userId: number): Promise<string | null> {
return (await this.resolveMapsKey(userId)).key;
}
/** The Amap credential, resolved through the identical three-step chain. */
resolveAmapKey(userId: number): { key: string | null; source: ApiKeySource | null } {
async resolveAmapKey(userId: number): Promise<{ key: string | null; source: ApiKeySource | null }> {
return resolveApiKey(this.database, 'amap_api_key', userId, readEnv().maps.amapApiKey);
}
@@ -1046,12 +1046,12 @@ export class MapsService {
* walked when there is no Google key, so an install on Google issues exactly
* the database reads it always did.
*/
keyedProvider(userId: number): KeyedProvider | null {
async keyedProvider(userId: number): Promise<KeyedProvider | null> {
const choice = this.placesProviderChoice();
if (choice === 'openstreetmap') return null;
if (choice !== 'amap') {
const google = this.resolveMapsKey(userId);
const google = await this.resolveMapsKey(userId);
if (google.key) return { id: 'google', key: google.key, source: google.source };
// An explicit 'google' choice with no key is not a reason to query Amap
// instead: this install is on Google and is misconfigured. OSM answers,
@@ -1059,15 +1059,15 @@ export class MapsService {
if (choice === 'google') return null;
}
const amap = this.resolveAmapKey(userId);
const amap = await this.resolveAmapKey(userId);
return amap.key
? { id: 'amap', provider: new AmapPlacesProvider({ key: amap.key, source: amap.source, userId }) }
: null;
}
/** The Amap provider, when Amap holds the keyed slot; null otherwise. */
resolvePlacesProvider(userId: number): AmapPlacesProvider | null {
const keyed = this.keyedProvider(userId);
async resolvePlacesProvider(userId: number): Promise<AmapPlacesProvider | null> {
const keyed = await this.keyedProvider(userId);
return keyed?.id === 'amap' ? keyed.provider : null;
}
@@ -1085,9 +1085,9 @@ export class MapsService {
* install that has since dropped its Amap key. Callers treat that as a miss,
* not an error.
*/
private providerForPlaceId(userId: number, placeId: string): AmapPlacesProvider | null {
private async providerForPlaceId(userId: number, placeId: string): Promise<AmapPlacesProvider | null> {
if (!isAmapPlaceId(placeId)) return null;
const amap = this.resolveAmapKey(userId);
const amap = await this.resolveAmapKey(userId);
return amap.key ? new AmapPlacesProvider({ key: amap.key, source: amap.source, userId }) : null;
}
@@ -2023,7 +2023,7 @@ export class MapsService {
locationBias?: { lat: number; lng: number; radius?: number },
opts: { googleIdentityOnly?: boolean } = {},
): Promise<{ places: Record<string, unknown>[]; source: string }> {
const keyed = this.keyedProvider(userId);
const keyed = await this.keyedProvider(userId);
const { key: apiKey, source: keySource } = keyed?.id === 'google' ? keyed : { key: null, source: null };
// The TREK index answers first, whether or not a Google key exists. It is
@@ -2179,7 +2179,7 @@ export class MapsService {
locationBias?: { low: { lat: number; lng: number }; high: { lat: number; lng: number } },
sessionToken?: string,
): Promise<MapsAutocompleteResult> {
const keyed = this.keyedProvider(userId);
const keyed = await this.keyedProvider(userId);
const { key: apiKey, source: keySource } = keyed?.id === 'google' ? keyed : { key: null, source: null };
// This is the path that mattered most. Nominatim's usage policy names
@@ -2468,7 +2468,7 @@ export class MapsService {
// (the 'de' the legacy service defaulted to was a development leftover;
// cache rows keyed 'de' for lang-less callers go cold once — 7-day TTL).
const langKey = toApiLang(lang);
const apiKey = this.getMapsKey(userId);
const apiKey = await this.getMapsKey(userId);
// No key means no way to resolve a Google id: they have no OpenStreetMap
// equivalent to fall back to. That is an empty result, not a client error.
// Search and autocomplete already answer their keyless case with the OSM
@@ -2567,7 +2567,7 @@ export class MapsService {
placeId: string,
lang?: string,
): Promise<{ place: Record<string, unknown> | null }> {
const provider = this.providerForPlaceId(userId, placeId);
const provider = await this.providerForPlaceId(userId, placeId);
if (!provider) return { place: null };
const langKey = toApiLang(lang);
@@ -2622,7 +2622,7 @@ export class MapsService {
}
const langKey = toApiLang(lang); // 'en' default — see getPlaceDetails
const apiKey = this.getMapsKey(userId);
const apiKey = await this.getMapsKey(userId);
// Same as the lean lookup above: an empty result, not a client error.
if (!apiKey) return { place: null };
@@ -2740,7 +2740,7 @@ export class MapsService {
const fetchPromise = (async (): Promise<{ attribution: string | null } | null> => {
await acquirePhotoFetchSlot();
try {
const apiKey = this.getMapsKey(userId);
const apiKey = await this.getMapsKey(userId);
// Coordinate-based Wikipedia/Wikimedia lookup. Used for coordinate-only
// (right-click) places and as a fallback when a Google place yields no photo,
@@ -2890,7 +2890,7 @@ export class MapsService {
// operator env var and the instance-wide row, and nobody's personal key is
// read on somebody else's behalf (#1939). Nominatim stays the fallback, so
// an Amap outage does not take a right-click down with it.
const amap = this.resolvePlacesProvider(0);
const amap = await this.resolvePlacesProvider(0);
if (amap) {
const latNum = Number.parseFloat(lat);
const lngNum = Number.parseFloat(lng);
@@ -448,7 +448,7 @@ export class PlaceEnrichmentService {
/** The record the caller already holds; only its category is read. */
details: Record<string, unknown> | null,
): Promise<PlacePhotoCandidate[]> {
const apiKey = this.maps.getMapsKey(userId);
const apiKey = await this.maps.getMapsKey(userId);
const wantsGoogle = !!apiKey && !this.maps.photosDisabled() && isGooglePlaceId(placeId);
const { wikidata, wikipedia } = identity;
@@ -693,7 +693,7 @@ export class PlaceEnrichmentService {
const fromSite = await this.websiteDescription(placeId);
if (fromSite) return fromSite;
const apiKey = this.maps.getMapsKey(userId);
const apiKey = await this.maps.getMapsKey(userId);
if (apiKey && !this.maps.detailsDisabled() && isGooglePlaceId(placeId)) {
const summary = await this.maps.fetchEditorialSummary(placeId, apiKey, req.lang);
if (summary) {
+2 -2
View File
@@ -1488,7 +1488,7 @@ export class PlacesService {
async enrichImportedPlaces(tripId: string, userId: number, places: EnrichablePlace[], lang?: string): Promise<void> {
try {
if (!places.length) return;
if (!this.maps.getMapsKey(userId)) return;
if (!(await this.maps.getMapsKey(userId))) return;
await mapWithConcurrency(places, ENRICH_CONCURRENCY, async (place) => {
try {
await this.enrichOne(tripId, userId, place, lang);
@@ -1566,7 +1566,7 @@ export class PlacesService {
const place = this.dbs.get<Place>('SELECT * FROM places WHERE id = ? AND trip_id = ?', placeId, tripId);
if (!place) return { error: 'Place not found', status: 404 };
return this.unsplash.searchUnsplashPhotos(place.name + (place.address ? ' ' + place.address : ''), 5, this.unsplash.getUnsplashKey(userId));
return this.unsplash.searchUnsplashPhotos(place.name + (place.address ? ' ' + place.address : ''), 5, await this.unsplash.getUnsplashKey(userId));
}
// -------------------------------------------------------------------------
@@ -145,7 +145,7 @@ export class RoadtripPlanService {
throw new HttpException({ error: 'This trip exceeds the 150-visit calculation limit.' }, 400);
const asked = new Set<string>();
const distanceUnit: DistanceUnit =
this.settings.getUserSettings(userId).distance_unit === 'imperial' ? 'imperial' : 'metric';
(await this.settings.getUserSettings(userId)).distance_unit === 'imperial' ? 'imperial' : 'metric';
const fetchRun = async (stops: RoadtripStop[], dayId: number, profile: string) => {
const points: { lat: number; lng: number }[] = [];
const stopAt: number[] = [];
@@ -151,7 +151,7 @@ export class RoadtripRouterService {
profile: string,
avoid: RouteAvoidClass[],
): Promise<RoadtripRoute> {
const settings = this.settings.getUserSettings(userId);
const settings = await this.settings.getUserSettings(userId);
const key = JSON.stringify([
userId,
tripId,
@@ -14,34 +14,34 @@ export class SchoolHolidaysController {
constructor(private readonly holidays: SchoolHolidaysService) {}
@Get()
catalog() { return this.holidays.catalog(); }
async catalog() { return this.holidays.catalog(); }
@Get('regions/:id')
region(@Param('id', ParseIntPipe) id: number) { return this.holidays.region(id); }
async region(@Param('id', ParseIntPipe) id: number) { return this.holidays.region(id); }
@Get('regions/:id/holidays/:year')
forYear(@Param('id', ParseIntPipe) id: number, @Param('year') year: string) {
async forYear(@Param('id', ParseIntPipe) id: number, @Param('year') year: string) {
if (!/^\d{4}$/.test(year)) throw new BadRequestException('Invalid year');
return this.holidays.holidays(id, year);
}
@Post('countries')
@UseGuards(AdminGuard)
createCountry(@Body() body: SchoolHolidayCountryDto) { return this.holidays.createCountry(body); }
async createCountry(@Body() body: SchoolHolidayCountryDto) { return this.holidays.createCountry(body); }
@Delete('countries/:code')
@UseGuards(AdminGuard)
deleteCountry(@Param('code') code: string) { return this.holidays.deleteCountry(code); }
async deleteCountry(@Param('code') code: string) { return this.holidays.deleteCountry(code); }
@Post('countries/:code/regions')
@UseGuards(AdminGuard)
createRegion(@Param('code') code: string, @Body() body: SchoolHolidayRegionDto) { return this.holidays.createRegion(code, body); }
async createRegion(@Param('code') code: string, @Body() body: SchoolHolidayRegionDto) { return this.holidays.createRegion(code, body); }
@Put('regions/:id')
@UseGuards(AdminGuard)
updateRegion(@Param('id', ParseIntPipe) id: number, @Body() body: SchoolHolidayRegionDto) { return this.holidays.updateRegion(id, body); }
async updateRegion(@Param('id', ParseIntPipe) id: number, @Body() body: SchoolHolidayRegionDto) { return this.holidays.updateRegion(id, body); }
@Delete('regions/:id')
@UseGuards(AdminGuard)
deleteRegion(@Param('id', ParseIntPipe) id: number, @Query('revision', ParseIntPipe) revision: number) { return this.holidays.deleteRegion(id, revision); }
async deleteRegion(@Param('id', ParseIntPipe) id: number, @Query('revision', ParseIntPipe) revision: number) { return this.holidays.deleteRegion(id, revision); }
}
@@ -10,9 +10,9 @@ import { SchoolHolidaysService } from './school-holidays.service';
export class SchoolHolidaysMcp {
constructor(private readonly holidays: SchoolHolidaysService, private readonly guards: McpToolGuardsService) {}
private adminWrite(ctx: McpContext, write: () => unknown) {
private async adminWrite(ctx: McpContext, write: () => unknown) {
if (!this.guards.isAdminUser(ctx.userId)) return adminRequired();
try { return ok(write()); }
try { return ok(await write()); }
catch (error) {
if (error instanceof HttpException || error instanceof z.ZodError) return errorResult(error.message);
throw error;
@@ -25,7 +25,7 @@ export class SchoolHolidaysMcp {
inputSchema: {}, annotations: TOOL_ANNOTATIONS_READONLY,
access: { group: 'vacay', mode: 'read' },
})
catalog() { return ok(this.holidays.catalog()); }
async catalog() { return ok(await this.holidays.catalog()); }
@Tool({
name: 'get_manual_school_holiday_region',
@@ -33,7 +33,7 @@ export class SchoolHolidaysMcp {
inputSchema: { regionId: idSchema }, annotations: TOOL_ANNOTATIONS_READONLY,
access: { group: 'vacay', mode: 'read' },
})
region({ regionId }: { regionId: number }) { return ok(this.holidays.region(regionId)); }
async region({ regionId }: { regionId: number }) { return ok(await this.holidays.region(regionId)); }
@Tool({
name: 'list_manual_school_holidays',
@@ -41,7 +41,7 @@ export class SchoolHolidaysMcp {
inputSchema: { regionId: idSchema, year: z.number().int().min(1000).max(9999) },
annotations: TOOL_ANNOTATIONS_READONLY, access: { group: 'vacay', mode: 'read' },
})
forYear({ regionId, year }: { regionId: number; year: number }) { return ok({ holidays: this.holidays.holidays(regionId, String(year)) }); }
async forYear({ regionId, year }: { regionId: number; year: number }) { return ok({ holidays: await this.holidays.holidays(regionId, String(year)) }); }
@Tool({
name: 'create_manual_school_holiday_country',
@@ -49,7 +49,7 @@ export class SchoolHolidaysMcp {
inputSchema: schoolHolidayCountryRequestSchema.shape, annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
access: { group: 'vacay', mode: 'write' },
})
createCountry(body: SchoolHolidayCountryRequest, ctx: McpContext) {
async createCountry(body: SchoolHolidayCountryRequest, ctx: McpContext) {
return this.adminWrite(ctx, () => this.holidays.createCountry(schoolHolidayCountryRequestSchema.parse(body)));
}
@@ -59,7 +59,7 @@ export class SchoolHolidaysMcp {
inputSchema: { country: schoolHolidayCountryRequestSchema.shape.code, ...schoolHolidayRegionRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT, access: { group: 'vacay', mode: 'write' },
})
createRegion({ country, ...body }: SchoolHolidayRegionRequest & { country: string }, ctx: McpContext) {
async createRegion({ country, ...body }: SchoolHolidayRegionRequest & { country: string }, ctx: McpContext) {
return this.adminWrite(ctx, () => this.holidays.createRegion(country, schoolHolidayRegionRequestSchema.parse(body)));
}
@@ -69,7 +69,7 @@ export class SchoolHolidaysMcp {
inputSchema: { regionId: idSchema, ...schoolHolidayRegionRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_WRITE, access: { group: 'vacay', mode: 'write' },
})
updateRegion({ regionId, ...body }: SchoolHolidayRegionRequest & { regionId: number }, ctx: McpContext) {
async updateRegion({ regionId, ...body }: SchoolHolidayRegionRequest & { regionId: number }, ctx: McpContext) {
return this.adminWrite(ctx, () => this.holidays.updateRegion(regionId, schoolHolidayRegionRequestSchema.parse(body)));
}
@@ -79,7 +79,7 @@ export class SchoolHolidaysMcp {
inputSchema: { regionId: idSchema, revision: z.number().int().positive() },
annotations: TOOL_ANNOTATIONS_DELETE, access: { group: 'vacay', mode: 'write' },
})
deleteRegion({ regionId, revision }: { regionId: number; revision: number }, ctx: McpContext) {
async deleteRegion({ regionId, revision }: { regionId: number; revision: number }, ctx: McpContext) {
return this.adminWrite(ctx, () => this.holidays.deleteRegion(regionId, revision));
}
@@ -89,7 +89,7 @@ export class SchoolHolidaysMcp {
inputSchema: { code: schoolHolidayCountryRequestSchema.shape.code },
annotations: TOOL_ANNOTATIONS_DELETE, access: { group: 'vacay', mode: 'write' },
})
deleteCountry({ code }: { code: string }, ctx: McpContext) {
async deleteCountry({ code }: { code: string }, ctx: McpContext) {
return this.adminWrite(ctx, () => this.holidays.deleteCountry(code));
}
}
@@ -1,33 +1,37 @@
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import type { SchoolHolidayCatalog, SchoolHolidayCountryRequest, SchoolHolidayPeriod, SchoolHolidayRegion, SchoolHolidayRegionDetail, SchoolHolidayRegionRequest } from '@trek/shared';
import { DatabaseService } from '../database/database.service';
import { UnitOfWork } from '../database/unit-of-work';
@Injectable()
export class SchoolHolidaysService {
constructor(private readonly db: DatabaseService) {}
constructor(
private readonly db: DatabaseService,
private readonly uow: UnitOfWork,
) {}
catalog(): SchoolHolidayCatalog {
async catalog(): Promise<SchoolHolidayCatalog> {
return {
countries: this.db.all<SchoolHolidayCountryRequest>('SELECT code, name FROM school_holiday_countries ORDER BY name, code'),
regions: this.db.all<SchoolHolidayRegion>("SELECT *, country || '-MANUAL-' || id AS code FROM school_holiday_regions ORDER BY name, id"),
};
}
country(code: string): SchoolHolidayCountryRequest {
async country(code: string): Promise<SchoolHolidayCountryRequest> {
const country = this.db.get<SchoolHolidayCountryRequest>('SELECT code, name FROM school_holiday_countries WHERE code = ?', code);
if (!country) throw new NotFoundException('Country not found');
return country;
}
createCountry(country: SchoolHolidayCountryRequest) {
async createCountry(country: SchoolHolidayCountryRequest) {
const inserted = this.db.run('INSERT OR IGNORE INTO school_holiday_countries (code, name) VALUES (?, ?)', country.code, country.name);
if (!inserted.changes) throw new ConflictException('Country already exists');
return country;
}
deleteCountry(code: string) {
return this.db.transaction(() => {
this.country(code);
async deleteCountry(code: string) {
return this.uow.transactional(async () => {
await this.country(code);
if (this.db.get('SELECT id FROM school_holiday_regions WHERE country = ? LIMIT 1', code)) {
throw new ConflictException('Remove the regions before deleting this country');
}
@@ -36,50 +40,50 @@ export class SchoolHolidaysService {
});
}
region(id: number): SchoolHolidayRegionDetail {
async region(id: number): Promise<SchoolHolidayRegionDetail> {
const region = this.db.get<SchoolHolidayRegion>("SELECT *, country || '-MANUAL-' || id AS code FROM school_holiday_regions WHERE id = ?", id);
if (!region) throw new NotFoundException('Region not found');
return { ...region, holidays: this.db.all<SchoolHolidayPeriod>('SELECT name, start_date AS startDate, end_date AS endDate FROM school_holiday_periods WHERE region_id = ? ORDER BY start_date, end_date, name', id) };
}
private checkName(country: string, name: string, id: number) {
private async checkName(country: string, name: string, id: number) {
if (this.db.get('SELECT id FROM school_holiday_regions WHERE country = ? AND name = ? COLLATE NOCASE AND id != ?', country, name, id)) {
throw new ConflictException('A region with this name already exists');
}
}
private writePeriods(id: number, holidays: SchoolHolidayPeriod[]) {
private async writePeriods(id: number, holidays: SchoolHolidayPeriod[]) {
this.db.run('DELETE FROM school_holiday_periods WHERE region_id = ?', id);
const insert = this.db.prepare('INSERT INTO school_holiday_periods (region_id, name, start_date, end_date) VALUES (?, ?, ?, ?)');
for (const holiday of holidays) insert.run(id, holiday.name, holiday.startDate, holiday.endDate);
}
createRegion(country: string, body: SchoolHolidayRegionRequest) {
return this.db.transaction(() => {
this.country(country);
this.checkName(country, body.name, 0);
async createRegion(country: string, body: SchoolHolidayRegionRequest) {
return this.uow.transactional(async () => {
await this.country(country);
await this.checkName(country, body.name, 0);
if (body.revision !== 0) throw new ConflictException('New regions must have revision zero');
const inserted = this.db.run('INSERT INTO school_holiday_regions (country, name) VALUES (?, ?)', country, body.name);
const id = Number(inserted.lastInsertRowid);
this.writePeriods(id, body.holidays);
await this.writePeriods(id, body.holidays);
return this.region(id);
});
}
updateRegion(id: number, body: SchoolHolidayRegionRequest) {
return this.db.transaction(() => {
const region = this.region(id);
this.checkName(region.country, body.name, id);
async updateRegion(id: number, body: SchoolHolidayRegionRequest) {
return this.uow.transactional(async () => {
const region = await this.region(id);
await this.checkName(region.country, body.name, id);
const updated = this.db.run('UPDATE school_holiday_regions SET name = ?, revision = revision + 1 WHERE id = ? AND revision = ?', body.name, id, body.revision);
if (!updated.changes) throw new ConflictException('This region changed. Reopen it before saving again.');
this.writePeriods(id, body.holidays);
await this.writePeriods(id, body.holidays);
return this.region(id);
});
}
deleteRegion(id: number, revision: number) {
return this.db.transaction(() => {
const region = this.region(id);
async deleteRegion(id: number, revision: number) {
return this.uow.transactional(async () => {
const region = await this.region(id);
if (region.revision !== revision) throw new ConflictException('This region changed. Reload before deleting it.');
if (this.db.get("SELECT id FROM vacay_holiday_calendars WHERE type = 'school_holiday' AND region = ? LIMIT 1", region.code)) {
throw new ConflictException('This region is used by vacation calendars and cannot be deleted');
@@ -90,7 +94,7 @@ export class SchoolHolidaysService {
});
}
holidays(id: number, year: string): SchoolHolidayPeriod[] {
return this.region(id).holidays.filter(holiday => holiday.startDate <= `${year}-12-31` && holiday.endDate >= `${year}-01-01`);
async holidays(id: number, year: string): Promise<SchoolHolidayPeriod[]> {
return (await this.region(id)).holidays.filter(holiday => holiday.startDate <= `${year}-12-31` && holiday.endDate >= `${year}-01-01`);
}
}
@@ -47,7 +47,7 @@ const USER_ROW_SQL: Record<InstanceApiKeyName, string> = {
};
/** The instance-wide value in cleartext, or null when unset/cleared. */
export function readInstanceApiKey(db: DatabaseService, name: InstanceApiKeyName): string | null {
export async function readInstanceApiKey(db: DatabaseService, name: InstanceApiKeyName): Promise<string | null> {
const row = db.get<{ value: string | null }>('SELECT value FROM app_settings WHERE key = ?', name);
if (!row?.value) return null;
return decrypt_api_key(row.value) || null;
@@ -59,7 +59,7 @@ export function readInstanceApiKey(db: DatabaseService, name: InstanceApiKeyName
* key", and a missing row would let the resolver fall through to whatever old
* value still sits in their own users column.
*/
export function writeInstanceApiKey(db: DatabaseService, name: InstanceApiKeyName, value: unknown): void {
export async function writeInstanceApiKey(db: DatabaseService, name: InstanceApiKeyName, value: unknown): Promise<void> {
db.run(
`INSERT INTO app_settings (key, value) VALUES (?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
@@ -80,15 +80,15 @@ export function writeInstanceApiKey(db: DatabaseService, name: InstanceApiKeyNam
* `userId` 0 means "nobody is asking" (the unauthenticated app-config read):
* there is no personal key to find, so the chain ends at the instance.
*/
export function resolveApiKey(
export async function resolveApiKey(
db: DatabaseService,
name: InstanceApiKeyName,
userId: number,
operatorKey: string | undefined,
): { key: string | null; source: ApiKeySource | null } {
): Promise<{ key: string | null; source: ApiKeySource | null }> {
if (operatorKey) return { key: operatorKey, source: 'operator-env' };
const instance = readInstanceApiKey(db, name);
const instance = await readInstanceApiKey(db, name);
if (instance) return { key: instance, source: 'instance' };
if (!userId) return { key: null, source: null };
@@ -55,12 +55,12 @@ export class SettingsController {
}
@Get()
list(@CurrentUser() user: User) {
return { settings: this.settings.getUserSettings(user.id) };
async list(@CurrentUser() user: User) {
return { settings: await this.settings.getUserSettings(user.id) };
}
@Put()
upsert(@CurrentUser() user: User, @Body() body: SettingUpsertDto) {
async upsert(@CurrentUser() user: User, @Body() body: SettingUpsertDto) {
this.assertMayWriteInstanceEndpoint({ [body.key]: body.value });
// assertMayWriteInstanceEndpoint only covers llm_base_url and provider 'local'.
// llm_api_key and llm_model are writable by every user, and on a managed
@@ -72,17 +72,17 @@ export class SettingsController {
if (body.value === MASKED_SETTING_VALUE) {
return { success: true, key: body.key, unchanged: true };
}
this.settings.upsertSetting(user.id, body.key, body.value);
await this.settings.upsertSetting(user.id, body.key, body.value);
return { success: true, key: body.key, value: body.value };
}
@Post('bulk')
@HttpCode(200) // Express answers bulk with res.json (200), not the POST-default 201.
bulk(@CurrentUser() user: User, @Body() body: SettingsBulkDto) {
async bulk(@CurrentUser() user: User, @Body() body: SettingsBulkDto) {
this.assertMayWriteInstanceEndpoint(body.settings);
const { allowed, blocked } = splitManagedKeys(body.settings, this.env.isManaged());
try {
const updated = this.settings.bulkUpsertSettings(user.id, allowed);
const updated = await this.settings.bulkUpsertSettings(user.id, allowed);
return { success: true, updated, ...(blocked.length ? { managed_keys: blocked } : {}) };
} catch (err) {
console.error('Error saving settings:', err);
@@ -108,7 +108,7 @@ export class AdminDefaultUserSettingsController {
) {}
@Get()
get() {
async get() {
return this.settings.getAdminUserDefaults();
}
@@ -123,7 +123,7 @@ export class AdminDefaultUserSettingsController {
body as unknown as Record<string, unknown>,
this.env.isManaged(),
);
this.settings.setAdminUserDefaults(allowed);
await this.settings.setAdminUserDefaults(allowed);
await this.audit.writeAudit({
userId: user.id,
action: 'admin.default_user_settings_update',
+5 -5
View File
@@ -101,8 +101,8 @@ export class SettingsMcp {
* injection before this filter runs, so the caller sees the same effective
* value the web UI does, minus everything not named on the allow-list.
*/
private readDisplayPreferences(userId: number): Record<string, unknown> {
const all = this.settings.getUserSettings(userId);
private async readDisplayPreferences(userId: number): Promise<Record<string, unknown>> {
const all = await this.settings.getUserSettings(userId);
const picked: Record<string, unknown> = {};
for (const key of DISPLAY_PREFERENCE_KEYS) {
if (Object.hasOwn(all, key)) picked[key] = all[key];
@@ -118,7 +118,7 @@ export class SettingsMcp {
access: { group: 'settings', mode: 'read' },
})
async getDisplaySettings(_input: Record<string, never>, ctx: McpContext) {
return ok({ settings: this.readDisplayPreferences(ctx.userId) });
return ok({ settings: await this.readDisplayPreferences(ctx.userId) });
}
@Tool({
@@ -163,9 +163,9 @@ export class SettingsMcp {
validated[key] = parsed.data;
}
const updated = this.settings.bulkUpsertSettings(ctx.userId, validated);
const updated = await this.settings.bulkUpsertSettings(ctx.userId, validated);
// Read back rather than echoing the input: an admin default or the managed
// token injection can still shape what the user ends up seeing.
return ok({ success: true, updated, settings: this.readDisplayPreferences(ctx.userId) });
return ok({ success: true, updated, settings: await this.readDisplayPreferences(ctx.userId) });
}
}
+14 -10
View File
@@ -1,5 +1,6 @@
import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { UnitOfWork } from '../database/unit-of-work';
import { decrypt_api_key, maybe_encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { MASKED_SETTING_VALUE, normalizeAppearance } from '@trek/shared';
import { readEnv } from '../../app-config';
@@ -149,9 +150,12 @@ function serializeValue(key: string, value: unknown): string {
*/
@Injectable()
export class SettingsService {
constructor(private readonly db: DatabaseService) {}
constructor(
private readonly db: DatabaseService,
private readonly uow: UnitOfWork,
) {}
getAdminUserDefaults(): Record<string, unknown> {
async getAdminUserDefaults(): Promise<Record<string, unknown>> {
const rows = this.db.all<{ key: string; value: string }>(
"SELECT key, value FROM app_settings WHERE key LIKE 'default_user_setting_%'"
);
@@ -167,14 +171,14 @@ export class SettingsService {
return defaults;
}
setAdminUserDefaults(partial: Record<string, unknown>): void {
async setAdminUserDefaults(partial: Record<string, unknown>): Promise<void> {
const upsert = this.db.prepare(
`INSERT INTO app_settings (key, value) VALUES (?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value`
);
const del = this.db.prepare("DELETE FROM app_settings WHERE key = ?");
this.db.transaction(() => {
await this.uow.transactional(async () => {
for (const [key, value] of Object.entries(partial)) {
if (!(DEFAULTABLE_USER_SETTING_KEYS as readonly string[]).includes(key)) {
throw new Error(`Invalid setting key: ${key}`);
@@ -206,8 +210,8 @@ export class SettingsService {
});
}
getUserSettings(userId: number): Record<string, unknown> {
const adminDefaults = this.getAdminUserDefaults();
async getUserSettings(userId: number): Promise<Record<string, unknown>> {
const adminDefaults = await this.getAdminUserDefaults();
const rows = this.db.all<{ key: string; value: string }>('SELECT key, value FROM settings WHERE user_id = ?', userId);
const userSettings: Record<string, unknown> = {};
@@ -277,20 +281,20 @@ export class SettingsService {
return merged;
}
upsertSetting(userId: number, key: string, value: unknown) {
async upsertSetting(userId: number, key: string, value: unknown) {
this.db.run(`
INSERT INTO settings (user_id, key, value) VALUES (?, ?, ?)
ON CONFLICT(user_id, key) DO UPDATE SET value = excluded.value
`, userId, key, serializeValue(key, value));
}
bulkUpsertSettings(userId: number, settings: Record<string, unknown>) {
async bulkUpsertSettings(userId: number, settings: Record<string, unknown>) {
const upsert = this.db.prepare(`
INSERT INTO settings (user_id, key, value) VALUES (?, ?, ?)
ON CONFLICT(user_id, key) DO UPDATE SET value = excluded.value
`);
let written = 0;
this.db.transaction(() => {
await this.uow.transactional(async () => {
for (const [key, value] of Object.entries(settings)) {
// The client echoes redacted secrets back unchanged — skip them so a
// bulk save can never overwrite a stored secret with the mask (the
@@ -309,7 +313,7 @@ export class SettingsService {
* returns the plaintext — for server-side use only (e.g. the LLM config
* resolver needs the real API key). Returns null when unset.
*/
getDecryptedUserSetting(userId: number, key: string): string | null {
async getDecryptedUserSetting(userId: number, key: string): Promise<string | null> {
const row = this.db.get<{ value: string }>('SELECT value FROM settings WHERE user_id = ? AND key = ?', userId, key);
if (!row || row.value === '' || row.value == null) return null;
if (ENCRYPTED_SETTING_KEYS.has(key)) return decrypt_api_key(row.value);
+1 -1
View File
@@ -431,7 +431,7 @@ export class ShareService {
// (`||` on purpose: an empty-string trip currency also falls back).
let baseCurrency = (trip as { currency?: string }).currency || 'EUR';
const ownerSettings: Record<string, unknown> = shareRow.created_by != null
? this.settings.getUserSettings(shareRow.created_by)
? await this.settings.getUserSettings(shareRow.created_by)
: {};
const ownerDefault = ownerSettings['default_currency'];
if (typeof ownerDefault === 'string' && ownerDefault.trim()) {
@@ -236,7 +236,7 @@ function stopFrom(stop: GoogleStop | undefined, fallback: GoogleLatLng | undefin
export class GoogleTransitProvider {
constructor(private readonly database: DatabaseService) {}
private resolveKey(userId: number): { key: string | null; source: ApiKeySource | null } {
private async resolveKey(userId: number): Promise<{ key: string | null; source: ApiKeySource | null }> {
return resolveApiKey(this.database, 'maps_api_key', userId, readEnv().maps.placesApiKey);
}
@@ -248,7 +248,7 @@ export class GoogleTransitProvider {
*/
async isActive(userId: number): Promise<boolean> {
if ((await readTransitProvider(this.database)) !== 'google') return false;
return !!this.resolveKey(userId).key;
return !!(await this.resolveKey(userId)).key;
}
private async call(endpoint: string, label: string, apiKey: string, body: unknown, fieldMask: string): Promise<unknown> {
@@ -284,7 +284,7 @@ export class GoogleTransitProvider {
/** Station/place search for the from/to pickers. `near` biases results. */
async geocode(text: string, language: string | undefined, near: string | undefined, userId: number): Promise<{ results: TransitPlace[] }> {
const { key: apiKey, source } = this.resolveKey(userId);
const { key: apiKey, source } = await this.resolveKey(userId);
if (!apiKey) {
const err = new Error('Transit provider error (no Google API key configured)') as Error & { status: number };
err.status = 502;
@@ -333,7 +333,7 @@ export class GoogleTransitProvider {
/** Route search between two coordinates. Returns the same compact shape MOTIS is mapped to. */
async plan(q: PlanQuery, language: string | undefined, userId: number): Promise<{ itineraries: TransitItinerary[] }> {
const { key: apiKey, source } = this.resolveKey(userId);
const { key: apiKey, source } = await this.resolveKey(userId);
if (!apiKey) {
const err = new Error('Transit provider error (no Google API key configured)') as Error & { status: number };
err.status = 502;
+2 -2
View File
@@ -378,8 +378,8 @@ export class TripsService {
return this.db.prepare('SELECT * FROM trips WHERE id = ?').get(tripId) as Trip | undefined;
}
searchCoverImages(query: string, userId: number) {
return this.unsplash.searchUnsplashPhotos(query, 9, this.unsplash.getUnsplashKey(userId));
async searchCoverImages(query: string, userId: number) {
return this.unsplash.searchUnsplashPhotos(query, 9, await this.unsplash.getUnsplashKey(userId));
}
getOwner(tripId: string | number): { user_id: number } | undefined {
+2 -2
View File
@@ -66,8 +66,8 @@ export class UnsplashService {
* the answer depend on who asked (#1939). Returns null when none is set, in
* which case the search falls back to the unauthenticated endpoint.
*/
getUnsplashKey(userId: number): string | null {
return resolveApiKey(this.db, 'unsplash_api_key', userId, this.env.env().integrations.unsplashAccessKey).key;
async getUnsplashKey(userId: number): Promise<string | null> {
return (await resolveApiKey(this.db, 'unsplash_api_key', userId, this.env.env().integrations.unsplashAccessKey)).key;
}
async searchUnsplashPhotos(query: string, perPage = 9, accessKey?: string | null) {