Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

15.8 KB
Raw Blame
import { Request } from 'express'
/*
 * Copyright 2025 Daytona Platforms Inc.
 * Modified by BoxLite AI, 2025-2026
 * SPDX-License-Identifier: AGPL-3.0
 */

import {
  Controller,
  Req,
  Get,
  Post,
  Body,
  Param,
  Query,
  Logger,
  UseGuards,
  HttpCode,
  UseInterceptors,
  Put,
} from '@nestjs/common'
import { CombinedAuthGuard } from '../../auth/combined-auth.guard'
import { BoxService } from '../services/box.service'
import {
  ApiOAuth2,
  ApiResponse,
  ApiQuery,
  ApiOperation,
  ApiParam,
  ApiTags,
  ApiHeader,
  ApiBearerAuth,
} from '@nestjs/swagger'
import { BoxDto } from '../dto/box.dto'
import { UpdateBoxStateDto } from '../dto/update-box-state.dto'
import { PaginatedBoxesDto } from '../dto/paginated-boxes.dto'
import { RunnerService } from '../services/runner.service'
import { RunnerAuthGuard } from '../../auth/runner-auth.guard'
import { RunnerContextDecorator } from '../../common/decorators/runner-context.decorator'
import { RunnerContext } from '../../common/interfaces/runner-context.interface'
import { BoxState } from '../enums/box-state.enum'
import { Box } from '../entities/box.entity'
import { ContentTypeInterceptor } from '../../common/interceptors/content-type.interceptors'
import { BoxAccessGuard } from '../guards/box-access.guard'
import { CustomHeaders } from '../../common/constants/header.constants'
import { AuthContext } from '../../common/decorators/auth-context.decorator'
import { UserContext } from '../../common/decorators/user-context.decorator'
import { Context } from '../../common/context/context'
import { OrganizationAuthContext, AuthContextType } from '../../common/interfaces/auth-context.interface'
import { isProxyContext } from '../../common/interfaces/proxy-context.interface'
import { RequiredOrganizationResourcePermissions } from '../../organization/decorators/required-organization-resource-permissions.decorator'
import { OrganizationResourcePermission } from '../../organization/enums/organization-resource-permission.enum'
import { OrganizationResourceActionGuard } from '../../organization/guards/organization-resource-action.guard'
import { BadRequestError } from '../../exceptions/bad-request.exception'
import { BoxStateUpdatedEvent } from '../events/box-state-updated.event'
import { Audit, AUDIT_TARGET_ID } from '../../audit/decorators/audit.decorator'
import { AuditAction } from '../../audit/enums/audit-action.enum'
import { AuditTarget } from '../../audit/enums/audit-target.enum'
// import { UpdateBoxNetworkSettingsDto } from '../dto/update-box-network-settings.dto'
import { ListBoxesQueryDto } from '../dto/list-boxes-query.dto'
import { ProxyGuard } from '../guards/proxy.guard'
import { OrGuard } from '../../auth/or.guard'
import { AuthenticatedRateLimitGuard } from '../../common/guards/authenticated-rate-limit.guard'
import { SkipThrottle } from '@nestjs/throttler'
import { ThrottlerScope } from '../../common/decorators/throttler-scope.decorator'
import { AttachTicketDto, CreateAttachTicketDto } from '../dto/attach-ticket.dto'
import { ATTACH_TICKET_TTL_SECONDS, AttachTicketService } from '../services/attach-ticket.service'
import { InjectRedis } from '@nestjs-modules/ioredis'
import { Redis } from 'ioredis'
import { BOX_EVENT_CHANNEL } from '../../common/constants/constants'
import { RegionBoxAccessGuard } from '../guards/region-box-access.guard'

@ApiTags('box')
@Controller('box')
@ApiHeader(CustomHeaders.ORGANIZATION_ID)
@UseGuards(CombinedAuthGuard, OrganizationResourceActionGuard, AuthenticatedRateLimitGuard)
@ApiOAuth2(['openid', 'profile', 'email'])
@ApiBearerAuth()
export class BoxController {
  private readonly logger = new Logger(BoxController.name)
  private readonly boxCallbacks: Map<string, (event: BoxStateUpdatedEvent) => void> = new Map()
  private readonly redisSubscriber: Redis
  constructor(
    private readonly runnerService: RunnerService,
    private readonly boxService: BoxService,
    @InjectRedis() private readonly redis: Redis,
    private readonly attachTickets: AttachTicketService,
  ) {
    this.redisSubscriber = this.redis.duplicate()
    this.redisSubscriber.subscribe(BOX_EVENT_CHANNEL)
    this.redisSubscriber.on('message', (channel, message) => {
      if (channel !== BOX_EVENT_CHANNEL) {
        return
      }

      try {
        const event = JSON.parse(message) as BoxStateUpdatedEvent
        this.handleBoxStateUpdated(event)
      } catch (error) {
        this.logger.error('Failed to parse box state updated event:', error)
        return
      }
    })
  }

