The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
/*
* Copyright 2025 Daytona Platforms Inc.
* Modified by BoxLite AI, 2025-2026
* SPDX-License-Identifier: AGPL-3.0
*/
import {
BadRequestException,
ConflictException,
Injectable,
NotFoundException,
UnprocessableEntityException,
} from '@nestjs/common'
import { createHash } from 'node:crypto'
import { ConfigService } from '@nestjs/config'
import { EventEmitter2 } from '@nestjs/event-emitter'
import { InjectRepository } from '@nestjs/typeorm'
import { DataSource, MoreThan, Repository } from 'typeorm'
import { OrganizationRoleService } from './organization-role.service'
import { OrganizationUserService } from './organization-user.service'
import { OrganizationService } from './organization.service'
import { OrganizationEvents } from '../constants/organization-events.constant'
import { CreateOrganizationInvitationDto } from '../dto/create-organization-invitation.dto'
import { UpdateOrganizationInvitationDto } from '../dto/update-organization-invitation.dto'
import { OrganizationInvitation } from '../entities/organization-invitation.entity'
import { OrganizationInvitationStatus } from '../enums/organization-invitation-status.enum'
import { OrganizationInvitationAcceptedEvent } from '../events/organization-invitation-accepted.event'
import { OrganizationInvitationCreatedEvent } from '../events/organization-invitation-created.event'
import { UserService } from '../../user/user.service'
import { EmailUtils } from '../../common/utils/email.util'
@Injectable()
export class OrganizationInvitationService {
constructor(
@InjectRepository(OrganizationInvitation)
private readonly organizationInvitationRepository: Repository<OrganizationInvitation>,
private readonly organizationService: OrganizationService,
private readonly organizationUserService: OrganizationUserService,
private readonly organizationRoleService: OrganizationRoleService,
private readonly userService: UserService,
private readonly eventEmitter: EventEmitter2,
private readonly dataSource: DataSource,
private readonly configService: ConfigService,
) {}
async create(
organizationId: string,
createOrganizationInvitationDto: CreateOrganizationInvitationDto,
invitedBy: string,
request?: { userId: string; idempotencyKey?: string },
): Promise<OrganizationInvitation> {
const prepare = () => {
if (
request &&
createOrganizationInvitationDto.expiresAt &&
createOrganizationInvitationDto.expiresAt <= new Date()
) {
throw new BadRequestException('expires_at must be in the future')
}
return this.prepareInvitation(organizationId, createOrganizationInvitationDto, invitedBy)
}
if (!request?.idempotencyKey) {
const invitation = await this.organizationInvitationRepository.save(await prepare())
this.notifyInvitationCreated(invitation)
return invitation
}
const key = [organizationId, request.userId, request.idempotencyKey.toLowerCase()]
const fingerprint = createHash('sha256')
.update(
JSON.stringify([
createOrganizationInvitationDto.email,
createOrganizationInvitationDto.role,
createOrganizationInvitationDto.expiresAt?.toISOString() ?? null,
]),
)
.digest('hex')
const result = await this.dataSource.transaction(async (manager) => {
const [lock] = await manager.query('SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0)) AS acquired', [
JSON.stringify(key),
])
if (!lock.acquired) throw new ConflictException('This Idempotency-Key is in progress; retry the request')
const [record] = await manager.query(
'SELECT "requestHash", response, "expiresAt" FROM organization_invitation_request WHERE "organizationId" = $1 AND "userId" = $2 AND key = $3',
key,
)
if (record && new Date(record.expiresAt) > new Date()) {
if (record.requestHash !== fingerprint)
throw new UnprocessableEntityException('Idempotency-Key was used with a different request')
return {
invitation: Object.assign(new OrganizationInvitation(), record.response, {
createdAt: new Date(record.response.createdAt),
expiresAt: new Date(record.response.expiresAt),
}),
created: false,
}
}
// Cleanup is organization-scoped; replay lookup and persistence share the invitation transaction.
await manager.query(
'DELETE FROM organization_invitation_request WHERE "organizationId" = $1 AND "expiresAt" <= now()',
[organizationId],
)
const invitation = await manager.save(await prepare())
const { id, email, role, status, createdAt, expiresAt } = invitation
await manager.query(
'INSERT INTO organization_invitation_request ("organizationId", "userId", key, "requestHash", response, "expiresAt") VALUES ($1, $2, $3, $4, $5, now() + interval \'24 hours\')',
[...key, fingerprint, { id, email, role, status, createdAt, expiresAt }],
)
return { invitation, created: true }
})
if (result.created) this.notifyInvitationCreated(result.invitation)
return result.invitation
}
private async prepareInvitation(
organizationId: string,
createOrganizationInvitationDto: CreateOrganizationInvitationDto,
invitedBy: string,
): Promise<OrganizationInvitation> {
const organization = await this.organizationService.findOne(organizationId)
if (!organization) {
throw new NotFoundException(`Organization with ID ${organizationId} not found`)
}
const normalizedEmail = EmailUtils.normalize(createOrganizationInvitationDto.email)
const existingUser = await this.userService.findOneByEmail(normalizedEmail, true)
if (existingUser) {
const organizationUser = await this.organizationUserService.findOne(organizationId, existingUser.id)
if (organizationUser) {
throw new ConflictException(`User with email ${normalizedEmail} is already associated with this organization`)
}
}
const existingInvitation = await this.organizationInvitationRepository.findOne({
where: {
organizationId,
email: normalizedEmail,
status: OrganizationInvitationStatus.PENDING,
expiresAt: MoreThan(new Date()),
},
})
if (existingInvitation) {
throw new ConflictException(`User with email "${normalizedEmail}" already invited to this organization`)
}
const invitation = new OrganizationInvitation()
invitation.organizationId = organizationId
invitation.organization = organization
invitation.email = normalizedEmail
invitation.expiresAt =
createOrganizationInvitationDto.expiresAt ||
new Date(Date.now() + this.configService.getOrThrow<number>('organizationInvitation.ttlSeconds') * 1000)
invitation.role = createOrganizationInvitationDto.role
invitation.invitedBy = invitedBy
const assignedRoles = await this.organizationRoleService.findByIds(createOrganizationInvitationDto.assignedRoleIds)
if (assignedRoles.length !== createOrganizationInvitationDto.assignedRoleIds.length) {
throw new BadRequestException('One or more role IDs are invalid')
}
invitation.assignedRoles = assignedRoles
return invitation
}
private notifyInvitationCreated(invitation: OrganizationInvitation): void {
this.eventEmitter.emit(
OrganizationEvents.INVITATION_CREATED,
new OrganizationInvitationCreatedEvent(
invitation.organization.name,
invitation.invitedBy,
invitation.email,
invitation.id,
invitation.expiresAt,
),
)
}
async update(
organizationId: string,
invitationId: string,
updateOrganizationInvitationDto: UpdateOrganizationInvitationDto,
): Promise<OrganizationInvitation> {
const invitation = await this.organizationInvitationRepository.findOne({
where: { id: invitationId, organizationId },
relations: {
organization: true,
assignedRoles: true,
},
})
if (!invitation) {
throw new NotFoundException(`Invitation with ID ${invitationId} not found`)
}
if (invitation.expiresAt && invitation.expiresAt < new Date()) {
throw new ConflictException(`Invitation with ID ${invitationId} is expired`)
}
if (invitation.status !== OrganizationInvitationStatus.PENDING) {
throw new ConflictException(`Invitation with ID ${invitationId} is already ${invitation.status}`)
}
if (updateOrganizationInvitationDto.expiresAt) {
invitation.expiresAt = updateOrganizationInvitationDto.expiresAt
}
invitation.role = updateOrganizationInvitationDto.role
const assignedRoles = await this.organizationRoleService.findByIds(updateOrganizationInvitationDto.assignedRoleIds)
if (assignedRoles.length !== updateOrganizationInvitationDto.assignedRoleIds.length) {
throw new BadRequestException('One or more role IDs are invalid')
}
invitation.assignedRoles = assignedRoles
return this.organizationInvitationRepository.save(invitation)
}
async findPending(
organizationId: string,
options: { includeExpired?: boolean } = {},
): Promise<OrganizationInvitation[]> {
return this.organizationInvitationRepository.find({
where: {
organizationId,
status: OrganizationInvitationStatus.PENDING,
...(options.includeExpired ? {} : { expiresAt: MoreThan(new Date()) }),
},
relations: {
organization: true,
assignedRoles: true,
},
})
}
async findPage(organizationId: string, pageSize: number, afterId?: string): Promise<OrganizationInvitation[]> {
return this.organizationInvitationRepository.find({
where: { organizationId, ...(afterId ? { id: MoreThan(afterId) } : {}) },
order: { id: 'ASC' },
take: pageSize + 1,
})
}
async findByUser(userId: string): Promise<OrganizationInvitation[]> {
const user = await this.userService.findOne(userId)
if (!user) {
throw new NotFoundException(`User with ID ${userId} not found`)
}
return this.organizationInvitationRepository.find({
where: {
email: EmailUtils.normalize(user.email),
status: OrganizationInvitationStatus.PENDING,
expiresAt: MoreThan(new Date()),
},
relations: {
organization: true,
assignedRoles: true,
},
})
}
async getCountByUser(userId: string): Promise<number> {
const user = await this.userService.findOne(userId)
if (!user) {
throw new NotFoundException(`User with ID ${userId} not found`)
}
return this.organizationInvitationRepository.count({
where: {
email: EmailUtils.normalize(user.email),
status: OrganizationInvitationStatus.PENDING,
expiresAt: MoreThan(new Date()),
},
})
}
async findOneOrFail(invitationId: string): Promise<OrganizationInvitation> {
return this.organizationInvitationRepository.findOneOrFail({
where: { id: invitationId },
relations: {
organization: true,
assignedRoles: true,
},
})
}
async accept(invitationId: string, userId: string): Promise<OrganizationInvitation> {
const invitation = await this.prepareStatusUpdate(invitationId, OrganizationInvitationStatus.ACCEPTED)
await this.dataSource.transaction(async (em) => {
await em.save(invitation)
await this.eventEmitter.emitAsync(
OrganizationEvents.INVITATION_ACCEPTED,
new OrganizationInvitationAcceptedEvent(
em,
invitation.organizationId,
userId,
invitation.role,
invitation.assignedRoles,
),
)
})
return invitation
}
async decline(invitationId: string): Promise<void> {
const invitation = await this.prepareStatusUpdate(invitationId, OrganizationInvitationStatus.DECLINED)
await this.organizationInvitationRepository.save(invitation)
}
async cancel(organizationId: string, invitationId: string): Promise<void> {
const invitation = await this.prepareStatusUpdate(
invitationId,
OrganizationInvitationStatus.CANCELLED,
organizationId,
)
await this.organizationInvitationRepository.save(invitation)
}
private async prepareStatusUpdate(
invitationId: string,
newStatus: OrganizationInvitationStatus,
organizationId?: string,
): Promise<OrganizationInvitation> {
const invitation = await this.organizationInvitationRepository.findOne({
where: { id: invitationId, ...(organizationId && { organizationId }) },
relations: {
organization: true,
assignedRoles: true,
},
})
if (!invitation) {
throw new NotFoundException(`Invitation with ID ${invitationId} not found`)
}
if (
newStatus !== OrganizationInvitationStatus.CANCELLED &&
invitation.expiresAt &&
invitation.expiresAt < new Date()
) {
throw new ConflictException(`Invitation with ID ${invitationId} is expired`)
}
if (invitation.status !== OrganizationInvitationStatus.PENDING) {
throw new ConflictException(`Invitation with ID ${invitationId} is already ${invitation.status}`)
}
invitation.status = newStatus
return invitation
}
}