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 {
ForbiddenException,
Injectable,
NotFoundException,
Logger,
OnModuleInit,
OnApplicationShutdown,
ConflictException,
BadRequestException,
} from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { InjectRedis } from '@nestjs-modules/ioredis'
import type Redis from 'ioredis'
import { EntityManager, In, Not, Repository } from 'typeorm'
import { CreateOrganizationInternalDto } from '../dto/create-organization.internal.dto'
import { Organization } from '../entities/organization.entity'
import { OrganizationUser } from '../entities/organization-user.entity'
import { OrganizationMemberRole } from '../enums/organization-member-role.enum'
import { APP_HOSTING_PERMISSIONS, OrganizationResourcePermission } from '../enums/organization-resource-permission.enum'
import { OnAsyncEvent } from '../../common/decorators/on-async-event.decorator'
import { UserEvents } from '../../user/constants/user-events.constant'
import { UserCreatedEvent } from '../../user/events/user-created.event'
import { UserDeletedEvent } from '../../user/events/user-deleted.event'
import { BoxState } from '../../box/enums/box-state.enum'
import { EventEmitter2 } from '@nestjs/event-emitter'
import { OrganizationEvents } from '../constants/organization-events.constant'
import { OrganizationUserRemovedEvent } from '../events/organization-user-removed.event'
import { UserEmailVerifiedEvent } from '../../user/events/user-email-verified.event'
import { Cron, CronExpression } from '@nestjs/schedule'
import { RedisLockProvider } from '../../box/common/redis-lock.provider'
import { OrganizationSuspendedBoxStoppedEvent } from '../events/organization-suspended-box-stopped.event'
import { BoxDesiredState } from '../../box/enums/box-desired-state.enum'
import { SystemRole } from '../../user/enums/system-role.enum'
import { TrackJobExecution } from '../../common/decorators/track-job-execution.decorator'
import { TrackableJobExecutions } from '../../common/interfaces/trackable-job-executions'
import { setTimeout } from 'timers/promises'
import { TypedConfigService } from '../../config/typed-config.service'
import { LogExecution } from '../../common/decorators/log-execution.decorator'
import { WithInstrumentation } from '../../common/decorators/otel.decorator'
import { RegionService } from '../../region/services/region.service'
import { Region } from '../../region/entities/region.entity'
import { RegionType } from '../../region/enums/region-type.enum'
import { EncryptionService } from '../../encryption/encryption.service'
import { OtelConfigDto } from '../dto/otel-config.dto'
import { boxLookupCacheKeyByAuthToken } from '../../box/utils/box-lookup-cache.util'
import { BoxRepository } from '../../box/repositories/box.repository'
import { Domain } from '../../box/entities/domain.entity'
@Injectable()
export class OrganizationService implements OnModuleInit, TrackableJobExecutions, OnApplicationShutdown {
private static readonly DEFAULT_ORGANIZATION_NAME = 'Default Organization'
private static readonly EMAIL_VERIFICATION_SUSPENSION_REASON = 'Please verify your email address'
activeJobs = new Set<string>()
private readonly logger = new Logger(OrganizationService.name)
@InjectRedis() private readonly redis: Redis
private defaultBoxLimitedNetworkEgress: boolean
constructor(
@InjectRepository(Organization)
private readonly organizationRepository: Repository<Organization>,
private readonly boxRepository: BoxRepository,
private readonly eventEmitter: EventEmitter2,
private readonly configService: TypedConfigService,
private readonly redisLockProvider: RedisLockProvider,
private readonly regionService: RegionService,
private readonly encryptionService: EncryptionService,
) {
this.defaultBoxLimitedNetworkEgress = this.configService.getOrThrow('organizationBoxDefaultLimitedNetworkEgress')
}
async onApplicationShutdown() {
// wait for all active jobs to finish
while (this.activeJobs.size > 0) {
this.logger.log(`Waiting for ${this.activeJobs.size} active jobs to finish`)
await setTimeout(1000)
}
}
async onModuleInit(): Promise<void> {
await this.stopSuspendedOrganizationBoxes()
}
async create(
createOrganizationDto: CreateOrganizationInternalDto,
createdBy: string,
defaultForCreator = false,
creatorEmailVerified = false,
): Promise<Organization> {
return this.createWithEntityManager(
this.organizationRepository.manager,
createOrganizationDto,
createdBy,
creatorEmailVerified,
defaultForCreator,
)
}
async findByUser(userId: string): Promise<Organization[]> {
return this.organizationRepository.find({
where: {
users: {
userId,
},
},
})
}
async findOne(organizationId: string): Promise<Organization | null> {
return this.organizationRepository.findOne({
where: { id: organizationId },
})
}
async getAppHostingPermissions(id: string): Promise<OrganizationResourcePermission[]> {
const org = await this.organizationRepository.findOne({
where: { id },
select: { appHostingPermissions: true },
cache: false,
})
if (!org) throw new NotFoundException('Organization not found')
return org.appHostingPermissions
}
async setAppHostingPermissions(id: string, requested: OrganizationResourcePermission[]) {
const after = APP_HOSTING_PERMISSIONS.filter((scope) => requested.includes(scope))
const before = await this.organizationRepository.manager.transaction(async (manager) => {
const org = await manager.findOne(Organization, {
where: { id },
select: { appHostingPermissions: true },
lock: { mode: 'pessimistic_write' },
})
if (!org) throw new NotFoundException('Organization not found')
await manager.update(Organization, id, { appHostingPermissions: after })
return org.appHostingPermissions
})
// Access decisions read Postgres. A cache eviction failure cannot undo the committed change.
await this.redis
.del(`organization:${id}`)
.catch((error) => this.logger.warn('Could not evict organization cache', error))
return { before, after }
}
async setNestedVirtualizationEnabled(organizationId: string, enabled: boolean): Promise<void> {
const result = await this.organizationRepository.update(organizationId, { nestedVirtualizationEnabled: enabled })
if (!result.affected) {
throw new NotFoundException(`Organization with ID ${organizationId} not found`)
}
}
async isNestedVirtualizationEnabled(organizationId: string): Promise<boolean> {
const organization = await this.organizationRepository.findOne({
where: { id: organizationId },
select: { id: true, nestedVirtualizationEnabled: true },
cache: false,
})
if (!organization) {
throw new NotFoundException(`Organization with ID ${organizationId} not found`)
}
return organization.nestedVirtualizationEnabled === true
}
async findByIds(organizationIds: string[]): Promise<Organization[]> {
if (organizationIds.length === 0) {
return []
}
return this.organizationRepository.find({
where: { id: In(organizationIds) },
})
}
async findByBoxId(boxId: string): Promise<Organization | null> {
const box = await this.boxRepository.findOne({
where: { id: boxId },
})
if (!box) {
return null
}
return this.organizationRepository.findOne({ where: { id: box.organizationId } })
}
async findByBoxAuthToken(authToken: string): Promise<Organization | null> {
const box = await this.boxRepository.findOne({
where: { authToken },
cache: {
id: boxLookupCacheKeyByAuthToken({ authToken }),
milliseconds: 10_000,
},
})
if (!box) {
return null
}
return this.organizationRepository.findOne({ where: { id: box.organizationId } })
}
async findDefaultForUser(userId: string): Promise<Organization> {
return this.findDefaultForUserWithEntityManager(this.organizationRepository.manager, userId)
}
async findByUserWithDefaultFlag(
userId: string,
): Promise<{ organization: Organization; isDefaultForAuthenticatedUser: boolean }[]> {
const memberships = await this.organizationRepository.manager.find(OrganizationUser, {
where: { userId },
relations: {
organization: true,
},
order: {
createdAt: 'ASC',
},
})
return memberships.map((membership) => ({
organization: membership.organization,
isDefaultForAuthenticatedUser: membership.isDefaultForUser,
}))
}
async delete(organizationId: string): Promise<void> {
const organization = await this.organizationRepository.findOne({ where: { id: organizationId } })
if (!organization) {
throw new NotFoundException(`Organization with ID ${organizationId} not found`)
}
return this.removeWithEntityManager(this.organizationRepository.manager, organization)
}
async updateName(organizationId: string, name: string): Promise<Organization> {
const organization = await this.organizationRepository.findOne({ where: { id: organizationId } })
if (!organization) {
throw new NotFoundException(`Organization with ID ${organizationId} not found`)
}
const trimmedName = name.trim()
if (!trimmedName) {
throw new BadRequestException('Organization name is required')
}
const saved = await this.organizationRepository.save({ id: organizationId, name: trimmedName })
return Object.assign(organization, saved)
}
async suspend(
organizationId: string,
suspensionReason?: string,
suspendedUntil?: Date,
suspensionCleanupGracePeriodHours?: number,
): Promise<void> {
const organization = await this.organizationRepository.findOne({ where: { id: organizationId } })
if (!organization) {
throw new NotFoundException(`Organization with ID ${organizationId} not found`)
}
await this.organizationRepository.save({
id: organizationId,
suspended: true,
suspensionReason: suspensionReason || null,
suspendedUntil: suspendedUntil || null,
suspendedAt: new Date(),
...(suspensionCleanupGracePeriodHours ? { suspensionCleanupGracePeriodHours } : {}),
})
}
/**
* @param organizationId - The ID of the organization.
* @param ifReason - When given, unsuspend only if the organization is currently suspended
* with exactly this reason. Omit for the unconditional admin unsuspend.
* @throws {NotFoundException} If the organization is not found.
* @throws {ConflictException} If ifReason is given and does not match the organization's
* current suspension reason — e.g. an admin re-suspended it for a different reason in the
* meantime. The organization is left untouched.
*/
async unsuspend(organizationId: string, ifReason?: string): Promise<void> {
const organization = await this.organizationRepository.findOne({ where: { id: organizationId } })
if (!organization) {
throw new NotFoundException(`Organization with ID ${organizationId} not found`)
}
// suspensionReason is free text an admin or support agent wrote, so it is never echoed
// back into the response — only that the caller's expectation didn't hold.
if (ifReason !== undefined && organization.suspensionReason !== ifReason) {
throw new ConflictException('Organization suspension reason does not match the expected reason')
}
await this.organizationRepository.save({
id: organizationId,
suspended: false,
suspensionReason: null,
suspendedUntil: null,
suspendedAt: null,
})
}
async updateBoxDefaultLimitedNetworkEgress(
organizationId: string,
boxDefaultLimitedNetworkEgress: boolean,
): Promise<void> {
const organization = await this.organizationRepository.findOne({ where: { id: organizationId } })
if (!organization) {
throw new NotFoundException(`Organization with ID ${organizationId} not found`)
}
await this.organizationRepository.save({
id: organizationId,
boxLimitedNetworkEgress: boxDefaultLimitedNetworkEgress,
})
}
/**
* @param organizationId - The ID of the organization.
* @param defaultRegionId - The ID of the region to set as the default region.
* @throws {NotFoundException} If the organization is not found.
* @throws {ConflictException} If the organization already has a default region set.
*/
async setDefaultRegion(organizationId: string, defaultRegionId: string): Promise<void> {
const organization = await this.organizationRepository.findOne({ where: { id: organizationId } })
if (!organization) {
throw new NotFoundException(`Organization with ID ${organizationId} not found`)
}
if (organization.defaultRegionId) {
throw new ConflictException('Organization already has a default region set')
}
await this.validateOrganizationDefaultRegion(defaultRegionId)
await this.organizationRepository.save({ id: organizationId, defaultRegionId })
}
async updateExperimentalConfig(
organizationId: string,
experimentalConfig: Record<string, any> | null,
): Promise<void> {
const organization = await this.organizationRepository.findOne({ where: { id: organizationId } })
if (!organization) {
throw new NotFoundException(`Organization with ID ${organizationId} not found`)
}
const existingConfig = organization._experimentalConfig
organization._experimentalConfig = await this.validatedExperimentalConfig(experimentalConfig)
// If experimentalConfig contains redacted fields, we need to preserve the existing encrypted values
if (experimentalConfig && experimentalConfig.otel && experimentalConfig.otel.headers) {
if (existingConfig && existingConfig.otel && existingConfig.otel.headers) {
for (const [key, value] of Object.entries(experimentalConfig.otel.headers)) {
if (
typeof value === 'string' &&
value.match(/\*/g)?.length === value.length &&
existingConfig.otel.headers[key]
) {
organization._experimentalConfig.otel.headers[key] = existingConfig.otel.headers[key]
}
}
}
}
await this.organizationRepository.save({
id: organizationId,
_experimentalConfig: organization._experimentalConfig,
})
}
async getOtelConfigByBoxAuthToken(boxAuthToken: string): Promise<OtelConfigDto | null> {
const organization = await this.findByBoxAuthToken(boxAuthToken)
if (!organization) {
return null
}
if (!organization._experimentalConfig || !organization._experimentalConfig.otel) {
return null
}
const otelConfig = organization._experimentalConfig.otel
const decryptedHeaders: Record<string, string> = {}
if (otelConfig.headers && typeof otelConfig.headers === 'object') {
for (const [key, value] of Object.entries(otelConfig.headers)) {
if (typeof key === 'string' && key.trim() && typeof value === 'string' && value.trim()) {
decryptedHeaders[key] = await this.encryptionService.decrypt(value)
}
}
}
return {
endpoint: otelConfig.endpoint,
headers: Object.keys(decryptedHeaders).length > 0 ? decryptedHeaders : undefined,
}
}
private async validatedExperimentalConfig(
experimentalConfig: Record<string, any> | null,
): Promise<Record<string, any> | null> {
if (!experimentalConfig) {
return null
}
if (!experimentalConfig.otel) {
return experimentalConfig
}
const otelConfig = { ...experimentalConfig.otel }
if (typeof otelConfig.endpoint !== 'string' || !otelConfig.endpoint.trim()) {
throw new ForbiddenException('Invalid OpenTelemetry endpoint')
}
if (otelConfig.headers && typeof otelConfig.headers === 'object') {
const headers: Record<string, string> = {}
for (const [key, value] of Object.entries(otelConfig.headers)) {
if (typeof key === 'string' && key.trim() && typeof value === 'string' && value.trim()) {
headers[key] = await this.encryptionService.encrypt(value)
}
}
otelConfig.headers = headers
} else {
otelConfig.headers = {}
}
return {
...experimentalConfig,
otel: otelConfig,
}
}
private async createWithEntityManager(
entityManager: EntityManager,
createOrganizationDto: CreateOrganizationInternalDto,
createdBy: string,
creatorEmailVerified: boolean,
defaultForCreator = false,
boxLimitedNetworkEgress: boolean = this.defaultBoxLimitedNetworkEgress,
): Promise<Organization> {
if (defaultForCreator) {
const count = await entityManager.count(OrganizationUser, {
where: {
userId: createdBy,
isDefaultForUser: true,
},
})
if (count > 0) {
throw new ForbiddenException('Default organization already exists for user')
}
}
// set some limit to the number of created organizations
const createdCount = await entityManager.count(Organization, {
where: { createdBy },
})
if (createdCount >= 10) {
throw new ForbiddenException('You have reached the maximum number of created organizations')
}
let organization = new Organization(createOrganizationDto.defaultRegionId)
organization.name = createOrganizationDto.name
organization.createdBy = createdBy
if (!creatorEmailVerified && !this.configService.get('skipUserEmailVerification')) {
organization.suspended = true
organization.suspendedAt = new Date()
organization.suspensionReason = OrganizationService.EMAIL_VERIFICATION_SUSPENSION_REASON
} else if (this.configService.get('requirePaymentMethod') && !defaultForCreator) {
// Gated on requirePaymentMethod, not on billingApiUrl: a stage can point the
// dashboard at a billing service without also demanding a card up front.
// Keyed off billingApiUrl, any deployed billing service that cannot register
// a payment method left every new organization suspended with no way out.
organization.suspended = true
organization.suspendedAt = new Date()
organization.suspensionReason = 'Payment method required'
}
organization.boxLimitedNetworkEgress = boxLimitedNetworkEgress
const owner = new OrganizationUser()
owner.userId = createdBy
owner.role = OrganizationMemberRole.OWNER
owner.isDefaultForUser = defaultForCreator
organization.users = [owner]
if (createOrganizationDto.defaultRegionId) {
await this.validateOrganizationDefaultRegion(createOrganizationDto.defaultRegionId)
}
await entityManager.transaction(async (em) => {
organization = await em.save(organization)
await this.eventEmitter.emitAsync(OrganizationEvents.CREATED, organization)
})
return organization
}
private async removeWithEntityManager(
entityManager: EntityManager,
organization: Organization,
force = false,
): Promise<void> {
await entityManager.transaction(async (manager) => {
// Claims lock this same row, so no new name can arrive between domain
// cleanup and organization removal. A failed removal restores both.
const current = await manager.findOne(Organization, {
where: { id: organization.id },
lock: { mode: 'pessimistic_write' },
})
if (!current) {
throw new NotFoundException(`Organization ${organization.id} not found`)
}
if (!force) {
const defaultMembershipsCount = await manager.count(OrganizationUser, {
where: { organizationId: organization.id, isDefaultForUser: true },
})
if (defaultMembershipsCount > 0) {
throw new ForbiddenException("Cannot delete an organization while it is a user's default organization")
}
}
// Keep exact cloud resource ownership after the organization disappears;
// explicit domain maintenance completes cleanup without needing a live subscription.
await manager.query(
`UPDATE custom_domain_config SET deleted_at = now(), phase = 'deleting',
dns_valid_until = '-infinity', next_check_at = now(), updated_at = now()
WHERE organization_id = $1 AND deleted_at IS NULL`,
[organization.id],
)
await manager.delete(Domain, { organizationId: organization.id })
await manager.remove(current)
})
}
private async unsuspendDefaultForUserWithEntityManager(entityManager: EntityManager, userId: string): Promise<void> {
const organization = await this.findDefaultForUserWithEntityManager(entityManager, userId)
// Email verification owns only the suspension it created. Billing, abuse,
// and administrator holds may have replaced that reason while the user was
// unverified and must survive this event.
if (
!organization.suspended ||
organization.suspensionReason !== OrganizationService.EMAIL_VERIFICATION_SUSPENSION_REASON
) {
return
}
await entityManager.save(Organization, {
id: organization.id,
suspended: false,
suspendedAt: null,
suspensionReason: null,
suspendedUntil: null,
})
}
private async findDefaultForUserWithEntityManager(
entityManager: EntityManager,
userId: string,
): Promise<Organization> {
const membership = await entityManager.findOne(OrganizationUser, {
where: {
userId,
isDefaultForUser: true,
},
relations: {
organization: true,
},
})
if (!membership?.organization) {
throw new NotFoundException(`Default organization for user ${userId} not found`)
}
return membership.organization
}
/**
* @throws NotFoundException - If the region is not found or not available to the organization
*/
async validateOrganizationDefaultRegion(defaultRegionId: string): Promise<Region> {
const region = await this.regionService.findOne(defaultRegionId)
if (!region || region.regionType !== RegionType.SHARED) {
throw new NotFoundException('Region not found')
}
return region
}
@Cron(CronExpression.EVERY_MINUTE, { name: 'stop-suspended-organization-boxes' })
@TrackJobExecution()
@LogExecution('stop-suspended-organization-boxes')
@WithInstrumentation()
async stopSuspendedOrganizationBoxes(): Promise<void> {
// lock the sync to only run one instance at a time
const lockKey = 'stop-suspended-organization-boxes'
if (!(await this.redisLockProvider.lock(lockKey, 60))) {
return
}
const queryResult = await this.organizationRepository
.createQueryBuilder('organization')
.select('id')
.where('suspended = true')
.andWhere(`"suspendedAt" < NOW() - INTERVAL '1 hour' * "suspensionCleanupGracePeriodHours"`)
.andWhere(`"suspendedAt" > NOW() - INTERVAL '7 day'`)
.andWhereExists(
this.boxRepository
.createQueryBuilder('box')
.select('1')
.where(
`"box"."organizationId" = "organization"."id" AND "box"."desiredState" = '${BoxDesiredState.STARTED}' and "box"."state" NOT IN ('${BoxState.ERROR}')`,
),
)
.take(100)
.getRawMany()
const suspendedOrganizationIds = queryResult.map((result) => result.id)
// Skip if no suspended organizations found to avoid empty IN clause
if (suspendedOrganizationIds.length === 0) {
await this.redisLockProvider.unlock(lockKey)
return
}
const boxes = await this.boxRepository.find({
where: {
organizationId: In(suspendedOrganizationIds),
desiredState: BoxDesiredState.STARTED,
state: Not(In([BoxState.ERROR])),
},
})
boxes.map((box) =>
this.eventEmitter.emitAsync(
OrganizationEvents.SUSPENDED_BOX_STOPPED,
new OrganizationSuspendedBoxStoppedEvent(box.id),
),
)
await this.redisLockProvider.unlock(lockKey)
}
// TODO(image-rewrite): deactivateSuspendedOrganizationTemplates cron removed with box_template;
// rebuild suspended-org template cleanup once the image/template model lands.
@OnAsyncEvent({
event: UserEvents.CREATED,
})
@TrackJobExecution()
async handleUserCreatedEvent(payload: UserCreatedEvent): Promise<Organization> {
return this.createWithEntityManager(
payload.entityManager,
{
name: OrganizationService.DEFAULT_ORGANIZATION_NAME,
defaultRegionId: payload.defaultOrganizationDefaultRegionId,
},
payload.user.id,
payload.user.role === SystemRole.ADMIN ? true : payload.user.emailVerified,
true,
payload.user.role === SystemRole.ADMIN ? false : undefined,
)
}
@OnAsyncEvent({
event: UserEvents.EMAIL_VERIFIED,
})
@TrackJobExecution()
async handleUserEmailVerifiedEvent(payload: UserEmailVerifiedEvent): Promise<void> {
await this.unsuspendDefaultForUserWithEntityManager(payload.entityManager, payload.userId)
}
@OnAsyncEvent({
event: UserEvents.DELETED,
})
@TrackJobExecution()
async handleUserDeletedEvent(payload: UserDeletedEvent): Promise<void> {
const organization = await this.findDefaultForUserWithEntityManager(payload.entityManager, payload.userId)
const removal = new OrganizationUserRemovedEvent(payload.entityManager, organization.id, payload.userId)
await this.eventEmitter.emitAsync(OrganizationEvents.USER_REMOVED, removal)
payload.afterCommit(() => removal.runAfterCommitTasks())
const membersCount = await payload.entityManager.count(OrganizationUser, {
where: {
organizationId: organization.id,
},
})
if (membersCount <= 1) {
await this.removeWithEntityManager(payload.entityManager, organization, true)
return
}
const deletedUserMembership = await payload.entityManager.findOne(OrganizationUser, {
where: {
organizationId: organization.id,
userId: payload.userId,
},
})
if (!deletedUserMembership) {
return
}
if (deletedUserMembership.role === OrganizationMemberRole.OWNER) {
const otherOwnersCount = await payload.entityManager.count(OrganizationUser, {
where: {
organizationId: organization.id,
role: OrganizationMemberRole.OWNER,
userId: Not(payload.userId),
},
})
if (otherOwnersCount === 0) {
const fallbackOwner = await payload.entityManager.findOne(OrganizationUser, {
where: {
organizationId: organization.id,
userId: Not(payload.userId),
},
order: {
createdAt: 'ASC',
},
})
if (fallbackOwner) {
fallbackOwner.role = OrganizationMemberRole.OWNER
await payload.entityManager.save(fallbackOwner)
}
}
}
await payload.entityManager.remove(deletedUserMembership)
}
assertOrganizationIsNotSuspended(organization: Organization): void {
if (!organization.suspended) {
return
}
// suspensionReason is free text an admin or support agent wrote and is never echoed back —
// it can carry details about a case (e.g. a fraud investigation) beyond "you are suspended".
if (organization.suspendedUntil ? organization.suspendedUntil > new Date() : true) {
throw new ForbiddenException('Organization is suspended')
}
}
}