refactor(llm-parse, mcp-shared, oauth, place-shadow, route-usage, storage, todo, trip-invite): async DB-touching methods; transactions through UnitOfWork

This commit is contained in:
jubnl
2026-09-21 23:27:01 +02:00
parent bb390a5407
commit e413308227
61 changed files with 977 additions and 925 deletions
+2 -2
View File
@@ -316,11 +316,11 @@ export class AdminController {
}
@Get('oauth-sessions')
listOAuthSessions() { return { sessions: this.oauth.listAllOAuthSessions() }; }
async listOAuthSessions() { return { sessions: await this.oauth.listAllOAuthSessions() }; }
@Delete('oauth-sessions/:id')
async revokeOAuthSession(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
ok(this.oauth.adminRevokeOAuthSession(id));
ok(await this.oauth.adminRevokeOAuthSession(id));
await this.audit.writeAudit({ userId: user.id, action: 'admin.oauth_session_revoke', resource: String(id), ip: getClientIp(req) });
return { success: true };
}
+1 -1
View File
@@ -518,7 +518,7 @@ export async function restoreFromZip(storage: StorageService, zipPath: string):
// entirely when reopen failed: with no live DB handle the registry has
// nothing to read, and the restore is already reported as "restart
// required" below — rehydrating into a stale/guessed config would be worse.
storage.reloadConfig();
await storage.reloadConfig();
const extractedUploads = path.join(extractDir, 'uploads');
if (fs.existsSync(extractedUploads)) {
+3 -3
View File
@@ -69,7 +69,7 @@ export class CategoriesMcp {
async createCategory({ name, color, icon }: { name: string; color?: string; icon?: string }, ctx: McpContext) {
if (await this.isDemoUser(ctx.userId)) return demoDenied();
// The palette is instance-wide; the REST route restricts management to admins. Match it.
if (!this.guards.isAdminUser(ctx.userId)) return adminRequired();
if (!(await this.guards.isAdminUser(ctx.userId))) return adminRequired();
const category = await this.categories.create(ctx.userId, name, color, icon);
return ok({ category });
}
@@ -88,7 +88,7 @@ export class CategoriesMcp {
})
async updateCategory({ categoryId, name, color, icon }: { categoryId: number; name?: string; color?: string; icon?: string }, ctx: McpContext) {
if (await this.isDemoUser(ctx.userId)) return demoDenied();
if (!this.guards.isAdminUser(ctx.userId)) return adminRequired();
if (!(await this.guards.isAdminUser(ctx.userId))) return adminRequired();
if (!(await this.categories.getById(categoryId))) return errorResult('Category not found');
const category = await this.categories.update(categoryId, name, color, icon);
return ok({ category });
@@ -105,7 +105,7 @@ export class CategoriesMcp {
})
async deleteCategory({ categoryId }: { categoryId: number }, ctx: McpContext) {
if (await this.isDemoUser(ctx.userId)) return demoDenied();
if (!this.guards.isAdminUser(ctx.userId)) return adminRequired();
if (!(await this.guards.isAdminUser(ctx.userId))) return adminRequired();
if (!(await this.categories.getById(categoryId))) return errorResult('Category not found');
await this.categories.remove(categoryId);
return ok({ success: true });
@@ -30,10 +30,10 @@ export class LlmConfigResolver {
*/
async resolve(userId: number): Promise<ResolvedLlmConfig | null> {
if (!(await this.addons.isAddonEnabled(ADDON_IDS.LLM_PARSING))) return null;
return this.readInstanceConfig() ?? (await this.readUserConfig(userId));
return (await this.readInstanceConfig()) ?? (await this.readUserConfig(userId));
}
private readInstanceConfig(): ResolvedLlmConfig | null {
private async readInstanceConfig(): Promise<ResolvedLlmConfig | null> {
const row = this.dbService.get<{ config?: string } | undefined>(
'SELECT config FROM addons WHERE id = ?',
ADDON_IDS.LLM_PARSING,
@@ -74,7 +74,7 @@ export class McpToolGuardsService {
}
/** True when the user has the global admin role (mirrors REST `user.role === 'admin'` gates). */
isAdminUser(userId: number): boolean {
async isAdminUser(userId: number): Promise<boolean> {
const userRow = this.db.get<{ role?: string }>('SELECT role FROM users WHERE id = ?', userId);
return userRow?.role === 'admin';
}
@@ -125,7 +125,7 @@ export class McpTransportService {
private readonly registry: McpRegistryService,
) {}
verifyToken(authHeader: string | undefined): VerifyTokenResult | null {
async verifyToken(authHeader: string | undefined): Promise<VerifyTokenResult | null> {
if (!authHeader) return null;
// M8: strictly require "Bearer" scheme (RFC 6750)
const spaceIdx = authHeader.indexOf(' ');
@@ -136,7 +136,7 @@ export class McpTransportService {
// OAuth 2.1 access token (trekoa_...)
if (token.startsWith('trekoa_')) {
const result = this.oauth.getUserByAccessToken(token);
const result = await this.oauth.getUserByAccessToken(token);
if (!result) return null;
// RFC 8707: audience must always match this resource endpoint.
// Pre-audit tokens with audience=null are revoked by the SEC-H6 migration.
@@ -164,7 +164,7 @@ export class McpTransportService {
return;
}
const tokenResult = this.verifyToken(req.headers['authorization']);
const tokenResult = await this.verifyToken(req.headers['authorization']);
if (!tokenResult) {
setAuthChallenge(res);
res.status(401).json({ error: 'Access token required' });
@@ -122,7 +122,7 @@ export class OauthApiController {
@UseGuards(JwtAuthGuard)
async listClients(@CurrentUser() user: User) {
await this.requireMcp403();
return { clients: this.oauth.listOAuthClients(user.id) };
return { clients: await this.oauth.listOAuthClients(user.id) };
}
@Post('clients')
@@ -164,7 +164,7 @@ export class OauthApiController {
@UseGuards(JwtAuthGuard)
async listSessions(@CurrentUser() user: User) {
await this.requireMcp403();
return { sessions: this.oauth.listOAuthSessions(user.id) };
return { sessions: await this.oauth.listOAuthSessions(user.id) };
}
@Delete('sessions/:id')
@@ -67,14 +67,14 @@ export class OauthPublicController {
if (pending.clientId !== client_id) return invalidGrant('client_id_mismatch', pending.userId);
if (pending.redirectUri !== redirect_uri) return invalidGrant('redirect_uri_mismatch', pending.userId);
if (pending.resource && resource && pending.resource !== stripTrailingSlashes(resource)) return invalidGrant('resource_mismatch', pending.userId);
if (!this.oauth.authenticateClient(client_id, client_secret)) {
if (!(await this.oauth.authenticateClient(client_id, client_secret))) {
logWarn(`[OAuth] Invalid client credentials for client_id=${client_id} ip=${ip ?? '-'}`);
await this.audit.writeAudit({ userId: pending.userId, action: 'oauth.token.client_auth_failed', details: { client_id }, ip });
res.status(401).json({ error: 'invalid_client', error_description: 'Invalid client credentials' });
return;
}
if (!this.oauth.verifyPKCE(code_verifier, pending.codeChallenge)) return invalidGrant('pkce_failed', pending.userId);
const tokens = this.oauth.issueTokens(client_id, pending.userId, pending.scopes, null, pending.resource ?? null);
const tokens = await this.oauth.issueTokens(client_id, pending.userId, pending.scopes, null, pending.resource ?? null);
await this.audit.writeAudit({ userId: pending.userId, action: 'oauth.token.issue', details: { client_id, scopes: pending.scopes, audience: pending.resource ?? null }, ip });
res.json(tokens);
return;
@@ -100,7 +100,7 @@ export class OauthPublicController {
res.status(401).json({ error: 'invalid_client', error_description: 'client_secret is required for client_credentials grant' });
return;
}
const client = this.oauth.authenticateClient(client_id, client_secret);
const client = await this.oauth.authenticateClient(client_id, client_secret);
if (!client) {
logWarn(`[OAuth] Invalid client credentials for client_id=${client_id} ip=${ip ?? '-'}`);
await this.audit.writeAudit({ userId: null, action: 'oauth.token.client_auth_failed', details: { client_id }, ip });
@@ -126,7 +126,7 @@ export class OauthPublicController {
grantedScopes = allowedScopes;
}
const audience = resource ? stripTrailingSlashes(resource) : `${stripTrailingSlashes(this.oauth.mcpSafeUrl())}/mcp`;
const tokens = this.oauth.issueClientCredentialsToken(client_id, client.user_id, grantedScopes, audience);
const tokens = await this.oauth.issueClientCredentialsToken(client_id, client.user_id, grantedScopes, audience);
await this.audit.writeAudit({ userId: client.user_id, action: 'oauth.token.issue', details: { client_id, scopes: grantedScopes, audience, grant: 'client_credentials' }, ip });
res.json(tokens);
return;
@@ -143,7 +143,7 @@ export class OauthPublicController {
res.status(401).json({ error: 'invalid_token' });
return;
}
const info = this.oauth.getUserByAccessToken(auth.slice(7));
const info = await this.oauth.getUserByAccessToken(auth.slice(7));
if (!info) {
res.set('WWW-Authenticate', 'Bearer realm="TREK MCP", error="invalid_token"');
res.status(401).json({ error: 'invalid_token' });
@@ -166,7 +166,7 @@ export class OauthPublicController {
res.status(400).json({ error: 'invalid_request', error_description: 'token and client_id are required' });
return;
}
if (!this.oauth.authenticateClient(client_id, client_secret)) {
if (!(await this.oauth.authenticateClient(client_id, client_secret))) {
logWarn(`[OAuth] Invalid client credentials on revoke for client_id=${client_id} ip=${ip ?? '-'}`);
await this.audit.writeAudit({ userId: null, action: 'oauth.token.client_auth_failed', details: { client_id, endpoint: 'revoke' }, ip });
res.status(401).json({ error: 'invalid_client', error_description: 'Invalid client credentials' });
+4 -4
View File
@@ -44,7 +44,7 @@ function assertValidRedirectUris(uris: string[]): void {
// Row → SDK client info shape
// ---------------------------------------------------------------------------
function rowToInfo(row: NonNullable<ReturnType<OauthService['getSdkClient']>>): OAuthClientInformationFull {
function rowToInfo(row: NonNullable<Awaited<ReturnType<OauthService['getSdkClient']>>>): OAuthClientInformationFull {
return {
client_id: row.client_id,
client_name: row.name,
@@ -65,7 +65,7 @@ export class TrekClientsStore implements OAuthRegisteredClientsStore {
constructor(private readonly oauth: OauthService) {}
async getClient(clientId: string): Promise<OAuthClientInformationFull | undefined> {
const row = this.oauth.getSdkClient(clientId);
const row = await this.oauth.getSdkClient(clientId);
return row ? rowToInfo(row) : undefined;
}
@@ -178,7 +178,7 @@ export class TrekOAuthProvider implements OAuthServerProvider {
if (!codeVerifier || !this.oauth.verifyPKCE(codeVerifier, pending.codeChallenge))
throw new Error('Authorization grant is invalid.');
const tokens = this.oauth.issueTokens(client.client_id, pending.userId, pending.scopes, null, pending.resource ?? null);
const tokens = await this.oauth.issueTokens(client.client_id, pending.userId, pending.scopes, null, pending.resource ?? null);
await this.audit.writeAudit({
userId: pending.userId,
action: 'oauth.token.issue',
@@ -200,7 +200,7 @@ export class TrekOAuthProvider implements OAuthServerProvider {
}
async verifyAccessToken(token: string): Promise<AuthInfo> {
const info = this.oauth.getUserByAccessToken(token);
const info = await this.oauth.getUserByAccessToken(token);
if (!info) throw new Error('Invalid or expired token');
return {
token,
+26 -26
View File
@@ -92,7 +92,7 @@ export class OauthService {
// Client management (self-service, gated by MCP addon)
// -------------------------------------------------------------------------
listOAuthClients(userId: number): Record<string, unknown>[] {
async listOAuthClients(userId: number): Promise<Record<string, unknown>[]> {
const rows = this.db.all<OAuthClientRow>(
'SELECT id, user_id, name, client_id, redirect_uris, allowed_scopes, created_at, is_public, created_via, allows_client_credentials FROM oauth_clients WHERE user_id = ? ORDER BY created_at DESC',
userId,
@@ -246,7 +246,7 @@ export class OauthService {
// Consent management
// -------------------------------------------------------------------------
getConsent(clientId: string, userId: number): string[] | null {
async getConsent(clientId: string, userId: number): Promise<string[] | null> {
const row = this.db.get<{ scopes: string }>(
'SELECT scopes FROM oauth_consents WHERE client_id = ? AND user_id = ?', clientId, userId,
);
@@ -255,7 +255,7 @@ export class OauthService {
async saveConsent(clientId: string, userId: number, scopes: string[], ip?: string | null): Promise<void> {
// Union existing consent with newly approved scopes (M5: never narrow stored consent)
const existing = this.getConsent(clientId, userId) ?? [];
const existing = (await this.getConsent(clientId, userId)) ?? [];
const merged = Array.from(new Set([...existing, ...scopes]));
this.db.run(
'INSERT OR REPLACE INTO oauth_consents (client_id, user_id, scopes, updated_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP)',
@@ -272,19 +272,19 @@ export class OauthService {
// Token issuance
// -------------------------------------------------------------------------
issueTokens(
async issueTokens(
clientId: string,
userId: number,
scopes: string[],
parentTokenId: number | null = null,
audience: string | null = null,
): {
): Promise<{
access_token: string;
refresh_token: string;
token_type: 'Bearer';
expires_in: number;
scope: string;
} {
}> {
const rawAccess = generateAccessToken();
const rawRefresh = generateRefreshToken();
const accessHash = hashToken(rawAccess);
@@ -316,17 +316,17 @@ export class OauthService {
* can never be presented as a valid refresh token (same precedent as public
* client secret hashes stored in client_secret_hash).
*/
issueClientCredentialsToken(
async issueClientCredentialsToken(
clientId: string,
userId: number,
scopes: string[],
audience: string,
): {
): Promise<{
access_token: string;
token_type: 'Bearer';
expires_in: number;
scope: string;
} {
}> {
const rawAccess = generateAccessToken();
const accessHash = hashToken(rawAccess);
const placeholderHash = randomBytes(32).toString('hex');
@@ -354,21 +354,21 @@ export class OauthService {
/** SDK clients-store read: the exact row shape the MCP SDK adapter
* (oauth-sdk.provider.ts) maps to OAuthClientInformationFull. */
getSdkClient(clientId: string): {
async getSdkClient(clientId: string): Promise<{
client_id: string;
name: string;
redirect_uris: string;
allowed_scopes: string;
is_public: number;
created_via: string;
} | undefined {
} | undefined> {
return this.db.get(
'SELECT client_id, name, redirect_uris, allowed_scopes, is_public, created_via FROM oauth_clients WHERE client_id = ?',
clientId,
);
}
getUserByAccessToken(rawToken: string): OAuthTokenInfo | null {
async getUserByAccessToken(rawToken: string): Promise<OAuthTokenInfo | null> {
const hash = hashToken(rawToken);
const row = this.db.get<OAuthTokenRow & { username: string; email: string; role: string }>(`
SELECT ot.scopes, ot.audience, ot.revoked_at, ot.access_token_expires_at,
@@ -395,7 +395,7 @@ export class OauthService {
// -------------------------------------------------------------------------
/** Walk parent_token_id upward to find the root token id of this rotation chain. */
private findChainRoot(tokenId: number): number {
private async findChainRoot(tokenId: number): Promise<number> {
let current = tokenId;
for (let i = 0; i < 100; i++) {
const row = this.db.get<{ id: number; parent_token_id: number | null }>('SELECT id, parent_token_id FROM oauth_tokens WHERE id = ?', current);
@@ -406,7 +406,7 @@ export class OauthService {
}
/** Revoke all tokens in the rotation chain rooted at rootId. Returns affected ids. */
private revokeChain(rootId: number): number[] {
private async revokeChain(rootId: number): Promise<number[]> {
const rows = this.db.all<{ id: number }>(`
WITH RECURSIVE chain(id) AS (
SELECT id FROM oauth_tokens WHERE id = ?
@@ -435,7 +435,7 @@ export class OauthService {
* explicit revoke leaves no live child, and a chain revoked after a real replay
* has every child revoked with it, so neither can slip through here.
*/
private isConcurrentRotation(row: OAuthTokenRow): boolean {
private async isConcurrentRotation(row: OAuthTokenRow): Promise<boolean> {
const revokedAt = parseSqliteUtc(row.revoked_at);
if (!revokedAt) return false;
if (Date.now() - revokedAt.getTime() > REFRESH_ROTATION_GRACE_MS) return false;
@@ -451,7 +451,7 @@ export class OauthService {
clientId: string,
clientSecret: string | undefined,
ip?: string | null,
): Promise<{ error?: string; status?: number; tokens?: ReturnType<OauthService['issueTokens']> }> {
): Promise<{ error?: string; status?: number; tokens?: Awaited<ReturnType<OauthService['issueTokens']>> }> {
const client = this.db.get<OAuthClientRow>('SELECT client_id, client_secret_hash, is_public FROM oauth_clients WHERE client_id = ?', clientId);
if (!client) return { error: 'invalid_client', status: 401 };
if (!client.is_public) {
@@ -476,8 +476,8 @@ export class OauthService {
// not theft (#1007): they share one token, both post it, and the loser used
// to take the whole chain down with it. Issue a sibling pair off the same
// parent so each client walks away with its own token.
if (this.isConcurrentRotation(row)) {
const tokens = this.issueTokens(clientId, row.user_id, JSON.parse(row.scopes), row.id, row.audience ?? null);
if (await this.isConcurrentRotation(row)) {
const tokens = await this.issueTokens(clientId, row.user_id, JSON.parse(row.scopes), row.id, row.audience ?? null);
await this.audit.writeAudit({
userId: row.user_id,
action: 'oauth.token.refresh',
@@ -488,8 +488,8 @@ export class OauthService {
}
// A revoked refresh token was replayed — assume token theft. Cascade-revoke the chain.
const rootId = this.findChainRoot(row.id);
this.revokeChain(rootId);
const rootId = await this.findChainRoot(row.id);
await this.revokeChain(rootId);
revokeUserSessionsForClient(row.user_id, clientId);
@@ -514,7 +514,7 @@ export class OauthService {
// MCP connections (#1475).
this.db.run('UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE id = ?', row.id);
const tokens = this.issueTokens(clientId, row.user_id, JSON.parse(row.scopes), row.id, row.audience ?? null);
const tokens = await this.issueTokens(clientId, row.user_id, JSON.parse(row.scopes), row.id, row.audience ?? null);
await this.audit.writeAudit({ userId: row.user_id, action: 'oauth.token.refresh', details: { client_id: clientId }, ip });
return { tokens };
@@ -550,7 +550,7 @@ export class OauthService {
// Active session listing (for user settings page)
// -------------------------------------------------------------------------
listOAuthSessions(userId: number): Record<string, unknown>[] {
async listOAuthSessions(userId: number): Promise<Record<string, unknown>[]> {
const rows = this.db.all<Record<string, unknown>>(`
SELECT ot.id, ot.client_id, oc.name AS client_name, ot.scopes,
ot.access_token_expires_at, ot.refresh_token_expires_at, ot.created_at
@@ -659,7 +659,7 @@ export class OauthService {
return { valid: true, loginRequired: true };
}
const existingConsent = this.getConsent(params.client_id, userId);
const existingConsent = await this.getConsent(params.client_id, userId);
const consentRequired = !existingConsent || !this.isConsentSufficient(existingConsent, grantedScopes);
return {
@@ -692,7 +692,7 @@ export class OauthService {
// Client authentication (for token endpoint)
// -------------------------------------------------------------------------
authenticateClient(clientId: string, clientSecret: string | undefined): OAuthClientRow | null {
async authenticateClient(clientId: string, clientSecret: string | undefined): Promise<OAuthClientRow | null> {
const client = this.db.get<OAuthClientRow>('SELECT * FROM oauth_clients WHERE client_id = ?', clientId);
if (!client) return null;
if (client.is_public) {
@@ -711,7 +711,7 @@ export class OauthService {
// panel route is under /api/admin. The route keeps its path and its guard.
// ---------------------------------------------------------------------------
listAllOAuthSessions() {
async listAllOAuthSessions() {
const rows = this.db.all<Record<string, unknown> & { scopes: string }>(`
SELECT ot.id, ot.client_id, oc.name AS client_name, ot.user_id, u.username,
ot.scopes, ot.access_token_expires_at, ot.refresh_token_expires_at, ot.created_at
@@ -734,7 +734,7 @@ export class OauthService {
});
}
adminRevokeOAuthSession(id: string) {
async adminRevokeOAuthSession(id: string) {
const row = this.db.get<{ id: number; user_id: number; client_id: string }>(
'SELECT id, user_id, client_id FROM oauth_tokens WHERE id = ?', id,
);
+2 -2
View File
@@ -481,7 +481,7 @@ export class PackingMcp {
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.guards.hasTripPermission('packing_edit', tripId, ctx.userId))) return permissionDenied();
// Templates are global; the REST route restricts saving to admins. Match it.
if (!this.guards.isAdminUser(ctx.userId)) return adminRequired();
if (!(await this.guards.isAdminUser(ctx.userId))) return adminRequired();
const template = this.packing.saveAsTemplate(tripId, ctx.userId, templateName);
if (!template) return errorResult('Nothing to save — the packing list is empty.');
return ok({ template });
@@ -500,7 +500,7 @@ export class PackingMcp {
async deletePackingTemplate({ templateId }: { templateId: number }, ctx: McpContext) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
// Templates are global; the REST route restricts management to admins. Match it.
if (!this.guards.isAdminUser(ctx.userId)) return adminRequired();
if (!(await this.guards.isAdminUser(ctx.userId))) return adminRequired();
const result = this.packing.deletePackingTemplate(String(templateId));
if ('error' in result) return errorResult(result.error);
return ok({ success: true, name: result.name });
@@ -29,26 +29,26 @@ export class PlaceShadowController {
*/
@Post('pick')
@HttpCode(200)
pick(@Body() body: PlaceShadowPickDto): PlaceShadowPickResult {
return { recorded: this.shadow.record(body) };
async pick(@Body() body: PlaceShadowPickDto): Promise<PlaceShadowPickResult> {
return { recorded: await this.shadow.record(body) };
}
@Get('summary')
@UseGuards(JwtAuthGuard, AdminGuard)
summary(): PlaceShadowSummaryResult {
return this.shadow.summary();
async summary(): Promise<PlaceShadowSummaryResult> {
return await this.shadow.summary();
}
@Get('export')
@UseGuards(JwtAuthGuard, AdminGuard)
export(@Query('after') after?: string): PlaceShadowExportResult {
async export(@Query('after') after?: string): Promise<PlaceShadowExportResult> {
const parsed = Number(after);
return this.shadow.export(Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined);
return await this.shadow.export(Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined);
}
@Delete()
@UseGuards(JwtAuthGuard, AdminGuard)
clear(): { removed: number } {
return { removed: this.shadow.clear() };
async clear(): Promise<{ removed: number }> {
return { removed: await this.shadow.clear() };
}
}
@@ -19,14 +19,17 @@ export class PlaceShadowRetentionJob implements OnApplicationBootstrap {
private readonly registrar: CronRegistrarService,
) {}
onApplicationBootstrap(): void {
// `async` only so the sweep's call-graph gate sees a non-sync DB-reaching
// frame here: nothing in the body awaits, and Nest awaits the returned
// promise before the next bootstrap hook, exactly as it did the `void`.
async onApplicationBootstrap(): Promise<void> {
if (!this.registrar.isEnabled()) return;
this.registrar.register('place-shadow-retention', '40 3 * * *', () => this.tick());
}
tick(): void {
async tick(): Promise<void> {
try {
const removed = this.shadow.purgeExpired();
const removed = await this.shadow.purgeExpired();
if (removed > 0) {
logInfo(`Place shadow retention: removed ${removed} expired row(s)`);
}
@@ -74,7 +74,7 @@ function toRow(r: DbRow): PlaceShadowRow {
export class PlaceShadowService {
constructor(private readonly db: DatabaseService) {}
enabled(): boolean {
async enabled(): Promise<boolean> {
const row = this.db.get<{ value: string }>(
"SELECT value FROM app_settings WHERE key = 'place_shadow_enabled'",
);
@@ -87,8 +87,8 @@ export class PlaceShadowService {
* somebody adds a place would be noise about a feature that is off on
* purpose.
*/
record(pick: PlaceShadowPickRequest): boolean {
if (!this.enabled()) return false;
async record(pick: PlaceShadowPickRequest): Promise<boolean> {
if (!(await this.enabled())) return false;
// A rank outside the returned list means the client and the server disagree
// about what was on screen. Storing it would poison the very number the
// corpus exists to produce, so the row is dropped instead.
@@ -119,7 +119,7 @@ export class PlaceShadowService {
* previous page; paging by id rather than by offset keeps the pages stable
* while new rows arrive underneath.
*/
export(after?: number, limit = EXPORT_PAGE_SIZE): PlaceShadowExportResult {
async export(after?: number, limit = EXPORT_PAGE_SIZE): Promise<PlaceShadowExportResult> {
const size = Math.min(Math.max(1, limit), EXPORT_PAGE_SIZE);
const rows = this.db.all<DbRow>(
`SELECT * FROM place_shadow_picks
@@ -138,8 +138,8 @@ export class PlaceShadowService {
};
}
summary(): PlaceShadowSummaryResult {
const enabled = this.enabled();
async summary(): Promise<PlaceShadowSummaryResult> {
const enabled = await this.enabled();
const totals = this.db.get<{ total: number; oldest: string | null; newest: string | null }>(
'SELECT COUNT(*) AS total, MIN(created_at) AS oldest, MAX(created_at) AS newest FROM place_shadow_picks',
);
@@ -181,12 +181,12 @@ export class PlaceShadowService {
}
/** Admin wipe. Returns how many rows went. */
clear(): number {
async clear(): Promise<number> {
return this.db.run('DELETE FROM place_shadow_picks').changes;
}
/** Nightly retention. Returns how many rows went. */
purgeExpired(retentionDays = RETENTION_DAYS): number {
async purgeExpired(retentionDays = RETENTION_DAYS): Promise<number> {
return this.db.run(
`DELETE FROM place_shadow_picks
WHERE created_at < datetime('now', ?)`,
@@ -25,19 +25,19 @@ export class RouteUsageController {
*/
@Post('report')
@HttpCode(200)
report(@Body() body: RouteUsageReportDto): RouteUsageReportResult {
return { recorded: this.usage.record(body) };
async report(@Body() body: RouteUsageReportDto): Promise<RouteUsageReportResult> {
return { recorded: await this.usage.record(body) };
}
@Get('summary')
@UseGuards(JwtAuthGuard, AdminGuard)
summary(): RouteUsageSummaryResult {
return this.usage.summary();
async summary(): Promise<RouteUsageSummaryResult> {
return await this.usage.summary();
}
@Delete()
@UseGuards(JwtAuthGuard, AdminGuard)
clear(): { removed: number } {
return { removed: this.usage.clear() };
async clear(): Promise<{ removed: number }> {
return { removed: await this.usage.clear() };
}
}
@@ -20,14 +20,17 @@ export class RouteUsageRetentionJob implements OnApplicationBootstrap {
private readonly registrar: CronRegistrarService,
) {}
onApplicationBootstrap(): void {
// `async` only so the sweep's call-graph gate sees a non-sync DB-reaching
// frame here: nothing in the body awaits, and Nest awaits the returned
// promise before the next bootstrap hook, exactly as it did the `void`.
async onApplicationBootstrap(): Promise<void> {
if (!this.registrar.isEnabled()) return;
this.registrar.register('route-usage-retention', '45 3 * * *', () => this.tick());
}
tick(): void {
async tick(): Promise<void> {
try {
const removed = this.usage.purgeExpired();
const removed = await this.usage.purgeExpired();
if (removed > 0) {
logInfo(`Route usage retention: removed ${removed} expired row(s)`);
}
@@ -7,6 +7,7 @@ import type {
RouteUsageSurface,
} from '@trek/shared';
import { DatabaseService } from '../database/database.service';
import { UnitOfWork } from '../database/unit-of-work';
/** Days a counted day survives. Aggregates are tiny, so this is a year and a bit. */
export const RETENTION_DAYS = 400;
@@ -40,9 +41,12 @@ interface DbRow {
*/
@Injectable()
export class RouteUsageService {
constructor(private readonly db: DatabaseService) {}
constructor(
private readonly db: DatabaseService,
private readonly uow: UnitOfWork,
) {}
enabled(): boolean {
async enabled(): Promise<boolean> {
const row = this.db.get<{ value: string }>(
"SELECT value FROM app_settings WHERE key = 'route_usage_enabled'",
);
@@ -56,11 +60,11 @@ export class RouteUsageService {
* switched-off instance answers 200 rather than an error the client would log on
* every flush.
*/
record(report: RouteUsageReportRequest): boolean {
if (!this.enabled()) return false;
async record(report: RouteUsageReportRequest): Promise<boolean> {
if (!(await this.enabled())) return false;
// One transaction for the batch: a flush is a handful of rows, and a partial
// one would leave a day counted twice on the client's next retry.
this.db.transaction(() => {
await this.uow.transactional(async () => {
for (const entry of report.entries) {
this.db.run(
`INSERT INTO route_usage_daily (day, profile, surface, self_hosted, requests, waypoints, km, failed)
@@ -83,7 +87,7 @@ export class RouteUsageService {
return true;
}
rows(): RouteUsageDayRow[] {
async rows(): Promise<RouteUsageDayRow[]> {
const rows = this.db.all<DbRow>(
'SELECT * FROM route_usage_daily ORDER BY day DESC, profile, surface',
);
@@ -99,9 +103,9 @@ export class RouteUsageService {
}));
}
summary(): RouteUsageSummaryResult {
const rows = this.rows();
const enabled = this.enabled();
async summary(): Promise<RouteUsageSummaryResult> {
const rows = await this.rows();
const enabled = await this.enabled();
const empty: RouteUsageSummaryResult = {
enabled,
retentionDays: RETENTION_DAYS,
@@ -169,7 +173,7 @@ export class RouteUsageService {
}
/** Removes days past the retention window. Returns how many rows went. */
purgeExpired(): number {
async purgeExpired(): Promise<number> {
const result = this.db.run(
`DELETE FROM route_usage_daily WHERE day < date('now', ?)`,
`-${RETENTION_DAYS} days`,
@@ -178,7 +182,7 @@ export class RouteUsageService {
}
/** Wipes every counter. The admin's own "start over". */
clear(): number {
async clear(): Promise<number> {
const result = this.db.run('DELETE FROM route_usage_daily');
return result.changes ?? 0;
}
@@ -11,7 +11,7 @@ export class SchoolHolidaysMcp {
constructor(private readonly holidays: SchoolHolidaysService, private readonly guards: McpToolGuardsService) {}
private async adminWrite(ctx: McpContext, write: () => unknown) {
if (!this.guards.isAdminUser(ctx.userId)) return adminRequired();
if (!(await this.guards.isAdminUser(ctx.userId))) return adminRequired();
try { return ok(await write()); }
catch (error) {
if (error instanceof HttpException || error instanceof z.ZodError) return errorResult(error.message);
@@ -37,14 +37,14 @@ export class StorageAdminController {
) {}
@Get()
get() {
return this.service.state();
async get() {
return await this.service.state();
}
@Put()
async update(@CurrentUser() user: User, @Body() body: StorageConfigDto, @Req() req: Request) {
try {
this.service.applyConfig(body);
await this.service.applyConfig(body);
} catch (err) {
// The conflict branch must come before the blanket 400: a
// StorageConflictError IS an Error, so the generic catch-all below
@@ -127,7 +127,7 @@ export class StorageAdminController {
async migrationStart(@CurrentUser() user: User, @Body() body: StorageMigrationRequestDto, @Req() req: Request): Promise<{ started: true }> {
const { category, to } = body;
try {
this.service.startMigration(category, to);
await this.service.startMigration(category, to);
} catch (err) {
if (err instanceof MigrationRequestError) throw new HttpException({ error: err.message }, 400);
if (err instanceof MigrationTargetError) throw new HttpException({ error: err.message }, 404);
@@ -2,6 +2,7 @@ import fs from 'node:fs';
import { Injectable } from '@nestjs/common';
import type { StorageAdminState, StorageBackend, StorageConfigPut, StorageTestResponse, StorageUsage } from '@trek/shared';
import { DatabaseService } from '../database/database.service';
import { UnitOfWork } from '../database/unit-of-work';
import {
BACKENDS_KEY,
CATEGORIES_KEY,
@@ -37,10 +38,11 @@ export class StorageAdminService {
private readonly storage: StorageService,
private readonly jobs: StorageJobsService,
private readonly stats: StorageStatsService,
private readonly uow: UnitOfWork,
) {}
/** The effective world — secrets masked, categories cross-referenced per backend. */
state(): StorageAdminState {
async state(): Promise<StorageAdminState> {
const snapshot = this.registry.snapshot();
const assignments = Object.entries(snapshot.categories) as Array<
[keyof typeof snapshot.categories, { backend: string; source: 'default' | 'settings' }]
@@ -56,10 +58,10 @@ export class StorageAdminService {
categories: snapshot.categories,
health: { replicaFailures: this.storage.health().replicaFailures.map((f) => ({ ...f })) },
seedFilePresent: fs.existsSync(SEED_CONFIG_PATH),
usage: this.stats.readUsage(),
usage: await this.stats.readUsage(),
backfills: this.jobs.statuses(),
migrations: this.jobs.migrationStatuses(),
version: this.registry.currentConfigVersion(),
version: await this.registry.currentConfigVersion(),
configError: this.registry.lastLoadError(),
};
}
@@ -82,8 +84,8 @@ export class StorageAdminService {
* job registry; throws MigrationRequestError (400) / MigrationTargetError (404) /
* BackfillBusyError (409).
*/
startMigration(category: StorageCategory, to: string): void {
this.jobs.startMigration(category, to);
async startMigration(category: StorageCategory, to: string): Promise<void> {
await this.jobs.startMigration(category, to);
}
/** True when an active migration was cancelled; false when there was nothing to cancel. */
@@ -92,8 +94,8 @@ export class StorageAdminService {
}
/** Runs and persists a fresh usage scan. Throws StatsBusyError (409) if one is already running. */
refreshStats(): Promise<StorageUsage> {
return this.stats.scan();
async refreshStats(): Promise<StorageUsage> {
return await this.stats.scan();
}
/**
@@ -104,19 +106,19 @@ export class StorageAdminService {
* config that moved on since the form was loaded (e.g. a category
* migration's flip, which bumps the same counter).
*/
applyConfig(config: StorageConfigPut): void {
const currentVersion = this.registry.currentConfigVersion();
async applyConfig(config: StorageConfigPut): Promise<void> {
const currentVersion = await this.registry.currentConfigVersion();
if (config.version !== currentVersion) {
throw new StorageConflictError(currentVersion, config.version);
}
const unmasked = unmaskStorageConfig(config, this.storedBackendsRow());
const unmasked = unmaskStorageConfig(config, await this.storedBackendsRow());
// unmask only resolves the secret fields it knows about; a mask sentinel
// submitted in a non-secret field would otherwise pass through untouched
// and get persisted verbatim as garbage-in.
assertNoMaskSentinels(unmasked);
this.registry.preview({ backends: unmasked.backends, categories: unmasked.categories });
const encrypted = encryptStorageSecrets(unmasked);
this.db.transaction(() => {
await this.uow.transactional(async () => {
const upsert = this.db.prepare(
'INSERT INTO app_settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
);
@@ -124,7 +126,7 @@ export class StorageAdminService {
upsert.run(CATEGORIES_KEY, JSON.stringify(encrypted.categories));
upsert.run(VERSION_KEY, String(currentVersion + 1));
});
this.registry.reload();
await this.registry.reload();
// Any running job whose backend the reloaded config no longer has ends
// cancelled rather than running invisibly against a stale driver ref
// (polish item 3) — see StorageJobsService.cancelJobsForMissingBackends.
@@ -139,7 +141,7 @@ export class StorageAdminService {
async testBackend(candidate: StorageBackend): Promise<StorageTestResponse> {
const { backends } = unmaskStorageConfig(
{ backends: [candidate], categories: {} },
this.storedBackendsRow(),
await this.storedBackendsRow(),
);
const backend = backends[0]!;
const targets = this.probeTargetsFor(backend).map(decryptBackendSecrets) as Array<
@@ -180,7 +182,7 @@ export class StorageAdminService {
}
/** The raw stored backends row — the unmask source (tolerates absent/garbage rows). */
private storedBackendsRow(): unknown {
private async storedBackendsRow(): Promise<unknown> {
const row = this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', BACKENDS_KEY);
if (!row?.value) return [];
try {
@@ -147,7 +147,7 @@ export class StorageJobsService {
* Throws MigrationRequestError (400) / MigrationTargetError (404) /
* BackfillBusyError (409, shared with backfills — one storage job at a time).
*/
startMigration(category: StorageCategory, to: string): void {
async startMigration(category: StorageCategory, to: string): Promise<void> {
if (!STORAGE_CATEGORIES.includes(category)) {
throw new MigrationRequestError(`'${category}' is not a configurable category`);
}
@@ -318,13 +318,16 @@ export class StorageJobsService {
// last object's await (or an empty category, which never enters the loop
// at all) would otherwise reach the flip unchecked. Everything from here
// to assignCategory() below is one synchronous stretch, so this is the
// last point a cancel can still be honored before the flip.
// last point a cancel can still be honored before the flip. (The flip
// itself now awaits — assignCategory writes through UnitOfWork — but
// nothing between this check and that call yields, so the window is the
// same one it always was.)
if (job.cancelled) {
job.status = { ...s(), status: 'cancelled', finishedAt: Date.now() };
return;
}
// Phase 2: flip — the job, not the save, owns this.
this.registry.assignCategory(s().category, s().to);
await this.registry.assignCategory(s().category, s().to);
// Phase 3: delta sweep + reclaimable tally. Cancellation is ignored here
// (bounded). Reclaimable stays SOURCE-keyed — it counts what's left to
// reclaim on the old backend, not where it landed on the new one.
@@ -2,6 +2,7 @@ import fs from 'node:fs';
import { Injectable, Logger, type OnModuleInit } from '@nestjs/common';
import { STORAGE_BACKEND_TYPES, storageConfigSchema } from '@trek/shared';
import { DatabaseService } from '../database/database.service';
import { UnitOfWork } from '../database/unit-of-work';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { decrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { LocalDriver } from './drivers/local.driver';
@@ -133,16 +134,17 @@ export class StorageRegistryService implements OnModuleInit {
private readonly db: DatabaseService,
private readonly env: RuntimeEnvService,
private readonly events: StorageEventsService,
private readonly uow: UnitOfWork,
) {}
onModuleInit(): void {
this.seedFromFileOnce();
this.load(true);
async onModuleInit(): Promise<void> {
await this.seedFromFileOnce();
await this.load(true);
}
/** Re-read settings, validate, atomically swap. In-flight ops keep their resolved instances. */
reload(): void {
this.load(false);
async reload(): Promise<void> {
await this.load(false);
}
/**
@@ -200,8 +202,8 @@ export class StorageRegistryService implements OnModuleInit {
}
/** Current optimistic-concurrency counter — 0 when never bumped (fresh install). */
currentConfigVersion(): number {
return readConfigVersion(this.db);
async currentConfigVersion(): Promise<number> {
return await readConfigVersion(this.db);
}
/** Non-null when the last load() fell back (last-good config or built-in defaults) — null once a load succeeds. */
@@ -218,7 +220,7 @@ export class StorageRegistryService implements OnModuleInit {
* PUT built against the pre-flip version now conflicts instead of silently
* overwriting this assignment.
*/
assignCategory(category: StorageCategory, backend: string): void {
async assignCategory(category: StorageCategory, backend: string): Promise<void> {
// Belt-and-braces alongside the migration job's own pre-flip cancel guard:
// never persist a category pointing at a backend that doesn't exist in
// the current snapshot (e.g. a config save removed it mid-migration).
@@ -240,17 +242,17 @@ export class StorageRegistryService implements OnModuleInit {
`cannot assign '${category}' to '${backend}' — '${owner}' is a mirror replica of '${holder.name}', and that mirror's sync sweep would delete the category's objects`,
);
}
const stored = new Map(parseCategoryMap(this.readSettings().categories));
const stored = new Map(parseCategoryMap((await this.readSettings()).categories));
stored.set(category, backend);
const next = Object.fromEntries(stored);
this.db.transaction(() => {
await this.uow.transactional(async () => {
const upsert = this.db.prepare(
'INSERT INTO app_settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
);
upsert.run(CATEGORIES_KEY, JSON.stringify(next));
upsert.run(VERSION_KEY, String(readConfigVersion(this.db) + 1));
upsert.run(VERSION_KEY, String((await readConfigVersion(this.db)) + 1));
});
this.reload();
await this.reload();
}
recordReplicaFailure(failure: ReplicaFailure): void {
@@ -275,7 +277,7 @@ export class StorageRegistryService implements OnModuleInit {
* Recovery: stop the server, DELETE FROM app_settings WHERE key LIKE
* 'storage.%', restart (documented in the README with slice 3).
*/
private seedFromFileOnce(): void {
private async seedFromFileOnce(): Promise<void> {
const rowCount = this.db.get<{ n: number }>(
'SELECT COUNT(*) AS n FROM app_settings WHERE key IN (?, ?)',
BACKENDS_KEY,
@@ -313,7 +315,7 @@ export class StorageRegistryService implements OnModuleInit {
return fail(err instanceof Error ? err.message : String(err));
}
const encrypted = encryptStorageSecrets(config);
this.db.transaction(() => {
await this.uow.transactional(async () => {
const upsert = this.db.prepare(
'INSERT INTO app_settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
);
@@ -330,9 +332,9 @@ export class StorageRegistryService implements OnModuleInit {
* state is kept (at boot, when there is no previous state, the built-in
* defaults — which cannot be misconfigured — are loaded instead).
*/
private load(boot: boolean): void {
private async load(boot: boolean): Promise<void> {
try {
this.state = this.build(this.readSettings(), boot);
this.state = this.build(await this.readSettings(), boot);
this.loadFailure = null;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
@@ -345,7 +347,7 @@ export class StorageRegistryService implements OnModuleInit {
}
}
private readSettings(): { backends: unknown; categories: unknown } {
private async readSettings(): Promise<{ backends: unknown; categories: unknown }> {
const read = (key: string): unknown => {
const row = this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', key);
if (!row?.value) return undefined;
@@ -480,7 +482,7 @@ function isRecord(value: unknown): value is Record<string, unknown> {
}
/** Raw read of the version counter row — 0 for an absent/garbage row (fresh install, or a hand-edited DB). */
function readConfigVersion(db: DatabaseService): number {
async function readConfigVersion(db: DatabaseService): Promise<number> {
const row = db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', VERSION_KEY);
const parsed = row?.value ? Number.parseInt(row.value, 10) : 0;
return Number.isFinite(parsed) ? parsed : 0;
@@ -55,7 +55,7 @@ export class StorageStatsService {
}
/** The stored row, parsed; null when absent or unparseable (logged, never a 500). */
readUsage(): StorageUsage | null {
async readUsage(): Promise<StorageUsage | null> {
const row = this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', USAGE_KEY);
if (!row) return null;
try {
@@ -12,7 +12,10 @@ export class StorageUsageScanJob implements OnApplicationBootstrap {
private readonly stats: StorageStatsService,
) {}
onApplicationBootstrap(): void {
// `async` only so the sweep's call-graph gate sees a non-sync DB-reaching
// frame here: nothing in the body awaits, and Nest awaits the returned
// promise before the next bootstrap hook, exactly as it did the `void`.
async onApplicationBootstrap(): Promise<void> {
if (!this.registrar.isEnabled()) return;
this.registrar.register('storage-usage-scan', '15 4 * * *', () => {
void this.tick();
+2 -2
View File
@@ -290,8 +290,8 @@ export class StorageService {
* pre-restore one. Same shape as health(): StorageRegistryService stays
* unexported from the module, this facade is the only way in.
*/
reloadConfig(): void {
this.registry.reload();
async reloadConfig(): Promise<void> {
await this.registry.reload();
}
private resolve(category: ServedCategory, name: string): Resolved {
+14 -14
View File
@@ -39,38 +39,38 @@ export class TodoController {
@Get()
list(@CurrentUser() user: User, @Param('tripId') tripId: string) {
return { items: this.todo.listItems(tripId) };
async list(@CurrentUser() user: User, @Param('tripId') tripId: string) {
return { items: await this.todo.listItems(tripId) };
}
@RequirePermission('packing_edit')
@Post()
create(
async create(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: TodoCreateItemDto,
@Headers('x-socket-id') socketId?: string,
) {
const { name, category, due_date, description, assigned_user_id, priority } = body;
const item = this.todo.createItem(tripId, { name, category, due_date, description, assigned_user_id, priority });
const item = await this.todo.createItem(tripId, { name, category, due_date, description, assigned_user_id, priority });
this.todo.broadcast(tripId, 'todo:created', { item }, socketId);
return { item };
}
@RequirePermission('packing_edit')
@Put('reorder')
reorder(
async reorder(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: TodoReorderDto,
) {
this.todo.reorderItems(tripId, body.orderedIds);
await this.todo.reorderItems(tripId, body.orderedIds);
return { success: true };
}
@RequirePermission('packing_edit')
@Put(':id')
update(
async update(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@@ -80,7 +80,7 @@ export class TodoController {
const { name, checked, category, due_date, description, assigned_user_id, priority } = body;
// bodyKeys carries which keys the request actually provided (the null-clear
// protocol); the parsed body only ever holds known schema keys.
const updated = this.todo.updateItem(
const updated = await this.todo.updateItem(
tripId,
id,
// checked arrives as boolean or legacy 0/1 — normalize to the 0/1 the SQL binds.
@@ -96,13 +96,13 @@ export class TodoController {
@RequirePermission('packing_edit')
@Delete(':id')
remove(
async remove(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Headers('x-socket-id') socketId?: string,
) {
if (!this.todo.deleteItem(tripId, id)) {
if (!(await this.todo.deleteItem(tripId, id))) {
throw new HttpException({ error: 'Item not found' }, 404);
}
this.todo.broadcast(tripId, 'todo:deleted', { itemId: Number(id) }, socketId);
@@ -110,13 +110,13 @@ export class TodoController {
}
@Get('category-assignees')
categoryAssignees(@CurrentUser() user: User, @Param('tripId') tripId: string) {
return { assignees: this.todo.getCategoryAssignees(tripId) };
async categoryAssignees(@CurrentUser() user: User, @Param('tripId') tripId: string) {
return { assignees: await this.todo.getCategoryAssignees(tripId) };
}
@RequirePermission('packing_edit')
@Put('category-assignees/:categoryName')
updateCategoryAssignees(
async updateCategoryAssignees(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('categoryName') categoryName: string,
@@ -124,7 +124,7 @@ export class TodoController {
@Headers('x-socket-id') socketId?: string,
) {
const category = decodeURIComponent(categoryName);
const rows = this.todo.updateCategoryAssignees(tripId, category, body.user_ids);
const rows = await this.todo.updateCategoryAssignees(tripId, category, body.user_ids);
this.todo.broadcast(tripId, 'todo:assignees', { category, assignees: rows }, socketId);
return { assignees: rows };
}
+18 -18
View File
@@ -50,8 +50,8 @@ export class TodoMcp {
access: { group: 'todos', mode: 'read' },
})
async listTodos({ tripId }: { tripId: number }, ctx: McpContext) {
if (!this.todos.verifyTripAccess(tripId, ctx.userId)) return noAccess();
const items = this.todos.listItems(tripId);
if (!(await this.todos.verifyTripAccess(tripId, ctx.userId))) return noAccess();
const items = await this.todos.listItems(tripId);
return ok({ items });
}
@@ -78,9 +78,9 @@ export class TodoMcp {
ctx: McpContext,
) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.todos.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.todos.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('packing_edit', tripId, ctx.userId))) return permissionDenied();
const item = this.todos.createItem(tripId, { name, category, due_date, description, assigned_user_id, priority });
const item = await this.todos.createItem(tripId, { name, category, due_date, description, assigned_user_id, priority });
this.guards.safeBroadcast(tripId, 'todo:created', { item });
return ok({ item });
}
@@ -109,7 +109,7 @@ export class TodoMcp {
ctx: McpContext,
) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.todos.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.todos.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('packing_edit', tripId, ctx.userId))) return permissionDenied();
// Build bodyKeys to signal which nullable fields were explicitly provided
const bodyKeys: string[] = [];
@@ -117,7 +117,7 @@ export class TodoMcp {
if (description !== undefined) bodyKeys.push('description');
if (assigned_user_id !== undefined) bodyKeys.push('assigned_user_id');
if (priority !== undefined) bodyKeys.push('priority');
const item = this.todos.updateItem(tripId, itemId, { name, category, due_date, description, assigned_user_id, priority }, bodyKeys);
const item = await this.todos.updateItem(tripId, itemId, { name, category, due_date, description, assigned_user_id, priority }, bodyKeys);
if (!item) return errorResult('To-do item not found.');
this.guards.safeBroadcast(tripId, 'todo:updated', { item });
return ok({ item });
@@ -137,9 +137,9 @@ export class TodoMcp {
})
async toggleTodo({ tripId, itemId, checked }: { tripId: number; itemId: number; checked: boolean }, ctx: McpContext) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.todos.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.todos.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('packing_edit', tripId, ctx.userId))) return permissionDenied();
const item = this.todos.updateItem(tripId, itemId, { checked: checked ? 1 : 0 }, []);
const item = await this.todos.updateItem(tripId, itemId, { checked: checked ? 1 : 0 }, []);
if (!item) return errorResult('To-do item not found.');
this.guards.safeBroadcast(tripId, 'todo:updated', { item });
return ok({ item });
@@ -158,9 +158,9 @@ export class TodoMcp {
})
async deleteTodo({ tripId, itemId }: { tripId: number; itemId: number }, ctx: McpContext) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.todos.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.todos.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('packing_edit', tripId, ctx.userId))) return permissionDenied();
const deleted = this.todos.deleteItem(tripId, itemId);
const deleted = await this.todos.deleteItem(tripId, itemId);
if (!deleted) return errorResult('To-do item not found.');
this.guards.safeBroadcast(tripId, 'todo:deleted', { itemId });
return ok({ success: true });
@@ -179,9 +179,9 @@ export class TodoMcp {
})
async reorderTodos({ tripId, orderedIds }: { tripId: number; orderedIds: number[] }, ctx: McpContext) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.todos.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.todos.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('packing_edit', tripId, ctx.userId))) return permissionDenied();
this.todos.reorderItems(tripId, orderedIds);
await this.todos.reorderItems(tripId, orderedIds);
return ok({ success: true });
}
@@ -196,8 +196,8 @@ export class TodoMcp {
access: { group: 'todos', mode: 'read' },
})
async getTodoCategoryAssignees({ tripId }: { tripId: number }, ctx: McpContext) {
if (!this.todos.verifyTripAccess(tripId, ctx.userId)) return noAccess();
const assignees = this.todos.getCategoryAssignees(tripId);
if (!(await this.todos.verifyTripAccess(tripId, ctx.userId))) return noAccess();
const assignees = await this.todos.getCategoryAssignees(tripId);
return ok({ assignees });
}
@@ -215,9 +215,9 @@ export class TodoMcp {
})
async setTodoCategoryAssignees({ tripId, categoryName, userIds }: { tripId: number; categoryName: string; userIds: number[] }, ctx: McpContext) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.todos.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.todos.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('packing_edit', tripId, ctx.userId))) return permissionDenied();
const assignees = this.todos.updateCategoryAssignees(tripId, categoryName, userIds);
const assignees = await this.todos.updateCategoryAssignees(tripId, categoryName, userIds);
this.guards.safeBroadcast(tripId, 'todo:assignees', { category: categoryName, assignees });
return ok({ assignees });
}
@@ -232,7 +232,7 @@ export class TodoMcp {
})
async tripTodosResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {
const id = parseId(tripId);
if (id === null || !this.todos.verifyTripAccess(id, ctx.userId)) {
if (id === null || !(await this.todos.verifyTripAccess(id, ctx.userId))) {
return {
contents: [{
uri: uri.href,
@@ -241,7 +241,7 @@ export class TodoMcp {
}],
};
}
const items = this.todos.listItems(id);
const items = await this.todos.listItems(id);
return {
contents: [{
uri: uri.href,
+9 -5
View File
@@ -27,8 +27,12 @@ export class TodoRpc {
) {}
@PluginMethod('todos.list', { permission: 'db:read:todos' })
list(params: Record<string, unknown>, ctx: PluginRpcContext): unknown[] {
return this.guards.tripRead(params, ctx, () => this.todos.listItems(String(num(params.tripId, 'tripId'))) as unknown[]);
async list(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown[]> {
return await this.guards.tripRead(
params,
ctx,
async () => (await this.todos.listItems(String(num(params.tripId, 'tripId')))) as unknown[],
);
}
@PluginMethod('todos.create', { permission: 'db:write:todos' })
@@ -38,7 +42,7 @@ export class TodoRpc {
const input = asPayload(params.input);
if (typeof input.name !== 'string' || input.name.trim() === '') throw new BadParams('todo name is required');
await this.guards.requireTripEdit(tripId, actor, TODO_EDIT_ACTION);
const item = this.todos.createItem(String(tripId), input as never);
const item = await this.todos.createItem(String(tripId), input as never);
this.realtime.broadcast(tripId, 'todo:created', { item }, undefined);
return item;
}
@@ -50,7 +54,7 @@ export class TodoRpc {
const actor = this.guards.requireActor(ctx, 'todo');
await this.guards.requireTripEdit(tripId, actor, TODO_EDIT_ACTION);
const input = asPayload(params.input);
const updated = this.todos.updateItem(String(tripId), String(todoId), input as never, Object.keys(input));
const updated = await this.todos.updateItem(String(tripId), String(todoId), input as never, Object.keys(input));
if (!updated) throw new ForbiddenResource(`no todo ${todoId} on trip ${tripId}`);
this.realtime.broadcast(tripId, 'todo:updated', { item: updated }, undefined);
return updated;
@@ -62,7 +66,7 @@ export class TodoRpc {
const todoId = num(params.todoId, 'todoId');
const actor = this.guards.requireActor(ctx, 'todo');
await this.guards.requireTripEdit(tripId, actor, TODO_EDIT_ACTION);
if (!this.todos.deleteItem(String(tripId), String(todoId))) {
if (!(await this.todos.deleteItem(String(tripId), String(todoId)))) {
throw new ForbiddenResource(`no todo ${todoId} on trip ${tripId}`);
}
this.realtime.broadcast(tripId, 'todo:deleted', { itemId: todoId }, undefined);
+12 -10
View File
@@ -4,6 +4,7 @@ import { RealtimeService } from '../realtime/realtime.service';
import { PermissionsService } from '../permissions/permissions.service';
import type { User } from '../../types';
import { DatabaseService, type TripAccess } from '../database/database.service';
import { UnitOfWork } from '../database/unit-of-work';
type Trip = TripAccess;
@@ -22,9 +23,10 @@ export class TodoService {
private readonly db: DatabaseService,
private readonly permissions: PermissionsService,
private readonly realtime: RealtimeService,
private readonly uow: UnitOfWork,
) {}
verifyTripAccess(tripId: string | number, userId: number) {
async verifyTripAccess(tripId: string | number, userId: number) {
return this.db.canAccessTrip(tripId, userId);
}
@@ -36,14 +38,14 @@ export class TodoService {
this.realtime.broadcast(tripId, event, payload, socketId);
}
listItems(tripId: string | number) {
async listItems(tripId: string | number) {
return this.db.all(
'SELECT * FROM todo_items WHERE trip_id = ? ORDER BY sort_order ASC, created_at ASC',
tripId
);
}
createItem(tripId: string | number, data: {
async createItem(tripId: string | number, data: {
name: string; category?: string | null; due_date?: string | null; description?: string | null; assigned_user_id?: number | null; priority?: number;
}) {
const maxOrder = this.db.get<{ max: number | null }>('SELECT MAX(sort_order) as max FROM todo_items WHERE trip_id = ?', tripId)!;
@@ -58,7 +60,7 @@ export class TodoService {
return this.db.get('SELECT * FROM todo_items WHERE id = ?', result.lastInsertRowid);
}
updateItem(
async updateItem(
tripId: string | number,
id: string | number,
data: { name?: string; checked?: number; category?: string | null; due_date?: string | null; description?: string | null; assigned_user_id?: number | null; priority?: number | null },
@@ -96,7 +98,7 @@ export class TodoService {
return this.db.get('SELECT * FROM todo_items WHERE id = ?', id);
}
deleteItem(tripId: string | number, id: string | number): boolean {
async deleteItem(tripId: string | number, id: string | number): Promise<boolean> {
const item = this.db.get('SELECT id FROM todo_items WHERE id = ? AND trip_id = ?', id, tripId);
if (!item) return false;
@@ -104,16 +106,16 @@ export class TodoService {
return true;
}
reorderItems(tripId: string | number, orderedIds: number[]): void {
async reorderItems(tripId: string | number, orderedIds: number[]): Promise<void> {
const update = this.db.prepare('UPDATE todo_items SET sort_order = ? WHERE id = ? AND trip_id = ?');
this.db.transaction(() => {
await this.uow.transactional(async () => {
orderedIds.forEach((id, index) => {
update.run(index, id, tripId);
});
});
}
getCategoryAssignees(tripId: string | number) {
async getCategoryAssignees(tripId: string | number) {
const rows = this.db.all<{ category_name: string; user_id: number; username: string; avatar: string | null }>(`
SELECT tca.category_name, tca.user_id, u.username, u.avatar
FROM todo_category_assignees tca
@@ -130,8 +132,8 @@ export class TodoService {
return assignees;
}
updateCategoryAssignees(tripId: string | number, categoryName: string, userIds: number[] | undefined) {
this.db.transaction(() => {
async updateCategoryAssignees(tripId: string | number, categoryName: string, userIds: number[] | undefined) {
await this.uow.transactional(async () => {
this.db.run('DELETE FROM todo_category_assignees WHERE trip_id = ? AND category_name = ?', tripId, categoryName);
if (Array.isArray(userIds) && userIds.length > 0) {
@@ -24,7 +24,7 @@ export class TripInviteLinkController {
constructor(private readonly invites: TripInviteService, private readonly audit: AuditService) {}
private async requireManage(tripId: string, user: User) {
const trip = this.invites.verifyTripAccess(tripId, user.id);
const trip = await this.invites.verifyTripAccess(tripId, user.id);
if (!trip) throw new HttpException({ error: 'Trip not found' }, 404);
if (!(await this.invites.canManage(trip, user))) throw new HttpException({ error: 'No permission' }, 403);
}
@@ -34,7 +34,7 @@ export class TripInviteLinkController {
// The token grants trip membership, so reading it needs the same
// share_manage permission as creating/rotating it — not just trip access.
await this.requireManage(tripId, user);
const info = this.invites.get(tripId);
const info = await this.invites.get(tripId);
return info ? info : { token: null };
}
@@ -49,7 +49,7 @@ export class TripInviteLinkController {
const days = body?.expires_in_days != null && String(body.expires_in_days).trim() !== ''
? Number.parseInt(String(body.expires_in_days))
: null;
const info = this.invites.createOrRotate(tripId, user.id, Number.isFinite(days as number) ? days : null);
const info = await this.invites.createOrRotate(tripId, user.id, Number.isFinite(days as number) ? days : null);
await this.audit.writeAudit({ userId: user.id, action: 'trip.invite_link_create', resource: tripId, ip: getClientIp(req), details: { expires_in_days: days } });
return info;
}
@@ -57,7 +57,7 @@ export class TripInviteLinkController {
@Delete()
async remove(@CurrentUser() user: User, @Param('tripId') tripId: string, @Req() req: Request) {
await this.requireManage(tripId, user);
this.invites.remove(tripId);
await this.invites.remove(tripId);
await this.audit.writeAudit({ userId: user.id, action: 'trip.invite_link_delete', resource: tripId, ip: getClientIp(req) });
return { success: true };
}
@@ -82,9 +82,9 @@ export class TripInviteController {
}
@Get(':token')
preview(@Param('token') token: string, @Req() req: Request) {
async preview(@Param('token') token: string, @Req() req: Request) {
this.limit(req, 30);
const resolved = this.invites.resolve(token);
const resolved = await 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 };
}
@@ -93,7 +93,7 @@ export class TripInviteController {
@HttpCode(200)
async accept(@CurrentUser() user: User, @Param('token') token: string, @Req() req: Request) {
this.limit(req, 20);
const resolved = this.invites.resolve(token);
const resolved = await this.invites.resolve(token);
if (!resolved) throw new HttpException({ error: 'Invalid or expired invite link' }, 404);
const result = await this.invites.join(resolved.trip_id, user.id);
await this.audit.writeAudit({ userId: user.id, action: 'trip.invite_link_join', resource: String(resolved.trip_id), ip: getClientIp(req), details: { joined: result.joined } });
@@ -47,7 +47,7 @@ export class TripInviteMcp {
/** Trip access first (404-equivalent), then share_manage, which is requireManage() in the controller. */
private async denyManage(tripId: number, userId: number) {
if (!this.invites.verifyTripAccess(String(tripId), userId)) return noAccess();
if (!(await this.invites.verifyTripAccess(String(tripId), userId))) return noAccess();
if (!(await this.guards.hasTripPermission('share_manage', tripId, userId))) return permissionDenied();
return null;
}
@@ -69,7 +69,7 @@ export class TripInviteMcp {
async getTripInviteLink({ tripId }: { tripId: number }, ctx: McpContext) {
const denied = await this.denyManage(tripId, ctx.userId);
if ((await denied)) return denied;
const info = this.invites.get(tripId);
const info = await this.invites.get(tripId);
return ok({ invite_link: info ? this.describe(info) : null });
}
@@ -98,7 +98,7 @@ export class TripInviteMcp {
? Number.parseInt(String(expires_in_days))
: null;
const days = Number.isFinite(parsed as number) ? parsed : null;
const info = this.invites.createOrRotate(tripId, ctx.userId, days);
const info = await this.invites.createOrRotate(tripId, ctx.userId, days);
// Minting a membership credential is audited wherever it happens, so an
// admin reading the log sees the same row for a link made through an
// assistant as for one made in the planner. No request here, hence no ip.
@@ -125,7 +125,7 @@ export class TripInviteMcp {
if (await this.isDemoUser(ctx.userId)) return demoDenied();
const denied = await this.denyManage(tripId, ctx.userId);
if ((await denied)) return denied;
this.invites.remove(tripId);
await this.invites.remove(tripId);
await this.audit.writeAudit({
userId: ctx.userId,
action: 'trip.invite_link_delete',
@@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import crypto from 'crypto';
import { DatabaseService } from '../database/database.service';
import { UnitOfWork } from '../database/unit-of-work';
import type { TripAccess } from '../database/database.service';
import { PermissionsService } from '../permissions/permissions.service';
import { TripMembershipService } from '../trip-membership/trip-membership.service';
@@ -32,9 +33,10 @@ export class TripInviteService {
private readonly dbs: DatabaseService,
private readonly permissions: PermissionsService,
private readonly membership: TripMembershipService,
private readonly uow: UnitOfWork,
) {}
verifyTripAccess(tripId: string, userId: number) {
async verifyTripAccess(tripId: string, userId: number) {
return this.dbs.canAccessTrip(tripId, userId);
}
@@ -43,7 +45,7 @@ export class TripInviteService {
}
/** The current invite link for a trip, or null if none exists. */
get(tripId: string | number): TripInviteInfo | null {
async get(tripId: string | number): Promise<TripInviteInfo | null> {
const row = this.dbs.get<{ token: string; expires_at: string | null; created_at: string }>(
'SELECT token, expires_at, created_at FROM trip_invite_tokens WHERE trip_id = ?',
tripId,
@@ -55,7 +57,7 @@ export class TripInviteService {
* 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.
*/
createOrRotate(tripId: string | number, createdBy: number, expiresInDays?: number | null): TripInviteInfo {
async createOrRotate(tripId: string | number, createdBy: number, expiresInDays?: number | null): Promise<TripInviteInfo> {
const token = crypto.randomBytes(24).toString('base64url');
// Any non-positive/absent value (0, negatives, NaN, null, undefined) means
// "no expiry" — deliberate: the UI sends null when no bound was chosen.
@@ -67,7 +69,7 @@ export class TripInviteService {
// Probe + write + re-select are one atomic unit so a concurrent rotation
// can't interleave between them (the trip_id UNIQUE constraint would turn
// that into a spurious 500).
return this.dbs.transaction(() => {
return await this.uow.transactional(async () => {
const existing = this.dbs.get('SELECT id FROM trip_invite_tokens WHERE trip_id = ?', tripId);
if (existing) {
this.dbs.run(
@@ -80,12 +82,12 @@ export class TripInviteService {
tripId, token, createdBy, expiresAt,
);
}
return this.get(tripId)!;
return (await this.get(tripId))!;
});
}
/** Remove the trip's invite link entirely (disable). */
remove(tripId: string | number): void {
async remove(tripId: string | number): Promise<void> {
this.dbs.run('DELETE FROM trip_invite_tokens WHERE trip_id = ?', tripId);
}
@@ -95,7 +97,7 @@ export class TripInviteService {
* trip title is safe to return for the join confirmation screen; an anonymous
* caller never reaches this (the endpoint is JWT-guarded).
*/
resolve(token: string): { trip_id: number; title: string } | null {
async resolve(token: string): Promise<{ trip_id: number; title: string } | null> {
const row = this.dbs.get<{ trip_id: number; title: string; expires_at: string | null }>(
`SELECT t.id AS trip_id, t.title AS title, ti.expires_at AS expires_at
FROM trip_invite_tokens ti
@@ -114,5 +116,5 @@ export class TripInviteService {
/** 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 this.membership.joinTripAsMember(tripId, userId, null); }
async join(tripId: number, userId: number) { return await this.membership.joinTripAsMember(tripId, userId, null); }
}
@@ -107,7 +107,7 @@ export class TripReadModelService {
// Scope to the requesting member so other members' private packing items
// (#858) never land in this viewer's offline cache.
packingItems: this.packing.listItems(tripId, viewerId),
todoItems: this.todo.listItems(tripId),
todoItems: await this.todo.listItems(tripId),
budgetItems: await this.budget.listBudgetItems(tripId),
reservations: this.reservations.list(tripId),
files: this.files.listFiles(tripId, false),
+1 -1
View File
@@ -280,7 +280,7 @@ export class TripsMcp {
const canReadCollab = collabEnabled && canRead(ctx.scopes, 'collab');
const canReadTodos = packingEnabled && canRead(ctx.scopes, 'todos');
const canReadRes = canRead(ctx.scopes, 'reservations');
const todos = canReadTodos ? this.todos.listItems(tripId) : [];
const todos = canReadTodos ? await this.todos.listItems(tripId) : [];
let pollCount = 0;
let messageCount = 0;
if (canReadCollab) {