The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
import { createServer } from 'node:http'
import { AddressInfo } from 'node:net'
import { Writable } from 'node:stream'
import { ForbiddenException, INestApplication, ValidationPipe } from '@nestjs/common'
import { Test } from '@nestjs/testing'
import { logs as otelLogs } from '@opentelemetry/api-logs'
import { InMemoryLogRecordExporter, LoggerProvider, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs'
import { generateKeyPair, exportJWK, SignJWT } from 'jose'
import { Logger as PinoLogger, LoggerModule } from 'nestjs-pino'
import { JwtStrategy } from '../auth/jwt.strategy'
import { swapMessageAndObject } from '../common/utils/pino.util'
import { ConsoleAnalyticsController } from './console-analytics.controller'
import { AnalyticsConsentService } from './services/analytics-consent.service'
import { AnalyticsService } from './services/analytics.service'
// Exercise the same Pino instrumentation used by the API bootstrap.
jest.mock('pino', () => {
const { PinoInstrumentation } = jest.requireActual('@opentelemetry/instrumentation-pino')
const [definition] = new PinoInstrumentation().getModuleDefinitions()
return definition.patch(jest.requireActual('pino'), jest.requireActual('pino/package.json').version)
})
describe('Console analytics HTTP boundary', () => {
const org = 'a98b01ab-0a84-4b06-955a-2cfacf733f09'
const capture = jest.fn()
const analytics = { capture, enabled: true }
const logs: string[] = []
const exporter = new InMemoryLogRecordExporter()
const provider = new LoggerProvider({ processors: [new SimpleLogRecordProcessor(exporter)] })
const decide = jest.fn(async (_id: string, allowed: boolean) => ({ allowed }))
const consent = {
claimSignupOrganization: jest.fn(async (): Promise<string | undefined> => undefined),
decide,
preference: jest.fn(async () => ({ allowed: true })),
consolePreference: jest.fn(async () => ({ allowed: true, enabledFrom: null })),
requireMember: jest.fn(async (id, organization) => {
if (id !== 'member' || organization !== org) throw new ForbiddenException()
}),
}
const jwks = createServer()
let app: INestApplication
let base: string
let bearer: string
const request = (path: string, method: string, token?: string, body?: unknown) =>
fetch(base + path, {
method,
headers: { 'Content-Type': 'application/json', ...(token && { Authorization: 'Bearer ' + token }) },
...(body !== undefined && { body: JSON.stringify(body) }),
})
beforeAll(async () => {
otelLogs.setGlobalLoggerProvider(provider)
const keys = await generateKeyPair('RS256')
const jwk = { ...(await exportJWK(keys.publicKey)), kid: 'test', alg: 'RS256', use: 'sig' }
jwks.on('request', (_req, res) =>
res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ keys: [jwk] })),
)
await new Promise<void>((r) => jwks.listen(0, '127.0.0.1', r))
const issuer = 'http://127.0.0.1:' + (jwks.address() as AddressInfo).port + '/'
const strategy = new JwtStrategy(
{ issuer, audience: 'api', jwksUri: issuer + 'jwks' },
{ findOne: async () => ({ id: 'member', emailVerified: true }) } as never,
{ get: () => undefined } as never,
{ recordFirstUse: async () => {} } as never,
)
bearer = await new SignJWT({})
.setProtectedHeader({ alg: 'RS256', kid: 'test' })
.setSubject('member')
.setAudience('api')
.setIssuer(issuer)
.setExpirationTime('5m')
.sign(keys.privateKey)
const module = await Test.createTestingModule({
imports: [
LoggerModule.forRoot({
pinoHttp: [
{
autoLogging: false,
quietReqLogger: true,
hooks: { logMethod: swapMessageAndObject },
},
new Writable({
write: (chunk, _encoding, done) => {
logs.push(chunk.toString())
done()
},
}),
],
}),
],
controllers: [ConsoleAnalyticsController],
providers: [
{ provide: JwtStrategy, useValue: strategy },
{ provide: AnalyticsConsentService, useValue: consent },
{ provide: AnalyticsService, useValue: analytics },
],
}).compile()
app = module.createNestApplication()
app.useLogger(app.get(PinoLogger))
app.useGlobalPipes(new ValidationPipe({ transform: true }))
await app.listen(0, '127.0.0.1')
base = await app.getUrl()
})
afterAll(async () => {
await app?.close()
await provider.shutdown()
otelLogs.disable()
await new Promise<void>((r) => jwks.close(() => r()))
})
it('attributes an eligible signup once by identity and rejects incomplete or expired evidence', async () => {
const path = '/analytics/signup-source'
const input = {
source: 'www.linkedin.com',
kind: 'referrer',
enteredAt: new Date(Date.now() - 60_000).toISOString(),
}
expect((await request(path, 'POST', undefined, input)).status).toBe(401)
expect(
(await request(path, 'POST', bearer, { ...input, source: 'https://www.linkedin.com/private-path' })).status,
).toBe(400)
expect(
(await request(path, 'POST', bearer, { ...input, enteredAt: new Date(Date.now() + 60_000).toISOString() }))
.status,
).toBe(204)
expect((await request(path, 'POST', bearer, { ...input, medium: 'bad label' })).status).toBe(400)
const utm = {
...input,
source: 'LinkedIn',
kind: 'utm',
medium: 'social',
campaign: 'winter_26',
content: 'private-content',
}
analytics.enabled = false
try {
expect((await request(path, 'POST', bearer, { ...input, enteredAt: '2000-01-01T00:00:00Z' })).status).toBe(204)
expect((await request(path, 'POST', bearer, utm)).status).toBe(204)
} finally {
analytics.enabled = true
}
expect(consent.claimSignupOrganization).not.toHaveBeenCalled()
expect(capture).not.toHaveBeenCalled()
expect((await request(path, 'POST', bearer, input)).status).toBe(204)
expect(capture).not.toHaveBeenCalled()
const signupLogs = logs
.flatMap((line) => line.trim().split('\n'))
.map((line) => JSON.parse(line))
.filter((entry) => entry['event.name'] === 'signup.attribution')
const hostReceipt = { outcome: 'received', 'signup.source_type': 'referrer', 'signup.source': 'www.linkedin.com' }
expect(signupLogs).toMatchObject([
{ outcome: 'skipped', reason: 'invalid_source' },
hostReceipt,
{ outcome: 'skipped', reason: 'invalid_entry_time' },
hostReceipt,
{ outcome: 'skipped', reason: 'expired_entry_time' },
{
outcome: 'received',
'signup.source': 'linkedin',
'signup.source_type': 'utm',
'signup.medium': 'social',
'signup.campaign': 'winter_26',
},
{ outcome: 'skipped', reason: 'analytics_disabled' },
hostReceipt,
{ outcome: 'skipped', reason: 'claim_not_accepted' },
])
const otlp = exporter
.getFinishedLogRecords()
.map((entry) => entry.attributes)
.filter((fields) => fields['event.name'] === 'signup.attribution')
const receiptFields = (rows: Record<string, unknown>[]) =>
rows
.filter((row) => row.outcome === 'received')
.map((row) => Object.fromEntries(Object.entries(row).filter(([key]) => key.startsWith('signup.'))))
expect(receiptFields(otlp)).toEqual(receiptFields(signupLogs))
expect(JSON.stringify([...signupLogs, ...otlp])).not.toMatch(/private-content|private-path/)
consent.claimSignupOrganization.mockResolvedValueOnce(org)
const midnight = new Date().setUTCHours(0, 0, 0, 0)
const source = { ...input, enteredAt: new Date(midnight - 60_000).toISOString() }
const clock = jest.spyOn(Date, 'now')
try {
for (const receivedAt of [midnight - 1, midnight + 1]) {
clock.mockReturnValue(receivedAt)
expect((await request(path, 'POST', bearer, source)).status).toBe(204)
}
} finally {
clock.mockRestore()
}
expect(
exporter.getFinishedLogRecords().filter((entry) => entry.body === 'signup.attribution received'),
).toHaveLength(6)
expect(consent.claimSignupOrganization).toHaveBeenCalledTimes(3)
const entries = capture.mock.calls.splice(0)
expect(entries).toHaveLength(1)
const event = entries[0][0]
expect(event).toMatchObject({
event: 'signup_attributed',
distinctId: 'member',
groups: { organization: org },
uuid: expect.any(String),
properties: { 'signup.source': 'www.linkedin.com', 'signup.source_type': 'referrer' },
})
expect(entries[0][1]).toEqual({ users: ['member'], organizations: [org] })
})
it('uses the authenticated person and rejects unsupported notice versions and service tokens', async () => {
for (const credential of [undefined, 'service-api-key']) {
expect((await request('/analytics/consent', 'PUT', credential, { allowed: true, version: 1 })).status).toBe(401)
}
expect((await request('/analytics/consent', 'PUT', bearer, { allowed: true, version: 90 })).status).toBe(400)
expect(decide).not.toHaveBeenCalled()
expect(
(await request('/analytics/consent', 'PUT', bearer, { allowed: false, version: 1, userId: 'outsider' })).status,
).toBe(200)
expect(decide).toHaveBeenCalledWith('member', false)
})
it('accepts only known templates and controls for the member’s organization', async () => {
const events = '/analytics/organizations/' + org + '/console-events'
const page = { event: '$pageview', page: '/dashboard/boxes', occurredAt: new Date().toISOString() }
expect((await request(events, 'POST', undefined, page)).status).toBe(401)
expect(
(await request(events.replace(org, 'ae7cc449-a06a-43f3-a8db-8a52ff6dfd1e'), 'POST', bearer, page)).status,
).toBe(403)
expect(
(await request(events, 'POST', bearer, { ...page, page: '/dashboard/boxes/secret?token=secret' })).status,
).toBe(400)
expect((await request(events, 'POST', bearer, { ...page, page: '/dashboard/user/account-settings' })).status).toBe(
400,
)
expect((await request(events, 'POST', bearer, { ...page, event: 'console_control_click' })).status).toBe(400)
expect(capture).not.toHaveBeenCalled()
expect(
(await request(events, 'POST', bearer, { ...page, rawText: 'private', distinctId: 'outsider' })).status,
).toBe(204)
expect(capture).toHaveBeenCalledWith(
expect.objectContaining({ distinctId: 'member', properties: { $pathname: page.page } }),
{ users: ['member'], organizations: [org] },
)
})
it('admits only scoped onboarding actions, controls, and selections', async () => {
const path = '/analytics/organizations/' + org + '/console-events'
const base = { event: 'console_onboarding_step', occurredAt: new Date().toISOString() }
const welcome = { ...base, page: '/dashboard/welcome', action: 'org_create_started' }
const quickstart = { ...base, page: '/dashboard/quickstart' }
const starter = { ...base, page: '/dashboard/billing/plan/:planId', action: 'starter_sub_click', control: 'button' }
const selections = [
{ ...quickstart, action: 'quickstart_deploy_mode_selected', control: 'button', selection: 'sdk_cli' },
{ ...quickstart, action: 'quickstart_sdk_tab_selected', control: 'tab', selection: 'typescript' },
{ ...quickstart, action: 'quickstart_template_selected', control: 'button', selection: 'pgvector' },
{ ...welcome, action: 'use_case_selected', selection: 'browser-agent' },
]
const legacy = { ...quickstart, event: 'console_control_click', action: 'create_box', control: 'button' }
capture.mockClear()
for (const input of [
welcome,
starter,
{ ...welcome, action: 'org_name_submit_click', control: 'button' },
{ ...welcome, action: 'use_case_submit_click', control: 'button' },
...[
'welcome_back_to_org_click',
'welcome_back_to_use_case_click',
'check_card_status_click',
'explore_boxlite_click',
'start_quickstart_click',
].map((action) => ({ ...welcome, action, control: 'button' })),
{ ...quickstart, action: 'quickstart_template_create_click', control: 'button' },
...selections,
]) {
expect((await request(path, 'POST', bearer, input)).status).toBe(204)
const { page, event, occurredAt, ...properties } = input
expect(capture).toHaveBeenLastCalledWith(
{
event,
distinctId: 'member',
groups: { organization: org },
timestamp: new Date(occurredAt),
properties: { $pathname: page, ...properties },
},
{ users: ['member'], organizations: [org] },
)
}
expect(capture).toHaveBeenCalledTimes(14)
capture.mockClear()
for (const input of [
...[legacy, selections[0]].flatMap((value) => [
{ ...value, page: undefined },
{ ...value, page: '/dashboard/private' },
{ ...value, occurredAt: undefined },
{ ...value, occurredAt: 'now' },
]),
...selections.map((value) => ({ ...value, selection: undefined })),
{ ...selections[0], selection: 'unlisted' },
{ ...welcome, action: 'use_case_selected', selection: 'console' },
{ ...starter, action: 'start_sub_click' },
{ ...selections[0], selection: null },
{ ...selections[1], control: 'button' },
{ ...welcome, action: undefined },
{ ...welcome, page: '/dashboard/boxes' },
{ ...welcome, control: 'button' },
{ ...welcome, destination: '/dashboard/boxes' },
{ ...welcome, billingTab: 'plans' },
{ ...welcome, selection: 'console' },
{ ...legacy, selection: 'console' },
{ ...welcome, event: '$pageview', action: undefined, selection: 'console' },
]) {
expect((await request(path, 'POST', bearer, input)).status).toBe(400)
}
expect(capture).not.toHaveBeenCalled()
})
})