Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

refactor(control-api): r10-m1 encapsulate password work lifecycle

Josuéc5c62ed90a35
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index c1b7b2031..eb52a7397 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.764",
+ "version": "0.1.765",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.764",
+ "version": "0.1.765",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index 0ce474a7d..5d8b9c550 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.764",
+ "version": "0.1.765",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/services/auth/passwordAdmissionError.ts b/control-api/src/services/auth/passwordAdmissionError.ts
new file mode 100644
index 000000000..811a7c484
--- /dev/null
+++ b/control-api/src/services/auth/passwordAdmissionError.ts
@@ -0,0 +1,19 @@
+import {
+ type PasswordAdmissionDenialReason,
+ passwordAdmissionDenialsTotal,
+} from '../../observability/metrics.js'
+
+export class PasswordAdmissionError extends Error {
+ constructor(
+ readonly status: 429 | 503,
+ readonly retryAfterSeconds: number,
+ readonly reason: PasswordAdmissionDenialReason,
+ readonly publicError:
+ | 'rate_limited'
+ | 'authority_unavailable'
+ | 'recovery_outcome_unknown' = status === 429 ? 'rate_limited' : 'authority_unavailable'
+ ) {
+ super(status === 429 ? 'rate_limited' : 'authority_unavailable')
+ passwordAdmissionDenialsTotal.inc({ reason })
+ }
+}
diff --git a/control-api/src/services/auth/passwordCredentialVerification.ts b/control-api/src/services/auth/passwordCredentialVerification.ts
index e3dde5ff7..9cc9b6f8d 100644
--- a/control-api/src/services/auth/passwordCredentialVerification.ts
+++ b/control-api/src/services/auth/passwordCredentialVerification.ts
@@ -1,10 +1,8 @@
import bcrypt from 'bcryptjs'
import { type DbTransactionClient, pool, withTransaction } from '../../db.js'
import { rootLogger } from '../../observability/logger.js'
-import {
- type PasswordAdmissionDenialReason,
- passwordAdmissionDenialsTotal,
-} from '../../observability/metrics.js'
+import { type PasswordAdmissionDenialReason } from '../../observability/metrics.js'
+import { PasswordAdmissionError } from './passwordAdmissionError.js'
import {
type PasswordIdentifierState,
admitPasswordIdentifier,
@@ -18,20 +16,8 @@ import { acquirePasswordWork } from './passwordWorkOwnership.js'
export const PASSWORD_DUMMY_HASH = '$2b$12$DdpJSFUb/dYx43plh72Ia.k9RJ8krESZ/DtTRUbdQq/ngzfJuyCUu'
const logger = rootLogger.child({ module: 'password-admission' })
-export class PasswordAdmissionError extends Error {
- constructor(
- readonly status: 429 | 503,
- readonly retryAfterSeconds: number,
- readonly reason: PasswordAdmissionDenialReason,
- readonly publicError:
- | 'rate_limited'
- | 'authority_unavailable'
- | 'recovery_outcome_unknown' = status === 429 ? 'rate_limited' : 'authority_unavailable'
- ) {
- super(status === 429 ? 'rate_limited' : 'authority_unavailable')
- passwordAdmissionDenialsTotal.inc({ reason })
- }
-}
+export { PasswordAdmissionError } from './passwordAdmissionError.js'
+
function denied(retryMs: number, reason: PasswordAdmissionDenialReason): never {
throw new PasswordAdmissionError(
429,
diff --git a/control-api/src/services/auth/passwordWorkOwnership.ts b/control-api/src/services/auth/passwordWorkOwnership.ts
index 8e726129b..ac8679b7e 100644
--- a/control-api/src/services/auth/passwordWorkOwnership.ts
+++ b/control-api/src/services/auth/passwordWorkOwnership.ts
@@ -1,20 +1,44 @@
import { randomUUID } from 'node:crypto'
import { hostname } from 'node:os'
import { type DbTransactionClient, withTransaction } from '../../db.js'
+import { rootLogger } from '../../observability/logger.js'
+import { PasswordAdmissionError } from './passwordAdmissionError.js'
+import { PASSWORD_ADMISSION_POLICY } from './passwordAdmissionState.js'
-// Process-incarnation identity is distinct from reusable host/PID diagnostics.
+export type PasswordCommitMode = 'standard' | 'one_use_recovery'
+export interface PasswordMutationLease {
+ commitWith<T>(
+ work: (db: DbTransactionClient) => Promise<T>,
+ options: { mode: PasswordCommitMode }
+ ): Promise<T>
+}
+export interface PasswordWorkLease {
+ release(): Promise<void>
+}
+// Existing protocol tests supply the raw acquired view. Both views resolve to
+// the same private reservation; compatibility never reacquires another owner.
+export type MemberPasswordWorkLease = PasswordMutationLease | PasswordWorkLease
+
+const logger = rootLogger.child({ module: 'password-admission' })
let ownerInstance: string | undefined
+const reservations = new WeakMap<object, PasswordMutationLease>()
+
+function authorityFailure() {
+ return new PasswordAdmissionError(503, 2, 'authority_failure')
+}
+function warn(event: string, message: string) {
+ logger.warn({ event }, message)
+}
+function sanitize(error: unknown): never {
+ if (error instanceof PasswordAdmissionError) throw error
+ warn('password_authority_unavailable', 'password authority unavailable')
+ throw authorityFailure()
+}
-/** Null means immediately busy. A persistence error propagates for sanitized fail-closed handling. */
-export async function acquirePasswordWork(): Promise<{
- release: () => Promise<void>
- releaseWithin: (db: Pick<DbTransactionClient, 'query'>) => Promise<void>
- confirmReleaseWithinCommitted: () => void
-} | null> {
+async function reservePasswordWork() {
const owner = (ownerInstance ??= randomUUID())
const operation = randomUUID()
const admitted = await withTransaction(async db => {
- // This must survive a database/process crash; never use the disposable limiter pool.
await db.query('SET LOCAL synchronous_commit = on')
const result = await db.query(
`INSERT INTO password_verification_work
@@ -26,6 +50,7 @@ export async function acquirePasswordWork(): Promise<{
return result.rows.length === 1
})
if (!admitted) return null
+
const releaseOwned = async (db: Pick<DbTransactionClient, 'query'>) => {
await db.query('SET LOCAL synchronous_commit = on')
const result = await db.query(
@@ -35,22 +60,163 @@ export async function acquirePasswordWork(): Promise<{
)
if (result.rows.length !== 1) throw new Error('password work ownership lost')
}
+ let state: 'reserved' | 'running' | 'terminal' = 'reserved'
let released: Promise<void> | undefined
- let releaseWithinCommitted = false
- return {
- // Password credential updates can release the durable owner in the same
- // transaction as their commit. If that transaction rolls back, callers
- // must fall back to release() so the persisted owner does not linger.
- releaseWithin: releaseOwned,
- confirmReleaseWithinCommitted: () => {
- releaseWithinCommitted = true
+ let releaseConfirmed = false
+ let terminalOperation: Promise<unknown> | undefined
+ const release = () => {
+ if (releaseConfirmed) return Promise.resolve()
+ released ??= withTransaction(async db => {
+ await releaseOwned(db)
+ })
+ return released
+ }
+
+ const mutation: PasswordMutationLease = {
+ commitWith<T>(
+ work: (db: DbTransactionClient) => Promise<T>,
+ options: { mode: PasswordCommitMode }
+ ) {
+ // Must happen before the first await, including before borrowing a client.
+ if (state !== 'reserved') return Promise.reject(authorityFailure())
+ state = 'running'
+ const result = (async () => {
+ let acknowledged = false
+ let unknown = false
+ let outcome!: T
+ try {
+ return await withTransaction(
+ async db => {
+ outcome = await work(db)
+ await releaseOwned(db)
+ return outcome
+ },
+ undefined,
+ {
+ onCommitAcknowledged: () => {
+ acknowledged = true
+ releaseConfirmed = true
+ },
+ onCommitOutcomeUnknown: () => {
+ unknown = true
+ },
+ }
+ )
+ } catch (error) {
+ if (unknown && options.mode === 'one_use_recovery') {
+ warn(
+ 'password_recovery_commit_outcome_unknown',
+ 'password recovery commit outcome is unknown'
+ )
+ throw new PasswordAdmissionError(
+ 503,
+ 2,
+ 'authority_failure',
+ 'recovery_outcome_unknown'
+ )
+ }
+ if (acknowledged) {
+ warn(
+ 'password_post_commit_cleanup_failed',
+ 'password transaction committed; connection cleanup failed'
+ )
+ return outcome
+ }
+ throw error
+ } finally {
+ try {
+ if (!acknowledged) {
+ try {
+ await release()
+ } catch (error) {
+ if (!unknown) throw error
+ warn(
+ 'password_owner_release_after_unknown_commit_failed',
+ 'password owner release after unknown commit failed'
+ )
+ }
+ }
+ } finally {
+ // Cleanup has been attempted, even if its disposition is unconfirmed.
+ // The outer reservation wrapper must never repeat this protocol.
+ state = 'terminal'
+ }
+ }
+ })().catch(sanitize)
+ terminalOperation = result
+ return result
},
+ }
+ const raw: PasswordWorkLease = {
release: () => {
- if (releaseWithinCommitted) return Promise.resolve()
- released ??= withTransaction(async db => {
- await releaseOwned(db)
- })
- return released
+ if (state === 'running') return Promise.reject(authorityFailure())
+ state = 'terminal'
+ return release()
+ },
+ }
+ reservations.set(raw, mutation)
+ reservations.set(mutation, mutation)
+ return {
+ raw,
+ mutation,
+ finish: async () => {
+ if (state === 'running') {
+ // Even an internal caller that forgot to await must settle its operation.
+ await terminalOperation
+ } else if (state === 'reserved') {
+ state = 'terminal'
+ try {
+ await release()
+ } catch (error) {
+ sanitize(error)
+ }
+ }
},
}
}
+
+/** Raw verifier view: release after bcrypt, before credential-state completion. */
+export async function acquirePasswordWork(): Promise<PasswordWorkLease | null> {
+ return (await reservePasswordWork())?.raw ?? null
+}
+
+async function acquireMutationReservation() {
+ try {
+ const reservation = await reservePasswordWork()
+ if (!reservation) {
+ throw new PasswordAdmissionError(
+ 429,
+ Math.ceil(PASSWORD_ADMISSION_POLICY.paceMs / 1000),
+ 'verification_busy'
+ )
+ }
+ return reservation
+ } catch (error) {
+ if (error instanceof PasswordAdmissionError) throw error
+ throw authorityFailure()
+ }
+}
+
+/** Reserve before earlier admin side effects, then consume once for member work. */
+export async function withPasswordWorkLease<T>(
+ work: (lease: PasswordMutationLease) => Promise<T>
+): Promise<T> {
+ const reservation = await acquireMutationReservation()
+ try {
+ return await work(reservation.mutation)
+ } finally {
+ await reservation.finish()
+ }
+}
+
+export async function runPasswordMutation<T>(
+ work: (db: DbTransactionClient) => Promise<T>,
+ options: { mode: PasswordCommitMode; lease?: MemberPasswordWorkLease }
+): Promise<T> {
+ if (options.lease) {
+ const mutation = reservations.get(options.lease)
+ if (!mutation) throw authorityFailure()
+ return mutation.commitWith(work, options)
+ }
+ return withPasswordWorkLease(lease => lease.commitWith(work, options))
+}
diff --git a/control-api/src/services/directory/index.ts b/control-api/src/services/directory/index.ts
index f5b27c024..42940b87f 100644
--- a/control-api/src/services/directory/index.ts
+++ b/control-api/src/services/directory/index.ts
@@ -59,9 +59,6 @@ export {
getMe,
listMembers,
listPendingInvitations,
- setInvitationPasswordForUser,
- setInvitationPasswordForEmail,
- withMemberPasswordWorkLease,
searchDirectory,
softDeleteMember,
startDraftInvitationCleanup,
@@ -69,9 +66,14 @@ export {
updateManagedMemberRoleForUser,
updateMemberRole,
updateProfile,
- updateUserPassword,
} from './membership.js'
-export type { MemberPasswordWorkLease } from './membership.js'
+export {
+ setInvitationPasswordForUser,
+ setInvitationPasswordForEmail,
+ updateUserPassword,
+} from './memberPassword.js'
+export { withPasswordWorkLease as withMemberPasswordWorkLease } from '../auth/passwordWorkOwnership.js'
+export type { MemberPasswordWorkLease } from '../auth/passwordWorkOwnership.js'
export {
getTeamContexts,
diff --git a/control-api/src/services/directory/invitationStore.ts b/control-api/src/services/directory/invitationStore.ts
new file mode 100644
index 000000000..d293e0c80
--- /dev/null
+++ b/control-api/src/services/directory/invitationStore.ts
@@ -0,0 +1,371 @@
+import { type DbClient } from '../../db.js'
+import { type InviteRole, normalizeTeamRoleInput } from './types.js'
+
+export const INVITATION_TTL_HOURS = 48
+
+export type InvitationRow = {
+ id: string
+ team_id: string | null
+ invitee_name: string | null
+ email: string
+ role: InviteRole
+ token: string
+ status: string
+ purpose: InvitationPurpose
+ created_at: Date
+ expires_at: Date
+ accepted_at: Date | null
+ accepted_user_id: string | null
+ team_name: string | null
+}
+
+export type InvitationPurpose = 'member_invitation' | 'password_reset' | 'admin_desktop_access'
+
+export type InvitationTeamAssignment = {
+ teamId: string
+ role: InviteRole
+}
+
+export type InvitationTeamRow = {
+ team_id: string
+ team_name: string
+ role: InviteRole
+}
+
+export type InvitationUserRow = {
+ id: string
+ email: string
+ name: string | null
+ picture: string | null
+ password_hash: string | null
+ lifecycle_state?: 'active' | 'retired' | string | null
+ lifecycle_version?: number | string | null
+}
+
+export type InvitationWithTeams = {
+ invitation: InvitationRow
+ teams: InvitationTeamRow[]
+}
+
+export type InvitationForTeamsInput = {
+ inviteeName: string
+ email: string
+ teamAssignments?: readonly InvitationTeamAssignment[]
+ purpose?: InvitationPurpose
+ fallbackRole?: InviteRole
+}
+
+export function normalizeInvitationPurpose(purpose?: InvitationPurpose): InvitationPurpose {
+ if (purpose === 'password_reset') return 'password_reset'
+ if (purpose === 'admin_desktop_access') return 'admin_desktop_access'
+ return 'member_invitation'
+}
+
+export async function getInvitationRecordByToken(
+ db: Pick<DbClient, 'query'>,
+ token: string
+): Promise<InvitationRow | null> {
+ const result = await db.query(
+ `SELECT i.id, i.team_id, i.invitee_name, i.email, i.role, i.token, i.status, i.purpose, i.created_at, i.expires_at, i.accepted_at,
+ i.accepted_user_id,
+ t.name AS team_name
+ FROM invitations i
+ LEFT JOIN teams t ON t.id = i.team_id
+ WHERE i.token = $1
+ LIMIT 1`,
+ [token]
+ )
+ return (result.rows[0] as InvitationRow | undefined) || null
+}
+
+export async function getInvitationRecordByTokenOrId(
+ db: Pick<DbClient, 'query'>,
+ token: string,
+ invitationId: string
+): Promise<InvitationRow | null> {
+ const normalizedToken = token.trim()
+ const normalizedInvitationId = invitationId.trim()
+ if (!normalizedToken && !normalizedInvitationId) {
+ return null
+ }
+
+ const result = await db.query(
+ `SELECT i.id, i.team_id, i.invitee_name, i.email, i.role, i.token, i.status, i.purpose, i.created_at, i.expires_at, i.accepted_at,
+ i.accepted_user_id,
+ t.name AS team_name
+ FROM invitations i
+ LEFT JOIN teams t ON t.id = i.team_id
+ WHERE ($1 <> '' AND i.token = $1)
+ OR ($2 <> '' AND i.id::text = $2)
+ ORDER BY i.created_at DESC
+ LIMIT 1`,
+ [normalizedToken, normalizedInvitationId]
+ )
+
+ return (result.rows[0] as InvitationRow | undefined) || null
+}
+
+export async function getInvitationRecordById(
+ db: Pick<DbClient, 'query'>,
+ invitationId: string,
+ lockForUpdate = false
+): Promise<InvitationRow | null> {
+ const normalizedInvitationId = invitationId.trim()
+ if (!normalizedInvitationId) return null
+
+ const result = await db.query(
+ `SELECT i.id, i.team_id, i.invitee_name, i.email, i.role, i.token, i.status, i.purpose, i.created_at, i.expires_at, i.accepted_at,
+ i.accepted_user_id,
+ t.name AS team_name
+ FROM invitations i
+ LEFT JOIN teams t ON t.id = i.team_id
+ WHERE i.id::text = $1
+ LIMIT 1
+ ${lockForUpdate ? 'FOR UPDATE OF i' : ''}`,
+ [normalizedInvitationId]
+ )
+ return (result.rows[0] as InvitationRow | undefined) || null
+}
+
+export async function lockPasswordResetUser(
+ db: Pick<DbClient, 'query'>,
+ email: string
+): Promise<InvitationUserRow | null> {
+ const result = await db.query(
+ `SELECT id, email, name, picture, password_hash, lifecycle_state, lifecycle_version
+ FROM users
+ WHERE email = $1
+ LIMIT 1
+ FOR NO KEY UPDATE`,
+ [email]
+ )
+ return (result.rows[0] as InvitationUserRow | undefined) ?? null
+}
+
+export async function ensureInvitationUser(
+ db: Pick<DbClient, 'query'>,
+ email: string,
+ inviteeName: string | null
+): Promise<InvitationUserRow> {
+ const normalizedEmail = email.trim().toLowerCase()
+ const normalizedInviteeName = String(inviteeName || '').trim() || null
+ const existing = await db.query(
+ `SELECT id, email, name, picture, password_hash, lifecycle_state, lifecycle_version
+ FROM users
+ WHERE email = $1
+ LIMIT 1`,
+ [normalizedEmail]
+ )
+
+ let user = (existing.rows[0] as InvitationUserRow | undefined) || null
+ if (!user) {
+ user = (
+ await db.query(
+ `INSERT INTO users(email, name)
+ VALUES($1, $2)
+ ON CONFLICT (email) DO UPDATE
+ SET name = COALESCE(users.name, EXCLUDED.name),
+ updated_at = NOW()
+ RETURNING id, email, name, picture, password_hash, lifecycle_state, lifecycle_version`,
+ [normalizedEmail, normalizedInviteeName]
+ )
+ ).rows[0] as InvitationUserRow
+ } else if (normalizedInviteeName && user.name !== normalizedInviteeName) {
+ user = (
+ await db.query(
+ `UPDATE users
+ SET name = $2,
+ updated_at = NOW()
+ WHERE id = $1
+ RETURNING id, email, name, picture, password_hash, lifecycle_state, lifecycle_version`,
+ [user.id, normalizedInviteeName]
+ )
+ ).rows[0] as InvitationUserRow
+ }
+
+ await db.query(
+ `INSERT INTO profiles(user_id, display_name)
+ VALUES($1, $2)
+ ON CONFLICT (user_id) DO NOTHING`,
+ [user.id, user.name || null]
+ )
+ if (normalizedInviteeName) {
+ await db.query(
+ `UPDATE profiles
+ SET display_name = $2,
+ updated_at = NOW()
+ WHERE user_id = $1`,
+ [user.id, normalizedInviteeName]
+ )
+ }
+
+ return user
+}
+
+export function invitationUserIsRetired(user: InvitationUserRow): boolean {
+ return user.lifecycle_state === 'retired'
+}
+
+export function normalizeInvitationTeamAssignments(
+ assignments: readonly InvitationTeamAssignment[] | null | undefined
+): InvitationTeamAssignment[] {
+ const byTeamId = new Map<string, InviteRole>()
+ for (const assignment of assignments || []) {
+ const teamId = String(assignment?.teamId || '').trim()
+ const role = normalizeTeamRoleInput(assignment?.role)
+ if (!teamId || !role) continue
+ byTeamId.set(teamId, role)
+ }
+ return Array.from(byTeamId.entries()).map(([teamId, role]) => ({ teamId, role }))
+}
+
+export async function loadInvitationTeams(
+ db: Pick<DbClient, 'query'>,
+ invitationId: string,
+ fallback?: Pick<InvitationRow, 'team_id' | 'team_name' | 'role'>
+): Promise<InvitationTeamRow[]> {
+ const result = await db.query(
+ `SELECT it.team_id, t.name AS team_name, it.role
+ FROM invitation_teams it
+ JOIN teams t ON t.id = it.team_id
+ WHERE it.invitation_id = $1
+ ORDER BY CASE WHEN it.team_id = $2::uuid THEN 0 ELSE 1 END, t.name ASC`,
+ [invitationId, fallback?.team_id || null]
+ )
+ const rows = result.rows as InvitationTeamRow[]
+ if (rows.length > 0) return rows
+ if (fallback?.team_id) {
+ return [
+ {
+ team_id: fallback.team_id,
+ team_name: fallback.team_name || 'Team',
+ role: fallback.role,
+ },
+ ]
+ }
+ return []
+}
+
+export async function insertInvitationTeams(
+ db: Pick<DbClient, 'query'>,
+ invitationId: string,
+ assignments: readonly InvitationTeamAssignment[]
+): Promise<void> {
+ if (assignments.length === 0) return
+ await db.query(
+ `INSERT INTO invitation_teams(invitation_id, team_id, role)
+ SELECT $1::uuid, item.team_id::uuid, item.role
+ FROM jsonb_to_recordset($2::jsonb) AS item(team_id text, role text)
+ ON CONFLICT (invitation_id, team_id)
+ DO UPDATE SET role = EXCLUDED.role`,
+ [
+ invitationId,
+ JSON.stringify(assignments.map(item => ({ team_id: item.teamId, role: item.role }))),
+ ]
+ )
+}
+
+export function invitationResponse(
+ invitation: InvitationRow,
+ user: InvitationUserRow | null,
+ teams: InvitationTeamRow[] = []
+): {
+ id: string
+ teamId: string | null
+ teamName: string | null
+ teams: Array<{ id: string; name: string; role: InviteRole }>
+ email: string
+ role: InviteRole
+ purpose: InvitationPurpose
+ status: string
+ expiresAt: string
+ acceptedAt: string | null
+ userId: string | null
+ passwordPending: boolean
+ authGeneration: number | null
+ lifecycleState: string | null
+} {
+ const primaryTeam = teams[0] || null
+ return {
+ id: invitation.id,
+ teamId: primaryTeam?.team_id || invitation.team_id,
+ teamName: primaryTeam?.team_name || invitation.team_name,
+ teams: teams.map(team => ({
+ id: team.team_id,
+ name: team.team_name,
+ role: team.role,
+ })),
+ email: invitation.email,
+ role: primaryTeam?.role || invitation.role,
+ purpose: invitation.purpose,
+ status: invitation.status,
+ expiresAt: invitation.expires_at.toISOString(),
+ acceptedAt: invitation.accepted_at ? invitation.accepted_at.toISOString() : null,
+ userId: invitation.accepted_user_id || user?.id || null,
+ passwordPending: !user?.password_hash,
+ authGeneration:
+ user?.lifecycle_version === undefined || user.lifecycle_version === null
+ ? null
+ : Number(user.lifecycle_version),
+ lifecycleState: user?.lifecycle_state ?? null,
+ }
+}
+
+export async function insertInvitationForTeams(
+ db: Pick<DbClient, 'query'>,
+ input: InvitationForTeamsInput & { status: 'draft' | 'pending' }
+): Promise<InvitationWithTeams> {
+ const normalizedAssignments = normalizeInvitationTeamAssignments(input.teamAssignments)
+ const primaryAssignment = normalizedAssignments[0] || null
+ const fallbackRole =
+ normalizeTeamRoleInput(input.fallbackRole) || primaryAssignment?.role || 'member'
+ const purpose = normalizeInvitationPurpose(input.purpose)
+ const invited = await db.query(
+ `WITH inserted AS (
+ INSERT INTO invitations(team_id, invitee_name, email, role, token, status, purpose, expires_at)
+ VALUES($1, $2, $3, $4, gen_random_uuid()::text, $5, $6, NOW() + ($7::text || ' hours')::interval)
+ RETURNING id, team_id, invitee_name, email, role, token, status, purpose, created_at, expires_at, accepted_at, accepted_user_id
+ )
+ SELECT inserted.id,
+ inserted.team_id,
+ inserted.invitee_name,
+ inserted.email,
+ inserted.role,
+ inserted.token,
+ inserted.status,
+ inserted.purpose,
+ inserted.created_at,
+ inserted.expires_at,
+ inserted.accepted_at,
+ inserted.accepted_user_id,
+ t.name AS team_name
+ FROM inserted
+ LEFT JOIN teams t ON t.id = inserted.team_id`,
+ [
+ primaryAssignment?.teamId || null,
+ input.inviteeName.trim(),
+ input.email.trim().toLowerCase(),
+ primaryAssignment?.role || fallbackRole,
+ input.status,
+ purpose,
+ String(INVITATION_TTL_HOURS),
+ ]
+ )
+ const invitation = invited.rows[0] as InvitationRow
+ await insertInvitationTeams(db, invitation.id, normalizedAssignments)
+ return {
+ invitation,
+ teams: await loadInvitationTeams(db, invitation.id, invitation),
+ }
+}
+
+export function invitationForTeamsResponse(invitation: InvitationRow, teams: InvitationTeamRow[]) {
+ return {
+ ...invitation,
+ teams: teams.map(team => ({
+ id: team.team_id,
+ name: team.team_name,
+ role: team.role,
+ })),
+ }
+}
diff --git a/control-api/src/services/directory/memberPassword.ts b/control-api/src/services/directory/memberPassword.ts
new file mode 100644
index 000000000..2b3e4651e
--- /dev/null
+++ b/control-api/src/services/directory/memberPassword.ts
@@ -0,0 +1,274 @@
+import bcrypt from 'bcryptjs'
+import { type DbClient, pool } from '../../db.js'
+import { type MemberPasswordWorkLease, runPasswordMutation } from '../auth/passwordWorkOwnership.js'
+import {
+ ensureInvitationUser,
+ getInvitationRecordById,
+ invitationResponse,
+ invitationUserIsRetired,
+ loadInvitationTeams,
+ lockPasswordResetUser,
+} from './invitationStore.js'
+import { getMemberSessionContext } from './login.js'
+
+type PasswordWorkLease = MemberPasswordWorkLease
+
+async function revokeSiblingPasswordResets(
+ db: Pick<DbClient, 'query'>,
+ email: string,
+ redeemedInvitationId: string,
+ userId: string
+): Promise<void> {
+ await db.query(
+ `UPDATE invitations
+ SET status = 'revoked'
+ WHERE lower(email) = $1
+ AND purpose = 'password_reset'
+ AND status IN ('draft', 'pending')
+ AND id <> $2::uuid
+ AND (accepted_user_id IS NULL OR accepted_user_id = $3)`,
+ [email, redeemedInvitationId, userId]
+ )
+}
+
+export async function setInvitationPasswordForUser(
+ userId: string,
+ email: string,
+ invitationId: string,
+ password: string,
+ passwordWorkLease?: PasswordWorkLease
+) {
+ const trimmedUserId = userId.trim()
+ const normalizedEmail = email.trim().toLowerCase()
+ const trimmedInvitationId = invitationId.trim()
+ const trimmedPassword = password.trim()
+ if (!trimmedUserId || !normalizedEmail || !trimmedInvitationId) {
+ return { error: 'not_found' as const }
+ }
+ if (trimmedPassword.length < 8 || trimmedPassword.length > 256) {
+ return { error: 'invalid_password' as const }
+ }
+
+ const candidate = await getInvitationRecordById(pool, trimmedInvitationId)
+ if (!candidate) return { error: 'not_found' as const }
+ if (candidate.email.toLowerCase() !== normalizedEmail) {
+ return { error: 'forbidden' as const }
+ }
+ if (candidate.purpose === 'password_reset') {
+ const result = await setInvitationPasswordForEmail(
+ normalizedEmail,
+ trimmedInvitationId,
+ trimmedPassword,
+ trimmedUserId,
+ passwordWorkLease
+ )
+ if ('error' in result) return result
+ const { sessionContext: _sessionContext, ...data } = result.data
+ return { data }
+ }
+ if (candidate.purpose !== 'member_invitation' && candidate.purpose !== 'admin_desktop_access') {
+ return { error: 'not_found' as const }
+ }
+ if (candidate.status !== 'accepted') return { error: 'not_accepted' as const }
+
+ return runPasswordMutation(
+ async db => {
+ const invitation = await getInvitationRecordById(db, trimmedInvitationId)
+ if (!invitation) return { error: 'not_found' as const }
+ if (invitation.email.toLowerCase() !== normalizedEmail) {
+ return { error: 'forbidden' as const }
+ }
+ if (
+ invitation.purpose !== 'member_invitation' &&
+ invitation.purpose !== 'admin_desktop_access'
+ ) {
+ return { error: 'not_found' as const }
+ }
+ if (invitation.status !== 'accepted') return { error: 'not_accepted' as const }
+ const user = await ensureInvitationUser(db, invitation.email, invitation.invitee_name)
+ if (invitationUserIsRetired(user)) return { error: 'user_retired' as const }
+ if (user.id !== trimmedUserId) return { error: 'forbidden' as const }
+ const passwordHash = await bcrypt.hash(trimmedPassword, 12)
+ const update = await db.query(
+ `UPDATE users
+ SET password_hash = $2,
+ password_set_at = NOW(),
+ updated_at = NOW()
+ WHERE id = $1
+ AND lifecycle_state = 'active'
+ RETURNING id`,
+ [user.id, passwordHash]
+ )
+ if (update.rows.length !== 1) return { error: 'user_retired' as const }
+
+ if (!invitation.accepted_user_id) {
+ await db.query(`UPDATE invitations SET accepted_user_id = $2 WHERE id = $1`, [
+ invitation.id,
+ user.id,
+ ])
+ }
+
+ const refreshed = await getInvitationRecordById(db, invitation.id)
+ if (!refreshed) return { error: 'not_found' as const }
+ const teams = await loadInvitationTeams(db, refreshed.id, refreshed)
+ return {
+ data: {
+ passwordUpdated: true,
+ ...invitationResponse(refreshed, { ...user, password_hash: passwordHash }, teams),
+ },
+ }
+ },
+ { mode: 'standard', lease: passwordWorkLease }
+ )
+}
+
+export async function setInvitationPasswordForEmail(
+ email: string,
+ invitationId: string,
+ password: string,
+ expectedUserId?: string,
+ passwordWorkLease?: PasswordWorkLease
+) {
+ const normalizedEmail = email.trim().toLowerCase()
+ const trimmedInvitationId = invitationId.trim()
+ const trimmedPassword = password.trim()
+ if (!normalizedEmail || !trimmedInvitationId) {
+ return { error: 'not_found' as const }
+ }
+ if (trimmedPassword.length < 8 || trimmedPassword.length > 256) {
+ return { error: 'invalid_password' as const }
+ }
+
+ return runPasswordMutation(
+ async db => {
+ const candidate = await getInvitationRecordById(db, trimmedInvitationId)
+ if (!candidate || candidate.purpose !== 'password_reset') {
+ return { error: 'not_found' as const }
+ }
+ if (candidate.email.toLowerCase() !== normalizedEmail) {
+ return { error: 'forbidden' as const }
+ }
+
+ const user = await lockPasswordResetUser(db, normalizedEmail)
+ if (!user) return { error: 'not_found' as const }
+ if (invitationUserIsRetired(user)) return { error: 'user_retired' as const }
+ if (expectedUserId && user.id !== expectedUserId.trim()) {
+ return { error: 'forbidden' as const }
+ }
+ const invitation = await getInvitationRecordById(db, trimmedInvitationId, true)
+ if (!invitation || invitation.purpose !== 'password_reset') {
+ return { error: 'not_found' as const }
+ }
+ if (invitation.email.toLowerCase() !== normalizedEmail) {
+ return { error: 'forbidden' as const }
+ }
+ if (invitation.status !== 'pending') return { error: 'not_pending' as const }
+ if (invitation.expires_at.getTime() <= Date.now()) return { error: 'expired' as const }
+ if (invitation.accepted_user_id && invitation.accepted_user_id !== user.id) {
+ return { error: 'forbidden' as const }
+ }
+
+ const passwordHash = await bcrypt.hash(trimmedPassword, 12)
+ const update = await db.query(
+ `UPDATE users
+ SET password_hash = $2,
+ password_set_at = NOW(),
+ updated_at = NOW()
+ WHERE id = $1
+ AND lifecycle_state = 'active'
+ RETURNING id`,
+ [user.id, passwordHash]
+ )
+ if (update.rows.length !== 1) return { error: 'user_retired' as const }
+
+ const redeemed = await db.query(
+ `UPDATE invitations
+ SET status = 'accepted',
+ accepted_at = NOW(),
+ accepted_user_id = $2
+ WHERE id = $1 AND status = 'pending'
+ RETURNING id`,
+ [invitation.id, user.id]
+ )
+ if (redeemed.rows.length !== 1) return { error: 'not_pending' as const }
+ await revokeSiblingPasswordResets(db, normalizedEmail, invitation.id, user.id)
+
+ const refreshed = await getInvitationRecordById(db, invitation.id)
+ if (!refreshed) return { error: 'not_found' as const }
+ const teams = await loadInvitationTeams(db, refreshed.id, refreshed)
+ const sessionContext = await getMemberSessionContext(db, user)
+ return {
+ data: {
+ passwordUpdated: true,
+ sessionContext,
+ ...invitationResponse(refreshed, { ...user, password_hash: passwordHash }, teams),
+ },
+ }
+ },
+ { mode: 'one_use_recovery', lease: passwordWorkLease }
+ )
+}
+
+export async function updateUserPassword(
+ userId: string,
+ email: string,
+ currentPassword: string,
+ newPassword: string
+) {
+ const normalizedUserId = userId.trim()
+ const normalizedEmail = email.trim().toLowerCase()
+ const nextPassword = newPassword.trim()
+ if (!normalizedUserId || !normalizedEmail) {
+ return { error: 'not_found' as const }
+ }
+ if (nextPassword.length < 8 || nextPassword.length > 256) {
+ return { error: 'invalid_password' as const }
+ }
+
+ return runPasswordMutation(
+ async db => {
+ const result = await db.query(
+ `SELECT password_hash, password_auth_generation
+ FROM users
+ WHERE id = $1
+ AND email = $2
+ LIMIT 1`,
+ [normalizedUserId, normalizedEmail]
+ )
+ const user =
+ (result.rows[0] as
+ | { password_hash: string | null; password_auth_generation: string | number }
+ | undefined) || null
+ if (!user) {
+ return { error: 'not_found' as const }
+ }
+ if (!user.password_hash) {
+ return { error: 'password_not_set' as const }
+ }
+ const currentOk = await bcrypt.compare(currentPassword, user.password_hash)
+ if (!currentOk) {
+ return { error: 'invalid_current_password' as const }
+ }
+
+ const update = await db.query(
+ `UPDATE users
+ SET password_hash = $3,
+ password_set_at = NOW(),
+ updated_at = NOW()
+ WHERE id = $1
+ AND password_auth_generation = $2
+ AND password_hash = $4
+ RETURNING id`,
+ [
+ normalizedUserId,
+ user.password_auth_generation,
+ await bcrypt.hash(nextPassword, 12),
+ user.password_hash,
+ ]
+ )
+ if (update.rows.length !== 1) return { error: 'credential_changed' as const }
+ return { updated: true as const }
+ },
+ { mode: 'standard' }
+ )
+}
diff --git a/control-api/src/services/directory/membership.ts b/control-api/src/services/directory/membership.ts
index 912a55a88..af1848cdc 100644
--- a/control-api/src/services/directory/membership.ts
+++ b/control-api/src/services/directory/membership.ts
@@ -1,12 +1,29 @@
-import bcrypt from 'bcryptjs'
-import { type DbClient, type DbTransactionClient, pool, withTransaction } from '../../db.js'
-import { rootLogger } from '../../observability/logger.js'
-import { PASSWORD_ADMISSION_POLICY } from '../auth/passwordAdmissionState.js'
-import { PasswordAdmissionError } from '../auth/passwordCredentialVerification.js'
-import { acquirePasswordWork } from '../auth/passwordWorkOwnership.js'
+import { type DbClient, pool, withTransaction } from '../../db.js'
import { registerAndSendInvitation } from '../invitationFlowRegistrationService.js'
import { appendControlApiPermissionEventsInTransaction } from '../tracing/controlApiPermissionEvents.js'
-import { getMemberSessionContext } from './login.js'
+import {
+ INVITATION_TTL_HOURS,
+ type InvitationForTeamsInput,
+ type InvitationPurpose,
+ type InvitationRow,
+ type InvitationTeamAssignment,
+ type InvitationTeamRow,
+ type InvitationUserRow,
+ type InvitationWithTeams,
+ ensureInvitationUser,
+ getInvitationRecordById,
+ getInvitationRecordByToken,
+ getInvitationRecordByTokenOrId,
+ insertInvitationForTeams,
+ insertInvitationTeams,
+ invitationForTeamsResponse,
+ invitationResponse,
+ invitationUserIsRetired,
+ loadInvitationTeams,
+ lockPasswordResetUser,
+ normalizeInvitationPurpose,
+ normalizeInvitationTeamAssignments,
+} from './invitationStore.js'
import type { InviteRole, TeamRole } from './types.js'
import {
normalizeChannels,
@@ -16,88 +33,21 @@ import {
} from './types.js'
import { DesktopUserRetirementError, retireDesktopUser } from './users.js'
-export const INVITATION_TTL_HOURS = 48
+export { INVITATION_TTL_HOURS } from './invitationStore.js'
+export type { InvitationPurpose, InvitationTeamAssignment } from './invitationStore.js'
+export {
+ setInvitationPasswordForUser,
+ setInvitationPasswordForEmail,
+ updateUserPassword,
+} from './memberPassword.js'
+export { withPasswordWorkLease as withMemberPasswordWorkLease } from '../auth/passwordWorkOwnership.js'
+export type { MemberPasswordWorkLease } from '../auth/passwordWorkOwnership.js'
+
const DRAFT_INVITATION_CLEANUP_HOURS = 24
const DRAFT_INVITATION_CLEANUP_INTERVAL_MS = 60 * 60 * 1000
let draftInvitationCleanupTimer: ReturnType<typeof setInterval> | null = null
class PasswordResetPrincipalUnavailableError extends Error {}
-const passwordSetupLogger = rootLogger.child({ module: 'password-admission' })
-
-type InvitationRow = {
- id: string
- team_id: string | null
- invitee_name: string | null
- email: string
- role: InviteRole
- token: string
- status: string
- purpose: InvitationPurpose
- created_at: Date
- expires_at: Date
- accepted_at: Date | null
- accepted_user_id: string | null
- team_name: string | null
-}
-
-export type InvitationPurpose = 'member_invitation' | 'password_reset' | 'admin_desktop_access'
-
-export type InvitationTeamAssignment = {
- teamId: string
- role: InviteRole
-}
-
-type InvitationTeamRow = {
- team_id: string
- team_name: string
- role: InviteRole
-}
-
-type InvitationUserRow = {
- id: string
- email: string
- name: string | null
- picture: string | null
- password_hash: string | null
- lifecycle_state?: 'active' | 'retired' | string | null
- lifecycle_version?: number | string | null
-}
-
-type InvitationWithTeams = {
- invitation: InvitationRow
- teams: InvitationTeamRow[]
-}
-
-type InvitationForTeamsInput = {
- inviteeName: string
- email: string
- teamAssignments?: readonly InvitationTeamAssignment[]
- purpose?: InvitationPurpose
- fallbackRole?: InviteRole
-}
-
-function normalizeInvitationPurpose(purpose?: InvitationPurpose): InvitationPurpose {
- if (purpose === 'password_reset') return 'password_reset'
- if (purpose === 'admin_desktop_access') return 'admin_desktop_access'
- return 'member_invitation'
-}
-
-async function getInvitationRecordByToken(
- db: Pick<DbClient, 'query'>,
- token: string
-): Promise<InvitationRow | null> {
- const result = await db.query(
- `SELECT i.id, i.team_id, i.invitee_name, i.email, i.role, i.token, i.status, i.purpose, i.created_at, i.expires_at, i.accepted_at,
- i.accepted_user_id,
- t.name AS team_name
- FROM invitations i
- LEFT JOIN teams t ON t.id = i.team_id
- WHERE i.token = $1
- LIMIT 1`,
- [token]
- )
- return (result.rows[0] as InvitationRow | undefined) || null
-}
async function cleanupStaleDraftInvitations(): Promise<void> {
await pool.query(
@@ -123,297 +73,6 @@ export function stopDraftInvitationCleanup() {
draftInvitationCleanupTimer = null
}
-async function getInvitationRecordByTokenOrId(
- db: Pick<DbClient, 'query'>,
- token: string,
- invitationId: string
-): Promise<InvitationRow | null> {
- const normalizedToken = token.trim()
- const normalizedInvitationId = invitationId.trim()
- if (!normalizedToken && !normalizedInvitationId) {
- return null
- }
-
- const result = await db.query(
- `SELECT i.id, i.team_id, i.invitee_name, i.email, i.role, i.token, i.status, i.purpose, i.created_at, i.expires_at, i.accepted_at,
- i.accepted_user_id,
- t.name AS team_name
- FROM invitations i
- LEFT JOIN teams t ON t.id = i.team_id
- WHERE ($1 <> '' AND i.token = $1)
- OR ($2 <> '' AND i.id::text = $2)
- ORDER BY i.created_at DESC
- LIMIT 1`,
- [normalizedToken, normalizedInvitationId]
- )
-
- return (result.rows[0] as InvitationRow | undefined) || null
-}
-
-async function getInvitationRecordById(
- db: Pick<DbClient, 'query'>,
- invitationId: string,
- lockForUpdate = false
-): Promise<InvitationRow | null> {
- const normalizedInvitationId = invitationId.trim()
- if (!normalizedInvitationId) return null
-
- const result = await db.query(
- `SELECT i.id, i.team_id, i.invitee_name, i.email, i.role, i.token, i.status, i.purpose, i.created_at, i.expires_at, i.accepted_at,
- i.accepted_user_id,
- t.name AS team_name
- FROM invitations i
- LEFT JOIN teams t ON t.id = i.team_id
- WHERE i.id::text = $1
- LIMIT 1
- ${lockForUpdate ? 'FOR UPDATE OF i' : ''}`,
- [normalizedInvitationId]
- )
- return (result.rows[0] as InvitationRow | undefined) || null
-}
-
-async function acquirePasswordSetupLease() {
- const retryAfterSeconds = Math.ceil(PASSWORD_ADMISSION_POLICY.paceMs / 1000)
- try {
- const lease = await acquirePasswordWork()
- if (!lease) {
- throw new PasswordAdmissionError(429, retryAfterSeconds, 'verification_busy')
- }
- return lease
- } catch (error) {
- if (error instanceof PasswordAdmissionError) throw error
- throw new PasswordAdmissionError(503, 2, 'authority_failure')
- }
-}
-
-export type MemberPasswordWorkLease = NonNullable<Awaited<ReturnType<typeof acquirePasswordWork>>>
-
-type PasswordWorkLease = MemberPasswordWorkLease
-
-/** Reserve the member-password lane around a multi-step invitation completion. */
-export async function withMemberPasswordWorkLease<T>(
- work: (lease: MemberPasswordWorkLease) => Promise<T>
-): Promise<T> {
- const lease = await acquirePasswordSetupLease()
- let outcome!: T
- let workFailed = false
- let workError: unknown
- try {
- outcome = await work(lease)
- } catch (error) {
- workFailed = true
- workError = error
- }
- try {
- await lease.release()
- } catch {
- passwordSetupLogger.warn(
- { event: 'password_authority_unavailable' },
- 'password authority unavailable'
- )
- throw new PasswordAdmissionError(503, 2, 'authority_failure')
- }
- if (workFailed) throw workError
- return outcome
-}
-
-/** Commit member credential mutations and durable-owner release as one outcome. */
-async function withPasswordWorkTransaction<T>(
- lease: PasswordWorkLease,
- work: (db: DbTransactionClient) => Promise<T>,
- options: { exposeUnknownCommitOutcome?: boolean } = {}
-): Promise<T> {
- let commitAcknowledged = false
- let commitOutcomeUnknown = false
- let hasOutcome = false
- let outcome!: T
- try {
- return await withTransaction(
- async db => {
- outcome = await work(db)
- hasOutcome = true
- await lease.releaseWithin(db)
- return outcome
- },
- undefined,
- {
- onCommitAcknowledged: () => {
- commitAcknowledged = true
- lease.confirmReleaseWithinCommitted()
- },
- onCommitOutcomeUnknown: () => {
- commitOutcomeUnknown = true
- },
- }
- )
- } catch (error) {
- if (commitOutcomeUnknown && options.exposeUnknownCommitOutcome) {
- passwordSetupLogger.warn(
- { event: 'password_recovery_commit_outcome_unknown' },
- 'password recovery commit outcome is unknown'
- )
- throw new PasswordAdmissionError(503, 2, 'authority_failure', 'recovery_outcome_unknown')
- }
- if (commitAcknowledged && hasOutcome) {
- passwordSetupLogger.warn(
- { event: 'password_post_commit_cleanup_failed' },
- 'password transaction committed; connection cleanup failed'
- )
- return outcome
- }
- throw error
- } finally {
- if (!commitAcknowledged) {
- try {
- await lease.release()
- } catch (error) {
- if (!commitOutcomeUnknown) throw error
- passwordSetupLogger.warn(
- { event: 'password_owner_release_after_unknown_commit_failed' },
- 'password owner release after unknown commit failed'
- )
- }
- }
- }
-}
-
-async function lockPasswordResetUser(
- db: Pick<DbClient, 'query'>,
- email: string
-): Promise<InvitationUserRow | null> {
- const result = await db.query(
- `SELECT id, email, name, picture, password_hash, lifecycle_state, lifecycle_version
- FROM users
- WHERE email = $1
- LIMIT 1
- FOR NO KEY UPDATE`,
- [email]
- )
- return (result.rows[0] as InvitationUserRow | undefined) ?? null
-}
-
-async function revokeSiblingPasswordResets(
- db: Pick<DbClient, 'query'>,
- email: string,
- redeemedInvitationId: string,
- userId: string
-): Promise<void> {
- await db.query(
- `UPDATE invitations
- SET status = 'revoked'
- WHERE lower(email) = $1
- AND purpose = 'password_reset'
- AND status IN ('draft', 'pending')
- AND id <> $2::uuid
- AND (accepted_user_id IS NULL OR accepted_user_id = $3)`,
- [email, redeemedInvitationId, userId]
- )
-}
-
-async function ensureInvitationUser(
- db: Pick<DbClient, 'query'>,
- email: string,
- inviteeName: string | null
-): Promise<InvitationUserRow> {
- const normalizedEmail = email.trim().toLowerCase()
- const normalizedInviteeName = String(inviteeName || '').trim() || null
- const existing = await db.query(
- `SELECT id, email, name, picture, password_hash, lifecycle_state, lifecycle_version
- FROM users
- WHERE email = $1
- LIMIT 1`,
- [normalizedEmail]
- )
-
- let user = (existing.rows[0] as InvitationUserRow | undefined) || null
- if (!user) {
- user = (
- await db.query(
- `INSERT INTO users(email, name)
- VALUES($1, $2)
- ON CONFLICT (email) DO UPDATE
- SET name = COALESCE(users.name, EXCLUDED.name),
- updated_at = NOW()
- RETURNING id, email, name, picture, password_hash, lifecycle_state, lifecycle_version`,
- [normalizedEmail, normalizedInviteeName]
- )
- ).rows[0] as InvitationUserRow
- } else if (normalizedInviteeName && user.name !== normalizedInviteeName) {
- user = (
- await db.query(
- `UPDATE users
- SET name = $2,
- updated_at = NOW()
- WHERE id = $1
- RETURNING id, email, name, picture, password_hash, lifecycle_state, lifecycle_version`,
- [user.id, normalizedInviteeName]
- )
- ).rows[0] as InvitationUserRow
- }
-
- await db.query(
- `INSERT INTO profiles(user_id, display_name)
- VALUES($1, $2)
- ON CONFLICT (user_id) DO NOTHING`,
- [user.id, user.name || null]
- )
- if (normalizedInviteeName) {
- await db.query(
- `UPDATE profiles
- SET display_name = $2,
- updated_at = NOW()
- WHERE user_id = $1`,
- [user.id, normalizedInviteeName]
- )
- }
-
- return user
-}
-
-function invitationUserIsRetired(user: InvitationUserRow): boolean {
- return user.lifecycle_state === 'retired'
-}
-
-function normalizeInvitationTeamAssignments(
- assignments: readonly InvitationTeamAssignment[] | null | undefined
-): InvitationTeamAssignment[] {
- const byTeamId = new Map<string, InviteRole>()
- for (const assignment of assignments || []) {
- const teamId = String(assignment?.teamId || '').trim()
- const role = normalizeTeamRoleInput(assignment?.role)
- if (!teamId || !role) continue
- byTeamId.set(teamId, role)
- }
- return Array.from(byTeamId.entries()).map(([teamId, role]) => ({ teamId, role }))
-}
-
-async function loadInvitationTeams(
- db: Pick<DbClient, 'query'>,
- invitationId: string,
- fallback?: Pick<InvitationRow, 'team_id' | 'team_name' | 'role'>
-): Promise<InvitationTeamRow[]> {
- const result = await db.query(
- `SELECT it.team_id, t.name AS team_name, it.role
- FROM invitation_teams it
- JOIN teams t ON t.id = it.team_id
- WHERE it.invitation_id = $1
- ORDER BY CASE WHEN it.team_id = $2::uuid THEN 0 ELSE 1 END, t.name ASC`,
- [invitationId, fallback?.team_id || null]
- )
- const rows = result.rows as InvitationTeamRow[]
- if (rows.length > 0) return rows
- if (fallback?.team_id) {
- return [
- {
- team_id: fallback.team_id,
- team_name: fallback.team_name || 'Team',
- role: fallback.role,
- },
- ]
- }
- return []
-}
-
async function loadInvitationTeamsByInvitationIds(
db: Pick<DbClient, 'query'>,
invitationIds: readonly string[]
@@ -476,71 +135,6 @@ async function applyInvitationMemberships(
return teams
}
-async function insertInvitationTeams(
- db: Pick<DbClient, 'query'>,
- invitationId: string,
- assignments: readonly InvitationTeamAssignment[]
-): Promise<void> {
- if (assignments.length === 0) return
- await db.query(
- `INSERT INTO invitation_teams(invitation_id, team_id, role)
- SELECT $1::uuid, item.team_id::uuid, item.role
- FROM jsonb_to_recordset($2::jsonb) AS item(team_id text, role text)
- ON CONFLICT (invitation_id, team_id)
- DO UPDATE SET role = EXCLUDED.role`,
- [
- invitationId,
- JSON.stringify(assignments.map(item => ({ team_id: item.teamId, role: item.role }))),
- ]
- )
-}
-
-function invitationResponse(
- invitation: InvitationRow,
- user: InvitationUserRow | null,
- teams: InvitationTeamRow[] = []
-): {
- id: string
- teamId: string | null
- teamName: string | null
- teams: Array<{ id: string; name: string; role: InviteRole }>
- email: string
- role: InviteRole
- purpose: InvitationPurpose
- status: string
- expiresAt: string
- acceptedAt: string | null
- userId: string | null
- passwordPending: boolean
- authGeneration: number | null
- lifecycleState: string | null
-} {
- const primaryTeam = teams[0] || null
- return {
- id: invitation.id,
- teamId: primaryTeam?.team_id || invitation.team_id,
- teamName: primaryTeam?.team_name || invitation.team_name,
- teams: teams.map(team => ({
- id: team.team_id,
- name: team.team_name,
- role: team.role,
- })),
- email: invitation.email,
- role: primaryTeam?.role || invitation.role,
- purpose: invitation.purpose,
- status: invitation.status,
- expiresAt: invitation.expires_at.toISOString(),
- acceptedAt: invitation.accepted_at ? invitation.accepted_at.toISOString() : null,
- userId: invitation.accepted_user_id || user?.id || null,
- passwordPending: !user?.password_hash,
- authGeneration:
- user?.lifecycle_version === undefined || user.lifecycle_version === null
- ? null
- : Number(user.lifecycle_version),
- lifecycleState: user?.lifecycle_state ?? null,
- }
-}
-
export async function findMembership(userId: string, teamId: string) {
const result = await pool.query(
`SELECT tm.team_id, tm.role, t.name AS team_name
@@ -757,65 +351,6 @@ export async function addMemberToTeam(
})
}
-async function insertInvitationForTeams(
- db: Pick<DbClient, 'query'>,
- input: InvitationForTeamsInput & { status: 'draft' | 'pending' }
-): Promise<InvitationWithTeams> {
- const normalizedAssignments = normalizeInvitationTeamAssignments(input.teamAssignments)
- const primaryAssignment = normalizedAssignments[0] || null
- const fallbackRole =
- normalizeTeamRoleInput(input.fallbackRole) || primaryAssignment?.role || 'member'
- const purpose = normalizeInvitationPurpose(input.purpose)
- const invited = await db.query(
- `WITH inserted AS (
- INSERT INTO invitations(team_id, invitee_name, email, role, token, status, purpose, expires_at)
- VALUES($1, $2, $3, $4, gen_random_uuid()::text, $5, $6, NOW() + ($7::text || ' hours')::interval)
- RETURNING id, team_id, invitee_name, email, role, token, status, purpose, created_at, expires_at, accepted_at, accepted_user_id
- )
- SELECT inserted.id,
- inserted.team_id,
- inserted.invitee_name,
- inserted.email,
- inserted.role,
- inserted.token,
- inserted.status,
- inserted.purpose,
- inserted.created_at,
- inserted.expires_at,
- inserted.accepted_at,
- inserted.accepted_user_id,
- t.name AS team_name
- FROM inserted
- LEFT JOIN teams t ON t.id = inserted.team_id`,
- [
- primaryAssignment?.teamId || null,
- input.inviteeName.trim(),
- input.email.trim().toLowerCase(),
- primaryAssignment?.role || fallbackRole,
- input.status,
- purpose,
- String(INVITATION_TTL_HOURS),
- ]
- )
- const invitation = invited.rows[0] as InvitationRow
- await insertInvitationTeams(db, invitation.id, normalizedAssignments)
- return {
- invitation,
- teams: await loadInvitationTeams(db, invitation.id, invitation),
- }
-}
-
-function invitationForTeamsResponse(invitation: InvitationRow, teams: InvitationTeamRow[]) {
- return {
- ...invitation,
- teams: teams.map(team => ({
- id: team.team_id,
- name: team.team_name,
- role: team.role,
- })),
- }
-}
-
async function createInvitationForTeamsRecord(
input: InvitationForTeamsInput,
options: { sendEmail: boolean }
@@ -1222,202 +757,6 @@ export async function getInvitationByToken(token: string) {
return invitationResponseForActiveRecord(await getInvitationRecordByToken(pool, token.trim()))
}
-export async function setInvitationPasswordForUser(
- userId: string,
- email: string,
- invitationId: string,
- password: string,
- passwordWorkLease?: PasswordWorkLease
-) {
- const trimmedUserId = userId.trim()
- const normalizedEmail = email.trim().toLowerCase()
- const trimmedInvitationId = invitationId.trim()
- const trimmedPassword = password.trim()
- if (!trimmedUserId || !normalizedEmail || !trimmedInvitationId) {
- return { error: 'not_found' as const }
- }
- if (trimmedPassword.length < 8 || trimmedPassword.length > 256) {
- return { error: 'invalid_password' as const }
- }
-
- const candidate = await getInvitationRecordById(pool, trimmedInvitationId)
- if (!candidate) return { error: 'not_found' as const }
- if (candidate.email.toLowerCase() !== normalizedEmail) {
- return { error: 'forbidden' as const }
- }
- if (candidate.purpose === 'password_reset') {
- const result = await setInvitationPasswordForEmail(
- normalizedEmail,
- trimmedInvitationId,
- trimmedPassword,
- trimmedUserId,
- passwordWorkLease
- )
- if ('error' in result) return result
- const { sessionContext: _sessionContext, ...data } = result.data
- return { data }
- }
- if (candidate.purpose !== 'member_invitation' && candidate.purpose !== 'admin_desktop_access') {
- return { error: 'not_found' as const }
- }
- if (candidate.status !== 'accepted') return { error: 'not_accepted' as const }
-
- const lease = passwordWorkLease ?? (await acquirePasswordSetupLease())
- try {
- return await withPasswordWorkTransaction(lease, async db => {
- const invitation = await getInvitationRecordById(db, trimmedInvitationId)
- if (!invitation) return { error: 'not_found' as const }
- if (invitation.email.toLowerCase() !== normalizedEmail) {
- return { error: 'forbidden' as const }
- }
- if (
- invitation.purpose !== 'member_invitation' &&
- invitation.purpose !== 'admin_desktop_access'
- ) {
- return { error: 'not_found' as const }
- }
- if (invitation.status !== 'accepted') return { error: 'not_accepted' as const }
- const user = await ensureInvitationUser(db, invitation.email, invitation.invitee_name)
- if (invitationUserIsRetired(user)) return { error: 'user_retired' as const }
- if (user.id !== trimmedUserId) return { error: 'forbidden' as const }
- const passwordHash = await bcrypt.hash(trimmedPassword, 12)
- const update = await db.query(
- `UPDATE users
- SET password_hash = $2,
- password_set_at = NOW(),
- updated_at = NOW()
- WHERE id = $1
- AND lifecycle_state = 'active'
- RETURNING id`,
- [user.id, passwordHash]
- )
- if (update.rows.length !== 1) return { error: 'user_retired' as const }
-
- if (!invitation.accepted_user_id) {
- await db.query(`UPDATE invitations SET accepted_user_id = $2 WHERE id = $1`, [
- invitation.id,
- user.id,
- ])
- }
-
- const refreshed = await getInvitationRecordById(db, invitation.id)
- if (!refreshed) return { error: 'not_found' as const }
- const teams = await loadInvitationTeams(db, refreshed.id, refreshed)
- return {
- data: {
- passwordUpdated: true,
- ...invitationResponse(refreshed, { ...user, password_hash: passwordHash }, teams),
- },
- }
- })
- } catch (error) {
- if (error instanceof PasswordAdmissionError) throw error
- passwordSetupLogger.warn(
- { event: 'password_authority_unavailable' },
- 'password authority unavailable'
- )
- throw new PasswordAdmissionError(503, 2, 'authority_failure')
- }
-}
-
-export async function setInvitationPasswordForEmail(
- email: string,
- invitationId: string,
- password: string,
- expectedUserId?: string,
- passwordWorkLease?: PasswordWorkLease
-) {
- const normalizedEmail = email.trim().toLowerCase()
- const trimmedInvitationId = invitationId.trim()
- const trimmedPassword = password.trim()
- if (!normalizedEmail || !trimmedInvitationId) {
- return { error: 'not_found' as const }
- }
- if (trimmedPassword.length < 8 || trimmedPassword.length > 256) {
- return { error: 'invalid_password' as const }
- }
-
- const lease = passwordWorkLease ?? (await acquirePasswordSetupLease())
- try {
- return await withPasswordWorkTransaction(
- lease,
- async db => {
- const candidate = await getInvitationRecordById(db, trimmedInvitationId)
- if (!candidate || candidate.purpose !== 'password_reset') {
- return { error: 'not_found' as const }
- }
- if (candidate.email.toLowerCase() !== normalizedEmail) {
- return { error: 'forbidden' as const }
- }
-
- const user = await lockPasswordResetUser(db, normalizedEmail)
- if (!user) return { error: 'not_found' as const }
- if (invitationUserIsRetired(user)) return { error: 'user_retired' as const }
- if (expectedUserId && user.id !== expectedUserId.trim()) {
- return { error: 'forbidden' as const }
- }
- const invitation = await getInvitationRecordById(db, trimmedInvitationId, true)
- if (!invitation || invitation.purpose !== 'password_reset') {
- return { error: 'not_found' as const }
- }
- if (invitation.email.toLowerCase() !== normalizedEmail) {
- return { error: 'forbidden' as const }
- }
- if (invitation.status !== 'pending') return { error: 'not_pending' as const }
- if (invitation.expires_at.getTime() <= Date.now()) return { error: 'expired' as const }
- if (invitation.accepted_user_id && invitation.accepted_user_id !== user.id) {
- return { error: 'forbidden' as const }
- }
-
- const passwordHash = await bcrypt.hash(trimmedPassword, 12)
- const update = await db.query(
- `UPDATE users
- SET password_hash = $2,
- password_set_at = NOW(),
- updated_at = NOW()
- WHERE id = $1
- AND lifecycle_state = 'active'
- RETURNING id`,
- [user.id, passwordHash]
- )
- if (update.rows.length !== 1) return { error: 'user_retired' as const }
-
- const redeemed = await db.query(
- `UPDATE invitations
- SET status = 'accepted',
- accepted_at = NOW(),
- accepted_user_id = $2
- WHERE id = $1 AND status = 'pending'
- RETURNING id`,
- [invitation.id, user.id]
- )
- if (redeemed.rows.length !== 1) return { error: 'not_pending' as const }
- await revokeSiblingPasswordResets(db, normalizedEmail, invitation.id, user.id)
-
- const refreshed = await getInvitationRecordById(db, invitation.id)
- if (!refreshed) return { error: 'not_found' as const }
- const teams = await loadInvitationTeams(db, refreshed.id, refreshed)
- const sessionContext = await getMemberSessionContext(db, user)
- return {
- data: {
- passwordUpdated: true,
- sessionContext,
- ...invitationResponse(refreshed, { ...user, password_hash: passwordHash }, teams),
- },
- }
- },
- { exposeUnknownCommitOutcome: true }
- )
- } catch (error) {
- if (error instanceof PasswordAdmissionError) throw error
- passwordSetupLogger.warn(
- { event: 'password_authority_unavailable' },
- 'password authority unavailable'
- )
- throw new PasswordAdmissionError(503, 2, 'authority_failure')
- }
-}
-
export async function acceptInvitation(
userId: string,
email: string,
@@ -2109,74 +1448,3 @@ export async function revokeManagedInvitationForUser(managerUserId: string, invi
await pool.query(`UPDATE invitations SET status = 'revoked' WHERE id = $1`, [invitation.id])
return { revoked: true as const, id: invitation.id, email: invitation.email }
}
-
-export async function updateUserPassword(
- userId: string,
- email: string,
- currentPassword: string,
- newPassword: string
-) {
- const normalizedUserId = userId.trim()
- const normalizedEmail = email.trim().toLowerCase()
- const nextPassword = newPassword.trim()
- if (!normalizedUserId || !normalizedEmail) {
- return { error: 'not_found' as const }
- }
- if (nextPassword.length < 8 || nextPassword.length > 256) {
- return { error: 'invalid_password' as const }
- }
-
- const lease = await acquirePasswordSetupLease()
- try {
- return await withPasswordWorkTransaction(lease, async db => {
- const result = await db.query(
- `SELECT password_hash, password_auth_generation
- FROM users
- WHERE id = $1
- AND email = $2
- LIMIT 1`,
- [normalizedUserId, normalizedEmail]
- )
- const user =
- (result.rows[0] as
- | { password_hash: string | null; password_auth_generation: string | number }
- | undefined) || null
- if (!user) {
- return { error: 'not_found' as const }
- }
- if (!user.password_hash) {
- return { error: 'password_not_set' as const }
- }
- const currentOk = await bcrypt.compare(currentPassword, user.password_hash)
- if (!currentOk) {
- return { error: 'invalid_current_password' as const }
- }
-
- const update = await db.query(
- `UPDATE users
- SET password_hash = $3,
- password_set_at = NOW(),
- updated_at = NOW()
- WHERE id = $1
- AND password_auth_generation = $2
- AND password_hash = $4
- RETURNING id`,
- [
- normalizedUserId,
- user.password_auth_generation,
- await bcrypt.hash(nextPassword, 12),
- user.password_hash,
- ]
- )
- if (update.rows.length !== 1) return { error: 'credential_changed' as const }
- return { updated: true as const }
- })
- } catch (error) {
- if (error instanceof PasswordAdmissionError) throw error
- passwordSetupLogger.warn(
- { event: 'password_authority_unavailable' },
- 'password authority unavailable'
- )
- throw new PasswordAdmissionError(503, 2, 'authority_failure')
- }
-}
diff --git a/control-api/test/passwordWorkOwnership.operation.realPostgres.integration.test.ts b/control-api/test/passwordWorkOwnership.operation.realPostgres.integration.test.ts
index 0bdf4a15d..cda94af5a 100644
--- a/control-api/test/passwordWorkOwnership.operation.realPostgres.integration.test.ts
+++ b/control-api/test/passwordWorkOwnership.operation.realPostgres.integration.test.ts
@@ -4,6 +4,10 @@ import { randomBytes } from 'node:crypto'
import { Pool } from 'pg'
import { initDb } from '../src/db.js'
import { acquirePasswordWork } from '../src/services/auth/passwordWorkOwnership.js'
+import {
+ runPasswordMutation,
+ withPasswordWorkLease,
+} from '../src/services/auth/passwordWorkOwnership.js'
import {
acceptInvitationForEmail,
createSilentInvitationForTeams,
@@ -178,4 +182,143 @@ realPg('password-work operation preservation on PostgreSQL 16', () => {
await local.query('DROP FUNCTION preservation_delete_failure()')
}
})
+
+ it('keeps a real lost-COMMIT outcome above failed owner cleanup in an outer reservation', async () => {
+ const fixture = await resetFixture()
+ const sibling = await createSilentInvitationForTeams({
+ email: fixture.email,
+ inviteeName: 'Synthetic sibling',
+ purpose: 'password_reset',
+ })
+ const blackhole = await createPostgresCommitReplyBlackhole(connectionString)
+ const proxyPool = new Pool({ connectionString: blackhole.connectionString, max: 1 })
+ const outcome = withMemberPasswordWorkLease(async lease => {
+ // Acquisition is acknowledged on the ordinary pool; only the credential COMMIT is lost.
+ holder.pool = proxyPool
+ return setInvitationPasswordForEmail(
+ fixture.email,
+ fixture.invitation.id,
+ 'Synthetic-preservation-password',
+ fixture.userId,
+ lease
+ )
+ }).then(
+ value => ({ value }),
+ error => ({ error })
+ )
+ try {
+ await blackhole.commitForwarded
+ const deadline = Date.now() + 2_000
+ while (blackhole.discardedReplyBytes === 0 && Date.now() < deadline) {
+ await new Promise(resolve => setTimeout(resolve, 10))
+ }
+ expect(blackhole.discardedReplyBytes).toBeGreaterThan(0)
+ const row = (
+ await local.query(
+ `SELECT u.password_hash, i.status, s.status AS sibling_status
+ FROM users u JOIN invitations i ON i.id = $2 JOIN invitations s ON s.id = $3
+ WHERE u.id = $1`,
+ [fixture.userId, fixture.invitation.id, sibling.id]
+ )
+ ).rows[0]
+ expect(row).toMatchObject({ status: 'accepted', sibling_status: 'revoked' })
+ expect(await bcrypt.compare('Synthetic-preservation-password', row.password_hash)).toBe(true)
+ expect(await ownerCount()).toBe(0)
+ // A successor exists before fallback cleanup. The old owner must neither delete it
+ // nor replace the chosen unknown outcome with its failed owned DELETE.
+ holder.pool = local
+ const successor = await acquirePasswordWork()
+ holder.pool = proxyPool
+ blackhole.failClientAfterCommitForwarded()
+ const result = await outcome
+ expect(result).toMatchObject({
+ error: { status: 503, publicError: 'recovery_outcome_unknown' },
+ })
+ expect(blackhole.commands.filter(command => command === 'COMMIT')).toHaveLength(1)
+ expect(await ownerCount()).toBe(1)
+ holder.pool = local
+ await successor!.release()
+ expect(
+ await setInvitationPasswordForEmail(
+ fixture.email,
+ fixture.invitation.id,
+ 'Synthetic-replay-password',
+ fixture.userId
+ )
+ ).toEqual({ error: 'not_pending' })
+ } finally {
+ holder.pool = local
+ blackhole.allowReplies()
+ await blackhole.close()
+ await endPoolAndWaitForClients(proxyPool)
+ await outcome
+ }
+ })
+
+ it('allows only one concurrent callback and rejects terminal reuse without touching a successor', async () => {
+ await withPasswordWorkLease(async lease => {
+ let resume!: () => void
+ const gate = new Promise<void>(resolve => {
+ resume = resolve
+ })
+ const work = vi.fn(async () => {
+ await gate
+ return 'committed'
+ })
+ const first = lease.commitWith(work, { mode: 'standard' })
+ try {
+ await expect(lease.commitWith(work, { mode: 'standard' })).rejects.toMatchObject({
+ status: 503,
+ })
+ } finally {
+ resume()
+ }
+ expect(await first).toBe('committed')
+ expect(work).toHaveBeenCalledTimes(1)
+ const successor = await acquirePasswordWork()
+ try {
+ await expect(runPasswordMutation(work, { mode: 'standard', lease })).rejects.toMatchObject({
+ status: 503,
+ })
+ expect(work).toHaveBeenCalledTimes(1)
+ expect(await ownerCount()).toBe(1)
+ } finally {
+ await successor!.release()
+ }
+ })
+ expect(await ownerCount()).toBe(0)
+ })
+
+ it('keeps concurrent supplied domain operations at one committed reset', async () => {
+ const fixture = await resetFixture()
+ const sibling = await createSilentInvitationForTeams({
+ email: fixture.email,
+ inviteeName: 'Synthetic sibling',
+ purpose: 'password_reset',
+ })
+ const hash = vi.spyOn(bcrypt, 'hash')
+ const outcomes = await withMemberPasswordWorkLease(lease =>
+ Promise.allSettled(
+ [fixture.invitation.id, sibling.id].map(id =>
+ setInvitationPasswordForEmail(
+ fixture.email,
+ id,
+ 'Synthetic-preservation-password',
+ fixture.userId,
+ lease
+ )
+ )
+ )
+ )
+ expect(outcomes.filter(outcome => outcome.status === 'fulfilled')).toHaveLength(1)
+ expect(outcomes.filter(outcome => outcome.status === 'rejected')).toHaveLength(1)
+ expect(hash).toHaveBeenCalledTimes(1)
+ const rows = (
+ await local.query('SELECT status FROM invitations WHERE id = ANY($1::uuid[])', [
+ [fixture.invitation.id, sibling.id],
+ ])
+ ).rows
+ expect(rows.map(row => row.status).sort()).toEqual(['accepted', 'revoked'])
+ expect(await ownerCount()).toBe(0)
+ })
})
diff --git a/control-api/test/passwordWorkOwnership.operation.test.ts b/control-api/test/passwordWorkOwnership.operation.test.ts
index 6e75bd60e..44c772a4a 100644
--- a/control-api/test/passwordWorkOwnership.operation.test.ts
+++ b/control-api/test/passwordWorkOwnership.operation.test.ts
@@ -1,7 +1,12 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import fc from 'fast-check'
+import { PasswordAdmissionError as LeafError } from '../src/services/auth/passwordAdmissionError.js'
import { PasswordAdmissionError } from '../src/services/auth/passwordCredentialVerification.js'
-import { acquirePasswordWork } from '../src/services/auth/passwordWorkOwnership.js'
+import {
+ acquirePasswordWork,
+ runPasswordMutation,
+ withPasswordWorkLease,
+} from '../src/services/auth/passwordWorkOwnership.js'
import { withMemberPasswordWorkLease } from '../src/services/directory/membership.js'
// Own-service lifecycle seam. Real PostgreSQL and wire faults are verified separately.
@@ -110,4 +115,130 @@ describe('password-work reservation preservation', () => {
await expect(first).rejects.toThrow('private release failure')
expect(query.mock.calls.filter(([sql]) => sql.includes('DELETE FROM'))).toHaveLength(1)
})
+
+ it('retains the exact error constructor identity at the compatibility export', () => {
+ expect(LeafError).toBe(PasswordAdmissionError)
+ })
+
+ it('retains an acknowledged result despite connection cleanup failure', async () => {
+ state.commit = 'ack_cleanup'
+ const value = { committed: true }
+ expect(await runPasswordMutation(async () => value, { mode: 'one_use_recovery' })).toBe(value)
+ expect(query.mock.calls.filter(([sql]) => sql.includes('DELETE FROM'))).toHaveLength(1)
+ })
+
+ it.each(['standard', 'one_use_recovery'] as const)(
+ 'preserves %s unknown outcome above fallback release failure without outer replay',
+ async mode => {
+ state.commit = 'unknown'
+ const work = vi.fn(async () => ({ committed: true }))
+ await expect(
+ withPasswordWorkLease(lease => lease.commitWith(work, { mode }))
+ ).rejects.toMatchObject({
+ status: 503,
+ publicError:
+ mode === 'one_use_recovery' ? 'recovery_outcome_unknown' : 'authority_unavailable',
+ })
+ expect(work).toHaveBeenCalledTimes(1)
+ expect(query.mock.calls.filter(([sql]) => sql.includes('DELETE FROM'))).toHaveLength(2)
+ }
+ )
+
+ it('maps a definitive transaction rejection to the existing authority contract', async () => {
+ state.commit = 'reject'
+ await expect(
+ runPasswordMutation(async () => 'result', { mode: 'one_use_recovery' })
+ ).rejects.toMatchObject({ status: 503, publicError: 'authority_unavailable' })
+ })
+
+ it('rejects concurrent, recursive and terminal reuse before another callback runs', async () => {
+ await fc.assert(
+ fc.asyncProperty(fc.integer({ min: 2, max: 16 }), async count => {
+ await withPasswordWorkLease(async lease => {
+ let calls = 0
+ const outcomes = await Promise.allSettled(
+ Array.from({ length: count }, () =>
+ lease.commitWith(
+ async () => {
+ calls++
+ await expect(
+ lease.commitWith(
+ async () => {
+ calls++
+ },
+ { mode: 'standard' }
+ )
+ ).rejects.toBeInstanceOf(PasswordAdmissionError)
+ return 'committed'
+ },
+ { mode: 'standard' }
+ )
+ )
+ )
+ expect(calls).toBe(1)
+ expect(outcomes.filter(outcome => outcome.status === 'fulfilled')).toHaveLength(1)
+ await expect(
+ lease.commitWith(
+ async () => {
+ calls++
+ },
+ { mode: 'standard' }
+ )
+ ).rejects.toBeInstanceOf(PasswordAdmissionError)
+ expect(calls).toBe(1)
+ })
+ }),
+ { numRuns: 30 }
+ )
+ })
+
+ it('rejects a foreign lease without acquiring or executing work', async () => {
+ const work = vi.fn()
+ await expect(
+ runPasswordMutation(work, {
+ mode: 'standard',
+ lease: { commitWith: vi.fn() },
+ })
+ ).rejects.toBeInstanceOf(PasswordAdmissionError)
+ expect(work).not.toHaveBeenCalled()
+ expect(query).not.toHaveBeenCalled()
+ })
+
+ it('does not release a raw reservation while its terminal callback is running', async () => {
+ const raw = await acquirePasswordWork()
+ let resume!: () => void
+ const gate = new Promise<void>(resolve => {
+ resume = resolve
+ })
+ const terminal = runPasswordMutation(
+ async () => {
+ await gate
+ return 'committed'
+ },
+ {
+ mode: 'standard',
+ lease: raw!,
+ }
+ )
+ try {
+ await expect(raw!.release()).rejects.toBeInstanceOf(PasswordAdmissionError)
+ expect(query.mock.calls.filter(([sql]) => sql.includes('DELETE FROM'))).toHaveLength(0)
+ } finally {
+ resume()
+ }
+ expect(await terminal).toBe('committed')
+ await raw!.release()
+ expect(query.mock.calls.filter(([sql]) => sql.includes('DELETE FROM'))).toHaveLength(1)
+ })
+
+ it('prevents mutation after raw release was already requested', async () => {
+ const raw = await acquirePasswordWork()
+ const releasing = raw!.release()
+ const work = vi.fn()
+ await expect(
+ runPasswordMutation(work, { mode: 'standard', lease: raw! })
+ ).rejects.toBeInstanceOf(PasswordAdmissionError)
+ await releasing
+ expect(work).not.toHaveBeenCalled()
+ })
})
diff --git a/control-api/test/routes.adminAuth.test.ts b/control-api/test/routes.adminAuth.test.ts
index cc7de0e6d..329acebfd 100644
--- a/control-api/test/routes.adminAuth.test.ts
+++ b/control-api/test/routes.adminAuth.test.ts
@@ -82,9 +82,7 @@ describe('routes/adminAuth', () => {
directorySvc.withMemberPasswordWorkLease.mockImplementation(
async (work: (lease: unknown) => Promise<unknown>) =>
work({
- release: async () => undefined,
- releaseWithin: async () => undefined,
- confirmReleaseWithinCommitted: () => undefined,
+ commitWith: vi.fn(),
})
)
adminSvc.isValidAdminEmail.mockReturnValue(true)