Skip to content

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

1.6 KB
Raw Blame
/*
 * Copyright 2025 Daytona Platforms Inc.
 * Modified by BoxLite AI, 2025-2026
 * SPDX-License-Identifier: AGPL-3.0
 */

import { Injectable, ExecutionContext, Logger, CanActivate, Type, mixin } from '@nestjs/common'
import { ModuleRef } from '@nestjs/core'

export const OR_GUARD_INNER_GUARDS = Symbol('OR_GUARD_INNER_GUARDS')

/**
 * Creates an OrGuard that allows access if at least one of the provided guards allows access.
 * It tries each guard in sequence and returns true on the first successful guard.
 * If all guards fail, it returns false.
 *
 * Usage:
 * ```typescript
 * @UseGuards(OrGuard([GuardA, GuardB]))
 * ```
 */
export function OrGuard(guards: Type<CanActivate>[]): Type<CanActivate> {
  @Injectable()
  class OrGuardMixin implements CanActivate {
    protected readonly logger = new Logger(`OrGuard`)

    constructor(private readonly moduleRef: ModuleRef) {}

    async canActivate(context: ExecutionContext): Promise<boolean> {
      for (const GuardClass of guards) {
        try {
          const guard = this.moduleRef.get(GuardClass, { strict: false })
          const result = await guard.canActivate(context)

          if (result) {
            this.logger.debug(`Guard ${GuardClass.name} succeeded`)
            return true
          }
        } catch (error) {
          this.logger.debug(`Guard ${GuardClass.name} failed: ${error.message}`)
        }
      }

      this.logger.debug('All guards in OrGuard failed')
      return false
    }
  }

  const guardClass = OrGuardMixin as Type<CanActivate> & {
    [OR_GUARD_INNER_GUARDS]?: Type<CanActivate>[]
  }
  guardClass[OR_GUARD_INNER_GUARDS] = guards

  return mixin(guardClass)
}