From af861e5816967cf22c5a5c1227deee05b32f13bf Mon Sep 17 00:00:00 2001 From: Maurice Date: Tue, 17 Nov 2026 14:14:40 +0100 Subject: [PATCH] fix(db): read the checks a write relies on in the transaction that writes On Postgres a check read before a transaction, or outside one, no longer holds at the write that follows: the pool runs other requests' writes in between. Moved into the unit of work that writes: - the last-admin guard of an admin's role edit and of an account deletion (deleteUserCompletely takes a precondition run in its transaction) - the login lockout guards of the auth settings save and the SSO settings save - the first-account check of an SSO sign-up, which starts over as an ordinary sign-up when another account won - the OAuth client caps, the token cap and the mail intake limits - the year check before a vacay year is opened, and the label name check of a rename A password sign-up that loses the last use of an invite is now refused, as the SSO sign-up already was, and a reset link is burned by one conditional update, so two resets with one link cannot both change the password. --- server/scripts/size-baseline.json | 2 +- .../PasswordResetTokens.repository.ts | 8 ++-- server/src/nest/admin/admin.service.ts | 26 +++++----- server/src/nest/auth/auth.service.ts | 37 +++++++-------- server/src/nest/auth/user-cleanup.service.ts | 5 +- .../nest/collections/collections.service.ts | 17 ++++--- .../mail-ingest/mail-ingest-intake.service.ts | 47 +++++++++++-------- server/src/nest/oauth/oauth.service.ts | 47 +++++++++++-------- server/src/nest/oidc/oidc.service.ts | 30 ++++++++---- server/src/nest/tokens/token.service.ts | 27 ++++++----- server/src/nest/vacay/vacay.service.ts | 14 +++--- .../PasswordResetTokens.repository.test.ts | 10 ++++ server/tests/unit/nest/auth.service.test.ts | 1 + .../tests/unit/nest/public-api-scopes.test.ts | 10 +++- server/tests/unit/nest/token.service.test.ts | 3 +- server/tests/websocket/connection.test.ts | 3 +- 16 files changed, 171 insertions(+), 116 deletions(-) diff --git a/server/scripts/size-baseline.json b/server/scripts/size-baseline.json index c27a7087f..5198cc04f 100644 --- a/server/scripts/size-baseline.json +++ b/server/scripts/size-baseline.json @@ -6,7 +6,7 @@ "src/db/repositories/Trips.repository.ts": 1120, "src/db/repositories/Users.repository.ts": 1421, "src/nest/atlas/atlas.service.ts": 1174, - "src/nest/auth/auth.service.ts": 1143, + "src/nest/auth/auth.service.ts": 1141, "src/nest/budget/budget.service.ts": 1607, "src/nest/collections/collections.service.ts": 1414, "src/nest/doc-sync/doc-sync.service.ts": 1060, diff --git a/server/src/db/repositories/PasswordResetTokens.repository.ts b/server/src/db/repositories/PasswordResetTokens.repository.ts index 493625186..3448d03f8 100644 --- a/server/src/db/repositories/PasswordResetTokens.repository.ts +++ b/server/src/db/repositories/PasswordResetTokens.repository.ts @@ -110,10 +110,12 @@ export class PasswordResetTokensRepository extends TrekRepository { + async markConsumed(id: number): Promise { const platform = this.getEntityManager().getPlatform(); - await this.nativeUpdate({ id }, { consumed_at: currentTimestamp(platform) }); + return (await this.nativeUpdate({ id, consumed_at: null }, { consumed_at: currentTimestamp(platform) })) === 1; } } diff --git a/server/src/nest/admin/admin.service.ts b/server/src/nest/admin/admin.service.ts index 56246a28d..613b36d10 100644 --- a/server/src/nest/admin/admin.service.ts +++ b/server/src/nest/admin/admin.service.ts @@ -260,19 +260,6 @@ export class AdminService { } const passwordHash = password ? bcrypt.hashSync(password, BCRYPT_COST) : null; - // Don't let the admin UI demote the last remaining admin — that would leave the - // instance with no one able to manage it (and on OIDC-only setups, no recovery). #1274 - // SECURITY: plain JS comparisons, deliberately never folded into a - // repository method's WHERE clause (R4) — two repository reads, one - // service-level `if`. - if (role && role !== 'admin') { - const currentRole = await this.users.getRole(userId); - if (currentRole === 'admin') { - const adminCount = await this.users.countAdmins(); - if (adminCount <= 1) throw new DomainError(400, 'Cannot remove the last admin'); - } - } - // An admin sets a password for exactly one reason: the account is believed // compromised. Without bumping password_version, verifyJwtAndLoadUser keeps // accepting every cookie the intruder already holds, so the one action taken @@ -299,6 +286,19 @@ export class AdminService { // call, never split across separate un-transacted repository calls. try { await this.uow.transactional(async () => { + // Don't let the admin UI demote the last remaining admin — that would leave the + // instance with no one able to manage it (and on OIDC-only setups, no recovery). #1274 + // SECURITY: plain JS comparisons, deliberately never folded into a + // repository method's WHERE clause (R4) — two repository reads, one + // service-level `if`. Read in the transaction that demotes, so two admins + // demoting each other at once cannot both see the other one still counted. + if (role && role !== 'admin') { + const currentRole = await this.users.getRole(userId); + if (currentRole === 'admin') { + const adminCount = await this.users.countAdmins(); + if (adminCount <= 1) throw new DomainError(400, 'Cannot remove the last admin'); + } + } await this.users.applyAdminEdit(userId, patch); if (password) { diff --git a/server/src/nest/auth/auth.service.ts b/server/src/nest/auth/auth.service.ts index b639bb7b3..90f004458 100644 --- a/server/src/nest/auth/auth.service.ts +++ b/server/src/nest/auth/auth.service.ts @@ -490,10 +490,8 @@ export class AuthService { const token = await this.generateToken(user, undefined, client); if (validInvite) { - const updated = await this.inviteTokens.incrementUsedCount(validInvite.token); - if (!updated) { - console.warn(`[Auth] Invite token ${validInvite.token.slice(0, 8)}... exceeded max_uses due to race condition`); - } + // The increment is the capacity check: another signup took the last use since the read above. + if (!(await this.inviteTokens.incrementUsedCount(validInvite.token))) throw new DomainError(410, 'Invite link has been fully used'); // Trip-bound invite (#1402): auto-add the freshly registered user to the // trip. Idempotent + owner-safe; no-ops if the bound trip was since deleted. if (validInvite.trip_id) { @@ -678,13 +676,13 @@ export class AuthService { if (readEnv().demo.enabled && isDemoEmail(userEmail)) { throw new DomainError(403, 'Account deletion is disabled in demo mode.'); } - if (userRole === 'admin') { + await this.userCleanup.deleteUserCompletely(userId, async () => { + if (userRole !== 'admin') return; const adminCount = await this.usersRepo.countAdmins(); if (adminCount <= 1) { throw new DomainError(400, 'Cannot delete the last admin account'); } - } - await this.userCleanup.deleteUserCompletely(userId); + }); await emitUserDeleted(userId); // let plugins erase their own per-user data return { success: true }; } @@ -740,17 +738,6 @@ export class AuthService { } } - // Lockout prevention: can't disable all login methods - if (body.password_login !== undefined || body.oidc_login !== undefined) { - const current = await this.resolveAuthToggles(); - const oidcConfigured = await isOidcConfigured(this.appSettings); - const nextPasswordLogin = body.password_login !== undefined ? (String(body.password_login) === 'true') : current.password_login; - const nextOidcLogin = body.oidc_login !== undefined ? (String(body.oidc_login) === 'true') : current.oidc_login; - if (!nextPasswordLogin && (!nextOidcLogin || !oidcConfigured)) { - throw new DomainError(400, 'Cannot disable all login methods. At least one must remain enabled.'); - } - } - // SMTP, the OIDC toggles and the WebAuthn pair share this handler with keys // the admin does own, so a managed install skips those names and keeps the // rest of the save working. Reported, never thrown: the settings tab sends @@ -758,6 +745,16 @@ export class AuthService { const blocked = [...splitManagedKeys(body, readEnv().managed.enabled).blocked, ...envLockedKeys(body)]; await this.uow.transactional(async () => { // the whole form lands, or none of it + // Lockout prevention: can't disable all login methods (read in the writing transaction). + if (body.password_login !== undefined || body.oidc_login !== undefined) { + const current = await this.resolveAuthToggles(); + const oidcConfigured = await isOidcConfigured(this.appSettings); + const nextPasswordLogin = body.password_login !== undefined ? (String(body.password_login) === 'true') : current.password_login; + const nextOidcLogin = body.oidc_login !== undefined ? (String(body.oidc_login) === 'true') : current.oidc_login; + if (!nextPasswordLogin && (!nextOidcLogin || !oidcConfigured)) { + throw new DomainError(400, 'Cannot disable all login methods. At least one must remain enabled.'); + } + } for (const key of ADMIN_FORM_SETTING_KEYS) { if (blocked.includes(key)) continue; if (body[key] !== undefined) { @@ -1064,8 +1061,8 @@ export class AuthService { const newPv = (user.password_version ?? 0) + 1; await this.uow.transactional(async () => { - // Burn the token first to keep it atomic with the password change. - await this.passwordResetTokens.markConsumed(row.id); + // Burn the token first, atomic with the password change; a second use racing this one loses here. + if (!(await this.passwordResetTokens.markConsumed(row.id))) throw new DomainError(400, 'This reset link has already been used'); // Also burn every OTHER live token for this user — a fresh login // should not leave a second door open. await this.passwordResetTokens.consumeAllLiveForUser(user.id, row.id); diff --git a/server/src/nest/auth/user-cleanup.service.ts b/server/src/nest/auth/user-cleanup.service.ts index 4159c55b1..0b3a6a30a 100644 --- a/server/src/nest/auth/user-cleanup.service.ts +++ b/server/src/nest/auth/user-cleanup.service.ts @@ -189,9 +189,12 @@ export class UserCleanupService { * `task-1-review.md`'s "contract gaps"). Everything above it (UC1–UC10) * stays raw, per each method's own docstring. */ - async deleteUserCompletely(userId: number): Promise { + async deleteUserCompletely(userId: number, precondition?: () => Promise): Promise { const avatar = await this.usersRepo.getAvatar(userId); const photos = await this.uow.transactional(async () => { + // A caller's check that has to hold when the row goes (the last admin), read in + // the transaction that deletes, so no other write lands between the two. + if (precondition) await precondition(); // The galleries of the journeys the user owns go with the cascade below, so // their photos are read first. A photo row none of the remaining trips and // journeys links goes too, as when one journey is deleted: left behind, it diff --git a/server/src/nest/collections/collections.service.ts b/server/src/nest/collections/collections.service.ts index 521460efe..73303f78a 100644 --- a/server/src/nest/collections/collections.service.ts +++ b/server/src/nest/collections/collections.service.ts @@ -1225,17 +1225,16 @@ export class CollectionsService { const collectionId = await this.collectionIdOfLabel(labelId); await this.assertCanEdit(userId, collectionId); const write: Parameters[1] = {}; - if (body.name !== undefined) { - const trimmed = body.name.trim(); - if (!trimmed) httpError(400, 'Label name is required'); - if (await this.labels.nameExistsExcluding(collectionId, trimmed, labelId)) { - httpError(409, 'A label with this name already exists'); - } - write.name = trimmed; - } + const trimmed = body.name?.trim(); + if (body.name !== undefined && !trimmed) httpError(400, 'Label name is required'); + if (trimmed) write.name = trimmed; if (body.color !== undefined) write.color = body.color; if (body.sort_order !== undefined) write.sort_order = body.sort_order; - await this.labels.updateFields(labelId, write); + // Checked in the renaming transaction, as createLabel does: no index keeps names unique. + await this.uow.transactional(async () => { + if (trimmed && (await this.labels.nameExistsExcluding(collectionId, trimmed, labelId))) httpError(409, 'A label with this name already exists'); + await this.labels.updateFields(labelId, write); + }); await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated'); return this.getLabelById(labelId); } diff --git a/server/src/nest/mail-ingest/mail-ingest-intake.service.ts b/server/src/nest/mail-ingest/mail-ingest-intake.service.ts index 9c545e853..635a7e982 100644 --- a/server/src/nest/mail-ingest/mail-ingest-intake.service.ts +++ b/server/src/nest/mail-ingest/mail-ingest-intake.service.ts @@ -4,6 +4,7 @@ import type { MailIngestAddressRow } from '../../db/repositories/MailIngestAddre import type { MailIngestCandidatesRepository } from '../../db/repositories/MailIngestCandidates.repository'; import type { MailIngestMessagesRepository } from '../../db/repositories/MailIngestMessages.repository'; import { dbNow } from '../../db/types'; +import { UnitOfWork } from '../database/unit-of-work'; import { MailReadService } from '../llm-parse/mail-read.service'; import type { WalkedMail } from '../llm-parse/mail-read.types'; import { MailIngestAddressService } from './mail-ingest-address.service'; @@ -54,6 +55,7 @@ export class MailIngestIntakeService { private readonly settings: MailIngestSettingsService, private readonly addresses: MailIngestAddressService, private readonly reader: MailReadService, + private readonly uow: UnitOfWork, ) {} /** @@ -135,30 +137,37 @@ export class MailIngestIntakeService { if (known !== null) return { status: 'duplicate', messageId: known }; const now = new Date(); - const today = await this.messages.countForAddressSince(address.id, dbNow(new Date(now.getTime() - DAY_MS))); - if (today >= MAIL_INGEST_LIMITS.mailsPerAddressPerDay) return { status: 'refused', reason: 'address_daily_limit' }; - if ((await this.candidates.countPending(address.user_id)) >= MAIL_INGEST_LIMITS.pendingPerUser) { - return { status: 'refused', reason: 'inbox_full' }; - } - - const id = await this.messages.insertIfNew({ - transport, - messageIdHdr: messageIdHdr?.slice(0, 500) ?? null, - dedupeHash, - addressId: address.id, - userId: address.user_id, - tripId: address.trip_id, - size: raw.length, - rawEnc: sealMail(raw), - receivedAt: dbNow(now), + const rawEnc = sealMail(raw); + // The limits are counted in the transaction that stores, so mails arriving at + // once cannot all pass them on the same count. + const stored = await this.uow.transactional(async (): Promise => { + const today = await this.messages.countForAddressSince(address.id, dbNow(new Date(now.getTime() - DAY_MS))); + if (today >= MAIL_INGEST_LIMITS.mailsPerAddressPerDay) + return { status: 'refused', reason: 'address_daily_limit' }; + if ((await this.candidates.countPending(address.user_id)) >= MAIL_INGEST_LIMITS.pendingPerUser) { + return { status: 'refused', reason: 'inbox_full' }; + } + const id = await this.messages.insertIfNew({ + transport, + messageIdHdr: messageIdHdr?.slice(0, 500) ?? null, + dedupeHash, + addressId: address.id, + userId: address.user_id, + tripId: address.trip_id, + size: raw.length, + rawEnc, + receivedAt: dbNow(now), + }); + if (id !== null) await this.addresses.touch(address.id); + return { id }; }); + if ('status' in stored) return stored; // Another delivery of the same mail won the insert in between: it is in, once. - if (id === null) { + if (stored.id === null) { const winner = await this.messages.findIdByDedupeHash(dedupeHash); return winner === null ? { status: 'refused', reason: 'not_a_mail' } : { status: 'duplicate', messageId: winner }; } - await this.addresses.touch(address.id); - return { status: 'accepted', messageId: id }; + return { status: 'accepted', messageId: stored.id }; } } diff --git a/server/src/nest/oauth/oauth.service.ts b/server/src/nest/oauth/oauth.service.ts index 9395e7ac1..0d4c30fdf 100644 --- a/server/src/nest/oauth/oauth.service.ts +++ b/server/src/nest/oauth/oauth.service.ts @@ -193,15 +193,6 @@ export class OauthService { const { valid, invalid } = validateScopes(allowedScopes); if (!valid) return { error: `Invalid scopes: ${invalid.join(', ')}`, status: 400 }; - if (userId !== null) { - const count = await this.clients.countByUser(userId); - if (count >= 10) return { error: 'Maximum of 10 OAuth clients per user', status: 400 }; - } else { - // Anonymous DCR clients: enforce a global cap to prevent unbounded registration abuse - const count = await this.clients.countAnonymous(); - if (count >= 500) return { error: 'server_error', status: 503 }; - } - // Machine clients (client_credentials) must always be confidential — ignore isPublic for them. const isPublic = isMachineClient ? false : (options?.isPublic ?? false); const createdVia = options?.createdVia ?? 'settings_ui'; @@ -211,18 +202,34 @@ export class OauthService { const rawSecret = isPublic ? null : 'trekcs_' + randomBytes(24).toString('hex'); const secretHash = rawSecret ? hashToken(rawSecret) : randomBytes(32).toString('hex'); - const row = await this.clients.insertClient({ - id, - user_id: userId, - name: name.trim(), - client_id: clientId, - client_secret_hash: secretHash, - redirect_uris: encodeJson(OAUTH_CLIENT_REDIRECT_URIS, redirectUris), - allowed_scopes: encodeJson(OAUTH_CLIENT_ALLOWED_SCOPES, allowedScopes), - is_public: isPublic ? 1 : 0, - created_via: createdVia, - allows_client_credentials: isMachineClient ? 1 : 0, + // The cap is counted in the transaction that inserts, so two registrations at once + // cannot both pass it on the same count. + const inserted = await this.uow.transactional(async () => { + if (userId !== null) { + const count = await this.clients.countByUser(userId); + if (count >= 10) return { refused: { error: 'Maximum of 10 OAuth clients per user', status: 400 } }; + } else { + // Anonymous DCR clients: enforce a global cap to prevent unbounded registration abuse + const count = await this.clients.countAnonymous(); + if (count >= 500) return { refused: { error: 'server_error', status: 503 } }; + } + return { + row: await this.clients.insertClient({ + id, + user_id: userId, + name: name.trim(), + client_id: clientId, + client_secret_hash: secretHash, + redirect_uris: encodeJson(OAUTH_CLIENT_REDIRECT_URIS, redirectUris), + allowed_scopes: encodeJson(OAUTH_CLIENT_ALLOWED_SCOPES, allowedScopes), + is_public: isPublic ? 1 : 0, + created_via: createdVia, + allows_client_credentials: isMachineClient ? 1 : 0, + }), + }; }); + if ('refused' in inserted) return inserted.refused; + const row = inserted.row; await this.audit.writeAudit({ userId, diff --git a/server/src/nest/oidc/oidc.service.ts b/server/src/nest/oidc/oidc.service.ts index ffeaaaac0..cf24e791a 100644 --- a/server/src/nest/oidc/oidc.service.ts +++ b/server/src/nest/oidc/oidc.service.ts @@ -814,8 +814,14 @@ export class OidcService implements OnModuleDestroy { // the user INSERT. Without this, two parallel OIDC callbacks could // both pass the earlier SELECT-based check and each create a user. const inviteRaceError = new Error('invite_exhausted'); + // The first account becomes the admin. The count above decided that outside any + // transaction, so it is read again in the one that inserts: two first sign-ins at + // once would otherwise both become admin. The one that lost starts over and is + // then an ordinary registration. + const firstUserRaceError = new Error('first_user_taken'); try { const insertedId = await this.uow.transactional(async () => { + if (isFirstUser && (await this.usersRepo.countNonGuest()) > 0) throw firstUserRaceError; if (validInvite) { const updated = await this.inviteTokens.incrementUsedCount(validInvite.token); if (!updated) throw inviteRaceError; @@ -852,6 +858,7 @@ export class OidcService implements OnModuleDestroy { // off this, so it has to be set here and nowhere else. return { user: toClientUser(created), created: true }; } catch (err) { + if (err === firstUserRaceError) return this.findOrCreateUser(userInfo, config, inviteToken); if (err === inviteRaceError) { console.warn( `[OIDC] Invite token ${inviteToken?.slice(0, 8)}... exhausted — concurrent callback won the last slot`, @@ -896,25 +903,30 @@ export class OidcService implements OnModuleDestroy { display_name?: string; discovery_url?: string; }): Promise<{ error?: string; status?: number; success?: boolean }> { - // Lockout prevention: can't remove OIDC config when password login is disabled - if ((data.issuer === '' || data.client_id === '') && !(await this.auth.resolveAuthToggles()).password_login) { - return { - error: 'Cannot remove SSO configuration while password login is disabled. Enable password login first.', - status: 400, - }; - } - const set = (key: string, val: string) => this.appSettings.setValue(key, val || ''); // All five writes are one SSO config — a partial apply would leave the // instance with an issuer but no client id (or vice versa). - await this.uow.transactional(async () => { + const saved = await this.uow.transactional(async () => { + // Lockout prevention: can't remove OIDC config when password login is disabled. + // Read in the transaction that writes, so a concurrent save that switches + // password login off cannot slip between the check and the removal. + if ((data.issuer === '' || data.client_id === '') && !(await this.auth.resolveAuthToggles()).password_login) { + return false; + } await set('oidc_issuer', data.issuer ?? ''); await set('oidc_client_id', data.client_id ?? ''); if (data.client_secret !== undefined) await set('oidc_client_secret', maybe_encrypt_api_key(data.client_secret) ?? ''); await set('oidc_display_name', data.display_name ?? ''); await set('oidc_discovery_url', data.discovery_url ?? ''); + return true; }); + if (!saved) { + return { + error: 'Cannot remove SSO configuration while password login is disabled. Enable password login first.', + status: 400, + }; + } return { success: true }; } } diff --git a/server/src/nest/tokens/token.service.ts b/server/src/nest/tokens/token.service.ts index 6639afddd..6a485f2a0 100644 --- a/server/src/nest/tokens/token.service.ts +++ b/server/src/nest/tokens/token.service.ts @@ -12,6 +12,7 @@ import { decodeJson } from '../../utils/json-column'; import { EphemeralTokenService } from '../auth-core/ephemeral-token.service'; import { DomainError } from '../common/domain-error'; import { toRowId } from '../common/row-id'; +import { UnitOfWork } from '../database/unit-of-work'; import { InjectRepository } from '@mikro-orm/nestjs'; import { Injectable } from '@nestjs/common'; import { PUBLIC_API_SCOPES, type PublicApiGrant, type PublicApiScope } from '@trek/shared'; @@ -49,6 +50,7 @@ export class TokenService { @InjectRepository(McpTokens) private readonly tokens: McpTokensRepository, @InjectRepository(Users) private readonly users: UsersRepository, private readonly ephemeral: EphemeralTokenService, + private readonly uow: UnitOfWork, ) {} async listMcpTokens(userId: number) { @@ -116,9 +118,6 @@ export class TokenService { if (!name?.trim()) throw new DomainError(400, 'Token name is required'); if (name.trim().length > 100) throw new DomainError(400, 'Token name must be 100 characters or less'); - const tokenCount = await this.tokens.countByUserAndKind(userId, kind); - if (tokenCount >= 10) throw new DomainError(400, 'Maximum of 10 tokens per user reached'); - const rawToken = 'trek_' + randomBytes(24).toString('hex'); const tokenHash = createHash('sha256').update(rawToken).digest('hex'); const tokenPrefix = rawToken.slice(0, 13); @@ -127,14 +126,20 @@ export class TokenService { // the column default — rather than being handed a list it would ignore. const narrowed = kind === 'api' ? sanitizeScopes(scopes) : null; - const inserted = await this.tokens.insertToken({ - user_id: userId, - name: name.trim(), - token_hash: tokenHash, - token_prefix: tokenPrefix, - kind, - scope_mode: narrowed ? 'limited' : 'all', - api_scopes: narrowed ? JSON.stringify(narrowed) : null, + // The cap is counted in the transaction that inserts, so two requests at once + // cannot both pass it on the same count. + const inserted = await this.uow.transactional(async () => { + const tokenCount = await this.tokens.countByUserAndKind(userId, kind); + if (tokenCount >= 10) throw new DomainError(400, 'Maximum of 10 tokens per user reached'); + return await this.tokens.insertToken({ + user_id: userId, + name: name.trim(), + token_hash: tokenHash, + token_prefix: tokenPrefix, + kind, + scope_mode: narrowed ? 'limited' : 'all', + api_scopes: narrowed ? JSON.stringify(narrowed) : null, + }); }); // A separate re-select, matching the legacy INSERT-then-SELECT shape diff --git a/server/src/nest/vacay/vacay.service.ts b/server/src/nest/vacay/vacay.service.ts index 5d5396e12..ae0d06dc9 100644 --- a/server/src/nest/vacay/vacay.service.ts +++ b/server/src/nest/vacay/vacay.service.ts @@ -997,14 +997,15 @@ export class VacayService { async addYear(planId: number, year: number, socketId: string | undefined): Promise { // A duplicate year is a no-op (the legacy blanket try/catch was written for exactly this // constraint hit); real errors propagate. The insert + per-user seeding runs atomically. - if (!(await this.years.exists(planId, year))) await this.openYear(planId, year); + await this.openYear(planId, year); await this.notifyPlanUsers(planId, socketId, 'vacay:settings'); return await this.listYears(planId); } - /** The year's row and every member's allowance for it, with no broadcast: the caller sends it after its commit. */ - private async openYear(planId: number, year: number): Promise { - await this.uow.transactional(async () => { + /** The year's row and every member's allowance, unbroadcast (sent after the commit); false when it exists. */ + private async openYear(planId: number, year: number): Promise { + return await this.uow.transactional(async () => { + if (await this.years.exists(planId, year)) return false; await this.years.insertYear(planId, year); const plan = await this.plans.findById(planId); const carryOverEnabled = plan ? !!plan.carry_over_enabled : true; @@ -1024,6 +1025,7 @@ export class VacayService { } await this.userYears.insertIgnore(u.id, planId, year, 30, carriedOver); } + return true; }); } @@ -1138,9 +1140,7 @@ export class VacayService { private async ensureYearOf(planId: number, userId: number, date: string): Promise { const [y, m, d] = date.split('-').map(Number); const year = await this.currentPeriodYear(userId, new Date(y, m - 1, d)); - if (await this.years.exists(planId, year)) return false; - await this.openYear(planId, year); - return true; + return await this.openYear(planId, year); } /** diff --git a/server/tests/unit/db/repositories/PasswordResetTokens.repository.test.ts b/server/tests/unit/db/repositories/PasswordResetTokens.repository.test.ts index 6e65e9154..c9b4e6f7b 100644 --- a/server/tests/unit/db/repositories/PasswordResetTokens.repository.test.ts +++ b/server/tests/unit/db/repositories/PasswordResetTokens.repository.test.ts @@ -125,6 +125,16 @@ describe('PasswordResetTokensRepository', () => { expect((await rawRow(target)).consumed_at).not.toBeNull(); expect((await rawRow(other)).consumed_at).toBeNull(); }); + + it('PWDRESETREPO-014: burns a token once: a second call finds it used and leaves the first stamp', async () => { + const { user } = createUser(testDb); + const target = await seedToken(user.id, hash('once')); + + expect(await tokens.markConsumed(target)).toBe(true); + const stamped = (await rawRow(target)).consumed_at; + expect(await tokens.markConsumed(target)).toBe(false); + expect((await rawRow(target)).consumed_at).toBe(stamped); + }); }); describe('consumeAllLiveForUser', () => { diff --git a/server/tests/unit/nest/auth.service.test.ts b/server/tests/unit/nest/auth.service.test.ts index 6ef7fd417..410792bf4 100644 --- a/server/tests/unit/nest/auth.service.test.ts +++ b/server/tests/unit/nest/auth.service.test.ts @@ -134,6 +134,7 @@ beforeAll(async () => { await createTestMcpTokensRepo(testDb), await createTestUsersRepo(testDb), new EphemeralTokenService(), + await createTestUnitOfWork(testDb), ); svc = new AuthService( new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), diff --git a/server/tests/unit/nest/public-api-scopes.test.ts b/server/tests/unit/nest/public-api-scopes.test.ts index f4b11104a..f233fe401 100644 --- a/server/tests/unit/nest/public-api-scopes.test.ts +++ b/server/tests/unit/nest/public-api-scopes.test.ts @@ -14,6 +14,7 @@ import { AuthController } from '../../../src/nest/auth/auth.controller'; import type { AuthService } from '../../../src/nest/auth/auth.service'; import type { UserProfileService } from '../../../src/nest/auth/user-profile.service'; import { RateLimitService } from '../../../src/nest/common/rate-limit.service'; +import type { UnitOfWork } from '../../../src/nest/database/unit-of-work'; import { ApiTokenGuard } from '../../../src/nest/public-api/api-token.guard'; import { grantedScopes, narrowToGrant, requireScope } from '../../../src/nest/public-api/public-api-request'; import { PublicApiController } from '../../../src/nest/public-api/public-api.controller'; @@ -24,7 +25,12 @@ import type { User } from '../../../src/types'; import { createUser } from '../../helpers/factories'; import { findRow, updateRows } from '../../helpers/factories/rows'; import { resetTestDb } from '../../helpers/test-db'; -import { createTestMcpTokensRepo, createTestUsersRepo, sharedTestOrm } from '../../helpers/test-uow'; +import { + createTestMcpTokensRepo, + createTestUnitOfWork, + createTestUsersRepo, + sharedTestOrm, +} from '../../helpers/test-uow'; import { HttpException } from '@nestjs/common'; import type { ExecutionContext } from '@nestjs/common'; import { @@ -398,6 +404,7 @@ describe('TokenService — storing and resolving a grant', () => { await createTestMcpTokensRepo(testDb), await createTestUsersRepo(testDb), new EphemeralTokenService(), + await createTestUnitOfWork(testDb), ); }); @@ -472,6 +479,7 @@ describe('TokenService — storing and resolving a grant', () => { } as unknown as McpTokensRepository, {} as UsersRepository, new EphemeralTokenService(), + {} as UnitOfWork, ); expect((await noColumns.verifyApiTokenWithGrant('trek_legacy'))?.grant).toEqual({ mode: 'all', diff --git a/server/tests/unit/nest/token.service.test.ts b/server/tests/unit/nest/token.service.test.ts index 4366614a7..837f9d625 100644 --- a/server/tests/unit/nest/token.service.test.ts +++ b/server/tests/unit/nest/token.service.test.ts @@ -14,7 +14,7 @@ import { createUser } from '../../helpers/factories'; import { countRows, findRow, insertRow, updateRows } from '../../helpers/factories/rows'; import { expectRegisteredProvider } from '../../helpers/module-providers'; import { resetTestDb } from '../../helpers/test-db'; -import { createTestMcpTokensRepo, createTestUsersRepo } from '../../helpers/test-uow'; +import { createTestMcpTokensRepo, createTestUnitOfWork, createTestUsersRepo } from '../../helpers/test-uow'; import { sharedTestOrm } from '../../helpers/test-uow'; import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest'; @@ -64,6 +64,7 @@ beforeAll(async () => { await createTestMcpTokensRepo(testDb), await createTestUsersRepo(testDb), new EphemeralTokenService(), + await createTestUnitOfWork(testDb), ); }); diff --git a/server/tests/websocket/connection.test.ts b/server/tests/websocket/connection.test.ts index fcf2f7ef9..bc5a712bb 100644 --- a/server/tests/websocket/connection.test.ts +++ b/server/tests/websocket/connection.test.ts @@ -18,7 +18,7 @@ import { deleteRows, updateRows } from '../helpers/factories/rows'; import { setAppSetting } from '../helpers/factories/settings'; import { readUser } from '../helpers/factories/users'; import { resetTestDb, resetRateLimits } from '../helpers/test-db'; -import { createTestMcpTokensRepo, createTestUsersRepo } from '../helpers/test-uow'; +import { createTestMcpTokensRepo, createTestUnitOfWork, createTestUsersRepo } from '../helpers/test-uow'; import { MikroORM } from '@mikro-orm/core'; import type { INestApplication } from '@nestjs/common'; @@ -55,6 +55,7 @@ beforeAll(async () => { await createTestMcpTokensRepo(testDb), await createTestUsersRepo(testDb), new EphemeralTokenService(), + await createTestUnitOfWork(testDb), ); // Real WebSocket against the unified NestJS app (Express is gone). buildApp owns // the same composition production uses; we attach the real ws server to it.