  @Get('paginated')
  @ApiOperation({
    summary: 'List all boxes paginated',
    operationId: 'listBoxesPaginated',
  })
  @ApiResponse({
    status: 200,
    description: 'Paginated list of all boxes',
    type: PaginatedBoxesDto,
  })
  async listBoxesPaginated(
    @AuthContext() authContext: OrganizationAuthContext,
    @Query() queryParams: ListBoxesQueryDto,
  ): Promise<PaginatedBoxesDto> {
    const {
      page,
      limit,
      id,
      name,
      labels,
      includeErroredDeleted: includeErroredDestroyed,
      states,
      regions,
      minCpu,
      maxCpu,
      minMemoryGiB,
      maxMemoryGiB,
      minDiskGiB,
      maxDiskGiB,
      lastEventAfter,
      lastEventBefore,
      sort: sortField,
      order: sortDirection,
    } = queryParams

    const result = await this.boxService.findAll(
      authContext.organizationId,
      page,
      limit,
      {
        id,
        name,
        labels: labels ? JSON.parse(labels) : undefined,
        includeErroredDestroyed,
        states,
        regionIds: regions,
        minCpu,
        maxCpu,
        minMemoryGiB,
        maxMemoryGiB,
        minDiskGiB,
        maxDiskGiB,
        lastEventAfter,
        lastEventBefore,
      },
      {
        field: sortField,
        direction: sortDirection,
      },
    )

    return {
      items: await this.boxService.toBoxDtos(result.items),
      total: result.total,
      page: result.page,
      totalPages: result.totalPages,
    }
  }

  @Get('for-runner')
  @UseGuards(RunnerAuthGuard)
  @ApiOperation({
    summary: 'Get boxes for the authenticated runner',
    operationId: 'getBoxesForRunner',
  })
  @ApiQuery({
    name: 'states',
    required: false,
    type: String,
    description: 'Comma-separated list of box states to filter by',
  })
  @ApiQuery({
    name: 'skipReconcilingBoxes',
    required: false,
    type: Boolean,
    description: 'Skip boxes where state differs from desired state',
  })
  @ApiResponse({
    status: 200,
    description: 'List of boxes for the authenticated runner',
    type: [BoxDto],
  })
  async getBoxesForRunner(
    @RunnerContextDecorator() runnerContext: RunnerContext,
    @Query('states') states?: string,
    @Query('skipReconcilingBoxes') skipReconcilingBoxes?: string,
  ): Promise<BoxDto[]> {
    const stateArray = states
      ? states.split(',').map((s) => {
          if (!Object.values(BoxState).includes(s as BoxState)) {
            throw new BadRequestError(`Invalid box state: ${s}`)
          }
          return s as BoxState
        })
      : undefined

    const skip = skipReconcilingBoxes === 'true'
    const boxes = await this.boxService.findByRunnerId(runnerContext.runnerId, stateArray, skip)

    return this.boxService.toBoxDtos(boxes)
  }

  @Get(':boxIdOrName')
  @ApiOperation({
    summary: 'Get box details',
    operationId: 'getBox',
  })
  @ApiParam({
    name: 'boxIdOrName',
    description: 'ID or name of the box',
    type: 'string',
  })
  @ApiQuery({
    name: 'verbose',
    required: false,
    type: Boolean,
    description: 'Include verbose output',
  })
  @ApiResponse({
    status: 200,
    description: 'Box details',
    type: BoxDto,
  })
  @UseGuards(BoxAccessGuard)
  async getBox(
    @AuthContext() authContext: OrganizationAuthContext,
    @Param('boxIdOrName') boxIdOrName: string,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    @Query('verbose') verbose?: boolean,
  ): Promise<BoxDto> {
    const box = await this.boxService.findOneByIdOrName(boxIdOrName, authContext.organizationId)

    return this.boxService.toBoxDtoWithExitCode(box)
  }

