The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
import { ForbiddenException, NotFoundException, ServiceUnavailableException } from '@nestjs/common'
import { IncomingMessage } from 'node:http'
import { Socket } from 'node:net'
import type { Duplex } from 'node:stream'
import { CloudAppService } from './cloud-app.service'
import type { EnvRow } from './engine/db'
import { sha256hex } from './engine/auth'
describe('hosted App platform contexts', () => {
function platform() {
const options = {
publicUrl: 'https://api.example.test/api/internal/apps',
supervisorUrl: 'https://guest.example.test',
artifactVersion: 'release',
artifactUrl: '',
runtimeImages: { node: 'node:test' },
startupTimeoutMs: 500,
buildTimeoutMs: 4000,
sessionSecret: 'local',
identityPrivateKey: '',
neon: {},
}
const settings = {
cloudApps: options,
'cloudApps.publicUrl': options.publicUrl,
'proxy.apiKey': 'proxy-test-key',
dashboardUrl: '',
}
const query = jest.fn()
const domains = { resolvePreview: jest.fn(), environmentUrl: jest.fn(async (env) => env.public_url) }
const orgs = { findOne: jest.fn(async (id: string) => ({ id })), assertOrganizationIsNotSuspended: jest.fn() }
const resources = {
forOrganization: jest.fn(),
boxesForOrganization: jest.fn(),
volumesForOrganization: jest.fn(),
tunnelHeaders: jest.fn().mockResolvedValue({ 'x-boxlite-access-token': 'tunnel-test-token' }),
}
const lease = { signal: new AbortController().signal, release: jest.fn() }
const acquireLease = jest.fn().mockResolvedValue(lease)
const service = new CloudAppService(
{ get: (name) => settings[name] } as never,
{ query } as never,
{} as never,
resources as never,
{} as never,
{} as never,
domains as never,
orgs as never,
{ acquireLease } as never,
)
return { service, settings, options, query, domains, orgs, resources, acquireLease, lease }
}
test('caches resources by organization and wires managed URLs, membership, and purge leases', async () => {
const h = platform()
await h.service.onModuleInit()
const ctx = h.service.context('org-a')
expect(h.service.context('org-a')).toBe(ctx)
expect(h.service.context('org-b')).not.toBe(ctx)
expect(h.resources.forOrganization.mock.calls).toEqual([['org-a'], ['org-b']])
expect(ctx.store.organizationId).toBe('org-a')
expect(ctx.config).toMatchObject({
managementUrl: 'https://api.example.test/api/v1/org-a',
artifactUrl: h.options.publicUrl + '/artifacts/release',
})
expect(ctx.timing).toMatchObject({ buildMs: 4000, supervisorReadyMs: 500, activateMs: 500 })
expect(ctx.origins.consoleUrl()).toBe('https://api.example.test')
h.settings.dashboardUrl = 'https://console.example.test'
expect(ctx.origins.consoleUrl()).toBe(h.settings.dashboardUrl)
expect(await ctx.origins.envUrl({ public_url: 'https://app.example.test' } as EnvRow)).toBe(
'https://app.example.test',
)
expect(await ctx.tunnelHeaders?.('https://box.example.test')).toMatchObject({
'x-boxlite-access-token': 'tunnel-test-token',
})
h.query.mockResolvedValueOnce([{ exists: 1 }]).mockResolvedValueOnce([])
expect(await ctx.organizationMember?.('org-a', 'github', '12')).toBe(true)
expect(await ctx.organizationMember?.('org-b', 'github', '12')).toBe(false)
expect(h.query.mock.calls.map(([, params]) => params)).toEqual([
['org-a', 'github|12'],
['org-b', 'github|12'],
])
await expect(ctx.withPurgeLock('app', async (signal) => signal === h.lease.signal)).resolves.toBe(true)
expect(h.acquireLease).toHaveBeenCalledWith('cloud-app:purge:app', 60)
expect(h.lease.release).toHaveBeenCalledTimes(1)
h.acquireLease.mockResolvedValueOnce(null)
await expect(ctx.withPurgeLock('app', jest.fn())).rejects.toThrow('already in progress')
h.options.publicUrl = ''
expect(() => h.service.context('disabled')).toThrow(ServiceUnavailableException)
})
test('management and supervisor requests enter the server with their own authentication', async () => {
const h = platform()
const ctx = h.service.context('org-a')
jest.spyOn(ctx.store, 'apps').mockResolvedValue([])
const principal = { organizationId: 'org-a', userId: 'owner', actor: 'user:owner', permissions: ['read:apps'] }
const listing = await h.service.management(new Request('https://api.example.test/v1/apps'), principal)
expect(listing.status).toBe(200)
expect(await listing.json()).toEqual([])
const internal = await h.service.internal(new Request('https://api.example.test/sv/v1/spec'), 'org-a')
expect(internal.status).toBe(401)
h.query.mockResolvedValueOnce([{ org_id: 'org-a' }]).mockResolvedValueOnce([])
expect(await h.service.supervisorOrganization('box-token')).toBe('org-a')
expect(h.query).toHaveBeenCalledWith(expect.stringContaining('revoked_at IS NULL'), [sha256hex('box-token')])
await expect(h.service.supervisorOrganization('revoked-token')).rejects.toThrow(ForbiddenException)
})
test('resolves the normalized domain or matching preview and checks organization status before ingress', async () => {
const h = platform()
await expect(h.service.ingressContext('env', 'example.test', undefined)).rejects.toThrow(ForbiddenException)
expect(h.query).not.toHaveBeenCalled()
h.query.mockResolvedValueOnce([{ org_id: 'org-a' }]).mockResolvedValue([])
const known = await h.service.ingressContext('env', 'APP.EXAMPLE.TEST.:443', 'proxy-test-key')
expect(known.store.organizationId).toBe('org-a')
expect(h.query).toHaveBeenCalledWith(expect.stringContaining('d.hostname = $2'), ['env', 'app.example.test'])
expect(h.domains.resolvePreview).not.toHaveBeenCalled()
h.domains.resolvePreview.mockResolvedValue({ environmentId: 'preview', organizationId: 'org-b' })
expect(
(await h.service.ingressContext('preview', 'preview.example.test', 'proxy-test-key')).store.organizationId,
).toBe('org-b')
await expect(h.service.ingressContext('other', 'preview.example.test', 'proxy-test-key')).rejects.toThrow(
NotFoundException,
)
expect(h.orgs.assertOrganizationIsNotSuspended.mock.calls).toEqual([[{ id: 'org-a' }], [{ id: 'org-b' }]])
})
test('strips the internal proxy token and ingress prefix before HTTP and socket dispatch', async () => {
const h = platform()
const ctx = h.service.context('org')
const env = { id: 'env', app_id: 'app' } as EnvRow
jest.spyOn(ctx.store, 'envById').mockResolvedValueOnce(undefined).mockResolvedValue(env)
jest.spyOn(ctx.store, 'appById').mockResolvedValue({ id: 'app', deleted_at: '2026-03-01' } as never)
h.query.mockResolvedValue([{ org_id: 'org' }])
const request = new Request('https://site.example.test/path', {
headers: { 'x-boxlite-proxy-token': 'proxy-test-key' },
})
const incoming = () =>
Object.assign(new IncomingMessage(new Socket()), {
headers: { host: 'site.example.test', 'x-boxlite-proxy-token': 'proxy-test-key' },
url: '/api/internal/apps/ingress/env/path?q=1',
})
await expect(h.service.ingress(request, env.id, incoming())).rejects.toThrow(NotFoundException)
expect((await h.service.ingress(request, env.id, incoming())).status).toBe(410)
expect(request.headers.has('x-boxlite-proxy-token')).toBe(false)
const upgrade = incoming()
const socket = { end: jest.fn() }
await h.service.upgradeIngress(upgrade, socket as unknown as Duplex, Buffer.alloc(0), env.id)
expect(upgrade.url).toBe('/path?q=1')
expect(upgrade.headers['x-boxlite-proxy-token']).toBeUndefined()
expect(socket.end).toHaveBeenCalledWith(expect.stringContaining('404 Not Found'))
})
})