diff --git a/server/src/nest/doc-sync/doc-sync-webhook.controller.ts b/server/src/nest/doc-sync/doc-sync-webhook.controller.ts index 47ad14cc6..10f0ba7a2 100644 --- a/server/src/nest/doc-sync/doc-sync-webhook.controller.ts +++ b/server/src/nest/doc-sync/doc-sync-webhook.controller.ts @@ -6,6 +6,7 @@ import { DatabaseService } from '../database/database.service'; import { SETTING_SYNC_ENABLED, WEBHOOK_NUDGE_DEBOUNCE_SECONDS } from './doc-sync.constants'; import { DocSyncConfigService, type LinkRow } from './doc-sync-config.service'; import { DocSyncService } from './doc-sync.service'; +import { logError } from '../audit/audit-log.logger'; /** * `/api/docsync/webhook/:token`: the one endpoint a provider calls. @@ -108,17 +109,24 @@ export class DocSyncWebhookController implements OnModuleDestroy { */ private schedule(linkId: number, reload: () => ReturnType, isRetry = false): void { if (this.pending.has(linkId)) return; - const timer = setTimeout(async () => { - this.pending.delete(linkId); - const fresh = reload(); - if (!fresh || fresh.sync_enabled !== 1) return; - if (!(await this.syncIsOn(fresh))) return; - void this.sync.syncLink(fresh).then((res) => { - // A run that was already in flight answers `busy`, and the changes this - // nudge was about may have landed after that run read the folder. Ask - // again once rather than waiting out a whole poll interval: once, and - // only for `busy`, so this cannot become a loop. - if (res?.state === 'busy' && !isRetry) this.schedule(linkId, reload, true); + // setTimeout cannot await its callback, so the now-async body runs in a + // helper and its rejection is observed here rather than left unhandled + // (recipe R1.5). + const timer = setTimeout(() => { + void (async () => { + this.pending.delete(linkId); + const fresh = reload(); + if (!fresh || fresh.sync_enabled !== 1) return; + if (!(await this.syncIsOn(fresh))) return; + void this.sync.syncLink(fresh).then((res) => { + // A run that was already in flight answers `busy`, and the changes this + // nudge was about may have landed after that run read the folder. Ask + // again once rather than waiting out a whole poll interval: once, and + // only for `busy`, so this cannot become a loop. + if (res?.state === 'busy' && !isRetry) this.schedule(linkId, reload, true); + }); + })().catch((err: unknown) => { + logError(`Document sync webhook nudge failed for link ${linkId}: ${err instanceof Error ? err.message : String(err)}`); }); }, WEBHOOK_NUDGE_DEBOUNCE_SECONDS * 1000); // A pending nudge must not hold the process open at shutdown. diff --git a/server/src/nest/realtime/realtime.gateway.ts b/server/src/nest/realtime/realtime.gateway.ts index 21d66fee2..4c54ecb3f 100644 --- a/server/src/nest/realtime/realtime.gateway.ts +++ b/server/src/nest/realtime/realtime.gateway.ts @@ -13,6 +13,7 @@ import type { WebSocketServer } from 'ws'; import { DatabaseService } from '../database/database.service'; import { EphemeralTokenService } from '../auth/ephemeral-token.service'; import { User } from '../../types'; +import { logError } from '../audit/audit-log.logger'; import { bookPeers, broadcastToBook, @@ -93,53 +94,62 @@ export class RealtimeGateway * password-version gate runs before the MFA one. */ async handleConnection(socket: TrekWebSocket, request: IncomingMessage): Promise { - const url = new URL(request.url ?? '/', 'http://localhost'); - const token = url.searchParams.get('token'); - if (!token) { - socket.close(4001, 'Authentication required'); - return; - } + // TrekWsAdapter.bindClientConnect fires this from a plain 'connection' + // listener and cannot await it, so a throw here would otherwise become an + // unhandled rejection once the handshake goes async below (recipe R1.5). + // Closed the same way every other rejected handshake already is. + try { + const url = new URL(request.url ?? '/', 'http://localhost'); + const token = url.searchParams.get('token'); + if (!token) { + socket.close(4001, 'Authentication required'); + return; + } - const consumed = this.tokens.consumeWithMeta(token, 'ws'); - if (!consumed) { - socket.close(4001, 'Invalid or expired token'); - return; - } + const consumed = this.tokens.consumeWithMeta(token, 'ws'); + if (!consumed) { + socket.close(4001, 'Invalid or expired token'); + return; + } - const row = this.db.get( - 'SELECT id, username, email, role, mfa_enabled, password_version FROM users WHERE id = ?', - consumed.userId, - ); - if (!row) { - socket.close(4001, 'User not found'); - return; - } + const row = this.db.get( + 'SELECT id, username, email, role, mfa_enabled, password_version FROM users WHERE id = ?', + consumed.userId, + ); + if (!row) { + socket.close(4001, 'User not found'); + return; + } - // Session gate (defence-in-depth): reject a ws-token minted before a - // password change. Tokens carry the pv they were issued with; tokens minted - // without a pv (legacy) are treated as version 0, matching the JWT `pv` - // claim semantics in verifyJwtAndLoadUser. - const tokenPv = typeof consumed.pv === 'number' ? consumed.pv : 0; - const currentPv = typeof row.password_version === 'number' ? row.password_version : 0; - if (tokenPv !== currentPv) { - socket.close(4001, 'Invalid or expired token'); - return; - } + // Session gate (defence-in-depth): reject a ws-token minted before a + // password change. Tokens carry the pv they were issued with; tokens minted + // without a pv (legacy) are treated as version 0, matching the JWT `pv` + // claim semantics in verifyJwtAndLoadUser. + const tokenPv = typeof consumed.pv === 'number' ? consumed.pv : 0; + const currentPv = typeof row.password_version === 'number' ? row.password_version : 0; + if (tokenPv !== currentPv) { + socket.close(4001, 'Invalid or expired token'); + return; + } - // Don't leak password_version beyond the handshake. - const { password_version: _pv, ...user } = row; - const requireMfa = - this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'require_mfa'")?.value === 'true'; - const mfaOk = user.mfa_enabled === 1 || user.mfa_enabled === true; - if (requireMfa && !mfaOk) { - socket.close(4403, 'MFA required'); - return; - } + // Don't leak password_version beyond the handshake. + const { password_version: _pv, ...user } = row; + const requireMfa = + this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'require_mfa'")?.value === 'true'; + const mfaOk = user.mfa_enabled === 1 || user.mfa_enabled === true; + if (requireMfa && !mfaOk) { + socket.close(4403, 'MFA required'); + return; + } - socket.isAlive = true; - const sid = registerSocket(socket, user as User); - socket.send(JSON.stringify({ type: 'welcome', socketId: sid })); - socket.on('pong', () => { socket.isAlive = true; }); + socket.isAlive = true; + const sid = registerSocket(socket, user as User); + socket.send(JSON.stringify({ type: 'welcome', socketId: sid })); + socket.on('pong', () => { socket.isAlive = true; }); + } catch (err) { + logError(`ws handshake failed: ${err instanceof Error ? err.message : String(err)}`); + socket.close(4001, 'connection setup failed'); + } } handleDisconnect(socket: TrekWebSocket): void { diff --git a/server/tests/integration/plugins/plugin-runtime.test.ts b/server/tests/integration/plugins/plugin-runtime.test.ts index 345140d2c..a194b0e67 100644 --- a/server/tests/integration/plugins/plugin-runtime.test.ts +++ b/server/tests/integration/plugins/plugin-runtime.test.ts @@ -148,10 +148,17 @@ describe('PluginRuntimeService (M2 end-to-end)', () => { // first activate is covered by the 'counter' happy-path test above.) }); - it('onApplicationBootstrap is a no-op when the runtime is disabled', () => { + it('onApplicationBootstrap is a no-op when the runtime is disabled', async () => { + // onApplicationBootstrap is synchronous (void), so the observed step is the + // runtime's own construction; the disabled path is then exercised — and + // reset — around that single, awaited call, not before it settles. process.env.TREK_PLUGINS_ENABLED = 'false'; - expect(async () => (await createPluginRuntime(new DatabaseService(dbConn))).onApplicationBootstrap()).not.toThrow(); - process.env.TREK_PLUGINS_ENABLED = 'true'; + try { + const rt = await createPluginRuntime(new DatabaseService(dbConn)); + expect(() => rt.onApplicationBootstrap()).not.toThrow(); + } finally { + process.env.TREK_PLUGINS_ENABLED = 'true'; + } }); it('deactivate stops the plugin and clears the enabled intent', async () => {