  @Post(':boxIdOrName/recover')
  @HttpCode(200)
  @SkipThrottle({ authenticated: true })
  @ThrottlerScope('box-lifecycle')
  @ApiOperation({
    summary: 'Recover box from error state',
    operationId: 'recoverBox',
  })
  @ApiParam({
    name: 'boxIdOrName',
    description: 'ID or name of the box',
    type: 'string',
  })
  @ApiResponse({
    status: 200,
    description: 'Recovery initiated',
    type: BoxDto,
  })
  @RequiredOrganizationResourcePermissions([OrganizationResourcePermission.WRITE_BOXES])
  @UseGuards(BoxAccessGuard)
  @Audit({
    action: AuditAction.RECOVER,
    targetType: AuditTarget.BOX,
    targetIdFromRequest: (req) => req.params.boxIdOrName,
    targetIdFromResult: (result: BoxDto) => result?.id,
  })
  async recoverBox(
    @AuthContext() authContext: OrganizationAuthContext,
    @Param('boxIdOrName') boxIdOrName: string,
    @UserContext() ctx: Context,
    @Req() request?: Request,
  ): Promise<BoxDto> {
    const recoveredBox = await this.boxService.recover(boxIdOrName, authContext.organization, ctx)
    if (request) request[AUDIT_TARGET_ID] = recoveredBox.id
    let boxDto = await this.boxService.toBoxDto(recoveredBox)

    if (boxDto.state !== BoxState.STARTED) {
      boxDto = await this.waitForBoxStarted(boxDto, 30)
    }

    return boxDto
  }

  @Put(':boxId/state')
  @UseInterceptors(ContentTypeInterceptor)
  @ApiOperation({
    summary: 'Update box state',
    operationId: 'updateBoxState',
  })
  @ApiParam({
    name: 'boxId',
    description: 'ID of the box',
    type: 'string',
  })
  @ApiResponse({
    status: 200,
    description: 'Box state has been successfully updated',
  })
  @UseGuards(RunnerAuthGuard)
  @UseGuards(BoxAccessGuard)
  async updateBoxState(@Param('boxId') boxId: string, @Body() updateStateDto: UpdateBoxStateDto): Promise<void> {
    await this.boxService.updateState(
      boxId,
      updateStateDto.state,
      updateStateDto.recoverable,
      updateStateDto.errorReason,
      // The two travel together; a report carrying a digest without a size is
      // malformed, and recording 0 for it says the same thing a manifest that
      // declared no layer sizes says.
      updateStateDto.imageDigest !== undefined
        ? { digest: updateStateDto.imageDigest, sizeBytes: updateStateDto.imageSizeBytes ?? 0 }
        : undefined,
    )
  }

  @Post(':boxId/last-activity')
  @ApiOperation({
    summary: 'Update box last activity',
    operationId: 'updateLastActivity',
  })
  @ApiParam({
    name: 'boxId',
    description: 'ID of the box',
    type: 'string',
  })
  @ApiResponse({
    status: 201,
    description: 'Last activity has been updated',
  })
  @UseGuards(OrGuard([BoxAccessGuard, ProxyGuard, RegionBoxAccessGuard]))
  async updateLastActivity(
    @Param('boxId') boxId: string,
    @AuthContext() authContext: AuthContextType,
    @Req() request: Request,
  ): Promise<void> {
    if (request.headers['x-boxlite-preview-open'] === '1' && authContext && isProxyContext(authContext)) {
      await this.boxService.updateLastActivityAt(boxId, new Date(), true)
      return
    }
    await this.boxService.updateLastActivityAt(boxId, new Date())
  }

  // TODO: Network settings endpoint will not be enabled for now
  // @Post(':boxIdOrName/network-settings')
  // @ApiOperation({
  //   summary: 'Update box network settings',
  //   operationId: 'updateNetworkSettings',
  // })
  // @ApiParam({
  //   name: 'boxIdOrName',
  //   description: 'ID or name of the box',
  //   type: 'string',
  // })
  // @ApiResponse({
  //   status: 200,
  //   description: 'Network settings have been updated',
  //   type: BoxDto,
  // })
  // @RequiredOrganizationResourcePermissions([OrganizationResourcePermission.WRITE_BOXES])
  // @UseGuards(BoxAccessGuard)
  // @Audit({
  //   action: AuditAction.UPDATE_NETWORK_SETTINGS,
  //   targetType: AuditTarget.BOX,
  //   targetIdFromRequest: (req) => req.params.boxIdOrName,
  //   targetIdFromResult: (result: BoxDto) => result?.id,
  //   requestMetadata: {
  //     body: (req: TypedRequest<UpdateBoxNetworkSettingsDto>) => ({
  //       outboundEnabled: req.body?.outboundEnabled,
  //       outboundAllowNet: req.body?.outboundAllowNet,
  //     }),
  //   },
  // })
  // async updateNetworkSettings(
  //   @AuthContext() authContext: OrganizationAuthContext,
  //   @Param('boxIdOrName') boxIdOrName: string,
  //   @Body() networkSettings: UpdateBoxNetworkSettingsDto,
  // ): Promise<BoxDto> {
  //   const box = await this.boxService.updateNetworkSettings(
  //     boxIdOrName,
  //     networkSettings.outboundEnabled,
  //     networkSettings.outboundAllowNet,
  //     authContext.organizationId,
  //   )
  //   return BoxDto.fromBox(box)
  // }

  // A browser cannot set `Authorization` on a WebSocket, so the dashboard trades
  // its bearer here for a ticket the `/v1` attach upgrade accepts as `?ticket=`
  // (see BoxliteWsProxyService). It lives on the cloud API, not the Box API,
  // because only the cloud serves browsers. Requires write:boxes, like exec.
  @Post(':boxIdOrName/attach-tickets')
  @HttpCode(200)
  @ApiOperation({
    summary: 'Get a one-time ticket for the attach WebSocket',
    operationId: 'createAttachTicket',
  })
  @ApiParam({
    name: 'boxIdOrName',
    description: 'ID or name of the box',
    type: 'string',
  })
  @ApiResponse({
    status: 200,
    description: 'A single-use ticket for one attach upgrade to the execution',
    type: AttachTicketDto,
  })
  @RequiredOrganizationResourcePermissions([OrganizationResourcePermission.WRITE_BOXES])
  @UseGuards(BoxAccessGuard)
  @Audit({
    action: AuditAction.ISSUE_ATTACH_TICKET,
    targetType: AuditTarget.BOX,
    targetIdFromRequest: (req) => req.params.boxIdOrName,
    requestMetadata: {
      executionId: (req) => (typeof req.body?.executionId === 'string' ? req.body.executionId : null),
    },
  })
  async createAttachTicket(
    @AuthContext() authContext: OrganizationAuthContext,
    @Param('boxIdOrName') boxIdOrName: string,
    @Body() dto: CreateAttachTicketDto,
    @Req() request?: Request,
  ): Promise<AttachTicketDto> {
    const box = await this.boxService.findOneByIdOrName(boxIdOrName, authContext.organizationId)
    if (request) request[AUDIT_TARGET_ID] = box.id
    const ticket = await this.attachTickets.issue({
      userId: authContext.userId,
      organizationId: authContext.organizationId,
      boxId: box.id,
      execId: dto.executionId,
      apiKeyHash: authContext.apiKey?.keyHash,
    })
    return { ticket, expiresIn: ATTACH_TICKET_TTL_SECONDS }
  }

  // wait up to `timeoutSeconds` for the box to start; if it doesn’t, return current box
  private async waitForBoxStarted(box: BoxDto, timeoutSeconds: number): Promise<BoxDto> {
    let latestBox: Box
    const waitForStarted = new Promise<BoxDto>((resolve, reject) => {
      let timeout: NodeJS.Timeout
      const handleStateUpdated = (event: BoxStateUpdatedEvent) => {
        if (event.box.id !== box.id) {
          return
        }
        latestBox = event.box
        if (event.box.state === BoxState.STARTED) {
          this.boxCallbacks.delete(box.id)
          clearTimeout(timeout)
          resolve(this.boxService.toBoxDto(event.box))
        }
        if (event.box.state === BoxState.ERROR) {
          this.boxCallbacks.delete(box.id)
          clearTimeout(timeout)
          reject(new BadRequestError(`Box failed to start: ${event.box.errorReason}`))
        }
      }

      this.boxCallbacks.set(box.id, handleStateUpdated)

      timeout = setTimeout(() => {
        this.boxCallbacks.delete(box.id)
        if (latestBox) {
          resolve(this.boxService.toBoxDto(latestBox))
        } else {
          resolve(box)
        }
      }, timeoutSeconds * 1000)
    })

    return waitForStarted
  }

  private handleBoxStateUpdated(event: BoxStateUpdatedEvent) {
    const callback = this.boxCallbacks.get(event.box.id)
    if (callback) {
      callback(event)
    }
  }
}