Skip to content

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

feat(metrics): collect Cloud and Console activity with analytics consent (#2809)

kekxyd8aa6efa1fc2
diff --git a/.github/workflows/README.md b/.github/workflows/README.md
index 3fb278671..4ddb02616 100644
--- a/.github/workflows/README.md
+++ b/.github/workflows/README.md
@@ -273,6 +273,7 @@ Formatting-only jobs disable module caching. Go test jobs initialize
submodules before Rust cache setup and retain build state for both the root Cargo
workspace and vendored libkrun. They retain workspace compilation outputs, while
still invoking `make coverage:go` to rebuild changed code and current Git metadata.
+On Linux x64, a second Go coverage pass enables KVM and exercises nested runtime metadata and the local SSH usage drain. The drain must return an empty batch for a configured Box and leave its PID at zero. Both Go coverage passes contribute to the patch report.
Finished native libraries are not reused without Cargo's freshness checks.
The Go lint job retains formatting checks. SDK and API test filters exclude Markdown and select
the Make recipes they execute; the changes job still parses every Make include with `make -n help`.
diff --git a/.github/workflows/build-runner-binary.yml b/.github/workflows/build-runner-binary.yml
index 208739ecb..30e9f7935 100644
--- a/.github/workflows/build-runner-binary.yml
+++ b/.github/workflows/build-runner-binary.yml
@@ -160,7 +160,7 @@ jobs:
VERSION_IDENTITY: ${{ steps.artifact.outputs.identity }}
run: |
set -euo pipefail
- CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -C apps \
+ CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -C apps -tags boxlite_runner \
-ldflags "-X 'github.com/boxlite-ai/runner/internal.Version=${VERSION_IDENTITY}'" \
-o /tmp/boxlite-runner \
./runner/cmd/runner/
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 21469af0a..f0322b851 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -47,6 +47,7 @@ on:
- 'rust-toolchain.toml'
- 'sdks/**'
- 'apps/api/**'
+ - 'apps/shared/**'
- 'apps/libs/ci-listener/**'
- 'apps/github-ci-runner/**'
- 'apps/image-service/**'
@@ -284,6 +285,7 @@ jobs:
- 'make/coverage.mk'
- 'make/dev.mk'
- 'apps/api/**/!(*.md)'
+ - 'apps/shared/**/!(*.md)'
- 'apps/libs/ci-listener/**/!(*.md)'
- 'apps/github-ci-runner/**/!(*.md)'
- 'openapi/box.openapi.yaml'
@@ -297,6 +299,7 @@ jobs:
dashboard:
- '.github/actions/setup-boxlite-runner/**/!(*.md)'
- 'apps/dashboard/**/!(*.md)'
+ - 'apps/shared/**/!(*.md)'
- 'apps/libs/api-client/**/!(*.md)'
- 'apps/package.json'
- 'apps/yarn.lock'
@@ -753,7 +756,7 @@ jobs:
- name: Run Go SDK, networking and app tests with coverage
run: make coverage:go
- - name: Qualify nested runtime metadata with KVM coverage
+ - name: Qualify native runtime metadata and SSH usage with KVM coverage
id: nested-runtime-coverage
if: matrix.platform.target == 'linux-x64-gnu'
timeout-minutes: 5
@@ -766,7 +769,7 @@ jobs:
done
sudo chmod a+rw /dev/kvm
make _ensure-kvm
- make coverage:go GOTEST_FILTER='-count=1 -run NestedVirtualization'
+ make coverage:go GO_SDK_COVERAGE_TAGS=boxlite_runner,boxlite_integration GOTEST_FILTER="-count=1 -run 'NestedVirtualization|SSHUsageConfiguredLocal'"
# Both passes instrument this checkout with the same atomic mode.
# Keep the complete suite's blocks as well as the hardware pass.
for module in go-sdk gvproxy runner image-service secret-server; do
diff --git a/apps/api/README.md b/apps/api/README.md
index 45f9527c6..efa0caf73 100644
--- a/apps/api/README.md
+++ b/apps/api/README.md
@@ -842,7 +842,7 @@ accept this field before rolling out the added response property.
`recordBusinessEvent` (`src/common/utils/business-event.util.ts`) writes one structured log record
per business event; the attributes reach OTLP through nestjs-pino, where alerts query them.
-The same sanitized attributes reach PostHog through the client shared with HTTP metrics.
+Eligible events send the same sanitized attributes through the consent-checked client shared with HTTP metrics.
Activity does not require the optional logging ClickHouse instance.
| Event | Recorded by | Outcomes |
@@ -909,16 +909,239 @@ id for box and tunnel events (volume ID or an API-key attempt UUID for those mut
can be counted from the log alone. `user.login` has none, since a login spans organizations, and a
registration carries its default organization on success only.
+### Occurrence identity and job timing
+
+Every business-event occurrence has an `event.id` UUID, created once before logging and analytics fan-out.
+PostHog receives it through the capture `uuid` option; both sinks receive the same `event.timestamp`.
+That field records source occurrence time when supplied, otherwise observation time.
+
+Native OTLP log time remains observation time. Replaying yesterday's completed job produces
+a log today with yesterday's `event.timestamp`. Operational occurrence-time queries must use that attribute.
+
+| Field | Source and meaning |
+| ------------------------------------------------------ | -------------------------------------------------------------------- |
+| `event.id` | Occurrence UUID, separate from resource identity |
+| `job.id` | Existing runner Job ID |
+| `job.created_at`, `job.started_at`, `job.completed_at` | Valid timestamps from the persisted Job |
+| `job.duration_ms` | Milliseconds from Job creation to completion, serialized as a string |
+
+Finished job outcomes derive occurrence identity from Job ID, event name and logical outcome.
+Repeated observations retain their UUID, completion time and duration; different jobs on one Box remain distinct.
+`JobService` preserves the first terminal timestamp while allowing result metadata refresh and completion callbacks.
+
+| Available source timing | Emitted evidence |
+| -------------------------------------- | -------------------------------------------------------------------------------- |
+| Job ID and valid completion time | Stable replay identity and source occurrence time |
+| Valid, ordered creation and completion | `job.duration_ms`, including zero |
+| Valid start time | `job.started_at`, independently of duration eligibility |
+| Missing or invalid completion | Ordinary occurrence identity; unsupported completion fields and duration omitted |
+
+Job timing excludes the customer's request before job creation and does not establish guest application readiness.
+Checkpoint-import outcomes use the accepted business receipt; an invalid receipt remains an exception even if its transport job completed.
+Source payloads and raw runner errors are excluded.
+
+### Cloud readiness metrics
+
+`cloud.box.create`, `cloud.box.start` and `cloud.box.resume` record server-side attempts through the shared PostHog/operational-log recorder.
+They carry `cloud_metrics_schema = '1'` in PostHog and have no `activity_schema`.
+Existing Activity operation totals exclude this event family.
+
+REST create/start observations cover canonical and prefixed v1 routes whose handlers wait for `STARTED`.
+Resume observations cover API proxy requests, WebSocket attaches and preview `ensure-ready`.
+Each caller that observes a pending start records one resume attempt, including when the Box reaches `STARTED` during lifecycle lock acquisition. Already-ready traffic emits no resume attempt. A stop-then-start wait counts as one attempt.
+
+HTTP ingress time is captured before body parsing and authentication, then only admitted operations are recorded.
+WebSocket timing starts at upgrade dispatch. A successful duration ends when the API observes `STARTED`, before dashboard notification enrichment and response metadata reads such as last activity. Client networking and guest application readiness are outside this measurement.
+
+| Attribute | Contract |
+| ------------------------ | ------------------------------------------------------------------ |
+| `operation.id` | UUID per invocation, shared by requested and terminal occurrences |
+| `operation.requested_at` | Original initiation time, retained on the terminal event |
+| `operation.scope` | `rest_api` or `proxy_api` |
+| `operation.boundary` | `cloud_api_to_started` |
+| `operation.duration_ms` | Nonnegative monotonic elapsed milliseconds, serialized as a string |
+| `operation.result` | `success`, `service_error`, `timeout`, `user_error` or `cancelled` |
+| `box.id` | Resolved resource ID when known; raw request names excluded |
+
+For this event family, `correlation.id` identifies the operation; use `box.id` for the resource.
+Requested and terminal occurrences have different `event.id` values. A terminal observation is recorded once per invocation.
+
+Runtime transition failures count as `service_error` while preserving their existing HTTP 400 response. This includes a Box created from a checkpoint that fails to start; its response includes the admitted Box ID.
+HTTP 408/504 count as `timeout`; other 4xx responses count as `user_error`.
+Unexpected errors and 5xx responses count as `service_error`; observable cancellation is separate.
+
+Guard refusals precede these observations. Resume policy checks before `ensureReady` and asynchronous dashboard admission routes remain outside this request cohort.
+Direct service invocation uses invocation time when an ingress timestamp is unavailable.
+
+`traffic.kind` is `unknown`: source headers do not prove probe or external customer identity.
+Use authoritative organization classification before presenting separate customer/probe rates.
+
+Delivery remains best effort. A process exit can leave a requested occurrence without its terminal observation;
+report that sample as unobserved, rather than inventing a timeout.
+
+Recorded timeouts remain failures if the Box later becomes ready.
+Count distinct `operation.id` values and assign results to their initiation window.
+Success rate is successes divided by successes plus service failures and timeouts; show user errors, cancellations and unobserved attempts separately.
+
+Compute P50/P95 from successful `operation.duration_ms` values, with sample size and failure counts alongside.
+For example, this HogQL query groups terminal duplicates before calculating successful readiness timing:
+
+```sql
+SELECT event, count() AS samples,
+ quantile(0.50)(duration_ms) / 1000 AS p50_seconds,
+ quantile(0.95)(duration_ms) / 1000 AS p95_seconds
+FROM (
+ SELECT event, properties['operation.id'] AS operation_id,
+ min(toFloat(properties['operation.duration_ms'])) AS duration_ms
+ FROM events
+ WHERE properties.cloud_metrics_schema = '1'
+ AND properties.environment = '<producer-environment>'
+ AND properties['operation.result'] = 'success'
+ AND properties['operation.boundary'] = 'cloud_api_to_started'
+ AND properties['operation.requested_at'] >= '2026-11-01T00:00:00.000Z'
+ AND properties['operation.requested_at'] < '2026-11-08T00:00:00.000Z'
+ AND timestamp >= toDateTime('2026-11-01 00:00:00')
+ AND timestamp < toDateTime('2026-11-08 00:05:00')
+ GROUP BY event, operation_id
+)
+GROUP BY event
+```
+
+This example has not run against a live PostHog project.
+Initiation timestamps are canonical UTC ISO strings; the five-minute completion grace is illustrative.
+Choose and disclose an observation cutoff, and check ingestion loss, source clocks and organization classification separately.
+
+See PostHog's [aggregations](https://posthog.com/docs/sql/aggregations) and
+[type conversions](https://posthog.com/docs/sql/expressions) for the supported query functions.
+
+### Cloud feature-use evidence
+
+`cloud.feature.use` reports accepted SSH authentication, successful preview forwarding,
+established tunnels, GitHub-reported CI job activity on an assigned BoxLite JIT runner, successful starts with tenant-owned images and committed checkpoint use.
+It uses `cloud_metrics_schema='1'` and the same occurrence UUID/time in PostHog and OTLP logs.
+
+| Feature | Evidence boundary | Excluded evidence |
+| ------------ | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
+| SSH | Accepted signed key or certificate, once per authenticated connection | Key probes, denied logins, SSH configuration |
+| Tunnel | Accepted CONNECT with a Runner connection, HTTP 101, or guest HTTP 2xx/3xx | Tunnel preparation, authorization failures, failed upstream requests |
+| CI | Signed `workflow_job.in_progress` or `completed` with a BoxLite label and assigned JIT runner | Worker creation, queued jobs, external runners, unassigned cancellations |
+| Custom image | Successful create/start job with stored `imageIsOrgOwned=true` | Admission alone, failed jobs, curated images, unknown historical provenance |
+| Checkpoint | Archive upload committed as ready (`archive_ready`), or an owned import receipt committed as completed (`box_restored`) | Create clicks, queued exports, failed or cancelled imports and replay |
+
+Feature attributes are `feature.name`, `feature.evidence` and `feature.source`.
+`correlation.id` identifies the CI Job for CI events and the Box for other features. Login, key, command, URL, repository and workflow names are omitted.
+Source evidence does not identify customer versus internal/probe traffic; use an authoritative organization cohort.
+
+`POST /api/telemetry/feature-usage` accepts at most 100 observations using existing Runner/Proxy authentication.
+Customer credentials are refused. The API resolves organization from the stored Box and checks Runner ownership;
+producers cannot choose a tenant. Only SSH evidence is accepted from Runners, and only tunnel evidence from Proxies.
+Unknown/deleted Boxes, warm stock, incompatible producers and timestamps outside seven days old/five minutes future are excluded.
+The response's `accepted` count measures local capture calls. Each observation starts its consent check independently.
+Eligible cache hits can be delivered while unrelated observations in the same batch are still waiting for PostgreSQL.
+The API returns without waiting for consent checks or HTTP delivery.
+
+```mermaid
+flowchart LR
+ SSH[Guest accepted SSH auth] --> Buffer[Local buffer: 128]
+ Buffer --> Collector[Runner background polling]
+ Proxy[Proxy forwarding] --> Queue[Nonblocking queue: 1024]
+ Collector --> Queue
+ Queue --> Batch[Background batches: 100]
+ Batch --> Ingest[API ownership validation]
+ CI[Managed CI execution] --> Event[Business event]
+ Image[Started tenant image] --> Event
+ Ingest --> Event
+ Event --> Consent[Check personal and creator grants]
+ Consent -->|Eligible| PH[PostHog]
+ Event --> OTLP[OTLP / HyperDX]
+```
+
+Guest producers use a try-lock; a full or contended buffer drops evidence.
+Runners poll every five seconds, with four concurrent one-second reads and at most 64 Boxes per round, rotating across larger inventories.
+Reads never boot a VM. The native/Go SDK exposes an explicit local drain; it does not send analytics.
+Older Guests return Unsupported. Run API ingestion before enabling reporting binaries, and ship the updated Guest with the native library to collect SSH.
+
+The Cloud reporter uses a dedicated HTTP transport, a one-second flush timer and a two-second request deadline, without retries or redirects.
+Forwarding and SSH authentication never await uploads; shutdown cancels uploads instead of flushing them synchronously.
+Overflow and collection failures have diagnostics, and failed uploads count observations as delivery-unconfirmed.
+API rejection counts are logged separately. Memory queues are volatile; process/Guest exits, failed drains and resource deletion can lose evidence.
+The hosted API records CI activity after accepting a signed GitHub `workflow_job` webhook for a connected organization.
+A BoxLite resource label on `queued` emits `cloud.ci.request` at `created_at`.
+An assigned runner ID and BoxLite JIT name on `in_progress` or `completed` emit `runner_started` at `started_at` or `runner_completed` at `completed_at`.
+Completion counts the reported end of execution for every conclusion, including failure.
+The creator's current analytics grant must cover Job creation (`ci.job_created_at` on usage events), including for delayed deliveries.
+Each accepted receipt has its own event ID. All three phases share an opaque Job correlation ID, derived from installation, repository and Job IDs.
+Count distinct correlation IDs for unique Jobs or event IDs for observations. Missing webhooks and dropped analytics can leave a partial lifecycle.
+These observations identify the receiving API environment and organization. They do not identify the executing Box or Listener.
+
+Adoption is the intersection of feature-using organizations with an explicitly eligible, active organization cohort.
+Do not label all organizations eligible, or an absent event as confirmed non-use.
+These events do not supply a capability/entitlement snapshot or a customer/probe organization registry.
+Keep that eligibility cohort authoritative and report telemetry coverage separately.
+
+This illustrative HogQL query returns per-organization usage and distinct UTC usage days for a chosen week;
+it does not prescribe an eligibility denominator or a repeat-use threshold:
+
+```sql
+SELECT properties['organization.id'] AS organization_id,
+ properties['feature.name'] AS feature,
+ uniq(properties['event.id']) AS observations,
+ uniq(toDate(toTimeZone(timestamp, 'UTC'))) AS usage_days
+FROM events
+WHERE event = 'cloud.feature.use'
+ AND properties.cloud_metrics_schema = '1'
+ AND properties.environment = '<producer-environment>'
+ AND properties['event.outcome'] = 'success'
+ AND (feature != 'ci' OR properties['feature.evidence'] IN ('runner_started', 'runner_completed'))
+ AND timestamp >= toDateTime('2026-11-01 00:00:00', 'UTC')
+ AND timestamp < toDateTime('2026-11-08 00:00:00', 'UTC')
+GROUP BY organization_id, feature
+```
+
+The query has not run against a live PostHog project. Supply the eligible cohort before computing adoption or repeat-use percentages.
+For time-aligned operation success, join requested and terminal `cloud.box.*` occurrences on `operation.id`,
+filter `operation.requested_at` into the reporting window, and disclose the terminal observation cutoff.
+A timeout stays a timeout; a missing terminal remains unobserved.
+
+### Cloud API product operations
+
+Filter on `properties.environment` to select the deployment for Cloud API operations, Console pageviews and clicks, and lifecycle events. Events ingested before these producers carried the field can have an unknown environment.
+
+Use `cloud.api.operation` for finished Cloud API requests. Select `properties['api.operation']` for the action, `properties['http.status_class']` for `2xx`, `4xx` or `5xx`, and `properties['client.source']` for attribution. For example, filter on `image.alias.create` and `2xx` to count successful alias requests across the supported clients. Each completed HTTP attempt counts separately, including client retries.
+
+| Product | Actions measured |
+| --- | --- |
+| Boxes, executions, files | Create, delete, start, stop, recover, request an attach ticket, start/signal/kill an execution, upload/download files |
+| Network, SSH, tunnels | Update inbound/outbound settings, configure/enable/disable SSH, prepare/revoke a tunnel |
+| Checkpoints | Request capture, delete, create a Box from a checkpoint (`checkpoint.restore`) |
+| Images, registries, volumes | Add/remove an alias, remove an image, create/update/delete credentials, create/delete a volume |
+| Domains | Claim, bind, unbind; create, verify, prepare, advance or delete a custom domain |
+| CI | Start/cancel a connection flow, select/complete an installation, update/remove a connection, change CI settings |
+| Onboarding and billing actions | Rename an organization, save onboarding, create/copy a quickstart handoff, submit a coupon claim or cancellation feedback. Only the operation and HTTP result are captured. |
+| Organization infrastructure | Create/update/delete a region, rotate its proxy key, create/delete one's own API key, open the webhook portal |
+
+For `volume.create`, group by `volume.storage_backend` to distinguish standard object storage (`standard`) from GCP Filestore (`performance`). The field reflects the requested class, including the default `standard` when omitted. Filter on `http.status_class=2xx` for successful requests. An unrecognized or null class leaves the field absent. Historical events without the field have an unknown class.
+
+Both v1 route spellings and the equivalent Console routes use the same action where available. The shared native SDK and CLI report `sdk`, the Dashboard reports `dashboard`, and verified in-process tool delegation reports `mcp`. Client source is descriptive; unmarked or unrecognized clients are `unattributed`.
+
+The HTTP response must finish after the guards verify the actor's organization membership. The request admission time anchors the consent check for the member and the org creator. A full queue, disabled analytics or early disconnect drops the measurement. The listener does no network or database work that the handler must await.
+
+Status polling, terminal resize frames, credential introspection and local-only SDK calls produce no operation rows. File and execution requests contribute at most one row per finished HTTP response, regardless of stream size. Use `cloud.feature.use` for committed checkpoint outcomes, an actual SSH session or tunnel traffic; the HTTP rows measure different stages and should not be summed with click or feature events.
+
### Querying Activity in PostHog
The producer uses the existing `POSTHOG_API_KEY`, `POSTHOG_HOST` and `POSTHOG_ENVIRONMENT` settings.
Cloud deployments set `POSTHOG_ENVIRONMENT` to the deployed stage name on both AWS and GCP.
Without the key or host, analytics is disabled while business operations and operational logs continue.
-AnalyticsService owns disabled-source and capture-error handling; the interceptor skips request extraction
-when analytics is disabled.
-Delivery is queued and best effort; application shutdown waits up to five seconds for the shared client.
-SDK diagnostics are separate from the sanitized business-event payload. Retention follows the PostHog
-project; BoxLite does not provision a second store or guarantee 400 days of history.
+Product analytics requires a current, explicit personal grant. An organization inherits its recorded creator’s choice. An event that identifies both a person and an organization needs both grants. An unknown subject, an unavailable decision, or an event predating the most recent grant produces no PostHog event. Dashboard activity and Cloud metrics therefore describe the consenting population. Operational logging, metering and functional flag evaluation run independently.
+
+Each event gets an asynchronous consent check and, if eligible, one HTTP attempt. An API instance shares concurrent reads for the same subject.
+Only messages needing a SQL lookup count towards the per-process backlog. Set `POSTHOG_CONSENT_BACKLOG_LIMIT` in the mstage API group to override the default of 1,000. Each excess message increments `posthog_consent_backlog_dropped_total`.
+Up to two SQL consent reads run concurrently on a pool of at least three connections, one on a pool of two, and none on a pool of one.
+The SQL slot is released after the query. HTTP deliveries have no application-level concurrency limit.
+Redis caches each organization creator and each user's grant time or denial for 30 seconds. A cache miss reads PostgreSQL without an explicit lock; the read finishes before the PostHog transfer.
+Saving a choice invalidates that user's cache entry, and linking accounts invalidates the moved organizations' cached creators. An in-flight transfer may finish after withdrawal. A stale cache entry expires within 30 seconds.
+The Console reads membership and effective consent together when loading organization preferences. A saturated consent backlog or unavailable Redis, database or transport can lose optional analytics. Retention follows the PostHog project.
An Activity consumer needs the PostHog **API origin** (for example `https://us.posthog.com`, distinct
from an ingestion origin such as `https://us.i.posthog.com`), project ID and a backend-only personal
@@ -947,7 +1170,7 @@ The example documents the contract; it has not been executed against a live Post
| Activity field | PostHog value |
| -------------------- | ---------------------------------------------------------------------------------------- |
-| Event/time | `event`, `timestamp` (the original event emission time) |
+| Event/time | `event`, `timestamp` (source occurrence time, otherwise emission time) |
| Outcome/entity | `properties['event.outcome']`, `properties['correlation.id']` |
| Organization/person | `properties['organization.id']`, optional `properties['user.id']` |
| Actor/reason/failure | `properties['actor.kind']`, `properties['event.reason']`, `properties['exception.type']` |
@@ -965,6 +1188,20 @@ to report truncation. Include requested/exception outcomes plus successes for `o
`user.login` and `user.registration`; ordinary success records confirm requests already listed.
Only requested outcomes contribute to operation totals. Preview presence remains anonymous and sampled.
+### Signup attribution
+
+The Console keeps the first eligible source in the current tab for up to 24 hours. At a signup entry it checks `utm_source`, `ref`, the hostname forwarded by the website, then the browser’s external HTTP(S) referrer. An untagged link from X can produce `x.com` or `t.co`, depending on the hostname the browser supplies.
+
+Use public campaign labels for `utm_source`, `ref`, `utm_medium`, `utm_campaign` and `utm_content`. Each label may contain 1–64 ASCII letters, digits, underscores or hyphens and must start with a letter or digit. For example, `spring_26` is valid.
+
+An identifier that fits the same format can also pass, so keep personal identifiers and secrets out of campaign links. For browser referrers, the Console keeps only the external hostname and skips login callbacks.
+
+Signup attribution uses the same **Product analytics** choice as Console page visits and clicks. After a saved grant, the Console may submit the pending source to `POST /analytics/signup-source`. The API verifies the grant, the account creation window and the creator-owned default organization.
+
+The API accepts one eligible claim per account, including across UTC midnight and concurrent tabs. It marks the claim in the existing consent row and submits `signup_attributed` with `signup.source` and `signup.source_type` for best-effort delivery. A delivery failure after the claim can therefore leave the signup unattributed.
+
+A refusal, account switch or expiry discards the pending source. Earlier page visits and clicks are never replayed.
+
### Who asked: the operation context
A service that records an event takes a required `ctx: Context` (`src/common/context/`) from its
@@ -1896,15 +2133,15 @@ promised. Deployment and dev data reset remain operator actions.
The removal release deletes these operations (paths relative to the hosted API base):
-| Removed operation | Supported path or behavior |
-| --- | --- |
-| `POST /users/{id}/regenerate-key-pair` | SSH gateway keys have no consumer; account creation no longer generates them |
-| `GET /box/{id}/telemetry/logs`, `traces`, `traces/{traceId}`, `metrics` | Dashboard queries the independent Analytics API |
-| `GET /object-storage/push-access` | Runner archives use infrastructure credentials; managed volumes retain their own S3 provisioning |
-| `GET /box` | Use `/box/paginated` or portable `/v1` listing |
-| `PUT /box/{id}/labels` | No replacement mutation; stored labels and label filters remain |
+| Removed operation | Supported path or behavior |
+| ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
+| `POST /users/{id}/regenerate-key-pair` | SSH gateway keys have no consumer; account creation no longer generates them |
+| `GET /box/{id}/telemetry/logs`, `traces`, `traces/{traceId}`, `metrics` | Dashboard queries the independent Analytics API |
+| `GET /object-storage/push-access` | Runner archives use infrastructure credentials; managed volumes retain their own S3 provisioning |
+| `GET /box` | Use `/box/paginated` or portable `/v1` listing |
+| `PUT /box/{id}/labels` | No replacement mutation; stored labels and label filters remain |
| `POST /box/{id}/autostop/{interval}`, `POST /box/{id}/autodelete/{interval}` | Set `auto_stop` and `auto_delete` in seconds when creating a Box through `/v1`; dynamic updates are retired |
-| `GET /volumes/by-name/{name}` | Look up volumes by ID; managed-volume selectors still accept names |
+| `GET /volumes/by-name/{name}` | Look up volumes by ID; managed-volume selectors still accept names |
Removed operations return 404 and are absent from regenerated TypeScript and Go cloud clients.
External consumers must stop calling them before this release; absence of repository callers does not establish absence of external use.
diff --git a/apps/api/src/analytics/analytics.module.ts b/apps/api/src/analytics/analytics.module.ts
index d460f38bf..3d9c3cb2d 100644
--- a/apps/api/src/analytics/analytics.module.ts
+++ b/apps/api/src/analytics/analytics.module.ts
@@ -7,8 +7,12 @@
import { Module } from '@nestjs/common'
import { AnalyticsService } from './services/analytics.service'
+import { ConsoleAnalyticsController } from './console-analytics.controller'
+import { AnalyticsConsentService } from './services/analytics-consent.service'
+
@Module({
- providers: [AnalyticsService],
+ controllers: [ConsoleAnalyticsController],
+ providers: [AnalyticsService, AnalyticsConsentService],
exports: [AnalyticsService],
})
export class AnalyticsModule {}
diff --git a/apps/api/src/analytics/console-analytics.controller.spec.ts b/apps/api/src/analytics/console-analytics.controller.spec.ts
new file mode 100644
index 000000000..d66193b19
--- /dev/null
+++ b/apps/api/src/analytics/console-analytics.controller.spec.ts
@@ -0,0 +1,143 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { createServer } from 'node:http'
+import { AddressInfo } from 'node:net'
+import { ForbiddenException, INestApplication, ValidationPipe } from '@nestjs/common'
+import { Test } from '@nestjs/testing'
+import { generateKeyPair, exportJWK, SignJWT } from 'jose'
+import { JwtStrategy } from '../auth/jwt.strategy'
+import { ConsoleAnalyticsController } from './console-analytics.controller'
+import { AnalyticsConsentService } from './services/analytics-consent.service'
+import { AnalyticsService } from './services/analytics.service'
+
+describe('Console analytics HTTP boundary', () => {
+ const org = 'a98b01ab-0a84-4b06-955a-2cfacf733f09'
+ const capture = jest.fn()
+ 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 () => {
+ 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({
+ controllers: [ConsoleAnalyticsController],
+ providers: [
+ { provide: JwtStrategy, useValue: strategy },
+ { provide: AnalyticsConsentService, useValue: consent },
+ { provide: AnalyticsService, useValue: { capture, enabled: true } },
+ ],
+ }).compile()
+ app = module.createNestApplication()
+ app.useGlobalPipes(new ValidationPipe({ transform: true }))
+ await app.listen(0, '127.0.0.1')
+ base = await app.getUrl()
+ })
+ afterAll(async () => {
+ await app?.close()
+ 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: 't.co', 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://t.co/private' })).status).toBe(400)
+ expect((await request(path, 'POST', bearer, { ...input, enteredAt: '2000-01-01T00:00:00Z' })).status).toBe(204)
+ expect(consent.claimSignupOrganization).not.toHaveBeenCalled()
+ expect((await request(path, 'POST', bearer, input)).status).toBe(204)
+ expect(capture).not.toHaveBeenCalled()
+ 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(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': 't.co', '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] },
+ )
+ })
+})
diff --git a/apps/api/src/analytics/console-analytics.controller.ts b/apps/api/src/analytics/console-analytics.controller.ts
new file mode 100644
index 000000000..aaca5ec61
--- /dev/null
+++ b/apps/api/src/analytics/console-analytics.controller.ts
@@ -0,0 +1,143 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import {
+ BadRequestException,
+ Body,
+ Controller,
+ Get,
+ Param,
+ HttpCode,
+ ParseUUIDPipe,
+ Post,
+ Put,
+ UseGuards,
+} from '@nestjs/common'
+import { ApiExcludeController } from '@nestjs/swagger'
+import { AuthGuard } from '@nestjs/passport'
+import { IsBoolean, IsIn, IsISO8601, IsOptional, IsString, Matches, MaxLength } from 'class-validator'
+import {
+ analyticsNoticeVersion,
+ billingTabs,
+ consoleActions,
+ consoleControls,
+ consolePages,
+} from '../../../shared/console-analytics'
+import { v5 } from 'uuid'
+import {
+ campaignLabel,
+ signupSourceLifetimeMs,
+ validSource,
+ type SignupSource,
+} from '../../../shared/signup-attribution'
+import { RoutePath } from '../../../shared/console-routes'
+import { AuthContext } from '../common/decorators/auth-context.decorator'
+import type { AuthContext as Principal } from '../common/interfaces/auth-context.interface'
+import { AnalyticsService } from './services/analytics.service'
+import { AnalyticsConsentService } from './services/analytics-consent.service'
+
+class ConsentChoice {
+ @IsBoolean() allowed: boolean
+ @IsIn([analyticsNoticeVersion]) version: number
+}
+
+class SignupSourceInput implements SignupSource {
+ @IsString() @MaxLength(253) source: string
+ @IsIn(['utm', 'ref', 'referrer']) kind: SignupSource['kind']
+ @IsISO8601({ strict: true }) enteredAt: string
+ @IsOptional() @Matches(campaignLabel) medium?: string
+ @IsOptional() @Matches(campaignLabel) campaign?: string
+ @IsOptional() @Matches(campaignLabel) content?: string
+}
+
+class ConsoleEvent {
+ @IsIn(['$pageview', 'console_control_click']) event: '$pageview' | 'console_control_click'
+ @IsIn(consolePages) page: RoutePath
+ @IsISO8601({ strict: true }) occurredAt: string
+ @IsOptional() @IsIn(consoleControls) control?: string
+ @IsOptional() @IsIn(consolePages) destination?: RoutePath
+ @IsOptional() @IsIn(consoleActions) action?: string
+ @IsOptional() @IsIn(billingTabs) billingTab?: string
+}
+
+@ApiExcludeController()
+@UseGuards(AuthGuard('jwt'))
+@Controller('analytics')
+export class ConsoleAnalyticsController {
+ constructor(
+ private readonly consent: AnalyticsConsentService,
+ private readonly analytics: AnalyticsService,
+ ) {}
+
+ @Get('consent')
+ preference(@AuthContext() actor: Principal) {
+ return this.consent.preference(actor.userId)
+ }
+
+ @Get('organizations/:organizationId/consent')
+ async consolePreference(
+ @AuthContext() actor: Principal,
+ @Param('organizationId', ParseUUIDPipe) organizationId: string,
+ ) {
+ return this.consent.consolePreference(actor.userId, organizationId)
+ }
+
+ @Put('consent')
+ decide(@AuthContext() actor: Principal, @Body() choice: ConsentChoice) {
+ return this.consent.decide(actor.userId, choice.allowed)
+ }
+
+ @Post('signup-source')
+ @HttpCode(204)
+ async attributeSignup(@AuthContext() actor: Principal, @Body() input: SignupSourceInput) {
+ if (!validSource(input.source, input.kind)) throw new BadRequestException('Invalid signup source')
+ const enteredAt = new Date(input.enteredAt)
+ const age = Date.now() - enteredAt.getTime()
+ if (!Number.isFinite(age) || age < 0 || age >= signupSourceLifetimeMs || !this.analytics.enabled) return
+ const organizationId = await this.consent.claimSignupOrganization(actor.userId, enteredAt)
+ if (!organizationId) return
+ this.analytics.capture(
+ {
+ event: 'signup_attributed',
+ distinctId: actor.userId,
+ uuid: v5('boxlite:signup-attributed:' + actor.userId, v5.URL),
+ groups: { organization: organizationId },
+ properties: {
+ 'signup.source': input.source.toLowerCase(),
+ 'signup.source_type': input.kind,
+ ...(input.medium && { 'signup.medium': input.medium }),
+ ...(input.campaign && { 'signup.campaign': input.campaign }),
+ ...(input.content && { 'signup.content': input.content }),
+ },
+ },
+ { users: [actor.userId], organizations: [organizationId] },
+ )
+ }
+
+ @Post('organizations/:organizationId/console-events')
+ @HttpCode(204)
+ async record(
+ @AuthContext() actor: Principal,
+ @Param('organizationId', ParseUUIDPipe) organizationId: string,
+ @Body() input: ConsoleEvent,
+ ) {
+ await this.consent.requireMember(actor.userId, organizationId)
+ if (input.event === 'console_control_click' && !input.control) throw new BadRequestException('Missing control')
+ this.analytics.capture(
+ {
+ event: input.event,
+ distinctId: actor.userId,
+ groups: { organization: organizationId },
+ timestamp: new Date(input.occurredAt),
+ properties: {
+ $pathname: input.page,
+ ...(input.page === RoutePath.BILLING && input.billingTab && { billing_tab: input.billingTab }),
+ ...(input.event === 'console_control_click' && {
+ control: input.control,
+ action: input.action,
+ destination: input.destination,
+ }),
+ },
+ },
+ { users: [actor.userId], organizations: [organizationId] },
+ )
+ }
+}
diff --git a/apps/api/src/analytics/services/analytics-consent.integration.spec.ts b/apps/api/src/analytics/services/analytics-consent.integration.spec.ts
new file mode 100644
index 000000000..46f8fa8ac
--- /dev/null
+++ b/apps/api/src/analytics/services/analytics-consent.integration.spec.ts
@@ -0,0 +1,397 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { createServer } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { recordBusinessEvent } from '../../common/utils/business-event.util'
+import { AnalyticsService } from './analytics.service'
+import { ConfigService } from '@nestjs/config'
+import { configuration } from '../../config/configuration'
+import { TypedConfigService } from '../../config/typed-config.service'
+import { randomUUID } from 'node:crypto'
+import { setTimeout as delay } from 'node:timers/promises'
+import Redis from 'ioredis'
+import { DataSource } from 'typeorm'
+import { metrics } from '@opentelemetry/api'
+import { ProductAnalyticsConsent1795420800000 } from '../../migrations/pre-deploy/1795420800000-product-analytics-consent-migration'
+import { AddSignupClaim1795996800000 } from '../../migrations/pre-deploy/1795996800000-add-signup-claim-migration'
+import { analyticsConsentCacheKey, AnalyticsConsentService } from './analytics-consent.service'
+
+const databaseSuite = process.env.DB_HOST ? describe : describe.skip
+
+databaseSuite('Product analytics consent in PostgreSQL', () => {
+ const schema = 'analytics_' + randomUUID().replaceAll('-', '')
+ const org = randomUUID()
+ let observer: DataSource
+ let redis: Redis
+ let db: DataSource
+ let consent: AnalyticsConsentService
+ const options = {
+ type: 'postgres' as const,
+ host: process.env.DB_HOST,
+ port: Number(process.env.DB_PORT || 5432),
+ username: process.env.DB_USERNAME,
+ password: process.env.DB_PASSWORD,
+ database: process.env.DB_DATABASE,
+ }
+ const defaultConfig = new TypedConfigService(new ConfigService(configuration))
+ const both = { users: ['member'], organizations: [org] }
+ beforeAll(async () => {
+ observer = await new DataSource(options).initialize()
+ await observer.query(`CREATE SCHEMA "${schema}"`)
+ db = await new DataSource({
+ ...options,
+ extra: { max: 3, options: '-c search_path=' + schema, application_name: schema },
+ }).initialize()
+ await db.query('CREATE TABLE "user" (id varchar PRIMARY KEY, "createdAt" timestamptz DEFAULT now())')
+ await db.query('CREATE TABLE organization (id uuid PRIMARY KEY, "createdBy" varchar)')
+ await db.query(
+ 'CREATE TABLE organization_user ("organizationId" uuid, "userId" varchar, "isDefaultForUser" boolean DEFAULT false)',
+ )
+ const runner = db.createQueryRunner()
+ try {
+ await new ProductAnalyticsConsent1795420800000().up(runner)
+ await new AddSignupClaim1795996800000().up(runner)
+ } finally {
+ await runner.release()
+ }
+ await db.query("INSERT INTO \"user\" VALUES ('creator'), ('member'), ('old-notice')")
+ await db.query("INSERT INTO organization VALUES ($1,'creator')", [org])
+ await db.query("INSERT INTO organization_user VALUES ($1,'member')", [org])
+ redis = new Redis({
+ host: process.env.REDIS_HOST ?? '127.0.0.1',
+ port: Number(process.env.REDIS_PORT ?? 6379),
+ keyPrefix: schema + ':',
+ lazyConnect: true,
+ maxRetriesPerRequest: 0,
+ commandTimeout: 1000,
+ })
+ await redis.connect()
+ consent = new AnalyticsConsentService(db, redis, defaultConfig)
+ })
+ beforeEach(async () => {
+ await db.query('TRUNCATE product_analytics_consent')
+ await redis.del(
+ analyticsConsentCacheKey('creator', org),
+ analyticsConsentCacheKey('grant', 'creator'),
+ analyticsConsentCacheKey('grant', 'member'),
+ )
+ })
+ afterAll(async () => {
+ redis?.disconnect()
+ if (db?.isInitialized) await db.destroy()
+ if (observer?.isInitialized) {
+ await observer.query(`DROP SCHEMA "${schema}" CASCADE`)
+ await observer.destroy()
+ }
+ })
+ it('credits only new accounts and their creator-owned default organization after permission', async () => {
+ const enteredAt = new Date(Date.now() - 60_000)
+ await db.query('INSERT INTO organization_user VALUES ($1,$2,true)', [org, 'creator'])
+ try {
+ await consent.decide('creator', false)
+ expect(await consent.claimSignupOrganization('creator', enteredAt)).toBeUndefined()
+ await consent.decide('creator', true)
+ expect(await consent.claimSignupOrganization('creator', new Date(Date.now() - 86_400_100))).toBeUndefined()
+ expect(await consent.claimSignupOrganization('creator', new Date(Date.now() + 60_000))).toBeUndefined()
+ const claims = await Promise.all([
+ consent.claimSignupOrganization('creator', enteredAt),
+ consent.claimSignupOrganization('creator', enteredAt),
+ ])
+ expect(claims.filter((id) => id !== undefined)).toEqual([org])
+ await consent.decide('creator', false)
+ await consent.decide('creator', true)
+ expect(await consent.claimSignupOrganization('creator', enteredAt)).toBeUndefined()
+ await consent.decide('member', true)
+ expect(await consent.claimSignupOrganization('member', enteredAt)).toBeUndefined()
+ } finally {
+ await db.query('DELETE FROM organization_user WHERE "userId" = $1', ['creator'])
+ }
+ })
+
+ it('requires each distinct subject, including the recorded creator even outside current membership', async () => {
+ const send = jest.fn(async () => {})
+ const userOnly = { users: ['member'], organizations: [] }
+ const orgOnly = { users: [], organizations: [org] }
+ expect((await consent.preference('member')).allowed).toBeNull()
+ await expect(consent.requireMember('creator', org)).rejects.toThrow('membership')
+ await consent.requireMember('member', org)
+ expect(await consent.dispatch(both, new Date(), send)).toBe(false)
+ await consent.decide('member', true)
+ await delay(3)
+ expect(await consent.dispatch(userOnly, new Date(), send)).toBe(true)
+ expect(await consent.dispatch(orgOnly, new Date(), send)).toBe(false)
+ expect(await consent.consolePreference('member', org)).toMatchObject({ allowed: true, enabledFrom: null })
+ await expect(consent.consolePreference('creator', org)).rejects.toThrow('membership')
+ const first = await consent.decide('creator', true)
+ expect(await consent.decide('creator', true)).toEqual(first)
+ await delay(3)
+ expect((await consent.consolePreference('member', org)).enabledFrom).toBe(first.decidedAt)
+ expect(await consent.dispatch(both, new Date(), send)).toBe(true)
+ expect(await consent.dispatch({ users: ['creator'], organizations: [org, org] }, new Date(), send)).toBe(true)
+ expect(await consent.dispatch({ users: [], organizations: [] }, new Date(), send)).toBe(false)
+ expect(await consent.dispatch({ users: ['member'], organizations: [randomUUID()] }, new Date(), send)).toBe(false)
+ await consent.decide('member', false)
+ expect(await consent.dispatch(both, new Date(), send)).toBe(false)
+ expect(await consent.dispatch(orgOnly, new Date(), send)).toBe(true)
+ expect(send).toHaveBeenCalledTimes(4)
+ })
+ it('discards pre-grant events, old notice versions, and events from a previous grant', async () => {
+ const send = jest.fn(async () => {})
+ const before = new Date()
+ await delay(5)
+ await consent.decide('creator', true)
+ await consent.decide('member', true)
+ expect(await consent.dispatch(both, before, send)).toBe(false)
+ await delay(5)
+ const during = new Date()
+ await consent.decide('member', false)
+ await delay(5)
+ await consent.decide('member', true)
+ expect(await consent.dispatch(both, during, send)).toBe(false)
+ await db.query(
+ "INSERT INTO product_analytics_consent (user_id, allowed, notice_version) VALUES ('old-notice',true,0)",
+ )
+ expect((await consent.preference('old-notice')).allowed).toBeNull()
+ expect(await consent.dispatch({ users: ['old-notice'], organizations: [] }, new Date(), send)).toBe(false)
+ expect(send).not.toHaveBeenCalled()
+ })
+ it('shares 30-second decisions and coalesces cold reads during concurrent creates', async () => {
+ await consent.decide('creator', true)
+ await consent.decide('member', true)
+ await delay(3)
+ const send = jest.fn(async () => {})
+ const reads = jest.spyOn(db, 'query')
+ try {
+ await Promise.all(Array.from({ length: 32 }, () => consent.dispatch(both, new Date(), send)))
+ expect(reads).toHaveBeenCalledTimes(3)
+ expect(send).toHaveBeenCalledTimes(32)
+ const other = new AnalyticsConsentService(db, redis, defaultConfig)
+ await other.dispatch(both, new Date(), send)
+ expect(send).toHaveBeenCalledTimes(33)
+ expect(reads).toHaveBeenCalledTimes(3)
+ const key = analyticsConsentCacheKey('grant', 'creator')
+ expect(await redis.pttl(key)).toBeGreaterThan(0)
+ expect(await redis.pttl(key)).toBeLessThanOrEqual(30_000)
+ await db.query("UPDATE product_analytics_consent SET allowed = false WHERE user_id = 'creator'")
+ await redis.pexpire(key, 1)
+ await delay(5)
+ expect(await other.dispatch(both, new Date(), send)).toBe(false)
+ reads.mockClear()
+ expect(await consent.dispatch(both, new Date(), send)).toBe(false)
+ expect(reads).not.toHaveBeenCalled()
+ } finally {
+ reads.mockRestore()
+ }
+ })
+ it('drops analytics without querying PostgreSQL when Redis is offline', async () => {
+ const offline = redis.duplicate({ lazyConnect: true })
+ const reads = jest.spyOn(db, 'query')
+ const send = jest.fn(async () => {})
+ try {
+ expect(await new AnalyticsConsentService(db, offline, defaultConfig).dispatch(both, new Date(), send)).toBe(false)
+ expect(reads).not.toHaveBeenCalled()
+ expect(send).not.toHaveBeenCalled()
+ } finally {
+ offline.disconnect()
+ reads.mockRestore()
+ }
+ })
+ it('sends CI webhook usage only when the creator consented before job creation', async () => {
+ const received: string[] = []
+ const server = createServer((req, res) => {
+ let body = ''
+ req.on('data', (chunk) => {
+ body += chunk
+ })
+ req.on('end', () => {
+ received.push(body)
+ res.writeHead(200).end('{"status":1}')
+ })
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ const config: Record<string, string> = {
+ 'posthog.apiKey': 'phc_test',
+ 'posthog.host': 'http://127.0.0.1:' + (server.address() as AddressInfo).port,
+ }
+ const analytics = new AnalyticsService({ get: (key: string) => config[key] } as TypedConfigService, consent)
+ try {
+ const before = new Date()
+ await delay(5)
+ await consent.decide('creator', true)
+ await delay(5)
+ for (const [correlationId, createdAt] of [
+ ['before-grant', before],
+ ['after-grant', new Date()],
+ ] as const) {
+ recordBusinessEvent({
+ name: 'cloud.feature.use',
+ outcome: 'success',
+ organizationId: org,
+ correlationId,
+ feature: { name: 'ci', evidence: 'runner_started', source: 'api', ciJobCreatedAt: createdAt },
+ })
+ }
+ await analytics.onApplicationShutdown()
+ expect(received).toHaveLength(1)
+ expect(received[0]).toContain('after-grant')
+ expect(received[0]).not.toContain('before-grant')
+ } finally {
+ await analytics.onApplicationShutdown()
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ }
+ })
+ it.each([
+ [3, 2],
+ [2, 1],
+ [1, 0],
+ ])('limits cold analytics SQL reads for a pool of %i to %i', async (poolSize, limit) => {
+ const pool = new DataSource({ ...options, extra: { max: poolSize } })
+ const limited = new AnalyticsConsentService(pool, redis, defaultConfig)
+ let release!: () => void
+ const blocked = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ let inUse = 0,
+ peak = 0
+ const read = jest.spyOn(pool, 'query').mockImplementation(async () => {
+ inUse++
+ peak = Math.max(peak, inUse)
+ try {
+ await blocked
+ return [{ value: '1' }]
+ } finally {
+ inUse--
+ }
+ })
+ const cache = jest.spyOn(redis, 'get').mockResolvedValue(null)
+ const send = jest.fn(async () => {})
+ const deliveries = Promise.all(
+ Array.from({ length: 6 }, () => limited.dispatch({ users: [randomUUID()], organizations: [] }, new Date(), send)),
+ )
+ try {
+ await new Promise<void>((resolve) => setImmediate(resolve))
+ expect(inUse).toBe(limit)
+ } finally {
+ release()
+ await deliveries
+ read.mockRestore()
+ cache.mockRestore()
+ }
+ expect(peak).toBe(limit)
+ expect(send).toHaveBeenCalledTimes(limit ? 6 : 0)
+ })
+
+ it.each([1000, 3])('admits warm events when the configured backlog of %i cold events is full', async (limit) => {
+ const meter = metrics.getMeter('')
+ const add = jest.fn()
+ jest.spyOn(meter, 'createCounter').mockReturnValue({ add })
+ jest.spyOn(metrics, 'getMeter').mockReturnValue(meter)
+ const settings = new TypedConfigService(new ConfigService({ posthog: { consentBacklogLimit: limit } }))
+ const limited = new AnalyticsConsentService(db, redis, settings)
+ let release!: () => void
+ const blocked = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ const read = jest.spyOn(db, 'query').mockImplementation(async () => {
+ await blocked
+ return [{ value: '1' }]
+ })
+ const cache = jest
+ .spyOn(redis, 'get')
+ .mockImplementation(async (key) => (key === analyticsConsentCacheKey('grant', 'warm') ? '1' : null))
+ const cold = jest.fn(async () => {})
+ const warm = jest.fn(async () => {})
+ const at = new Date()
+ const dispatch = (id: string, send: () => Promise<void>) =>
+ limited.dispatch({ users: [id], organizations: [] }, at, send)
+ try {
+ const deliveries = Array.from({ length: limit + 1 }, () => dispatch('cold', cold))
+ try {
+ await new Promise<void>((resolve) => setImmediate(resolve))
+ expect(await dispatch('warm', warm)).toBe(true)
+ expect(warm).toHaveBeenCalledTimes(1)
+ expect(cold).not.toHaveBeenCalled()
+ expect(read).toHaveBeenCalledTimes(1)
+ } finally {
+ release()
+ await Promise.all(deliveries)
+ }
+ expect(cold).toHaveBeenCalledTimes(limit)
+ expect(add.mock.calls).toEqual([[1]])
+ expect(await dispatch('cold', cold)).toBe(true)
+ } finally {
+ read.mockRestore()
+ cache.mockRestore()
+ jest.restoreAllMocks()
+ }
+ })
+
+ it('allows business queries and checks new consent while an HTTP transfer is stalled', async () => {
+ await consent.decide('member', true)
+ await delay(3)
+ let count = 0
+ let full!: () => void
+ const saturated = new Promise<void>((resolve) => {
+ full = resolve
+ })
+ const receiver = createServer((req) => {
+ req.resume()
+ count++
+ full()
+ })
+ await new Promise<void>((resolve) => receiver.listen(0, '127.0.0.1', resolve))
+ const config: Record<string, unknown> = {
+ 'posthog.apiKey': 'phc_test',
+ 'posthog.host': 'http://127.0.0.1:' + (receiver.address() as AddressInfo).port,
+ }
+ const analytics = new AnalyticsService({ get: (key: string) => config[key] } as TypedConfigService, consent)
+ try {
+ const record = () =>
+ analytics.capture({ event: 'test', distinctId: 'member' }, { users: ['member'], organizations: [] })
+ record()
+ await saturated
+ expect(await db.query('SELECT 1 AS available')).toEqual([{ available: 1 }])
+ await consent.decide('member', false)
+ record()
+ await analytics.onApplicationShutdown()
+ expect(count).toBe(1)
+ } finally {
+ receiver.closeAllConnections()
+ await new Promise<void>((r) => receiver.close(() => r()))
+ await analytics.onApplicationShutdown()
+ }
+ })
+
+ it('lets withdrawal finish while an already admitted transfer is still running', async () => {
+ await consent.decide('creator', true)
+ await consent.decide('member', true)
+ await delay(3)
+ let entered!: () => void
+ let finish!: () => void
+ const started = new Promise<void>((resolve) => {
+ entered = resolve
+ })
+ const barrier = new Promise<void>((resolve) => {
+ finish = resolve
+ })
+ const transfer = consent.dispatch(both, new Date(), async () => {
+ entered()
+ await barrier
+ })
+ await started
+ const withdrawal = consent.decide('creator', false)
+ let timeout: ReturnType<typeof setTimeout> | undefined
+ try {
+ await Promise.race([
+ withdrawal,
+ new Promise((_resolve, reject) => {
+ timeout = setTimeout(() => reject(new Error('withdrawal waited for PostHog')), 1500)
+ }),
+ ])
+ expect(await consent.dispatch(both, new Date(), jest.fn())).toBe(false)
+ } finally {
+ clearTimeout(timeout)
+ finish()
+ await Promise.all([transfer, withdrawal])
+ }
+ })
+})
diff --git a/apps/api/src/analytics/services/analytics-consent.service.ts b/apps/api/src/analytics/services/analytics-consent.service.ts
new file mode 100644
index 000000000..d92d49935
--- /dev/null
+++ b/apps/api/src/analytics/services/analytics-consent.service.ts
@@ -0,0 +1,195 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { InjectRedis } from '@nestjs-modules/ioredis'
+import { ForbiddenException, Injectable } from '@nestjs/common'
+import { metrics } from '@opentelemetry/api'
+import Redis from 'ioredis'
+import { DataSource } from 'typeorm'
+import { TypedConfigService } from '../../config/typed-config.service'
+import { analyticsNoticeVersion } from '../../../../shared/console-analytics'
+
+export interface AnalyticsSubjects {
+ users: string[]
+ organizations: string[]
+}
+
+type Decision = { allowed: boolean | null; notice_version: number | null; decided_at: Date | null }
+type Subject = 'creator' | 'grant'
+const ttlMs = 30_000
+export const analyticsConsentCacheKey = (kind: Subject, id: string) =>
+ `analytics:consent:v${analyticsNoticeVersion}:${kind}:${id}`
+
+function preference(row?: Decision) {
+ const current = row?.allowed === false || (row?.allowed === true && row.notice_version === analyticsNoticeVersion)
+ return {
+ allowed: current ? row.allowed : null,
+ version: analyticsNoticeVersion,
+ decidedAt: current ? row.decided_at!.toISOString() : null,
+ }
+}
+
+function sharedRead<T>(reads: Map<string, Promise<T>>, key: string, read: () => Promise<T>): Promise<T> {
+ let pending = reads.get(key)
+ if (!pending) {
+ pending = read().finally(() => reads.delete(key))
+ reads.set(key, pending)
+ }
+ return pending
+}
+
+@Injectable()
+export class AnalyticsConsentService {
+ private readonly cacheReads = new Map<string, Promise<string | null>>()
+ private readonly databaseReads = new Map<string, Promise<string>>()
+ private readonly sqlWaiters: (() => void)[] = []
+ private readonly maxColdEvents: number
+ private readonly maxSqlReads: number
+ private activeSqlReads = 0
+ private coldEvents = 0
+ private readonly overflow = metrics.getMeter('').createCounter('posthog_consent_backlog_dropped_total', {
+ description: 'Analytics events dropped when the per-instance SQL consent backlog is full',
+ })
+
+ constructor(
+ private readonly db: DataSource,
+ @InjectRedis() private readonly redis: Redis,
+ config: TypedConfigService,
+ ) {
+ this.maxColdEvents = config.getOrThrow('posthog.consentBacklogLimit')
+ const poolMax = db.options.extra?.max ?? db.options.poolSize ?? 10
+ this.maxSqlReads = Math.max(0, Math.min(2, poolMax - 1))
+ }
+
+ async preference(userId: string) {
+ const [row]: Decision[] = await this.db.query(
+ 'SELECT allowed, notice_version, decided_at FROM product_analytics_consent WHERE user_id = $1',
+ [userId],
+ )
+ return preference(row)
+ }
+
+ async decide(userId: string, allowed: boolean) {
+ const [row]: Decision[] = await this.db.query(
+ `INSERT INTO product_analytics_consent AS existing (user_id, allowed, notice_version)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (user_id) DO UPDATE SET allowed = excluded.allowed, notice_version = excluded.notice_version,
+ decided_at = clock_timestamp()
+ WHERE (existing.allowed, existing.notice_version) IS DISTINCT FROM (excluded.allowed, excluded.notice_version)
+ RETURNING allowed, notice_version, decided_at`,
+ [userId, allowed, analyticsNoticeVersion],
+ )
+ // A saved preference stands even when best-effort cache invalidation fails.
+ if (this.redis.status === 'ready') {
+ void this.redis.del(analyticsConsentCacheKey('grant', userId)).catch(() => {})
+ }
+ return row ? preference(row) : this.preference(userId)
+ }
+
+ async claimSignupOrganization(userId: string, enteredAt: Date): Promise<string | undefined> {
+ const [row]: { id: string }[] = await this.db.query(
+ `WITH claimed AS (
+ UPDATE product_analytics_consent c SET signup_claimed = true
+ FROM "user" u
+ JOIN organization_user m ON m."userId" = u.id AND m."isDefaultForUser"
+ JOIN organization o ON o.id = m."organizationId" AND o."createdBy" = u.id
+ WHERE u.id = $1 AND c.user_id = u.id AND c.allowed AND c.notice_version = $3 AND NOT c.signup_claimed
+ AND u."createdAt" BETWEEN $2 AND CURRENT_TIMESTAMP
+ AND $2::timestamptz > CURRENT_TIMESTAMP - INTERVAL '24 hours'
+ RETURNING o.id
+ ) SELECT id FROM claimed`,
+ [userId, enteredAt, analyticsNoticeVersion],
+ )
+ return row?.id
+ }
+
+ async requireMember(userId: string, organizationId: string) {
+ const rows = await this.db.query('SELECT 1 FROM organization_user WHERE "userId" = $1 AND "organizationId" = $2', [
+ userId,
+ organizationId,
+ ])
+ if (!rows.length) throw new ForbiddenException('Organization membership required')
+ }
+
+ async consolePreference(userId: string, organizationId: string) {
+ const [row]: (Decision & { since: Date | null })[] = await this.db.query(
+ `SELECT person.allowed, person.notice_version, person.decided_at,
+ CASE WHEN person.allowed AND creator.allowed AND person.notice_version = $3 AND creator.notice_version = $3
+ THEN greatest(person.decided_at, creator.decided_at) END AS since
+ FROM organization_user member JOIN organization o ON o.id = member."organizationId"
+ LEFT JOIN product_analytics_consent person ON person.user_id = member."userId"
+ LEFT JOIN product_analytics_consent creator ON creator.user_id = o."createdBy"
+ WHERE member."userId" = $1 AND member."organizationId" = $2`,
+ [userId, organizationId, analyticsNoticeVersion],
+ )
+ if (!row) throw new ForbiddenException('Organization membership required')
+ return { ...preference(row), enabledFrom: row.since?.toISOString() ?? null }
+ }
+
+ private async subject(kind: Subject, id: string, admitCold: () => boolean): Promise<string> {
+ const key = analyticsConsentCacheKey(kind, id)
+ const cached = await sharedRead(this.cacheReads, key, () => this.redis.get(key))
+ if (cached !== null) return cached
+ if (!this.maxSqlReads || !admitCold()) return ''
+ return sharedRead(this.databaseReads, key, () => this.readDatabase(kind, id, key))
+ }
+
+ private async readDatabase(kind: Subject, id: string, key: string): Promise<string> {
+ if (this.activeSqlReads < this.maxSqlReads) this.activeSqlReads++
+ else await new Promise<void>((resolve) => this.sqlWaiters.push(resolve))
+ const expiresAt = Date.now() + ttlMs
+ let value: string
+ try {
+ const sql =
+ kind === 'creator'
+ ? 'SELECT "createdBy" AS value FROM organization WHERE id = $1'
+ : `SELECT ceil(extract(epoch FROM decided_at) * 1000)::bigint::text AS value
+ FROM product_analytics_consent WHERE user_id = $1 AND allowed AND notice_version = $2`
+ const [row]: { value: string }[] = await this.db.query(
+ sql,
+ kind === 'creator' ? [id] : [id, analyticsNoticeVersion],
+ )
+ value = row?.value ?? ''
+ } finally {
+ // Hand this slot to the next reader before doing any cache write or HTTP work.
+ const next = this.sqlWaiters.shift()
+ if (next) next()
+ else this.activeSqlReads--
+ }
+ // Cache misses and denials, too. Slow reads must not extend a stale decision's lifetime.
+ if (Date.now() >= expiresAt) return ''
+ await this.redis.set(key, value, 'PXAT', expiresAt, 'NX')
+ return value
+ }
+
+ async dispatch(subjects: AnalyticsSubjects, occurredAt: Date, send: () => Promise<void>): Promise<boolean> {
+ const at = occurredAt.getTime()
+ if (!Number.isFinite(at) || at > Date.now() || this.redis.status !== 'ready') return false
+ let cold = false
+ const admitCold = () => {
+ if (cold) return true
+ if (this.coldEvents >= this.maxColdEvents) {
+ this.overflow.add(1)
+ return false
+ }
+ this.coldEvents++
+ cold = true
+ return true
+ }
+ try {
+ const users = new Set(subjects.users)
+ for (const org of new Set(subjects.organizations)) {
+ const creator = await this.subject('creator', org, admitCold)
+ if (!creator) return false
+ users.add(creator)
+ }
+ if (!users.size) return false
+ for (const user of users) {
+ const grant = await this.subject('grant', user, admitCold)
+ if (!/^\d+$/.test(grant) || Number(grant) > at) return false
+ }
+ } finally {
+ if (cold) this.coldEvents--
+ }
+ await send()
+ return true
+ }
+}
diff --git a/apps/api/src/analytics/services/analytics.consent-delivery.spec.ts b/apps/api/src/analytics/services/analytics.consent-delivery.spec.ts
new file mode 100644
index 000000000..28c2c8674
--- /dev/null
+++ b/apps/api/src/analytics/services/analytics.consent-delivery.spec.ts
@@ -0,0 +1,31 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { createServer } from 'node:http'
+import { AddressInfo } from 'node:net'
+import { AnalyticsConsentService } from './analytics-consent.service'
+import { AnalyticsService } from './analytics.service'
+import { TypedConfigService } from '../../config/typed-config.service'
+import { recordBusinessEvent } from '../../common/utils/business-event.util'
+
+it('sends no analytics request for an organization without a creator grant', async () => {
+ let requests = 0
+ const server = createServer((req, res) => {
+ requests++
+ req.resume()
+ res.writeHead(200).end('{"status":1}')
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ try {
+ const config: Record<string, string> = {
+ 'posthog.apiKey': 'phc_test',
+ 'posthog.host': 'http://127.0.0.1:' + (server.address() as AddressInfo).port,
+ }
+ const denied = Object.create(AnalyticsConsentService.prototype) as AnalyticsConsentService
+ jest.spyOn(denied, 'dispatch').mockResolvedValue(false)
+ const analytics = new AnalyticsService({ get: (key: string) => config[key] } as TypedConfigService, denied)
+ recordBusinessEvent({ name: 'box.open', outcome: 'success', correlationId: 'box', organizationId: 'org' })
+ await analytics.onApplicationShutdown()
+ expect(requests).toBe(0)
+ } finally {
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ }
+})
diff --git a/apps/api/src/analytics/services/analytics.delivery.spec.ts b/apps/api/src/analytics/services/analytics.delivery.spec.ts
new file mode 100644
index 000000000..7a1f72592
--- /dev/null
+++ b/apps/api/src/analytics/services/analytics.delivery.spec.ts
@@ -0,0 +1,136 @@
+/*
+ * 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 { Test, TestingModule } from '@nestjs/testing'
+import { logs } from '@opentelemetry/api-logs'
+import { InMemoryLogRecordExporter, LoggerProvider, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs'
+import { LoggerModule, Logger as PinoLogger } from 'nestjs-pino'
+import { swapMessageAndObject } from '../../common/utils/pino.util'
+import { Job } from '../../box/entities/job.entity'
+import { JobStatus } from '../../box/enums/job-status.enum'
+import { JobType } from '../../box/enums/job-type.enum'
+import { ResourceType } from '../../box/enums/resource-type.enum'
+import { recordBoxJobOutcome } from '../../box/utils/box-business-event.util'
+import { TypedConfigService } from '../../config/typed-config.service'
+import { grantedAnalyticsConsent } from '../../../test/granted-analytics-consent'
+import { AnalyticsService } from './analytics.service'
+
+// Apply the production instrumentation hook inside Jest's module registry.
+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)
+})
+
+it('delivers historical job identity and occurrence time through real PostHog HTTP and OTLP logging', async () => {
+ type Captured = {
+ event: string
+ uuid: string
+ distinct_id: string
+ timestamp: string
+ properties: Record<string, unknown>
+ }
+ const received: Captured[] = []
+ const server = createServer((request, response) => {
+ const chunks: Buffer[] = []
+ request.on('data', (chunk) => chunks.push(chunk))
+ request.on('end', () => {
+ received.push(...JSON.parse(Buffer.concat(chunks).toString()).batch)
+ response.writeHead(200, { 'content-type': 'application/json' }).end('{"status":1}')
+ })
+ })
+ const exporter = new InMemoryLogRecordExporter()
+ const provider = new LoggerProvider({ processors: [new SimpleLogRecordProcessor(exporter)] })
+ let app: TestingModule | undefined
+ let analytics: AnalyticsService | undefined
+ try {
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', resolve)
+ })
+ logs.setGlobalLoggerProvider(provider)
+ app = await Test.createTestingModule({
+ imports: [
+ LoggerModule.forRoot({
+ pinoHttp: [
+ { level: 'info', hooks: { logMethod: swapMessageAndObject } },
+ new Writable({ write: (_chunk, _encoding, done) => done() }),
+ ],
+ }),
+ ],
+ }).compile()
+ app.useLogger(app.get(PinoLogger))
+ const config: Record<string, string> = {
+ 'posthog.apiKey': 'phc_test',
+ 'posthog.host': 'http://127.0.0.1:' + (server.address() as AddressInfo).port,
+ 'posthog.environment': 'test',
+ }
+ analytics = new AnalyticsService(
+ { get: (key: string) => config[key] } as TypedConfigService,
+ grantedAnalyticsConsent,
+ )
+ const job = new Job({
+ id: 'job-1',
+ type: JobType.START_BOX,
+ runnerId: 'runner-1',
+ resourceType: ResourceType.BOX,
+ resourceId: 'box-1',
+ completedAt: new Date('2020-01-01T00:00:03Z'),
+ })
+ job.createdAt = new Date('2020-01-01T00:00:00Z')
+ const box = { id: job.resourceId, organizationId: 'org-1', imageIsOrgOwned: true }
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, box, job)
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, box, job)
+ await analytics.onApplicationShutdown()
+ analytics = undefined
+
+ const exported = exporter.getFinishedLogRecords().filter((record) => record.body === 'box.start success')
+ const features = received.filter((event) => event.event === 'cloud.feature.use')
+ const featureLogs = exporter.getFinishedLogRecords().filter((record) => record.body === 'cloud.feature.use success')
+ expect(features).toHaveLength(2)
+ expect(featureLogs).toHaveLength(2)
+ expect(features[0].uuid).toBe(features[1].uuid)
+ for (const [index, event] of features.entries()) {
+ expect(event.uuid).toBe(featureLogs[index].attributes['event.id'])
+ expect(event.timestamp).toBe(job.completedAt!.toISOString())
+ expect(event.properties).toMatchObject({
+ cloud_metrics_schema: '1',
+ 'feature.name': 'custom_image',
+ 'feature.evidence': 'started_image',
+ $groups: { organization: box.organizationId },
+ })
+ expect(event.properties).not.toHaveProperty('activity_schema')
+ }
+ const captured = received.filter((event) => event.event === 'box.start')
+ expect(exported).toHaveLength(2)
+ expect(captured).toHaveLength(2)
+ expect(captured[0].uuid).toEqual(expect.any(String))
+ expect(captured[1].uuid).toBe(captured[0].uuid)
+ for (const [index, event] of captured.entries()) {
+ expect(event.uuid).toBe(exported[index].attributes['event.id'])
+ expect(event.distinct_id).toBe('anonymous:box-1')
+ expect(event.timestamp).toBe(job.completedAt!.toISOString())
+ expect(event.properties).toMatchObject({
+ 'event.id': exported[index].attributes['event.id'],
+ 'event.timestamp': job.completedAt!.toISOString(),
+ 'job.id': job.id,
+ 'job.duration_ms': '3000',
+ $groups: { organization: box.organizationId },
+ $process_person_profile: false,
+ })
+ expect(exported[index].attributes['event.timestamp']).toBe(event.timestamp)
+ expect(exported[index].hrTime[0]).toBeGreaterThan(job.completedAt!.getTime() / 1000)
+ }
+ } finally {
+ await analytics?.onApplicationShutdown()
+ await app?.close()
+ await provider.shutdown()
+ logs.disable()
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ }
+})
diff --git a/apps/api/src/analytics/services/analytics.service.spec.ts b/apps/api/src/analytics/services/analytics.service.spec.ts
index c4837bd66..9492a62cf 100644
--- a/apps/api/src/analytics/services/analytics.service.spec.ts
+++ b/apps/api/src/analytics/services/analytics.service.spec.ts
@@ -3,25 +3,25 @@
* SPDX-License-Identifier: AGPL-3.0
*/
const mockCapture = jest.fn()
-const mockGroupIdentify = jest.fn()
const mockOn = jest.fn()
const mockShutdown = jest.fn().mockResolvedValue(undefined)
-jest.mock('posthog-node', () => ({
- PostHog: jest.fn(() => ({
- capture: mockCapture,
+jest.mock('./consent-bound-posthog', () => ({
+ ConsentBoundPostHog: jest.fn(() => ({
+ deliver: mockCapture,
shutdown: mockShutdown,
on: mockOn,
- groupIdentify: mockGroupIdentify,
})),
}))
import { Logger } from '@nestjs/common'
import { Test, TestingModule } from '@nestjs/testing'
-import { PostHog } from 'posthog-node'
+import { ConsentBoundPostHog } from './consent-bound-posthog'
import { Context } from '../../common/context/context'
import { PlatformReason } from '../../common/context/platform-reason.enum'
import { recordBusinessEvent, recordOutcomes, subscribeBusinessEvents } from '../../common/utils/business-event.util'
import { TypedConfigService } from '../../config/typed-config.service'
+import { AnalyticsConsentService } from './analytics-consent.service'
+import { grantedAnalyticsConsent } from '../../../test/granted-analytics-consent'
import { AnalyticsService } from './analytics.service'
describe('PostHog business events', () => {
@@ -39,7 +39,11 @@ describe('PostHog business events', () => {
jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined)
jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined)
module = await Test.createTestingModule({
- providers: [AnalyticsService, { provide: TypedConfigService, useValue: { get: (key: string) => config[key] } }],
+ providers: [
+ AnalyticsService,
+ { provide: AnalyticsConsentService, useValue: grantedAnalyticsConsent },
+ { provide: TypedConfigService, useValue: { get: (key: string) => config[key] } },
+ ],
}).compile()
await module.init()
})
@@ -76,13 +80,18 @@ describe('PostHog business events', () => {
}),
}),
)
- expect(PostHog).toHaveBeenCalledTimes(1)
+ expect(ConsentBoundPostHog).toHaveBeenCalledTimes(1)
})
it('captures classified failures without leaking the business exception', async () => {
const failure = new Error('secret database failure')
await expect(
recordOutcomes(
- { name: 'box.stop', correlationId: 'box-1', ctx: Context.platform(PlatformReason.AUTO_STOP) },
+ {
+ name: 'box.stop',
+ correlationId: 'box-1',
+ organizationId: 'org-1',
+ ctx: Context.platform(PlatformReason.AUTO_STOP),
+ },
async () => {
throw failure
},
@@ -100,7 +109,7 @@ describe('PostHog business events', () => {
}),
}),
)
- expect(PostHog).toHaveBeenCalledTimes(1)
+ expect(ConsentBoundPostHog).toHaveBeenCalledTimes(1)
expect(JSON.stringify(mockCapture.mock.calls)).not.toContain('secret database failure')
})
it('does not invent a person for preview presence', () => {
@@ -114,13 +123,37 @@ describe('PostHog business events', () => {
expect(mockCapture.mock.calls[0][0].properties).not.toHaveProperty('user.id')
})
+ it('keeps Cloud operation metrics out of Activity totals', () => {
+ recordBusinessEvent({
+ name: 'cloud.box.create',
+ outcome: 'requested',
+ correlationId: 'operation-1',
+ organizationId: 'org-1',
+ })
+ const capture = mockCapture.mock.calls[0][0]
+ expect(capture.properties.cloud_metrics_schema).toBe('1')
+ expect(capture.properties).not.toHaveProperty('activity_schema')
+ expect(capture.groups).toEqual({ organization: 'org-1' })
+ })
+
+ it('uses the same occurrence UUID and timestamp as the operational log', () => {
+ recordBusinessEvent({ name: 'box.start', outcome: 'success', correlationId: 'box-1', organizationId: 'org-1' })
+ const attributes = jest
+ .mocked(Logger.prototype.log)
+ .mock.calls.find(([message]) => message === 'box.start success')?.[1] as Record<string, string>
+ const capture = mockCapture.mock.calls[0][0]
+ expect(capture.uuid).toEqual(expect.any(String))
+ expect(capture.uuid).toBe(attributes['event.id'])
+ expect(capture.timestamp.toISOString()).toBe(attributes['event.timestamp'])
+ })
+
it('preserves business results when capture throws', async () => {
mockCapture.mockImplementation(() => {
throw new Error('transport secret')
})
await expect(
recordOutcomes(
- { name: 'box.stop', correlationId: 'box-1' },
+ { name: 'box.stop', correlationId: 'box-1', organizationId: 'org-1' },
async () => 42,
() => 'internal',
),
@@ -134,7 +167,12 @@ describe('PostHog business events', () => {
['user.login', 'user-1', 'user-1', true],
['box.stop', 'box-1', 'anonymous:box-1', false],
] as const)('keeps %s identity and person-profile semantics', (name, correlationId, distinctId, profile) => {
- recordBusinessEvent({ name, outcome: 'success', correlationId })
+ recordBusinessEvent({
+ name,
+ outcome: 'success',
+ correlationId,
+ organizationId: name === 'box.stop' ? 'org-1' : undefined,
+ })
expect(mockCapture).toHaveBeenCalledWith(
expect.objectContaining({
event: name,
@@ -156,7 +194,7 @@ describe('PostHog business events', () => {
})
const stop = subscribeBusinessEvents(observed)
try {
- recordBusinessEvent({ name: 'box.stop', outcome: 'success', correlationId: 'box-1' })
+ recordBusinessEvent({ name: 'box.stop', outcome: 'success', correlationId: 'box-1', organizationId: 'org-1' })
expect(observed).toHaveBeenCalledWith(expect.objectContaining({ 'event.name': 'box.stop' }))
expect(Logger.prototype.warn).toHaveBeenCalledWith('Business event analytics capture failed')
expect(JSON.stringify(jest.mocked(Logger.prototype.warn).mock.calls)).not.toContain('private-observer-error')
@@ -167,7 +205,7 @@ describe('PostHog business events', () => {
})
it('keeps group-identification and SDK delivery failures out of business results', async () => {
- mockGroupIdentify.mockImplementationOnce(() => {
+ mockCapture.mockImplementationOnce(() => {
throw new Error('private-group-error')
})
await expect(
@@ -179,10 +217,15 @@ describe('PostHog business events', () => {
users: [{ userId: 'user-1', isDefaultForUser: true }],
} as never),
).resolves.toBeUndefined()
- expect(mockGroupIdentify).toHaveBeenCalledWith(expect.objectContaining({ groupKey: 'org-1' }))
+ expect(mockCapture).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: '$groupidentify',
+ properties: expect.objectContaining({ $group_key: 'org-1' }),
+ }),
+ )
const deliveryFailure = mockOn.mock.calls.find(([name]) => name === 'error')![1]
deliveryFailure(new Error('private-delivery-error'))
- expect(Logger.prototype.warn).toHaveBeenCalledWith('PostHog organization identification failed')
+ expect(Logger.prototype.warn).toHaveBeenCalledWith('PostHog analytics capture failed')
expect(Logger.prototype.warn).toHaveBeenCalledWith('PostHog analytics delivery failed')
expect(JSON.stringify(jest.mocked(Logger.prototype.warn).mock.calls)).not.toContain('private-')
})
@@ -195,7 +238,7 @@ describe('PostHog business events', () => {
})
it('unsubscribes before shutdown and waits for the queued delivery', async () => {
- recordBusinessEvent({ name: 'box.stop', outcome: 'requested', correlationId: 'box-1' })
+ recordBusinessEvent({ name: 'box.stop', outcome: 'requested', correlationId: 'box-1', organizationId: 'org-1' })
expect(mockCapture).toHaveBeenCalledTimes(1)
let finish: () => void
let start: () => void
@@ -216,7 +259,7 @@ describe('PostHog business events', () => {
// Nest shutdown visits module-destroy hooks before application-shutdown hooks.
await started
expect(mockShutdown).toHaveBeenCalledWith(5000)
- recordBusinessEvent({ name: 'box.stop', outcome: 'success', correlationId: 'box-1' })
+ recordBusinessEvent({ name: 'box.stop', outcome: 'success', correlationId: 'box-1', organizationId: 'org-1' })
expect(mockCapture).toHaveBeenCalledTimes(1)
expect(closed).toBe(false)
finish!()
diff --git a/apps/api/src/analytics/services/analytics.service.ts b/apps/api/src/analytics/services/analytics.service.ts
index 846e582d4..7a73a0813 100644
--- a/apps/api/src/analytics/services/analytics.service.ts
+++ b/apps/api/src/analytics/services/analytics.service.ts
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: AGPL-3.0
*/
+import { AnalyticsConsentService, AnalyticsSubjects } from './analytics-consent.service'
import { Injectable, Logger, OnApplicationShutdown } from '@nestjs/common'
import { OnEvent } from '@nestjs/event-emitter'
import { BoxEvents } from '../../box/constants/box-events.constants'
@@ -14,7 +15,8 @@ import { BoxInboundModeUpdatedEvent } from '../../box/events/box-inbound-mode-up
import { BoxStartedEvent } from '../../box/events/box-started.event'
import { BoxStateUpdatedEvent } from '../../box/events/box-state-updated.event'
import { BoxStoppedEvent } from '../../box/events/box-stopped.event'
-import { PostHog } from 'posthog-node'
+import type { PostHog } from 'posthog-node'
+import { ConsentBoundPostHog } from './consent-bound-posthog'
import { OnAsyncEvent } from '../../common/decorators/on-async-event.decorator'
import { Organization } from '../../organization/entities/organization.entity'
import { OrganizationEvents } from '../../organization/constants/organization-events.constant'
@@ -24,65 +26,93 @@ import { subscribeBusinessEvents } from '../../common/utils/business-event.util'
@Injectable()
export class AnalyticsService implements OnApplicationShutdown {
private readonly logger = new Logger(AnalyticsService.name)
- private readonly posthog?: PostHog
+ private readonly posthog?: ConsentBoundPostHog
private readonly unsubscribe?: () => void
+ private readonly pending = new Set<Promise<unknown>>()
+ private closing = false
+
get enabled(): boolean {
return !!this.posthog
}
- constructor(private readonly configService: TypedConfigService) {
- if (!this.configService.get('posthog.apiKey')) {
- return
- }
-
- if (!this.configService.get('posthog.host')) {
- return
- }
+ constructor(
+ private readonly configService: TypedConfigService,
+ private readonly consent: AnalyticsConsentService,
+ ) {
+ if (!this.configService.get('posthog.apiKey') || !this.configService.get('posthog.host')) return
// Initialize PostHog client
- this.posthog = new PostHog(this.configService.get('posthog.apiKey'), {
+ this.posthog = new ConsentBoundPostHog(this.configService.get('posthog.apiKey'), {
host: this.configService.get('posthog.host'),
+ requestTimeout: 1200,
+ fetchRetryCount: 0,
})
this.posthog.on('error', () => this.logger.warn('PostHog analytics delivery failed'))
this.unsubscribe = subscribeBusinessEvents((attributes) => {
- const userId =
- attributes['user.id'] ||
- (attributes['event.name'].startsWith('user.') ? attributes['correlation.id'] : undefined)
+ const accountEvent = attributes['event.name'] === 'user.login' || attributes['event.name'] === 'user.registration'
+ const targetUser = accountEvent ? attributes['correlation.id'] : undefined
+ const userId = attributes['user.id'] || targetUser
const organizationId = attributes['organization.id']
- this.capture({
- event: attributes['event.name'],
- distinctId: userId || `${attributes['actor.kind'] || 'anonymous'}:${attributes['correlation.id']}`,
- timestamp: new Date(attributes['event.timestamp']),
- groups: organizationId ? { organization: organizationId } : undefined,
- properties: {
- ...attributes,
- activity_schema: '1',
- environment: this.configService.get('posthog.environment'),
- $process_person_profile: !!userId,
+ if (!accountEvent && !organizationId) return
+ if (['user', 'admin'].includes(attributes['actor.kind']) && !attributes['user.id']) return
+ this.capture(
+ {
+ event: attributes['event.name'],
+ uuid: attributes['event.id'],
+ distinctId: userId || `${attributes['actor.kind'] || 'anonymous'}:${attributes['correlation.id']}`,
+ timestamp: new Date(attributes['event.timestamp']),
+ groups: organizationId ? { organization: organizationId } : undefined,
+ properties: {
+ ...attributes,
+ ...(attributes['event.name'].startsWith('cloud.')
+ ? { cloud_metrics_schema: '1' }
+ : { activity_schema: '1' }),
+ $process_person_profile: !!userId,
+ },
+ },
+ {
+ users: [...new Set([userId, targetUser].filter((id): id is string => !!id))],
+ organizations: organizationId ? [organizationId] : [],
},
- })
+ attributes['ci.job_created_at'] ? new Date(attributes['ci.job_created_at']) : undefined,
+ )
})
}
- capture(event: Parameters<PostHog['capture']>[0]): void {
- try {
- this.posthog?.capture(event)
- } catch {
- this.logger.warn('PostHog analytics capture failed')
- }
+ capture(event: Parameters<PostHog['capture']>[0], subjects: AnalyticsSubjects, consentSince?: Date): void {
+ const client = this.posthog
+ if (!client || this.closing || (!subjects.users.length && !subjects.organizations.length)) return
+ const occurredAt = event.timestamp ?? new Date()
+ const delivery = this.consent
+ .dispatch(subjects, consentSince ?? occurredAt, () =>
+ client.deliver({
+ ...event,
+ timestamp: occurredAt,
+ properties: { ...event.properties, environment: this.configService.get('posthog.environment') },
+ }),
+ )
+ .catch(() => this.logger.warn('PostHog analytics capture failed'))
+ this.pending.add(delivery)
+ void delivery.finally(() => this.pending.delete(delivery))
}
- groupIdentify(group: Parameters<PostHog['groupIdentify']>[0]): void {
- try {
- this.posthog?.groupIdentify(group)
- } catch {
- this.logger.warn('PostHog organization identification failed')
- }
+ groupIdentify(group: Parameters<PostHog['groupIdentify']>[0], users: string[] = []): void {
+ if (!group.groupKey) return
+ this.capture(
+ {
+ event: '$groupidentify',
+ distinctId: group.distinctId || `$${group.groupType}_${group.groupKey}`,
+ properties: { $group_type: group.groupType, $group_key: group.groupKey, $group_set: group.properties },
+ },
+ { users, organizations: [group.groupKey] },
+ )
}
async onApplicationShutdown(): Promise<void> {
+ this.closing = true
this.unsubscribe?.()
+ await Promise.allSettled(this.pending)
try {
await this.posthog?.shutdown(5000)
} catch {
@@ -139,7 +169,6 @@ export class AnalyticsService implements OnApplicationShutdown {
properties: {
name: payload.name,
created_at: payload.createdAt,
- created_by: payload.createdBy,
is_default_for_creator: payload.users?.some(
(user) => user.userId === payload.createdBy && user.isDefaultForUser,
),
diff --git a/apps/api/src/analytics/services/consent-bound-posthog.ts b/apps/api/src/analytics/services/consent-bound-posthog.ts
new file mode 100644
index 000000000..315c80335
--- /dev/null
+++ b/apps/api/src/analytics/services/consent-bound-posthog.ts
@@ -0,0 +1,17 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { PostHog } from 'posthog-node'
+
+export class ConsentBoundPostHog extends PostHog {
+ // The public captureImmediate in posthog-node 4.18 resolves before its HTTP request.
+ // Track the HTTP attempt through shutdown and report transport failures.
+ deliver({
+ distinctId,
+ event,
+ properties,
+ groups,
+ timestamp,
+ uuid,
+ }: Parameters<PostHog['capture']>[0]): Promise<void> {
+ return this.captureStatelessImmediate(distinctId, event, { ...properties, $groups: groups }, { timestamp, uuid })
+ }
+}
diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts
index 785c04942..442223f3f 100644
--- a/apps/api/src/app.module.ts
+++ b/apps/api/src/app.module.ts
@@ -34,6 +34,8 @@ import { MaintenanceMiddleware } from './common/middleware/maintenance.middlewar
import { AuditModule } from './audit/audit.module'
import { HealthModule } from './health/health.module'
import { StatusSyncModule } from './status-sync/status-sync.module'
+import { AnalyticsService } from './analytics/services/analytics.service'
+import { OpenFeature } from '@openfeature/server-sdk'
import { OpenFeatureModule } from '@openfeature/nestjs-sdk'
import { OpenFeaturePostHogProvider } from './common/providers/openfeature-posthog.provider'
import { LoggerModule } from 'nestjs-pino'
@@ -214,18 +216,31 @@ import { McpModule } from './mcp/mcp.module'
organizationId: req.user?.organizationId,
}
},
- defaultProvider: new OpenFeaturePostHogProvider({
- clientOptions: {
- host: process.env.POSTHOG_HOST,
- },
- apiKey: process.env.POSTHOG_API_KEY,
- }),
}),
],
controllers: [],
providers: [AppService],
})
export class AppModule implements NestModule {
+ constructor(analytics: AnalyticsService) {
+ OpenFeature.setProvider(
+ new OpenFeaturePostHogProvider({
+ apiKey: process.env.POSTHOG_API_KEY,
+ clientOptions: { host: process.env.POSTHOG_HOST },
+ reportExposure: (flag, value, userId, orgId) =>
+ analytics.capture(
+ {
+ event: '$feature_flag_called',
+ distinctId: userId,
+ groups: orgId ? { organization: orgId } : undefined,
+ properties: { $feature_flag: flag, $feature_flag_response: value },
+ },
+ { users: [userId], organizations: orgId ? [orgId] : [] },
+ ),
+ }),
+ )
+ }
+
configure(consumer: MiddlewareConsumer) {
consumer.apply(VersionHeaderMiddleware).forRoutes({ path: '{*path}', method: RequestMethod.ALL })
consumer.apply(FailedAuthRateLimitMiddleware).forRoutes({ path: '{*path}', method: RequestMethod.ALL })
diff --git a/apps/api/src/audit/audit-targets.spec.ts b/apps/api/src/audit/audit-targets.spec.ts
index 658096cc5..7c12105f8 100644
--- a/apps/api/src/audit/audit-targets.spec.ts
+++ b/apps/api/src/audit/audit-targets.spec.ts
@@ -105,7 +105,7 @@ describe('audit targets at HTTP boundaries', () => {
} else {
expect(boxes.create).toHaveBeenCalledTimes(1)
expect(boxes.create.mock.calls[0][0]).toMatchObject({ cmd, entrypoint })
- if (outcome === 'timeout') expect(waitForStarted).toHaveBeenCalledWith(box.id, 'org', 30)
+ if (outcome === 'timeout') expect(waitForStarted).toHaveBeenCalledWith(box.id, 'org', 30, expect.any(Function))
else expect(waitForStarted).not.toHaveBeenCalled()
}
})
@@ -120,7 +120,7 @@ describe('audit targets at HTTP boundaries', () => {
expect(res.status).toBe(408)
expect(await res.json()).toMatchObject({ boxId: box.id })
expect(boxes.create).toHaveBeenCalledTimes(1)
- expect(waitForStarted).toHaveBeenCalledWith(box.id, 'org', 30)
+ expect(waitForStarted).toHaveBeenCalledWith(box.id, 'org', 30, expect.any(Function))
expect(audit.updateLog).toHaveBeenCalledWith(
'audit',
expect.objectContaining({ statusCode: 408, targetId: box.id }),
diff --git a/apps/api/src/auth/mcp-delegation.ts b/apps/api/src/auth/mcp-delegation.ts
index 62e10c022..b9cb8deb9 100644
--- a/apps/api/src/auth/mcp-delegation.ts
+++ b/apps/api/src/auth/mcp-delegation.ts
@@ -20,6 +20,12 @@ const NONCE_TTL_MS = 30_000
/** Nonce → caller. One map per process: a nonce never leaves this process and its own socket. */
const callers = new Map<string, { caller: AuthContextType; expiresAt: number }>()
+const delegatedRequests = new WeakSet<Request>()
+
+export function isDelegatedMcpRequest(request: Request): boolean {
+ return delegatedRequests.has(request)
+}
+
function take(nonce: unknown): AuthContextType | undefined {
if (typeof nonce !== 'string') return undefined
const entry = callers.get(nonce)
@@ -35,6 +41,7 @@ passport.use(MCP_DELEGATION_STRATEGY, {
const caller = take(req.headers[MCP_DELEGATION_HEADER])
// fail() without a challenge lets passport try the next strategy.
if (caller) {
+ delegatedRequests.add(req)
this.success(caller)
} else {
this.fail()
diff --git a/apps/api/src/box/box.module.ts b/apps/api/src/box/box.module.ts
index ef78e74fa..477c83a24 100644
--- a/apps/api/src/box/box.module.ts
+++ b/apps/api/src/box/box.module.ts
@@ -9,6 +9,7 @@ import { SecretCredentialService } from './services/secret-credential.service'
import { SecretCredentialController } from './controllers/secret-credential.controller'
import { DataSource } from 'typeorm'
import { BoxController } from './controllers/box.controller'
+import { FeatureUsageController } from './controllers/feature-usage.controller'
import { BoxService } from './services/box.service'
import { SecretServerClient } from './services/secret-server-client'
import { BoxExitCodeService } from './services/box-exit-code.service'
@@ -121,6 +122,7 @@ import { GcpDiskClient } from './services/gcp-disk-client'
JobController,
CustomDomainController,
CustomDomainMaintenanceController,
+ FeatureUsageController,
],
providers: [
SecretCredentialService,
diff --git a/apps/api/src/box/controllers/feature-usage.auth.spec.ts b/apps/api/src/box/controllers/feature-usage.auth.spec.ts
new file mode 100644
index 000000000..47b844f98
--- /dev/null
+++ b/apps/api/src/box/controllers/feature-usage.auth.spec.ts
@@ -0,0 +1,85 @@
+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
+import { INestApplication, Logger } from '@nestjs/common'
+import { Test } from '@nestjs/testing'
+import { getRepositoryToken } from '@nestjs/typeorm'
+import passport from 'passport'
+import { AddressInfo } from 'node:net'
+import { ApiKeyStrategy } from '../../auth/api-key.strategy'
+import { FeatureUsageController } from './feature-usage.controller'
+import { Box } from '../entities/box.entity'
+import { subscribeBusinessEvents } from '../../common/utils/business-event.util'
+
+describe('Cloud feature ingestion credential boundary', () => {
+ let app: INestApplication, find: jest.Mock, dispose: () => void
+ let observed: Readonly<Record<string, string>>[]
+ beforeEach(async () => {
+ jest.spyOn(Logger.prototype, 'log').mockImplementation(() => {})
+ jest.spyOn(Logger.prototype, 'debug').mockImplementation(() => {})
+ jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => {})
+ observed = []
+ dispose = subscribeBusinessEvents((event) => observed.push(event))
+ const strategy = new ApiKeyStrategy(
+ { get: async () => null, setex: async () => {} } as any,
+ {
+ getApiKeyByValue: async (token) => {
+ if (token === 'customer-fixture') return { userId: 'customer', organizationId: 'org-1', name: 'customer' }
+ throw new Error('unknown key')
+ },
+ updateLastUsedAt: async () => {},
+ } as any,
+ { findOne: async () => ({ id: 'customer', role: 'user' }) } as any,
+ { get: (key) => (key === 'proxy.apiKey' ? 'proxy-fixture' : undefined) } as any,
+ { findByApiKey: async (token) => (token === 'runner-fixture' ? { id: 'runner-1' } : null) } as any,
+ { findOneByProxyApiKey: async () => null } as any,
+ )
+ // These are bearer-key tests; JWT verification has its own suite.
+ passport.use('jwt', {
+ authenticate() {
+ this.fail()
+ },
+ } as passport.Strategy)
+ find = jest.fn().mockResolvedValue([{ id: 'CloudBox1234', organizationId: 'org-1', runnerId: 'runner-1' }])
+ const module = await Test.createTestingModule({
+ controllers: [FeatureUsageController],
+ providers: [
+ { provide: ApiKeyStrategy, useValue: strategy },
+ { provide: getRepositoryToken(Box), useValue: { find } },
+ ],
+ }).compile()
+ app = module.createNestApplication()
+ await app.listen(0, '127.0.0.1')
+ })
+ afterEach(async () => {
+ await app?.close()
+ dispose()
+ passport.unuse('api-key')
+ passport.unuse('jwt')
+ jest.restoreAllMocks()
+ })
+ it.each([
+ [undefined, 'ssh', 401],
+ ['unknown-fixture', 'ssh', 401],
+ ['customer-fixture', 'ssh', 403],
+ ['runner-fixture', 'ssh', 202],
+ ['proxy-fixture', 'tunnel_request', 202],
+ ])('authenticates %s before admitting %s evidence', async (token, kind, status) => {
+ const address = app.getHttpServer().address() as AddressInfo
+ const response = await fetch('http://127.0.0.1:' + address.port + '/telemetry/feature-usage', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: 'Bearer ' + token } : {}) },
+ body: JSON.stringify({
+ events: [
+ {
+ id: '11111111-1111-4111-8111-111111111111',
+ boxId: 'CloudBox1234',
+ kind,
+ occurredAt: new Date().toISOString(),
+ },
+ ],
+ }),
+ })
+ expect(response.status).toBe(status)
+ expect(observed).toHaveLength(status === 202 ? 1 : 0)
+ expect(find).toHaveBeenCalledTimes(status === 202 ? 1 : 0)
+ })
+})
diff --git a/apps/api/src/box/controllers/feature-usage.controller.spec.ts b/apps/api/src/box/controllers/feature-usage.controller.spec.ts
new file mode 100644
index 000000000..7ae0e4d26
--- /dev/null
+++ b/apps/api/src/box/controllers/feature-usage.controller.spec.ts
@@ -0,0 +1,207 @@
+/*
+ * Copyright 2026 BoxLite AI
+ * SPDX-License-Identifier: AGPL-3.0
+ */
+
+import { INestApplication, Logger } from '@nestjs/common'
+import { Test } from '@nestjs/testing'
+import { getRepositoryToken } from '@nestjs/typeorm'
+import { randomUUID } from 'node:crypto'
+import { createServer } from 'node:http'
+import { AddressInfo } from 'node:net'
+import { AnalyticsService } from '../../analytics/services/analytics.service'
+import { AnalyticsConsentService } from '../../analytics/services/analytics-consent.service'
+import { TypedConfigService } from '../../config/typed-config.service'
+import { CombinedAuthGuard } from '../../auth/combined-auth.guard'
+import { subscribeBusinessEvents } from '../../common/utils/business-event.util'
+import { FeatureUsageController } from './feature-usage.controller'
+import { Box } from '../entities/box.entity'
+
+describe('authenticated Cloud feature usage ingestion', () => {
+ const boxId = 'AbCdEf123456'
+ const id = '11111111-1111-4111-8111-111111111111'
+ let actor: Record<string, unknown>
+ let app: INestApplication
+ let observed: Readonly<Record<string, string>>[]
+ let dispose: () => void
+ let find: jest.Mock
+ let occurredAt: string
+
+ beforeEach(async () => {
+ jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined)
+ jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined)
+ actor = { role: 'runner', runnerId: 'runner-1' }
+ occurredAt = new Date(Date.now() - 1000).toISOString()
+ observed = []
+ dispose = subscribeBusinessEvents((event) => observed.push(event))
+ find = jest.fn().mockResolvedValue([{ id: boxId, organizationId: 'org-1', runnerId: 'runner-1' }])
+ const module = await Test.createTestingModule({
+ controllers: [FeatureUsageController],
+ providers: [{ provide: getRepositoryToken(Box), useValue: { find } }],
+ })
+ .overrideGuard(CombinedAuthGuard)
+ .useValue({
+ canActivate: (context) => {
+ context.switchToHttp().getRequest().user = actor
+ return true
+ },
+ })
+ .compile()
+ app = module.createNestApplication()
+ app.setGlobalPrefix('api')
+ await app.listen(0, '127.0.0.1')
+ })
+ afterEach(async () => {
+ await app?.close()
+ dispose()
+ jest.restoreAllMocks()
+ })
+
+ function send(events: unknown[], extra = {}): Promise<Response> {
+ const address = app.getHttpServer().address() as AddressInfo
+ return fetch('http://127.0.0.1:' + address.port + '/api/telemetry/feature-usage', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ events, ...extra }),
+ })
+ }
+ const event = (occurredAt: string, overrides = {}) => ({ id, boxId, kind: 'ssh', occurredAt, ...overrides })
+
+ it('preserves source identity/time and derives the organization from the owned Box', async () => {
+ const source = event(occurredAt)
+ const response = await send([source, source])
+ expect(response.status).toBe(202)
+ expect(await response.json()).toEqual({ accepted: 1 })
+ expect(find).toHaveBeenCalledTimes(1)
+ expect(observed).toEqual([
+ expect.objectContaining({
+ 'event.id': id,
+ 'event.timestamp': occurredAt,
+ 'organization.id': 'org-1',
+ 'feature.name': 'ssh',
+ 'feature.evidence': 'authenticated_session',
+ 'feature.source': 'runner',
+ }),
+ ])
+ })
+
+ it('admits overlapping SSH batches without waiting for consent or limiting HTTP sends', async () => {
+ const received: string[] = []
+ let firstBatchDelivered!: () => void
+ const warmFirstBatch = new Promise<void>((resolve) => {
+ firstBatchDelivered = resolve
+ })
+ const sink = createServer(async (request, response) => {
+ const chunks: Buffer[] = []
+ for await (const chunk of request) chunks.push(chunk)
+ const { batch } = JSON.parse(Buffer.concat(chunks).toString())
+ received.push(...batch.map((entry: { uuid: string }) => entry.uuid))
+ if (received.length === 98) firstBatchDelivered()
+ response.writeHead(200).end('{"status":1}')
+ })
+ let consentChecks = 0
+ let release!: () => void
+ const gate = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ let analytics: AnalyticsService | undefined
+ const observations = Array.from({ length: 200 }, () => event(occurredAt, { id: randomUUID() }))
+ try {
+ await new Promise<void>((resolve) => sink.listen(0, '127.0.0.1', resolve))
+ const config = {
+ 'posthog.apiKey': 'phc_test',
+ 'posthog.host': 'http://127.0.0.1:' + (sink.address() as AddressInfo).port,
+ }
+ analytics = new AnalyticsService(
+ { get: (key: string) => config[key] } as TypedConfigService,
+ {
+ dispatch: async (_subjects, _at, deliver) => {
+ consentChecks++
+ if (consentChecks <= 2) await gate
+ await deliver()
+ return true
+ },
+ } as AnalyticsConsentService,
+ )
+ expect(await (await send(observations.slice(0, 100))).json()).toEqual({ accepted: 100 })
+ expect(consentChecks).toBe(100)
+ await warmFirstBatch
+ expect(received).not.toContain(observations[0].id)
+ expect(received).not.toContain(observations[1].id)
+ expect(await (await send(observations.slice(100))).json()).toEqual({ accepted: 100 })
+ expect(consentChecks).toBe(200)
+ } finally {
+ release()
+ await analytics?.onApplicationShutdown()
+ await new Promise<void>((resolve) => sink.close(() => resolve()))
+ }
+ expect(received).toHaveLength(200)
+ expect(new Set(received)).toEqual(new Set(observations.map((entry) => entry.id)))
+ })
+
+ it.each(['tunnel_connection', 'tunnel_request'])('accepts Proxy evidence for %s', async (kind) => {
+ actor = { role: 'proxy' }
+ const response = await send([event(occurredAt, { kind })])
+ expect(await response.json()).toEqual({ accepted: 1 })
+ expect(observed[0]).toMatchObject({ 'feature.name': 'tunnel', 'feature.source': 'proxy' })
+ })
+
+ it('rejects a Runner reporting another Runner or another producer kind', async () => {
+ actor = { role: 'runner', runnerId: 'runner-2' }
+ expect(await (await send([event(occurredAt)])).json()).toEqual({ accepted: 0 })
+ actor = { role: 'runner', runnerId: 'runner-1' }
+ expect(await (await send([event(occurredAt, { kind: 'tunnel_connection' })])).json()).toEqual({ accepted: 0 })
+ expect(observed).toEqual([])
+ })
+
+ it('rejects Proxy claims of authenticated SSH and unknown resources', async () => {
+ actor = { role: 'proxy' }
+ expect(await (await send([event(occurredAt)])).json()).toEqual({ accepted: 0 })
+ find.mockResolvedValue([])
+ expect(await (await send([event(occurredAt, { kind: 'tunnel_connection' })])).json()).toEqual({ accepted: 0 })
+ expect(observed).toEqual([])
+ })
+
+ it('denies customer principals before reading resource ownership', async () => {
+ actor = { role: 'user', userId: 'user-1', organizationId: 'org-1' }
+ expect((await send([event(occurredAt)])).status).toBe(403)
+ expect(find).not.toHaveBeenCalled()
+ expect(observed).toEqual([])
+ })
+
+ it.each([
+ { id: 'invalid' },
+ { boxId: '../private' },
+ { kind: 'exec' },
+ { occurredAt: 'invalid' },
+ { occurredAt: '2026-02-31T00:00:00Z' },
+ { command: 'private-command' },
+ { organizationId: 'other-org' },
+ ])('validates the actual HTTP payload: %s', async (override) => {
+ expect((await send([event(occurredAt, override)])).status).toBe(400)
+ expect(find).not.toHaveBeenCalled()
+ expect(observed).toEqual([])
+ })
+
+ it('bounds batch sizes and rejects arbitrary envelope fields', async () => {
+ expect((await send([])).status).toBe(400)
+ expect((await send(Array.from({ length: 101 }, () => event(occurredAt)))).status).toBe(400)
+ expect((await send([event(occurredAt)], { token: 'private-token' })).status).toBe(400)
+ expect(find).not.toHaveBeenCalled()
+ })
+
+ it('omits stale and implausibly future evidence instead of changing its source time', async () => {
+ const past = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString()
+ const future = new Date(Date.now() + 6 * 60 * 1000).toISOString()
+ expect(await (await send([event(past), event(future)])).json()).toEqual({ accepted: 0 })
+ expect(observed).toEqual([])
+ })
+
+ it('reports collection unavailability without emitting data or exposing database errors', async () => {
+ find.mockRejectedValue(new Error('private-database-password'))
+ const response = await send([event(occurredAt)])
+ expect(response.status).toBe(503)
+ expect(await response.text()).not.toContain('private-database-password')
+ expect(observed).toEqual([])
+ })
+})
diff --git a/apps/api/src/box/controllers/feature-usage.controller.ts b/apps/api/src/box/controllers/feature-usage.controller.ts
new file mode 100644
index 000000000..f98f06c45
--- /dev/null
+++ b/apps/api/src/box/controllers/feature-usage.controller.ts
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2026 BoxLite AI
+ * SPDX-License-Identifier: AGPL-3.0
+ */
+
+import {
+ Body,
+ Controller,
+ ForbiddenException,
+ HttpCode,
+ Logger,
+ Post,
+ ServiceUnavailableException,
+ UseGuards,
+ ValidationPipe,
+} from '@nestjs/common'
+import { ApiExcludeController } from '@nestjs/swagger'
+import { InjectRepository } from '@nestjs/typeorm'
+import { In, Repository } from 'typeorm'
+import { CombinedAuthGuard } from '../../auth/combined-auth.guard'
+import { AuthContext } from '../../common/decorators/auth-context.decorator'
+import { AuthContextType } from '../../common/interfaces/auth-context.interface'
+import { recordBusinessEvent } from '../../common/utils/business-event.util'
+import { BOX_WARM_POOL_UNASSIGNED_ORGANIZATION } from '../constants/box.constants'
+import { FeatureUsageBatchDto } from '../dto/feature-usage.dto'
+import { Box } from '../entities/box.entity'
+
+const EVIDENCE = {
+ ssh: { name: 'ssh', evidence: 'authenticated_session', source: 'runner' },
+ tunnel_connection: { name: 'tunnel', evidence: 'established_connection', source: 'proxy' },
+ tunnel_request: { name: 'tunnel', evidence: 'successful_request', source: 'proxy' },
+} as const
+
+@ApiExcludeController()
+@Controller('telemetry/feature-usage')
+@UseGuards(CombinedAuthGuard)
+export class FeatureUsageController {
+ private readonly logger = new Logger(FeatureUsageController.name)
+ constructor(@InjectRepository(Box) private readonly boxes: Repository<Box>) {}
+
+ @Post()
+ @HttpCode(202)
+ async receive(
+ @AuthContext() actor: AuthContextType,
+ @Body(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))
+ batch: FeatureUsageBatchDto,
+ ): Promise<{ accepted: number }> {
+ if (actor.role !== 'runner' && actor.role !== 'proxy') throw new ForbiddenException()
+ let boxes: Pick<Box, 'id' | 'organizationId' | 'runnerId'>[]
+ try {
+ boxes = await this.boxes.find({
+ where: { id: In([...new Set(batch.events.map((event) => event.boxId))]) },
+ select: { id: true, organizationId: true, runnerId: true },
+ })
+ } catch {
+ this.logger.warn('Cloud feature usage lookup failed', { errorType: 'database_error' })
+ throw new ServiceUnavailableException('Feature usage collection unavailable')
+ }
+ const resources = new Map(boxes.map((box) => [box.id, box]))
+ const now = Date.now()
+ const seen = new Set<string>()
+ let accepted = 0
+ for (const event of batch.events) {
+ const box = resources.get(event.boxId)
+ const evidence = EVIDENCE[event.kind]
+ const occurredAt = new Date(event.occurredAt)
+ if (
+ !box ||
+ box.organizationId === BOX_WARM_POOL_UNASSIGNED_ORGANIZATION ||
+ !Number.isFinite(occurredAt.getTime()) ||
+ evidence.source !== actor.role ||
+ (actor.role === 'runner' && box.runnerId !== actor.runnerId) ||
+ occurredAt.getTime() < now - 7 * 24 * 60 * 60 * 1000 ||
+ occurredAt.getTime() > now + 5 * 60 * 1000
+ )
+ continue
+ const key = box.id + ':' + event.kind + ':' + event.id
+ if (seen.has(key)) continue
+ seen.add(key)
+ recordBusinessEvent({
+ name: 'cloud.feature.use',
+ outcome: 'success',
+ correlationId: box.id,
+ organizationId: box.organizationId,
+ eventId: event.id,
+ occurredAt,
+ feature: evidence,
+ })
+ accepted++
+ }
+ if (accepted < batch.events.length) {
+ this.logger.warn('Cloud feature usage observations rejected', {
+ producer: actor.role,
+ rejected: batch.events.length - accepted,
+ })
+ }
+ return { accepted }
+ }
+}
diff --git a/apps/api/src/box/controllers/preview.controller.spec.ts b/apps/api/src/box/controllers/preview.controller.spec.ts
index 81846e304..08343c46f 100644
--- a/apps/api/src/box/controllers/preview.controller.spec.ts
+++ b/apps/api/src/box/controllers/preview.controller.spec.ts
@@ -194,7 +194,15 @@ describe('PreviewController ensure-ready', () => {
expect(calls).toEqual(['activity', 'ensureReady'])
expect(organizationService.findOne).toHaveBeenCalledWith('org-1')
- expect(autoResume.ensureReady).toHaveBeenCalledWith('box-1', organization)
+ expect(autoResume.ensureReady).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'box-1' }),
+ organization,
+ undefined,
+ {
+ requestedAt: expect.any(Date),
+ monotonicStart: expect.any(Number),
+ },
+ )
})
it('refuses to wake a box that disabled auto-resume, without recording activity', async () => {
@@ -230,7 +238,15 @@ describe('PreviewController ensure-ready', () => {
await controller.ensureReady('box-1')
- expect(autoResume.ensureReady).toHaveBeenCalledWith('box-1', organization)
+ expect(autoResume.ensureReady).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'box-1' }),
+ organization,
+ undefined,
+ {
+ requestedAt: expect.any(Date),
+ monotonicStart: expect.any(Number),
+ },
+ )
})
it.each([BoxState.ARCHIVED, BoxState.ARCHIVING, BoxState.RESIZING, BoxState.ERROR])(
diff --git a/apps/api/src/box/controllers/preview.controller.ts b/apps/api/src/box/controllers/preview.controller.ts
index 97b8fc982..908a4e29d 100644
--- a/apps/api/src/box/controllers/preview.controller.ts
+++ b/apps/api/src/box/controllers/preview.controller.ts
@@ -40,6 +40,7 @@ import { TunnelService } from '../services/tunnel.service'
import { DomainService } from '../services/domain.service'
import { ProxyGuard } from '../guards/proxy.guard'
import { OrganizationService } from '../../organization/services/organization.service'
+import { requestTiming } from '../../common/utils/request-timing.util'
import { AUTO_RESUMABLE_STATES, BoxAutoResumeService } from '../services/box-auto-resume.service'
import { BoxState } from '../enums/box-state.enum'
import { BoxDesiredState } from '../enums/box-desired-state.enum'
@@ -152,7 +153,8 @@ export class PreviewController {
@ApiExcludeEndpoint()
@UseGuards(CombinedAuthGuard, ProxyGuard)
@HttpCode(HttpStatus.NO_CONTENT)
- async ensureReady(@Param('boxId') boxId: string): Promise<void> {
+ async ensureReady(@Param('boxId') boxId: string, @Req() request?: object): Promise<void> {
+ const timing = requestTiming(request)
const box = await this.boxService.findOne(boxId)
const organization = await this.organizationService.findOne(box.organizationId)
if (!organization) {
@@ -174,7 +176,7 @@ export class PreviewController {
await this.boxService
.updateLastActivityAt(box.id, new Date())
.catch((err) => this.logger.warn(`updateLastActivityAt failed for ${box.id}: ${err}`))
- await this.autoResume.ensureReady(box.id, organization)
+ await this.autoResume.ensureReady(box, organization, undefined, timing)
}
@Get(':boxId/inbound')
diff --git a/apps/api/src/box/dto/feature-usage.dto.ts b/apps/api/src/box/dto/feature-usage.dto.ts
new file mode 100644
index 000000000..e8d2a0e14
--- /dev/null
+++ b/apps/api/src/box/dto/feature-usage.dto.ts
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2026 BoxLite AI
+ * SPDX-License-Identifier: AGPL-3.0
+ */
+
+import { Type } from 'class-transformer'
+import {
+ ArrayMaxSize,
+ ArrayMinSize,
+ IsArray,
+ IsIn,
+ IsISO8601,
+ IsString,
+ IsUUID,
+ Matches,
+ ValidateNested,
+} from 'class-validator'
+import { MAX_FEATURE_USAGE_BATCH_SIZE } from '../../common/constants/constants'
+import { BOX_ID_REGEX } from '../utils/box-id.util'
+
+export const FEATURE_USAGE_KINDS = ['ssh', 'tunnel_connection', 'tunnel_request'] as const
+
+export class FeatureUsageEventDto {
+ @IsUUID()
+ id: string
+
+ @IsString()
+ @Matches(BOX_ID_REGEX)
+ boxId: string
+
+ @IsIn(FEATURE_USAGE_KINDS)
+ kind: (typeof FEATURE_USAGE_KINDS)[number]
+
+ @IsISO8601({ strict: true })
+ @Matches(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/)
+ occurredAt: string
+}
+
+export class FeatureUsageBatchDto {
+ @IsArray()
+ @ArrayMinSize(1)
+ @ArrayMaxSize(MAX_FEATURE_USAGE_BATCH_SIZE)
+ @ValidateNested({ each: true })
+ @Type(() => FeatureUsageEventDto)
+ events: FeatureUsageEventDto[]
+}
diff --git a/apps/api/src/box/errors/box-readiness.error.ts b/apps/api/src/box/errors/box-readiness.error.ts
new file mode 100644
index 000000000..aab6c0690
--- /dev/null
+++ b/apps/api/src/box/errors/box-readiness.error.ts
@@ -0,0 +1,9 @@
+/*
+ * Copyright 2026 BoxLite AI
+ * SPDX-License-Identifier: AGPL-3.0
+ */
+
+import { BadRequestException } from '@nestjs/common'
+
+/** A failed runtime transition retains its HTTP contract and a typed telemetry category. */
+export class BoxReadinessError extends BadRequestException {}
diff --git a/apps/api/src/box/interceptors/box-readiness.interceptor.spec.ts b/apps/api/src/box/interceptors/box-readiness.interceptor.spec.ts
new file mode 100644
index 000000000..2bb5d042f
--- /dev/null
+++ b/apps/api/src/box/interceptors/box-readiness.interceptor.spec.ts
@@ -0,0 +1,258 @@
+/*
+ * Copyright 2026 BoxLite AI
+ * SPDX-License-Identifier: AGPL-3.0
+ */
+
+import { INestApplication, Logger, RequestTimeoutException } from '@nestjs/common'
+import { Test } from '@nestjs/testing'
+import { AddressInfo } from 'node:net'
+import { Reflector } from '@nestjs/core'
+import { lastValueFrom, Subject } from 'rxjs'
+import { CombinedAuthGuard } from '../../auth/combined-auth.guard'
+import { OrganizationResourceActionGuard } from '../../organization/guards/organization-resource-action.guard'
+import { SystemRole } from '../../user/enums/system-role.enum'
+import { BoxliteBoxController } from '../../boxlite-rest/boxlite-box.controller'
+import { CommerceBoxLimitService } from '../../boxlite-rest/commerce-box-limit.service'
+import { subscribeBusinessEvents } from '../../common/utils/business-event.util'
+import { captureRequestTiming, requestTiming } from '../../common/utils/request-timing.util'
+import { BoxService } from '../services/box.service'
+import { BoxStateWaiterService } from '../services/box-state-waiter.service'
+import { CheckpointRecoverService } from '../services/checkpoint-recover.service'
+import { BoxState } from '../enums/box-state.enum'
+import { BoxDesiredState } from '../enums/box-desired-state.enum'
+import { BoxReadinessError } from '../errors/box-readiness.error'
+import { BoxReadinessInterceptor } from './box-readiness.interceptor'
+
+describe('Cloud readiness metrics at actual REST routes', () => {
+ const organization = { id: 'org-1' }
+ const started = {
+ id: 'box-1',
+ organizationId: organization.id,
+ state: BoxState.STARTED,
+ desiredState: BoxDesiredState.STARTED,
+ }
+ let app: INestApplication
+ let observed: Readonly<Record<string, string>>[]
+ let dispose: () => void
+ let allow: boolean
+ let arrivals: string[]
+ let boxService: { create: jest.Mock; findOneByIdOrName: jest.Mock; start: jest.Mock; toBoxDto: jest.Mock }
+ let waiter: { waitForStarted: jest.Mock }
+
+ beforeEach(async () => {
+ jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined)
+ jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined)
+ allow = true
+ arrivals = []
+ observed = []
+ dispose = subscribeBusinessEvents((event) => {
+ if (event['event.name'].startsWith('cloud.')) observed.push(event)
+ })
+ boxService = {
+ create: jest.fn().mockResolvedValue({ ...started, state: BoxState.CREATING }),
+ findOneByIdOrName: jest
+ .fn()
+ .mockResolvedValue({ ...started, state: BoxState.STOPPED, desiredState: BoxDesiredState.STOPPED }),
+ start: jest.fn().mockResolvedValue({ ...started, state: BoxState.STARTING }),
+ toBoxDto: jest.fn(async (box) => box),
+ }
+ waiter = { waitForStarted: jest.fn().mockResolvedValue(started) }
+ const module = await Test.createTestingModule({
+ controllers: [BoxliteBoxController],
+ providers: [
+ { provide: BoxService, useValue: boxService },
+ { provide: BoxStateWaiterService, useValue: waiter },
+ { provide: CommerceBoxLimitService, useValue: { resolveMaxCreatedBoxes: async () => undefined } },
+ { provide: CheckpointRecoverService, useValue: { createBox: async () => started } },
+ ],
+ })
+ .overrideGuard(CombinedAuthGuard)
+ .useValue({
+ canActivate: (context) => {
+ arrivals.push(requestTiming(context.switchToHttp().getRequest()).requestedAt.toISOString())
+ context.switchToHttp().getRequest().user = {
+ role: SystemRole.USER,
+ userId: 'user-1',
+ organizationId: organization.id,
+ organization,
+ }
+ return allow
+ },
+ })
+ .overrideGuard(OrganizationResourceActionGuard)
+ .useValue({ canActivate: () => true })
+ .compile()
+ app = module.createNestApplication()
+ app.setGlobalPrefix('api')
+ app.use(captureRequestTiming)
+ await app.listen(0, '127.0.0.1')
+ })
+
+ afterEach(async () => {
+ await app?.close()
+ dispose()
+ jest.restoreAllMocks()
+ })
+
+ function post(path: string, body: unknown = {}): Promise<Response> {
+ const address = app.getHttpServer().address() as AddressInfo
+ return fetch('http://127.0.0.1:' + address.port + path, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ })
+ }
+
+ it.each(['/api/v1/boxes', '/api/v1/cloud/boxes'])(
+ 'records create readiness at %s without a PostHog configuration',
+ async (path) => {
+ const response = await post(path)
+ expect(response.status).toBe(201)
+ expect((await response.json()).status).toBe('running')
+ expect(observed.map((event) => event['event.outcome'])).toEqual(['requested', 'success'])
+ expect(observed[0]['operation.id']).toBe(observed[1]['operation.id'])
+ expect(observed[0]['operation.requested_at']).toBe(arrivals[0])
+ expect(observed[1]).toMatchObject({
+ 'event.name': 'cloud.box.create',
+ 'operation.result': 'success',
+ 'operation.scope': 'rest_api',
+ 'box.id': started.id,
+ 'organization.id': organization.id,
+ 'user.id': 'user-1',
+ })
+ expect(Number(observed[1]['operation.duration_ms'])).toBeGreaterThanOrEqual(0)
+ },
+ )
+
+ it('includes a checkpoint readiness failure in service failures while returning the admitted Box ID', async () => {
+ waiter.waitForStarted.mockRejectedValue(new BoxReadinessError('restore failed'))
+ const response = await post('/api/v1/boxes', { checkpoint_id: 'checkpoint-1' })
+ expect(response.status).toBe(400)
+ expect(await response.json()).toMatchObject({ boxId: started.id })
+ expect(observed[1]).toMatchObject({ 'event.name': 'cloud.box.create', 'operation.result': 'service_error' })
+ })
+
+ it('waits for readiness before recording terminal success', async () => {
+ let release!: (box: typeof started) => void
+ let entered!: () => void
+ const waiting = new Promise<void>((resolve) => {
+ entered = resolve
+ })
+ waiter.waitForStarted.mockImplementation(() => {
+ entered()
+ return new Promise((resolve) => {
+ release = resolve
+ })
+ })
+ const pending = post('/api/v1/boxes')
+ try {
+ await waiting
+ expect(observed.map((event) => event['event.outcome'])).toEqual(['requested'])
+ } finally {
+ release(started)
+ }
+ expect((await pending).status).toBe(201)
+ expect(observed.map((event) => event['event.outcome'])).toEqual(['requested', 'success'])
+ })
+
+ it.each(['already started', 'waiter'])('excludes response enrichment after %s confirms readiness', async (path) => {
+ let now = 100
+ const clock = jest.spyOn(performance, 'now').mockImplementation(() => now)
+ try {
+ boxService.findOneByIdOrName.mockResolvedValue(started)
+ boxService.start.mockImplementation(async () => {
+ now += 25
+ return started
+ })
+ boxService.toBoxDto.mockImplementation(async (box) => {
+ now += 800
+ return box
+ })
+ if (path === 'waiter') {
+ boxService.create.mockImplementation(async () => {
+ now += 25
+ return { ...started, state: BoxState.CREATING }
+ })
+ const service = new BoxStateWaiterService(boxService as never, {} as never)
+ waiter.waitForStarted.mockImplementation(service.waitForStarted.bind(service))
+ }
+ const response = await post(path === 'waiter' ? '/api/v1/boxes' : '/api/v1/boxes/box-1/start')
+ expect(response.status).toBe(201)
+ expect((await response.json()).status).toBe('running')
+ expect(Number(observed[1]['operation.duration_ms'])).toBe(25)
+ } finally {
+ clock.mockRestore()
+ }
+ })
+
+ it('records separate attempts for concurrent starts of the same Box', async () => {
+ const responses = await Promise.all([post('/api/v1/boxes/box-1/start'), post('/api/v1/boxes/box-1/start')])
+ expect(responses.map((response) => response.status)).toEqual([201, 201])
+ const attempts = observed.filter((event) => event['event.outcome'] === 'requested')
+ expect(attempts).toHaveLength(2)
+ expect(attempts[0]['operation.id']).not.toBe(attempts[1]['operation.id'])
+ for (const attempt of attempts) {
+ expect(
+ observed
+ .filter((event) => event['operation.id'] === attempt['operation.id'])
+ .map((event) => event['event.outcome']),
+ ).toEqual(['requested', 'success'])
+ }
+ })
+
+ it.each([
+ [new RequestTimeoutException('private-timeout'), 408, 'timeout'],
+ [new BoxReadinessError('private-runtime-error'), 400, 'service_error'],
+ [new Error('private-database-error'), 500, 'service_error'],
+ ])('preserves the HTTP failure and records a sanitized category: %s', async (error, status, result) => {
+ waiter.waitForStarted.mockRejectedValue(error)
+ expect((await post('/api/v1/boxes')).status).toBe(status)
+ expect(observed[1]).toMatchObject({ 'operation.result': result, 'box.id': started.id })
+ expect(JSON.stringify(observed)).not.toContain('private-')
+ })
+
+ it('separates validation refusals from service failures', async () => {
+ expect((await post('/api/v1/boxes', { unexpected: 'private-value' })).status).toBe(400)
+ expect(boxService.create).not.toHaveBeenCalled()
+ expect(observed[1]['operation.result']).toBe('user_error')
+ expect(observed[1]).not.toHaveProperty('box.id')
+ expect(JSON.stringify(observed)).not.toContain('private-value')
+ })
+
+ it('excludes requests refused by guards before interception', async () => {
+ allow = false
+ expect((await post('/api/v1/boxes')).status).toBe(403)
+ expect(observed).toEqual([])
+ })
+
+ it('records cancellation once when the handler observable is unsubscribed', () => {
+ const request = { user: { userId: 'user-1', organizationId: organization.id }, get: () => undefined }
+ const context = {
+ getHandler: () => BoxliteBoxController.prototype.createBox,
+ switchToHttp: () => ({ getRequest: () => request }),
+ }
+ const stream = new Subject<unknown>()
+ const subscription = new BoxReadinessInterceptor(new Reflector())
+ .intercept(context as never, { handle: () => stream })
+ .subscribe()
+ subscription.unsubscribe()
+ expect(observed.map((event) => event['event.outcome'])).toEqual(['requested', 'exception'])
+ expect(observed[1]['operation.result']).toBe('cancelled')
+ })
+
+ it('accounts for a synchronous handler error without changing its identity', async () => {
+ const failure = new Error('private-handler-error')
+ const request = { user: { userId: 'user-1', organizationId: organization.id }, get: () => undefined }
+ const context = {
+ getHandler: () => BoxliteBoxController.prototype.createBox,
+ switchToHttp: () => ({ getRequest: () => request }),
+ }
+ const stream = new BoxReadinessInterceptor(new Reflector()).intercept(context as never, {
+ handle: () => {
+ throw failure
+ },
+ })
+ await expect(lastValueFrom(stream)).rejects.toBe(failure)
+ expect(observed[1]['operation.result']).toBe('service_error')
+ })
+})
diff --git a/apps/api/src/box/interceptors/box-readiness.interceptor.ts b/apps/api/src/box/interceptors/box-readiness.interceptor.ts
new file mode 100644
index 000000000..d0c088098
--- /dev/null
+++ b/apps/api/src/box/interceptors/box-readiness.interceptor.ts
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2026 BoxLite AI
+ * SPDX-License-Identifier: AGPL-3.0
+ */
+
+import {
+ applyDecorators,
+ CallHandler,
+ ExecutionContext,
+ Injectable,
+ NestInterceptor,
+ SetMetadata,
+ UseInterceptors,
+} from '@nestjs/common'
+import { Reflector } from '@nestjs/core'
+import { Request } from 'express'
+import { defer, finalize, Observable, tap } from 'rxjs'
+import { AUDIT_TARGET_ID } from '../../audit/decorators/audit.decorator'
+import { requestContext } from '../../common/decorators/user-context.decorator'
+import { OrganizationAuthContext } from '../../common/interfaces/auth-context.interface'
+import { beginBoxOperation } from '../utils/box-operation.util'
+import { requestTiming } from '../../common/utils/request-timing.util'
+
+export const ON_BOX_STARTED = Symbol('on_box_started')
+
+const READINESS_OPERATION = Symbol('readiness_operation')
+
+@Injectable()
+export class BoxReadinessInterceptor implements NestInterceptor {
+ constructor(private readonly reflector: Reflector) {}
+
+ intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
+ const kind = this.reflector.get<'create' | 'start'>(READINESS_OPERATION, context.getHandler())
+ if (!kind) return next.handle()
+ const request = context.switchToHttp().getRequest<
+ Request & {
+ user?: OrganizationAuthContext
+ [AUDIT_TARGET_ID]?: string
+ [ON_BOX_STARTED]?: () => void
+ }
+ >()
+ if (!request.user?.organizationId) return next.handle()
+ const finish = beginBoxOperation({
+ kind,
+ organizationId: request.user.organizationId,
+ ctx: requestContext(request),
+ scope: 'rest_api',
+ timing: requestTiming(request),
+ })
+ let confirmedAt: number | undefined
+ request[ON_BOX_STARTED] = () => {
+ confirmedAt ??= performance.now()
+ }
+ return defer(() => next.handle()).pipe(
+ tap({
+ next: () => finish({ outcome: 'success', boxId: request[AUDIT_TARGET_ID], confirmedAt }),
+ error: (error) => finish({ outcome: 'exception', error, boxId: request[AUDIT_TARGET_ID] }),
+ }),
+ finalize(() => finish({ outcome: 'cancelled', boxId: request[AUDIT_TARGET_ID] })),
+ )
+ }
+}
+
+/** Only attach to handlers that wait for STARTED before returning success. */
+export const ObserveBoxReadiness = (kind: 'create' | 'start') =>
+ applyDecorators(SetMetadata(READINESS_OPERATION, kind), UseInterceptors(BoxReadinessInterceptor))
diff --git a/apps/api/src/box/services/box-auto-resume.service.spec.ts b/apps/api/src/box/services/box-auto-resume.service.spec.ts
index 3120d8fed..3ccbb40c6 100644
--- a/apps/api/src/box/services/box-auto-resume.service.spec.ts
+++ b/apps/api/src/box/services/box-auto-resume.service.spec.ts
@@ -6,6 +6,8 @@
import { BoxAutoResumeService } from './box-auto-resume.service'
import { BoxState } from '../enums/box-state.enum'
import { BoxDesiredState } from '../enums/box-desired-state.enum'
+import { Logger, RequestTimeoutException } from '@nestjs/common'
+import { subscribeBusinessEvents } from '../../common/utils/business-event.util'
const organization = { id: 'org-1', suspended: false } as any
@@ -20,6 +22,7 @@ function makeHarness(initial: Record<string, unknown>) {
unlock: jest.fn().mockResolvedValue(undefined),
}
return {
+ admittedBox: initial as never,
service: new BoxAutoResumeService(boxService as never, waiter as never, redisLockProvider as never),
boxService,
waiter,
@@ -28,32 +31,54 @@ function makeHarness(initial: Record<string, unknown>) {
}
describe('BoxAutoResumeService', () => {
+ let observed: Readonly<Record<string, string>>[]
+ let dispose: () => void
+ beforeEach(() => {
+ observed = []
+ dispose = subscribeBusinessEvents((event) => observed.push(event))
+ jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined)
+ jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined)
+ })
+ afterEach(() => {
+ dispose()
+ jest.restoreAllMocks()
+ jest.useRealTimers()
+ })
it('returns immediately for an already STARTED box', async () => {
- const { service, waiter, redisLockProvider } = makeHarness({
+ const { service, admittedBox, waiter, redisLockProvider } = makeHarness({
id: 'box-1',
state: BoxState.STARTED,
desiredState: BoxDesiredState.STARTED,
})
- await service.ensureReady('box-1', organization)
+ await service.ensureReady(admittedBox, organization)
expect(waiter.waitForStarted).not.toHaveBeenCalled()
expect(redisLockProvider.lock.mock.calls).toEqual([['box:box-1:state-change', 30]])
expect(redisLockProvider.unlock.mock.calls).toEqual([['box:box-1:state-change']])
+ expect(observed).toEqual([])
})
it('joins an in-flight Start and waits for STARTED', async () => {
- const { service, waiter } = makeHarness({
+ const { service, admittedBox, waiter } = makeHarness({
id: 'box-1',
state: BoxState.STARTING,
desiredState: BoxDesiredState.STARTED,
})
- await service.ensureReady('box-1', organization)
- expect(waiter.waitForStarted).toHaveBeenCalledWith('box-1', 'org-1', 30)
+ await service.ensureReady(admittedBox, organization)
+ expect(waiter.waitForStarted).toHaveBeenCalledWith('box-1', 'org-1', 30, expect.any(Function))
+ expect(observed.map((event) => event['event.outcome'])).toEqual(['requested', 'success'])
+ expect(observed[1]).toMatchObject({
+ 'event.name': 'cloud.box.resume',
+ 'operation.scope': 'proxy_api',
+ 'actor.kind': 'platform',
+ 'event.reason': 'auto_resume',
+ 'box.id': 'box-1',
+ })
})
it('waits for an in-flight Stop, submits Start, then waits for STARTED', async () => {
- const { service, boxService, waiter } = makeHarness({
+ const { service, admittedBox, boxService, waiter } = makeHarness({
id: 'box-1',
state: BoxState.STOPPING,
desiredState: BoxDesiredState.STOPPED,
@@ -69,21 +94,38 @@ describe('BoxAutoResumeService', () => {
desiredState: BoxDesiredState.STARTED,
})
- await service.ensureReady('box-1', organization)
+ await service.ensureReady(admittedBox, organization)
expect(waiter.waitForStopped).toHaveBeenCalledWith('box-1', 'org-1', 30)
- expect(waiter.waitForStarted).toHaveBeenCalledWith('box-1', 'org-1', 30)
+ expect(waiter.waitForStarted).toHaveBeenCalledWith('box-1', 'org-1', 30, expect.any(Function))
expect(boxService.ensureStartedForProxy).toHaveBeenCalledTimes(2)
+ expect(observed.map((event) => event['event.outcome'])).toEqual(['requested', 'success'])
})
it('propagates timeout or transition failures', async () => {
- const { service, waiter } = makeHarness({
+ const { service, admittedBox, waiter } = makeHarness({
id: 'box-1',
state: BoxState.STARTING,
desiredState: BoxDesiredState.STARTED,
})
- waiter.waitForStarted.mockRejectedValue(new Error('start timeout'))
+ waiter.waitForStarted.mockRejectedValue(new RequestTimeoutException('start timeout'))
+
+ await expect(service.ensureReady(admittedBox, organization)).rejects.toThrow('start timeout')
+ expect(observed[1]['operation.result']).toBe('timeout')
+ })
- await expect(service.ensureReady('box-1', organization)).rejects.toThrow('start timeout')
+ it('includes lifecycle-lock waiting in timeout accounting', async () => {
+ jest.useFakeTimers()
+ const { service, admittedBox, redisLockProvider, boxService } = makeHarness({
+ id: 'box-1',
+ state: BoxState.STOPPED,
+ })
+ redisLockProvider.lock.mockResolvedValue(false)
+ const pending = service.ensureReady(admittedBox, organization).catch((error) => error)
+ await jest.advanceTimersByTimeAsync(30_000)
+ expect(await pending).toBeInstanceOf(RequestTimeoutException)
+ expect(boxService.ensureStartedForProxy).not.toHaveBeenCalled()
+ expect(observed[1]).toMatchObject({ 'operation.result': 'timeout', 'operation.duration_ms': '30000' })
+ expect(observed[0]['operation.requested_at']).toBe(observed[1]['operation.requested_at'])
})
})
diff --git a/apps/api/src/box/services/box-auto-resume.service.ts b/apps/api/src/box/services/box-auto-resume.service.ts
index 2e9e80811..50ea6ac05 100644
--- a/apps/api/src/box/services/box-auto-resume.service.ts
+++ b/apps/api/src/box/services/box-auto-resume.service.ts
@@ -12,6 +12,10 @@ import { Box } from '../entities/box.entity'
import { BoxState } from '../enums/box-state.enum'
import { BoxDesiredState } from '../enums/box-desired-state.enum'
import { Organization } from '../../organization/entities/organization.entity'
+import { Context } from '../../common/context/context'
+import { PlatformReason } from '../../common/context/platform-reason.enum'
+import { beginBoxOperation } from '../utils/box-operation.util'
+import { RequestTiming, requestTiming } from '../../common/utils/request-timing.util'
export const AUTO_RESUME_TIMEOUT_SECONDS = 30
@@ -29,6 +33,12 @@ export const AUTO_RESUMABLE_STATES: readonly BoxState[] = [
BoxState.RESTORING,
]
+type ResumeBox = Pick<Box, 'id' | 'state' | 'desiredState'>
+
+function isReady(box: ResumeBox): boolean {
+ return box.state === BoxState.STARTED && box.desiredState !== BoxDesiredState.STOPPED
+}
+
@Injectable()
export class BoxAutoResumeService {
constructor(
@@ -38,23 +48,55 @@ export class BoxAutoResumeService {
) {}
/** Submit or join Start and return only after the Box is actually STARTED. */
- async ensureReady(boxId: string, organization: Organization, admit?: ProxyAdmission): Promise<void> {
- let box = await this.submitOrJoinStart(boxId, organization, admit)
-
- const stopping =
- box.state === BoxState.STOPPING ||
- (box.state === BoxState.STARTED && box.desiredState === BoxDesiredState.STOPPED)
- if (stopping) {
- await this.boxStateWaiter.waitForStopped(box.id, organization.id, AUTO_RESUME_TIMEOUT_SECONDS)
- box = await this.submitOrJoinStart(box.id, organization, admit)
+ async ensureReady(
+ admittedBox: ResumeBox,
+ organization: Organization,
+ admit?: ProxyAdmission,
+ timing: RequestTiming = requestTiming(),
+ ): Promise<void> {
+ const boxId = admittedBox.id
+ let confirmedAt: number | undefined
+ const onStarted = () => {
+ confirmedAt = performance.now()
}
-
- if (box.state !== BoxState.STARTED) {
- await this.boxStateWaiter.waitForStarted(box.id, organization.id, AUTO_RESUME_TIMEOUT_SECONDS)
+ const begin = () =>
+ beginBoxOperation({
+ kind: 'resume',
+ organizationId: organization.id,
+ ctx: Context.platform(PlatformReason.AUTO_RESUME),
+ scope: 'proxy_api',
+ boxId,
+ timing,
+ })
+ let finish = isReady(admittedBox) ? undefined : begin()
+ try {
+ let box = await this.submitOrJoinStart(boxId, organization, admit, onStarted)
+ const stopping =
+ box.state === BoxState.STOPPING ||
+ (box.state === BoxState.STARTED && box.desiredState === BoxDesiredState.STOPPED)
+ if (isReady(box) && !finish) return
+ finish ??= begin()
+ if (stopping) {
+ await this.boxStateWaiter.waitForStopped(box.id, organization.id, AUTO_RESUME_TIMEOUT_SECONDS)
+ box = await this.submitOrJoinStart(box.id, organization, admit, onStarted)
+ }
+ if (box.state !== BoxState.STARTED) {
+ await this.boxStateWaiter.waitForStarted(box.id, organization.id, AUTO_RESUME_TIMEOUT_SECONDS, onStarted)
+ }
+ finish({ outcome: 'success', boxId: box.id, confirmedAt })
+ } catch (error) {
+ finish ??= begin()
+ finish({ outcome: 'exception', error })
+ throw error
}
}
- private async submitOrJoinStart(boxId: string, organization: Organization, admit?: ProxyAdmission): Promise<Box> {
+ private async submitOrJoinStart(
+ boxId: string,
+ organization: Organization,
+ admit: ProxyAdmission | undefined,
+ onStarted: () => void,
+ ): Promise<Box> {
const lockKey = getStateChangeLockKey(boxId)
const deadline = Date.now() + AUTO_RESUME_TIMEOUT_SECONDS * 1000
while (!(await this.redisLockProvider.lock(lockKey, AUTO_RESUME_TIMEOUT_SECONDS))) {
@@ -65,7 +107,9 @@ export class BoxAutoResumeService {
}
try {
- return await this.boxService.ensureStartedForProxy(boxId, organization, admit)
+ const box = await this.boxService.ensureStartedForProxy(boxId, organization, admit)
+ if (isReady(box)) onStarted()
+ return box
} finally {
await this.redisLockProvider.unlock(lockKey)
}
diff --git a/apps/api/src/box/services/box-state-waiter.service.spec.ts b/apps/api/src/box/services/box-state-waiter.service.spec.ts
index 2787918fe..4abb31c74 100644
--- a/apps/api/src/box/services/box-state-waiter.service.spec.ts
+++ b/apps/api/src/box/services/box-state-waiter.service.spec.ts
@@ -8,8 +8,11 @@ import { HttpStatus, RequestTimeoutException } from '@nestjs/common'
import { BoxProgressPhase } from '../enums/box-progress-phase.enum'
import { BoxState } from '../enums/box-state.enum'
import { BoxPreparingImageTimeoutError } from '../errors/box-preparing-image-timeout.error'
+import { BoxReadinessError } from '../errors/box-readiness.error'
import { BoxStateWaiterService } from './box-state-waiter.service'
import { BOX_EVENT_CHANNEL } from '../../common/constants/constants'
+import { NotificationService } from '../../notification/services/notification.service'
+import { BoxDesiredState } from '../enums/box-desired-state.enum'
function makeWaiter(initialState = BoxState.STARTING, toBoxDto?: (box: any) => Promise<any>) {
const subscriber = new EventEmitter() as any
@@ -48,6 +51,8 @@ describe('BoxStateWaiterService', () => {
const error = await waiter.waitForStarted('box-1', 'org-1', 1).catch((failure) => failure)
+ expect(error).toBeInstanceOf(BoxReadinessError)
+ expect(error.getStatus()).toBe(400)
expect(error.getResponse()).toMatchObject({
message: 'Box state transition failed: runner has not declared filestore',
code: 'BOX_STATE_TRANSITION_FAILED',
@@ -55,6 +60,49 @@ describe('BoxStateWaiterService', () => {
})
})
+ it.each(['state', 'desired state'])('observes the %s notification before dashboard enrichment', async (kind) => {
+ const { waiter, subscriber } = makeWaiter()
+ const onStarted = jest.fn()
+ const pending = waiter.waitForStarted('box-1', 'org-1', 5, onStarted)
+ await new Promise((resolve) => setImmediate(resolve))
+
+ let release!: () => void
+ const metadata = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ const box = { id: 'box-1', state: BoxState.STARTED } as never
+ const emitter = { emitBoxStateUpdated: jest.fn(), emitBoxDesiredStateUpdated: jest.fn() }
+ const notifications = new NotificationService(
+ emitter as never,
+ {} as never,
+ {
+ toBoxDto: async () => {
+ await metadata
+ return { lastActivityAt: 'enriched' }
+ },
+ } as never,
+ { publish: async (channel: string, message: string) => subscriber.emit('message', channel, message) } as never,
+ )
+ const dispatch =
+ kind === 'state'
+ ? notifications.handleBoxStateUpdated({ box, oldState: BoxState.STARTING, newState: BoxState.STARTED })
+ : notifications.handleBoxDesiredStateUpdated({
+ box,
+ oldDesiredState: BoxDesiredState.STOPPED,
+ newDesiredState: BoxDesiredState.STARTED,
+ })
+ const notify = kind === 'state' ? emitter.emitBoxStateUpdated : emitter.emitBoxDesiredStateUpdated
+ try {
+ expect(onStarted).toHaveBeenCalledTimes(1)
+ expect(notify).not.toHaveBeenCalled()
+ } finally {
+ release()
+ await dispatch
+ await pending
+ }
+ expect(notify.mock.calls[0][0]).toEqual({ lastActivityAt: 'enriched' })
+ })
+
it('rejects instead of returning a non-target state on timeout', async () => {
jest.useFakeTimers()
const { waiter } = makeWaiter()
diff --git a/apps/api/src/box/services/box-state-waiter.service.ts b/apps/api/src/box/services/box-state-waiter.service.ts
index 2d281fcef..9ad50cde3 100644
--- a/apps/api/src/box/services/box-state-waiter.service.ts
+++ b/apps/api/src/box/services/box-state-waiter.service.ts
@@ -10,6 +10,7 @@ import Redis from 'ioredis'
import { BOX_EVENT_CHANNEL } from '../../common/constants/constants'
import { BoxDto } from '../dto/box.dto'
import { BoxPreparingImageTimeoutError } from '../errors/box-preparing-image-timeout.error'
+import { BoxReadinessError } from '../errors/box-readiness.error'
import { BoxState } from '../enums/box-state.enum'
import { BoxStateUpdatedEvent } from '../events/box-state-updated.event'
import { BoxService } from './box.service'
@@ -52,8 +53,13 @@ export class BoxStateWaiterService implements OnModuleDestroy {
return this.subscription
}
- waitForStarted(boxId: string, organizationId: string, timeoutSeconds: number): Promise<BoxDto> {
- return this.waitForState(boxId, organizationId, BoxState.STARTED, timeoutSeconds)
+ waitForStarted(
+ boxId: string,
+ organizationId: string,
+ timeoutSeconds: number,
+ onStarted?: () => void,
+ ): Promise<BoxDto> {
+ return this.waitForState(boxId, organizationId, BoxState.STARTED, timeoutSeconds, onStarted)
}
waitForStopped(boxId: string, organizationId: string, timeoutSeconds: number): Promise<BoxDto> {
@@ -65,9 +71,13 @@ export class BoxStateWaiterService implements OnModuleDestroy {
organizationId: string,
targetState: BoxState,
timeoutSeconds: number,
+ onReached?: () => void,
): Promise<BoxDto> {
const current = await this.boxService.findOneByIdOrName(boxId, organizationId)
- if (current.state === targetState) return this.boxService.toBoxDto(current)
+ if (current.state === targetState) {
+ onReached?.()
+ return this.boxService.toBoxDto(current)
+ }
await this.ensureSubscribed()
this.assertNotFailed(current.id, current.state, current.errorReason)
@@ -86,6 +96,7 @@ export class BoxStateWaiterService implements OnModuleDestroy {
finished = true
cleanup()
try {
+ onReached?.()
resolve(await this.boxService.toBoxDto(eventBox))
} catch (error) {
reject(error)
@@ -167,7 +178,7 @@ export class BoxStateWaiterService implements OnModuleDestroy {
private assertNotFailed(boxId: string, state: BoxState, errorReason?: string | null) {
if (state === BoxState.ERROR) {
- throw new BadRequestException({
+ throw new BoxReadinessError({
message: `Box state transition failed: ${errorReason || 'Unknown error'}`,
code: 'BOX_STATE_TRANSITION_FAILED',
boxId,
diff --git a/apps/api/src/box/services/box.service.spec.ts b/apps/api/src/box/services/box.service.spec.ts
index 43f831a86..555a70ef6 100644
--- a/apps/api/src/box/services/box.service.spec.ts
+++ b/apps/api/src/box/services/box.service.spec.ts
@@ -1434,6 +1434,7 @@ describe('BoxService inbound defaults', () => {
{ name: 'assigned-box', inboundEnabled: requested },
{ id: 'org-1' },
{},
+ {},
)
expect(update).toHaveBeenCalledWith(
diff --git a/apps/api/src/box/services/box.service.ts b/apps/api/src/box/services/box.service.ts
index 1aede8782..4f04a1d9f 100644
--- a/apps/api/src/box/services/box.service.ts
+++ b/apps/api/src/box/services/box.service.ts
@@ -135,6 +135,7 @@ const DEFAULT_BOX_GPU = 0
const PREVIEW_ACTIVITY_TIMEOUT_MS = 1500
export type BoxCreationOptions = {
+ onStarted?: () => void
maxCreatedBoxes?: number
/** Authenticated creator, supplied by the caller rather than the request DTO. */
createdBy?: string
@@ -426,7 +427,7 @@ export class BoxService {
})
if (warmPoolBox) {
- return await this.assignWarmPoolBox(warmPoolBox, createBoxDto, organization, ctx, options.maxCreatedBoxes)
+ return await this.assignWarmPoolBox(warmPoolBox, createBoxDto, organization, ctx, options)
}
}
}
@@ -535,6 +536,7 @@ export class BoxService {
.emitAsync(BoxEvents.CREATED, new BoxCreatedEvent(insertedBox))
.catch((err) => this.logger.error('Failed to emit BoxCreatedEvent', err))
+ if (insertedBox.state === BoxState.STARTED) options.onStarted?.()
return this.toBoxDto(insertedBox)
} catch (error) {
if (error.code === '23505') {
@@ -554,7 +556,7 @@ export class BoxService {
createBoxDto: CreateBoxDto,
organization: Organization,
ctx: Context,
- maxCreatedBoxes?: number,
+ { maxCreatedBoxes, onStarted }: BoxCreationOptions,
): Promise<BoxDto> {
const now = new Date()
const updateData: Partial<Box> = {
@@ -619,6 +621,7 @@ export class BoxService {
BoxEvents.STATE_UPDATED,
new BoxStateUpdatedEvent(updatedBox, BoxState.STARTED, BoxState.STARTED),
)
+ if (updatedBox.state === BoxState.STARTED) onStarted?.()
return this.toBoxDto(updatedBox)
}
diff --git a/apps/api/src/box/services/checkpoint-job-receiver.service.ts b/apps/api/src/box/services/checkpoint-job-receiver.service.ts
index f71dbe686..c2f5bfafd 100644
--- a/apps/api/src/box/services/checkpoint-job-receiver.service.ts
+++ b/apps/api/src/box/services/checkpoint-job-receiver.service.ts
@@ -5,6 +5,8 @@ import { Injectable, Logger, Optional } from '@nestjs/common'
import { EventEmitter2 } from '@nestjs/event-emitter'
import { Cron, CronExpression } from '@nestjs/schedule'
import { DataSource } from 'typeorm'
+import { v5 } from 'uuid'
+import { recordBusinessEvent } from '../../common/utils/business-event.util'
import { InjectRedis } from '@nestjs-modules/ioredis'
import { Redis } from 'ioredis'
import { Checkpoint, CheckpointArchive } from '../entities/checkpoint.entity'
@@ -46,7 +48,7 @@ export class CheckpointJobReceiver {
}
let source: Box | null = null
let queuedUpload: Job | null = null
- await this.dataSource.transaction(async (manager) => {
+ const ready = await this.dataSource.transaction(async (manager) => {
// The persisted job is authoritative. A delayed caller must not replace
// current terminal metadata or advance a different checkpoint operation.
const job = await manager.findOneBy(Job, { id: notification.id })
@@ -118,7 +120,15 @@ export class CheckpointJobReceiver {
checkpoint.activeJobId = null
}
await manager.save(Checkpoint, checkpoint)
+ if (checkpoint.state === 'ready') return { job, checkpoint }
})
+ if (ready)
+ this.recordCheckpointUse(
+ ready.job,
+ ready.checkpoint.organizationId,
+ ready.checkpoint.sourceBoxId,
+ 'archive_ready',
+ )
if (queuedUpload) {
try {
await this.redis.lpush(runnerJobQueueKey(queuedUpload.runnerId), queuedUpload.id)
@@ -130,6 +140,29 @@ export class CheckpointJobReceiver {
if (source) this.cache.invalidate(source)
}
+ // Only committed job receipts supply both the occurrence time and a replay-stable identity.
+ private recordCheckpointUse(
+ job: Job,
+ organizationId: string,
+ boxId: string,
+ evidence: 'archive_ready' | 'box_restored',
+ ): void {
+ if (!(job.completedAt instanceof Date) || !Number.isFinite(job.completedAt.getTime())) return
+ try {
+ recordBusinessEvent({
+ name: 'cloud.feature.use',
+ outcome: 'success',
+ organizationId,
+ correlationId: boxId,
+ occurredAt: job.completedAt,
+ eventId: v5('boxlite:checkpoint:' + evidence + ':' + job.id, v5.URL),
+ feature: { name: 'checkpoint', evidence, source: 'api' },
+ })
+ } catch {
+ this.logger.warn('Checkpoint usage capture failed')
+ }
+ }
+
/** Commit only the owned import receipt; report its logical outcome after commit. */
private async handleImportCompletion(jobId: string): Promise<void> {
const changed = await this.dataSource.transaction(async (manager) => {
@@ -205,10 +238,12 @@ export class CheckpointJobReceiver {
}
await manager.save(Box, box)
await manager.save(CheckpointOperation, operation)
- return { box, previousState, outcome: accepted ? JobStatus.COMPLETED : JobStatus.FAILED }
+ return { box, previousState, outcome: accepted ? JobStatus.COMPLETED : JobStatus.FAILED, job }
})
if (changed) {
- recordBoxJobOutcome('box.create', changed.outcome, changed.box)
+ recordBoxJobOutcome('box.create', changed.outcome, changed.box, changed.job)
+ if (changed.outcome === JobStatus.COMPLETED)
+ this.recordCheckpointUse(changed.job, changed.box.organizationId, changed.box.id, 'box_restored')
this.cache.invalidate(changed.box)
if (changed.previousState !== changed.box.state)
this.events?.emit(
diff --git a/apps/api/src/box/services/checkpoint.integration.spec.ts b/apps/api/src/box/services/checkpoint.integration.spec.ts
index 33c00f53c..b24f5eca9 100644
--- a/apps/api/src/box/services/checkpoint.integration.spec.ts
+++ b/apps/api/src/box/services/checkpoint.integration.spec.ts
@@ -314,13 +314,32 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>
)
await receiver.handleJobCompletion(job)
await receiver.reconcile()
- expect(observed).toEqual([
+ expect(observed.filter((event) => event['event.name'] === 'box.create')).toEqual([
expect.objectContaining({
'event.name': 'box.create',
'event.outcome': outcome === 'success' ? 'success' : 'exception',
'correlation.id': admitted.id,
+ 'job.id': job.id,
+ 'job.completed_at': job.completedAt!.toISOString(),
+ 'event.timestamp': job.completedAt!.toISOString(),
+ 'event.id': expect.any(String),
}),
])
+ const uses = observed.filter((event) => event['event.name'] === 'cloud.feature.use')
+ expect(uses).toEqual(
+ outcome === 'success'
+ ? [
+ expect.objectContaining({
+ 'feature.name': 'checkpoint',
+ 'feature.evidence': 'box_restored',
+ 'organization.id': organizationId,
+ 'correlation.id': admitted.id,
+ 'event.timestamp': job.completedAt!.toISOString(),
+ }),
+ ]
+ : [],
+ )
+ if (uses.length) expect(uses[0]['event.id']).not.toBe(observed[0]['event.id'])
expect(await boxes.findOneByOrFail({ id: admitted.id })).toMatchObject({
state: outcome === 'success' ? BoxState.STOPPED : BoxState.ERROR,
})
@@ -330,6 +349,34 @@ describeWithDatabase('checkpoint create/export/upload (real PostgreSQL)', () =>
},
)
+ it('records archive readiness only after an owned upload succeeds, once across replay', async () => {
+ const box = await source()
+ const checkpoint = await service.create(organizationId, box.id, 'ready-evidence')
+ const observed: Readonly<Record<string, string>>[] = []
+ const dispose = subscribeBusinessEvents((event) => {
+ if (event['event.name'] === 'cloud.feature.use') observed.push(event)
+ })
+ try {
+ await finish(checkpoint.exportJobId!, archive(checkpoint))
+ expect(observed).toEqual([])
+ const uploading = await service.get(organizationId, checkpoint.id)
+ const job = await finish(uploading.activeJobId!, archive(checkpoint))
+ await receiver.handleJobCompletion(job)
+ expect(observed).toEqual([
+ expect.objectContaining({
+ 'feature.name': 'checkpoint',
+ 'feature.evidence': 'archive_ready',
+ 'correlation.id': box.id,
+ 'organization.id': organizationId,
+ 'event.timestamp': job.completedAt!.toISOString(),
+ }),
+ ])
+ expect(observed[0]['user.id']).toBeUndefined()
+ } finally {
+ dispose()
+ }
+ })
+
it('prefers the exact Box ID over a colliding name during capture', async () => {
const target = await source('exact-source')
const shadow = await source(target.id)
diff --git a/apps/api/src/box/services/job-state-handler.business-event.spec.ts b/apps/api/src/box/services/job-state-handler.business-event.spec.ts
index cf8bd3549..08974b767 100644
--- a/apps/api/src/box/services/job-state-handler.business-event.spec.ts
+++ b/apps/api/src/box/services/job-state-handler.business-event.spec.ts
@@ -15,6 +15,12 @@ import { BOX_WARM_POOL_UNASSIGNED_ORGANIZATION } from '../constants/box.constant
jest.mock('../../common/utils/business-event.util', () => ({ recordBusinessEvent: jest.fn() }))
describe('JobStateHandlerService business events', () => {
+ const timing = {
+ id: 'job-1',
+ createdAt: new Date('2026-09-29T08:00:00.000Z'),
+ startedAt: new Date('2026-09-29T08:00:01.000Z'),
+ completedAt: new Date('2026-09-29T08:00:03.000Z'),
+ }
function makeService(
desiredState: BoxDesiredState,
update = jest.fn().mockResolvedValue(undefined),
@@ -29,15 +35,18 @@ describe('JobStateHandlerService business events', () => {
}
function job(type: JobType, status: JobStatus, errorMessage?: string): Job {
- return new Job({
- id: 'job-1',
- type,
- status,
- runnerId: 'runner-1',
- resourceType: ResourceType.BOX,
- resourceId: 'box-1',
- errorMessage,
- })
+ return Object.assign(
+ new Job({
+ id: 'job-1',
+ type,
+ status,
+ runnerId: 'runner-1',
+ resourceType: ResourceType.BOX,
+ resourceId: 'box-1',
+ errorMessage,
+ }),
+ timing,
+ )
}
beforeEach(() => jest.mocked(recordBusinessEvent).mockClear())
@@ -49,6 +58,9 @@ describe('JobStateHandlerService business events', () => {
expect(recordBusinessEvent).toHaveBeenCalledWith({
name: 'box.create',
+ job: timing,
+ occurredAt: timing.completedAt,
+ eventId: expect.any(String),
outcome: 'exception',
correlationId: 'box-1',
organizationId: 'org-1',
@@ -63,6 +75,9 @@ describe('JobStateHandlerService business events', () => {
expect(recordBusinessEvent).toHaveBeenCalledWith({
name: 'box.start',
+ job: timing,
+ occurredAt: timing.completedAt,
+ eventId: expect.any(String),
outcome: 'success',
correlationId: 'box-1',
organizationId: 'org-1',
@@ -76,6 +91,9 @@ describe('JobStateHandlerService business events', () => {
expect(recordBusinessEvent).toHaveBeenCalledWith({
name: 'box.start',
+ job: timing,
+ occurredAt: timing.completedAt,
+ eventId: expect.any(String),
outcome: 'exception',
correlationId: 'box-1',
organizationId: 'org-1',
@@ -90,6 +108,9 @@ describe('JobStateHandlerService business events', () => {
expect(recordBusinessEvent).toHaveBeenCalledWith({
name: 'box.delete',
+ job: timing,
+ occurredAt: timing.completedAt,
+ eventId: expect.any(String),
outcome: 'success',
correlationId: 'box-1',
organizationId: 'org-1',
@@ -103,6 +124,9 @@ describe('JobStateHandlerService business events', () => {
expect(recordBusinessEvent).toHaveBeenCalledWith({
name: 'box.stop',
+ job: timing,
+ occurredAt: timing.completedAt,
+ eventId: expect.any(String),
outcome: 'success',
correlationId: 'box-1',
organizationId: 'org-1',
diff --git a/apps/api/src/box/services/job-state-handler.service.ts b/apps/api/src/box/services/job-state-handler.service.ts
index bb5346978..d26ac1aca 100644
--- a/apps/api/src/box/services/job-state-handler.service.ts
+++ b/apps/api/src/box/services/job-state-handler.service.ts
@@ -137,7 +137,7 @@ export class JobStateHandlerService {
// Warm-pool top-up creates stock no one requested; the claim records
// that box's box.create pair instead (BoxService.assignWarmPoolBox).
if (box.organizationId !== BOX_WARM_POOL_UNASSIGNED_ORGANIZATION) {
- recordBoxJobOutcome('box.create', job.status, box)
+ recordBoxJobOutcome('box.create', job.status, box, job)
}
} catch (error) {
this.logger.error(`Error handling CREATE_BOX job completion for box ${boxId}:`, error)
@@ -183,7 +183,7 @@ export class JobStateHandlerService {
}
await this.boxRepository.update(boxId, { updateData, entity: box })
- recordBoxJobOutcome('box.start', job.status, box)
+ recordBoxJobOutcome('box.start', job.status, box, job)
} catch (error) {
this.logger.error(`Error handling START_BOX job completion for box ${boxId}:`, error)
}
@@ -222,7 +222,7 @@ export class JobStateHandlerService {
}
await this.boxRepository.update(boxId, { updateData, entity: box })
- recordBoxJobOutcome('box.stop', job.status, box)
+ recordBoxJobOutcome('box.stop', job.status, box, job)
} catch (error) {
this.logger.error(`Error handling STOP_BOX job completion for box ${boxId}:`, error)
}
@@ -255,7 +255,7 @@ export class JobStateHandlerService {
}
await this.boxRepository.update(boxId, { updateData, entity: box })
- recordBoxJobOutcome('box.delete', job.status, box)
+ recordBoxJobOutcome('box.delete', job.status, box, job)
return true
} catch (error) {
this.logger.error(`Error handling DESTROY_BOX job completion for box ${boxId}:`, error)
diff --git a/apps/api/src/box/services/job.service.transaction.spec.ts b/apps/api/src/box/services/job.service.transaction.spec.ts
index 947d93f51..b158501b5 100644
--- a/apps/api/src/box/services/job.service.transaction.spec.ts
+++ b/apps/api/src/box/services/job.service.transaction.spec.ts
@@ -130,8 +130,21 @@ describe('JobService.updateJobStatus transaction boundary', () => {
).resolves.toBe(completedJob)
expect(entityManager.save).toHaveBeenCalledWith(Job, completedJob)
- expect(completedJob.completedAt).not.toBe(originalCompletedAt)
+ expect(completedJob.completedAt).toEqual(originalCompletedAt)
expect(completedJob.resultMetadata).toBe('{"daemonVersion":"new"}')
expect(jobStateHandlerService.handleJobCompletion).toHaveBeenCalledWith(completedJob)
})
+
+ it('preserves the first failure time when a runner repeats a terminal report', async () => {
+ const failedJob = makeJob(JobStatus.FAILED)
+ failedJob.completedAt = new Date('2026-07-29T04:05:00.000Z')
+ const originalCompletedAt = failedJob.completedAt
+ const { service, jobStateHandlerService } = makeService(failedJob)
+
+ await service.updateJobStatus(failedJob.id, JobStatus.FAILED, 'runner failed')
+ await service.updateJobStatus(failedJob.id, JobStatus.FAILED, 'runner failed again')
+
+ expect(failedJob.completedAt).toEqual(originalCompletedAt)
+ expect(jobStateHandlerService.handleJobCompletion).toHaveBeenCalledTimes(2)
+ })
})
diff --git a/apps/api/src/box/services/job.service.ts b/apps/api/src/box/services/job.service.ts
index ad3b4a04b..6a17ed895 100644
--- a/apps/api/src/box/services/job.service.ts
+++ b/apps/api/src/box/services/job.service.ts
@@ -263,7 +263,7 @@ export class JobService {
job.startedAt = new Date()
}
- if (status === JobStatus.COMPLETED || status === JobStatus.FAILED) {
+ if ((status === JobStatus.COMPLETED || status === JobStatus.FAILED) && !job.completedAt) {
job.completedAt = new Date()
if (job.type === JobType.CREATE_BOX) {
const payload = job.getPayload()
diff --git a/apps/api/src/box/utils/box-business-event.util.spec.ts b/apps/api/src/box/utils/box-business-event.util.spec.ts
new file mode 100644
index 000000000..b4171a523
--- /dev/null
+++ b/apps/api/src/box/utils/box-business-event.util.spec.ts
@@ -0,0 +1,143 @@
+/*
+ * Copyright 2026 BoxLite AI
+ * SPDX-License-Identifier: AGPL-3.0
+ */
+
+import { Logger } from '@nestjs/common'
+import { subscribeBusinessEvents } from '../../common/utils/business-event.util'
+import { Job } from '../entities/job.entity'
+import { JobStatus } from '../enums/job-status.enum'
+import { JobType } from '../enums/job-type.enum'
+import { ResourceType } from '../enums/resource-type.enum'
+import { recordBoxJobOutcome } from './box-business-event.util'
+
+describe('finished Box job observations', () => {
+ const box = { id: 'box-1', organizationId: 'org-1' }
+ let observed: Readonly<Record<string, string>>[]
+ let dispose: () => void
+
+ function finishedJob(id = 'job-1'): Job {
+ const job = new Job({
+ id,
+ type: JobType.START_BOX,
+ status: JobStatus.COMPLETED,
+ runnerId: 'runner-1',
+ resourceType: ResourceType.BOX,
+ resourceId: box.id,
+ payload: '{"secret":"private-payload"}',
+ errorMessage: 'private-runner-error',
+ startedAt: new Date('2026-09-29T08:00:01Z'),
+ completedAt: new Date('2026-09-29T08:00:03Z'),
+ })
+ job.createdAt = new Date('2026-09-29T08:00:00Z')
+ return job
+ }
+
+ beforeEach(() => {
+ jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined)
+ jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined)
+ observed = []
+ dispose = subscribeBusinessEvents((attributes) => observed.push(attributes))
+ })
+ afterEach(() => {
+ dispose()
+ jest.restoreAllMocks()
+ })
+
+ it.each([true, false, null, undefined])(
+ 'counts started custom images only with persisted tenant provenance %s',
+ (owned) => {
+ const job = finishedJob()
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, { ...box, imageIsOrgOwned: owned }, job)
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, { ...box, imageIsOrgOwned: owned }, job)
+ const features = observed.filter((event) => event['event.name'] === 'cloud.feature.use')
+ if (owned === true) {
+ expect(features).toHaveLength(2)
+ expect(features[0]).toMatchObject({
+ 'feature.name': 'custom_image',
+ 'feature.evidence': 'started_image',
+ 'event.timestamp': job.completedAt!.toISOString(),
+ })
+ expect(features[0]['event.id']).toBe(features[1]['event.id'])
+ expect(features[0]['event.id']).not.toBe(observed[0]['event.id'])
+ } else expect(features).toHaveLength(0)
+ },
+ )
+
+ it('excludes failed starts and stops from custom image evidence', () => {
+ const custom = { ...box, imageIsOrgOwned: true }
+ recordBoxJobOutcome('box.start', JobStatus.FAILED, custom, finishedJob())
+ recordBoxJobOutcome('box.stop', JobStatus.COMPLETED, custom, finishedJob())
+ const imported = finishedJob()
+ imported.type = JobType.IMPORT_CHECKPOINT
+ recordBoxJobOutcome('box.create', JobStatus.COMPLETED, custom, imported)
+ expect(observed.every((event) => event['event.name'] !== 'cloud.feature.use')).toBe(true)
+ })
+
+ it('preserves occurrence identity, source time and duration when a finished job is observed again', () => {
+ const job = finishedJob()
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, box, job)
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, box, job)
+
+ expect(observed[0]).toMatchObject({
+ 'job.id': job.id,
+ 'job.created_at': job.createdAt.toISOString(),
+ 'job.started_at': job.startedAt!.toISOString(),
+ 'job.completed_at': job.completedAt!.toISOString(),
+ 'job.duration_ms': '3000',
+ 'event.timestamp': job.completedAt!.toISOString(),
+ 'event.id': expect.stringMatching(/^[0-9a-f-]{36}$/),
+ })
+ expect(observed[1]).toEqual(observed[0])
+ expect(JSON.stringify(observed)).not.toMatch(/private-payload|private-runner-error|runner-1/)
+ })
+
+ it('distinguishes jobs on one Box and logical outcomes for one job', () => {
+ const first = finishedJob()
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, box, first)
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, box, finishedJob('job-2'))
+ recordBoxJobOutcome('box.start', JobStatus.FAILED, box, first)
+ expect(new Set(observed.map((event) => event['event.id'])).size).toBe(3)
+ expect(observed[2]).toMatchObject({ 'event.outcome': 'exception', 'exception.type': 'runner_job_failed' })
+ })
+
+ it.each([null, new Date(NaN)])('omits unsupported completion timing for %s', (completedAt) => {
+ const job = finishedJob()
+ job.completedAt = completedAt
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, box, job)
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, box, job)
+ expect(observed[0]).not.toHaveProperty('job.completed_at')
+ expect(observed[0]).not.toHaveProperty('job.duration_ms')
+ expect(observed[0]['event.id']).not.toBe(observed[1]['event.id'])
+ })
+
+ it.each([new Date(NaN), new Date('2026-09-29T08:00:04Z')])(
+ 'omits invalid or reversed durations without discarding valid completion identity',
+ (createdAt) => {
+ const job = finishedJob()
+ job.createdAt = createdAt
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, box, job)
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, box, job)
+ expect(observed[0]).not.toHaveProperty('job.duration_ms')
+ expect(observed[1]['event.id']).toBe(observed[0]['event.id'])
+ },
+ )
+
+ it('retains zero duration and replay identity when startedAt is missing', () => {
+ const job = finishedJob()
+ job.startedAt = null
+ job.createdAt = job.completedAt!
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, box, job)
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, box, job)
+ expect(observed[0]['job.duration_ms']).toBe('0')
+ expect(observed[0]).not.toHaveProperty('job.started_at')
+ expect(observed[1]['event.id']).toBe(observed[0]['event.id'])
+ })
+
+ it('keeps callers without a Job compatible', () => {
+ recordBoxJobOutcome('box.start', JobStatus.COMPLETED, box)
+ expect(observed[0]).toMatchObject({ 'event.outcome': 'success', 'correlation.id': box.id })
+ expect(observed[0]).not.toHaveProperty('job.id')
+ expect(observed[0]).not.toHaveProperty('job.duration_ms')
+ })
+})
diff --git a/apps/api/src/box/utils/box-business-event.util.ts b/apps/api/src/box/utils/box-business-event.util.ts
index 37a91d2d1..f80533db1 100644
--- a/apps/api/src/box/utils/box-business-event.util.ts
+++ b/apps/api/src/box/utils/box-business-event.util.ts
@@ -4,8 +4,10 @@
*/
import { Context } from '../../common/context/context'
-import { recordBusinessEvent } from '../../common/utils/business-event.util'
+import { BusinessEventJobTiming, recordBusinessEvent } from '../../common/utils/business-event.util'
import { JobStatus } from '../enums/job-status.enum'
+import { JobType } from '../enums/job-type.enum'
+import { v5 } from 'uuid'
// Box events record their request where it is accepted (BoxService, the
// auto-stop and auto-delete crons) and their outcome where the runner reports
@@ -13,7 +15,7 @@ import { JobStatus } from '../enums/job-status.enum'
type BoxEventName = 'box.create' | 'box.start' | 'box.stop' | 'box.delete'
/** The box an event is about; its organization travels with every record of it. */
-export type BoxRef = { id: string; organizationId: string }
+export type BoxRef = { id: string; organizationId: string; imageIsOrgOwned?: boolean | null }
export function recordBoxRequested(name: BoxEventName, box: BoxRef, ctx: Context): void {
recordBusinessEvent({ name, outcome: 'requested', correlationId: box.id, organizationId: box.organizationId, ctx })
@@ -35,10 +37,52 @@ export function recordWarmPoolClaim(box: BoxRef, ctx: Context): void {
* Records the outcome of a finished box job. Call it only after the box row
* reflecting that outcome has been written, and only for COMPLETED or FAILED jobs.
*/
-export function recordBoxJobOutcome(name: BoxEventName, jobStatus: JobStatus, box: BoxRef): void {
- const event = { name, correlationId: box.id, organizationId: box.organizationId }
+export function recordBoxJobOutcome(
+ name: BoxEventName,
+ jobStatus: JobStatus,
+ box: BoxRef,
+ job?: Readonly<BusinessEventJobTiming & { type?: JobType }>,
+): void {
+ // Copy only timing fields: Job payloads and runner errors may contain secrets.
+ const timing = job && {
+ id: job.id,
+ createdAt: job.createdAt,
+ startedAt: job.startedAt,
+ completedAt: job.completedAt,
+ }
+ const outcome = jobStatus === JobStatus.COMPLETED ? 'success' : 'exception'
+ const completedAt = timing?.completedAt
+ const occurrence =
+ timing?.id && completedAt instanceof Date && Number.isFinite(completedAt.getTime())
+ ? {
+ eventId: v5(`boxlite:job-outcome:${timing.id}:${name}:${outcome}`, v5.URL),
+ occurredAt: completedAt,
+ }
+ : {}
+ const event = {
+ name,
+ correlationId: box.id,
+ organizationId: box.organizationId,
+ ...(timing ? { job: timing } : {}),
+ ...occurrence,
+ }
if (jobStatus === JobStatus.COMPLETED) {
recordBusinessEvent({ ...event, outcome: 'success' })
+ // Persisted provenance is authoritative; older unclassified boxes stay unknown.
+ const startedImage =
+ (name === 'box.create' && job?.type === JobType.CREATE_BOX) ||
+ (name === 'box.start' && job?.type === JobType.START_BOX)
+ if (startedImage && box.imageIsOrgOwned === true && occurrence.eventId) {
+ recordBusinessEvent({
+ name: 'cloud.feature.use',
+ outcome: 'success',
+ organizationId: box.organizationId,
+ correlationId: box.id,
+ occurredAt: completedAt,
+ eventId: v5('boxlite:custom-image-start:' + occurrence.eventId, v5.URL),
+ feature: { name: 'custom_image', evidence: 'started_image', source: 'api' },
+ })
+ }
return
}
recordBusinessEvent({ ...event, outcome: 'exception', exceptionType: 'runner_job_failed' })
diff --git a/apps/api/src/box/utils/box-operation.util.spec.ts b/apps/api/src/box/utils/box-operation.util.spec.ts
new file mode 100644
index 000000000..fdd61c43c
--- /dev/null
+++ b/apps/api/src/box/utils/box-operation.util.spec.ts
@@ -0,0 +1,77 @@
+/*
+ * Copyright 2026 BoxLite AI
+ * SPDX-License-Identifier: AGPL-3.0
+ */
+
+import { BadRequestException, GatewayTimeoutException, Logger, RequestTimeoutException } from '@nestjs/common'
+import { Context } from '../../common/context/context'
+import { subscribeBusinessEvents } from '../../common/utils/business-event.util'
+import { BoxReadinessError } from '../errors/box-readiness.error'
+import { beginBoxOperation } from './box-operation.util'
+
+describe('Cloud Box operation accounting', () => {
+ let observed: Readonly<Record<string, string>>[]
+ let dispose: () => void
+ const options = { kind: 'create', organizationId: 'org-1', ctx: Context.user(), scope: 'rest_api' } as const
+
+ beforeEach(() => {
+ jest.useFakeTimers().setSystemTime(new Date('2026-09-29T08:00:00Z'))
+ jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined)
+ jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined)
+ observed = []
+ dispose = subscribeBusinessEvents((event) => observed.push(event))
+ })
+ afterEach(() => {
+ dispose()
+ jest.restoreAllMocks()
+ jest.useRealTimers()
+ })
+
+ it('correlates distinct occurrences and measures monotonic time across a wall-clock correction', () => {
+ const finish = beginBoxOperation(options)
+ jest.advanceTimersByTime(25)
+ jest.setSystemTime(new Date('2000-01-01T00:00:00Z'))
+ finish({ outcome: 'success', boxId: 'box-1' })
+ finish({ outcome: 'exception', error: new Error('late error') })
+
+ expect(observed).toHaveLength(2)
+ expect(observed[0]['event.id']).not.toBe(observed[1]['event.id'])
+ expect(observed[0]['operation.id']).toBe(observed[1]['operation.id'])
+ expect(observed[0]['operation.requested_at']).toBe(observed[1]['operation.requested_at'])
+ expect(observed[1]).toMatchObject({
+ 'operation.result': 'success',
+ 'operation.duration_ms': '25',
+ 'operation.boundary': 'cloud_api_to_started',
+ 'traffic.kind': 'unknown',
+ 'box.id': 'box-1',
+ })
+ })
+
+ it.each([
+ [new RequestTimeoutException('private-timeout'), 'timeout'],
+ [new GatewayTimeoutException('private-timeout'), 'timeout'],
+ [new BadRequestException('private-validation'), 'user_error'],
+ [new BoxReadinessError('private-runner-error'), 'service_error'],
+ [new Error('private-database-error'), 'service_error'],
+ [undefined, 'service_error'],
+ ])('classifies a failure without exporting its message: %s', (error, result) => {
+ beginBoxOperation(options)({ outcome: 'exception', error })
+ expect(observed[1]).toMatchObject({ 'operation.result': result, 'exception.type': result })
+ expect(JSON.stringify(observed)).not.toContain('private-')
+ })
+
+ it('keeps zero elapsed time and separates cancelled observations from service failures', () => {
+ beginBoxOperation(options)({ outcome: 'cancelled' })
+ expect(observed[1]).toMatchObject({ 'operation.result': 'cancelled', 'operation.duration_ms': '0' })
+ })
+
+ it('gives concurrent callers independent attempts', () => {
+ const first = beginBoxOperation(options)
+ const second = beginBoxOperation(options)
+ second({ outcome: 'success' })
+ first({ outcome: 'success' })
+ expect(observed[0]['operation.id']).not.toBe(observed[1]['operation.id'])
+ expect(observed[2]['operation.id']).toBe(observed[1]['operation.id'])
+ expect(observed[3]['operation.id']).toBe(observed[0]['operation.id'])
+ })
+})
diff --git a/apps/api/src/box/utils/box-operation.util.ts b/apps/api/src/box/utils/box-operation.util.ts
new file mode 100644
index 000000000..a46cc4bc0
--- /dev/null
+++ b/apps/api/src/box/utils/box-operation.util.ts
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2026 BoxLite AI
+ * SPDX-License-Identifier: AGPL-3.0
+ */
+
+import { HttpException } from '@nestjs/common'
+import { v4 } from 'uuid'
+import { Context } from '../../common/context/context'
+import { BusinessEventName, BusinessEventOperation, recordBusinessEvent } from '../../common/utils/business-event.util'
+import { BoxReadinessError } from '../errors/box-readiness.error'
+
+type Completion = { boxId?: string } & (
+ | { outcome: 'success'; confirmedAt?: number }
+ | { outcome: 'exception'; error: unknown }
+ | { outcome: 'cancelled' }
+)
+
+/** One server-side attempt, independent of resource identity and runner-job retries. */
+export function beginBoxOperation(options: {
+ kind: 'create' | 'start' | 'resume'
+ organizationId: string
+ ctx: Context
+ scope: BusinessEventOperation['scope']
+ boxId?: string
+ timing?: { requestedAt: Date; monotonicStart: number }
+}): (completion: Completion) => void {
+ const operation = {
+ id: v4(),
+ requestedAt: options.timing?.requestedAt ?? new Date(),
+ scope: options.scope,
+ boxId: options.boxId,
+ }
+ const started = options.timing?.monotonicStart ?? performance.now()
+ const event = {
+ name: ('cloud.box.' + options.kind) as BusinessEventName,
+ correlationId: operation.id,
+ organizationId: options.organizationId,
+ ctx: options.ctx,
+ }
+ recordBusinessEvent({ ...event, operation, occurredAt: operation.requestedAt, outcome: 'requested' })
+ let finished = false
+ return (completion) => {
+ if (finished) return
+ finished = true
+ const result = completion.outcome === 'exception' ? failureResult(completion.error) : completion.outcome
+ const ended = completion.outcome === 'success' ? (completion.confirmedAt ?? performance.now()) : performance.now()
+ const timing: BusinessEventOperation = {
+ ...operation,
+ boxId: completion.boxId ?? operation.boxId,
+ durationMs: Math.max(0, ended - started),
+ result,
+ }
+ recordBusinessEvent({
+ ...event,
+ operation: timing,
+ ...(completion.outcome === 'success' ? { outcome: 'success' } : { outcome: 'exception', exceptionType: result }),
+ })
+ }
+}
+
+function failureResult(error: unknown): 'service_error' | 'timeout' | 'user_error' {
+ if (
+ error instanceof BoxReadinessError ||
+ (error instanceof HttpException && error.cause instanceof BoxReadinessError)
+ ) {
+ return 'service_error'
+ }
+ const status = error instanceof HttpException ? error.getStatus() : 500
+ if (status === 408 || status === 504) return 'timeout'
+ return status >= 400 && status < 500 ? 'user_error' : 'service_error'
+}
diff --git a/apps/api/src/boxlite-rest/boxlite-box.controller.ts b/apps/api/src/boxlite-rest/boxlite-box.controller.ts
index bc38b472a..23c347de5 100644
--- a/apps/api/src/boxlite-rest/boxlite-box.controller.ts
+++ b/apps/api/src/boxlite-rest/boxlite-box.controller.ts
@@ -54,6 +54,7 @@ import { ReplayValidationPipe } from '../common/replay-validation.pipe'
import { noEffect } from '../common/replay-no-effect'
import { Context } from '../common/context/context'
import { BoxPageQuery } from './dto/box-page-query.dto'
+import { ObserveBoxReadiness, ON_BOX_STARTED } from '../box/interceptors/box-readiness.interceptor'
const CHECKPOINT_BOX_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/
@@ -91,6 +92,7 @@ export class BoxliteBoxController {
) {}
@Post()
+ @ObserveBoxReadiness('create')
@RequiredOrganizationResourcePermissions([OrganizationResourcePermission.WRITE_BOXES])
@HttpCode(201)
@ApiResponse({
@@ -147,11 +149,12 @@ export class BoxliteBoxController {
let box = await this.boxService.create(createBoxDto, organization, ctx, {
maxCreatedBoxes,
createdBy: authContext.userId,
+ onStarted: request?.[ON_BOX_STARTED],
})
boxId = box.id
if (request) request[AUDIT_TARGET_ID] = box.id
if (box.state !== BoxState.STARTED) {
- box = await this.boxStateWaiter.waitForStarted(box.id, organization.id, 30)
+ box = await this.boxStateWaiter.waitForStarted(box.id, organization.id, 30, request?.[ON_BOX_STARTED])
}
return boxToBoxResponse(box)
} catch (error) {
@@ -219,7 +222,9 @@ export class BoxliteBoxController {
recordBoxRequested('box.create', box, ctx)
if (request) request[AUDIT_TARGET_ID] = box.id
try {
- return boxToBoxResponse(await this.boxStateWaiter.waitForStarted(box.id, authContext.organizationId, 30))
+ return boxToBoxResponse(
+ await this.boxStateWaiter.waitForStarted(box.id, authContext.organizationId, 30, request?.[ON_BOX_STARTED]),
+ )
} catch (error) {
// Admission already created this identity. Clients must query it after
// any wait failure instead of submitting another anonymous Box.
@@ -339,6 +344,7 @@ export class BoxliteBoxController {
targetIdFromRequest: (req) => req.params.boxId,
targetIdFromResult: (result: BoxResponseDto) => result?.box_id,
})
+ @ObserveBoxReadiness('start')
async startBox(
@AuthContext() authContext: OrganizationAuthContext,
@Param('boxId') boxId: string,
@@ -349,14 +355,20 @@ export class BoxliteBoxController {
if (request) request[AUDIT_TARGET_ID] = box.id
if (this.isStartAlreadyInProgress(box)) {
- const dto = await this.boxStateWaiter.waitForStarted(box.id, authContext.organizationId, 30)
+ const dto = await this.boxStateWaiter.waitForStarted(
+ box.id,
+ authContext.organizationId,
+ 30,
+ request?.[ON_BOX_STARTED],
+ )
return boxToBoxResponse(dto)
}
box = await this.boxService.start(box.id, authContext.organization, ctx, { idOnly: true })
+ if (box.state === BoxState.STARTED) request?.[ON_BOX_STARTED]?.()
let dto = await this.boxService.toBoxDto(box)
if (dto.state !== BoxState.STARTED) {
- dto = await this.boxStateWaiter.waitForStarted(box.id, authContext.organizationId, 30)
+ dto = await this.boxStateWaiter.waitForStarted(box.id, authContext.organizationId, 30, request?.[ON_BOX_STARTED])
}
return boxToBoxResponse(dto)
}
diff --git a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts
index 690299db4..f5de536fe 100644
--- a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts
+++ b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts
@@ -29,12 +29,15 @@ import { BoxliteCheckpointController } from './boxlite-checkpoint.controller'
import { CommerceBoxLimitService } from './commerce-box-limit.service'
import { BoxliteBoxController } from './boxlite-box.controller'
import { BoxService } from '../box/services/box.service'
+import { MetricsInterceptor } from '../interceptors/metrics.interceptor'
+import { McpDelegation, MCP_DELEGATION_HEADER } from '../auth/mcp-delegation'
// Real HTTP, Passport API-key validation and organization permission guards;
// credential storage, membership, Redis and checkpoint persistence are fixtures.
describe('Checkpoint REST authentication and request admission', () => {
let app: INestApplication
const organizationId = 'checkpoint-org'
+ const capture = jest.fn()
const checkpoints = { create: jest.fn(), list: jest.fn(), get: jest.fn(), remove: jest.fn() }
const recovery = { createBox: jest.fn() }
const boxes = { create: jest.fn() }
@@ -145,6 +148,12 @@ describe('Checkpoint REST authentication and request admission', () => {
}).compile()
app = module.createNestApplication()
app.setGlobalPrefix('api')
+ app.useGlobalInterceptors(
+ new MetricsInterceptor(
+ { getOrThrow: () => 'test', get: () => undefined } as never,
+ { enabled: true, capture } as never,
+ ),
+ )
app.useGlobalFilters(new AllExceptionsFilter({ incrementFailedAuth: jest.fn() } as never))
await app.listen(0, '127.0.0.1')
})
@@ -162,14 +171,71 @@ describe('Checkpoint REST authentication and request admission', () => {
limits.resolveMaxCreatedBoxes.mockReset().mockResolvedValue(2)
})
- function request(path: string, token?: string, body?: unknown, method?: string) {
+ function request(path: string, token?: string, body?: unknown, method?: string, headers?: Record<string, string>) {
return fetch(`http://127.0.0.1:${(app.getHttpServer().address() as AddressInfo).port}/api${path}`, {
method: method ?? (body === undefined ? 'GET' : 'POST'),
- headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
+ headers: {
+ 'content-type': 'application/json',
+ ...headers,
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
+ },
body: body === undefined ? undefined : JSON.stringify(body),
})
}
+ it.each([
+ ['/v1/checkpoints', 'sdk', 'sdk'],
+ ['/v1/default/checkpoints', 'dashboard', 'dashboard'],
+ ['/v1/checkpoint-org/checkpoints', 'mcp', 'unattributed'],
+ ['/v1/checkpoints', undefined, 'unattributed'],
+ ])('records a finished checkpoint request at %s from %s', async (path, label, source) => {
+ const headers = label ? { 'X-BoxLite-Source': label } : {}
+ capture.mockImplementationOnce(() => new Promise(() => {}))
+ const response = await request(path, 'checkpoint-write-key', { source_box_id: 'private-box' }, 'POST', headers)
+ expect(response.status).toBe(201)
+ expect(capture.mock.calls).toEqual([
+ [
+ {
+ event: 'cloud.api.operation',
+ distinctId: 'owner',
+ timestamp: expect.any(Date),
+ groups: { organization: organizationId },
+ properties: { 'api.operation': 'checkpoint.create', 'client.source': source, 'http.status_class': '2xx' },
+ },
+ { users: ['owner'], organizations: [organizationId] },
+ ],
+ ])
+ })
+
+ it('attributes a consumed MCP delegation and drops denied or polling requests', async () => {
+ const nonce = new McpDelegation().issue({
+ role: SystemRole.USER,
+ userId: 'owner',
+ email: '[email protected]',
+ organizationId,
+ })
+ const response = await request('/v1/checkpoints', undefined, { source_box_id: 'private-box' }, 'POST', {
+ [MCP_DELEGATION_HEADER]: nonce,
+ })
+ expect(response.status).toBe(201)
+ expect(capture.mock.calls[0][0].properties['client.source']).toBe('mcp')
+ capture.mockClear()
+ expect((await request('/v1/checkpoints', 'checkpoint-read-key', { source_box_id: 'private-box' })).status).toBe(403)
+ expect((await request('/v1/checkpoints', 'checkpoint-read-key')).status).toBe(200)
+ expect(capture).not.toHaveBeenCalled()
+ })
+
+ it('records a rejected restore intent without exporting its selector or validation error', async () => {
+ await request('/v1/boxes', 'checkpoint-write-key', { checkpoint_id: 'private', image: 'private-image' })
+ const events = capture.mock.calls.filter(([row]) => row.event === 'cloud.api.operation')
+ expect(events).toHaveLength(1)
+ expect(events[0][0].properties).toEqual({
+ 'api.operation': 'checkpoint.restore',
+ 'client.source': 'unattributed',
+ 'http.status_class': '4xx',
+ })
+ })
+
it.each(['pageToken', 'page_token'])('passes the %s pagination cursor to checkpoint storage', async (parameter) => {
const response = await request(`/v1/checkpoints?${parameter}=next-page`, 'checkpoint-write-key')
expect(response.status).toBe(200)
@@ -313,7 +379,7 @@ describe('Checkpoint REST authentication and request admission', () => {
expect(recovery.createBox.mock.calls).toEqual(
Array.from({ length: 3 }, () => [{ id: organizationId }, 'base', 'new-target', 2]),
)
- expect(waiter.waitForStarted).toHaveBeenCalledWith('target-id', organizationId, 30)
+ expect(waiter.waitForStarted).toHaveBeenCalledWith('target-id', organizationId, 30, expect.any(Function))
expect(boxes.create).not.toHaveBeenCalled()
})
diff --git a/apps/api/src/boxlite-rest/boxlite-proxy-ssh.spec.ts b/apps/api/src/boxlite-rest/boxlite-proxy-ssh.spec.ts
index e94edf552..f27650ed7 100644
--- a/apps/api/src/boxlite-rest/boxlite-proxy-ssh.spec.ts
+++ b/apps/api/src/boxlite-rest/boxlite-proxy-ssh.spec.ts
@@ -15,6 +15,7 @@ import { OrganizationResourceActionGuard } from '../organization/guards/organiza
import { OrganizationService } from '../organization/services/organization.service'
import { OrganizationUserService } from '../organization/services/organization-user.service'
import { BoxService } from '../box/services/box.service'
+import { subscribeBusinessEvents } from '../common/utils/business-event.util'
import { RunnerService } from '../box/services/runner.service'
import { BoxAutoResumeService } from '../box/services/box-auto-resume.service'
import { BoxliteProxyController } from './boxlite-proxy.controller'
@@ -70,12 +71,41 @@ describe('BoxliteProxyController SSH routes', () => {
expect(proxiedPath()).toBe('/v1/boxes/box-uuid/ssh')
})
+ it('records a start which finishes between admission and the lifecycle lock', async () => {
+ const { call, boxService, autoResume, proxyHandler } = makeHarness({ state: 'starting', desiredState: 'started' })
+ const lifecycle = { ensureStartedForProxy: jest.fn().mockResolvedValue({ id: 'box-uuid', ...running }) }
+ const lock = { lock: jest.fn().mockResolvedValue(true), unlock: jest.fn().mockResolvedValue(undefined) }
+ const resume = new BoxAutoResumeService(lifecycle as never, {} as never, lock as never)
+ autoResume.ensureReady.mockImplementation(resume.ensureReady.bind(resume))
+ const outcomes: string[] = []
+ const dispose = subscribeBusinessEvents((event) => {
+ if (event['event.name'] === 'cloud.box.resume') outcomes.push(event['event.outcome'])
+ })
+ try {
+ await call('configureSsh')
+ expect(boxService.findOneByIdOrName).toHaveBeenCalledTimes(1)
+ expect(lifecycle.ensureStartedForProxy).toHaveBeenCalledTimes(1)
+ expect(proxyHandler).toHaveBeenCalledTimes(1)
+ expect(outcomes).toEqual(['requested', 'success'])
+ } finally {
+ dispose()
+ }
+ })
+
it('resumes a stopped box that runs its image default command', async () => {
const { call, autoResume, proxyHandler } = makeHarness({ state: 'stopped', desiredState: 'stopped' })
await call('configureSsh')
- expect(autoResume.ensureReady).toHaveBeenCalledWith('box-uuid', expect.anything(), expect.any(Function))
+ expect(autoResume.ensureReady).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'box-uuid', state: 'stopped' }),
+ expect.anything(),
+ expect.any(Function),
+ {
+ requestedAt: expect.any(Date),
+ monotonicStart: expect.any(Number),
+ },
+ )
expect(proxyHandler).toHaveBeenCalledTimes(1)
})
@@ -110,7 +140,7 @@ describe('BoxliteProxyController SSH routes', () => {
try {
await Promise.race([waiting, request])
await new Promise<void>((resolve) => setImmediate(resolve))
- expect(waitForStarted).toHaveBeenCalledWith('box-uuid', 'org-1', 30)
+ expect(waitForStarted).toHaveBeenCalledWith('box-uuid', 'org-1', 30, expect.any(Function))
expect(waitForStarted).toHaveBeenCalledTimes(1)
expect(boxService.findOneByIdOrName).toHaveBeenCalledTimes(2)
expect(createProxyMiddleware).not.toHaveBeenCalled()
diff --git a/apps/api/src/boxlite-rest/boxlite-proxy.controller.ts b/apps/api/src/boxlite-rest/boxlite-proxy.controller.ts
index d5e658aef..522576464 100644
--- a/apps/api/src/boxlite-rest/boxlite-proxy.controller.ts
+++ b/apps/api/src/boxlite-rest/boxlite-proxy.controller.ts
@@ -45,6 +45,7 @@ import { reportedBoxState } from '../box/utils/box-state.util'
import { Box } from '../box/entities/box.entity'
import { TunnelService } from '../box/services/tunnel.service'
import { PrepareTunnelDto } from '../box/dto/tunnel.dto'
+import { requestTiming } from '../common/utils/request-timing.util'
import { requestContext, UserContext } from '../common/decorators/user-context.decorator'
import { Context } from '../common/context/context'
import { recordBusinessEvent, recordOutcomes } from '../common/utils/business-event.util'
@@ -568,7 +569,7 @@ export class BoxliteProxyController {
}
if (policy.autoResume && box.autoResume) {
- await this.autoResume.ensureReady(box.id, authContext.organization, opts?.admit)
+ await this.autoResume.ensureReady(box, authContext.organization, opts?.admit, requestTiming(req))
}
const runner = await this.runnerService.findOne(box.runnerId)
diff --git a/apps/api/src/boxlite-rest/boxlite-rest.module.ts b/apps/api/src/boxlite-rest/boxlite-rest.module.ts
index 47bd312ba..8b72d889d 100644
--- a/apps/api/src/boxlite-rest/boxlite-rest.module.ts
+++ b/apps/api/src/boxlite-rest/boxlite-rest.module.ts
@@ -40,6 +40,7 @@ import { CommerceBoxLimitService } from './commerce-box-limit.service'
import { RequestReplayModule } from './request-replay.module'
import { AuditModule } from '../audit/audit.module'
import { BoxliteCheckpointController } from './boxlite-checkpoint.controller'
+import { BoxReadinessInterceptor } from '../box/interceptors/box-readiness.interceptor'
@Module({
imports: [
@@ -72,6 +73,7 @@ import { BoxliteCheckpointController } from './boxlite-checkpoint.controller'
BoxliteInvitationController,
],
providers: [
+ BoxReadinessInterceptor,
BoxliteWsProxyService,
CommerceBoxLimitService,
CiConnectService,
diff --git a/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.spec.ts b/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.spec.ts
index a7bdb4c98..e3dadef36 100644
--- a/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.spec.ts
+++ b/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.spec.ts
@@ -182,7 +182,15 @@ describe('BoxliteWsProxyService', () => {
Buffer.alloc(0),
)
- expect(autoResume.ensureReady).toHaveBeenCalledWith('box-uuid', expect.objectContaining({ id: 'org-1' }))
+ expect(autoResume.ensureReady).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'box-uuid' }),
+ expect.objectContaining({ id: 'org-1' }),
+ undefined,
+ {
+ requestedAt: expect.any(Date),
+ monotonicStart: expect.any(Number),
+ },
+ )
expect(proxyHandler.upgrade).not.toHaveBeenCalled()
expect(socket.destroy).toHaveBeenCalled()
})
diff --git a/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.ts b/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.ts
index 7ebe4967f..c6ee80df9 100644
--- a/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.ts
+++ b/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.ts
@@ -25,6 +25,7 @@ import { OrganizationResourcePermission } from '../organization/enums/organizati
import { AttachTicketService } from '../box/services/attach-ticket.service'
import { AuditService } from '../audit/services/audit.service'
import { AttachAuditSession } from './attach-audit-session'
+import { requestTiming } from '../common/utils/request-timing.util'
type RunnerUpgradeRequest = IncomingMessage & {
__boxliteRunner?: Runner
@@ -124,6 +125,7 @@ export class BoxliteWsProxyService {
* proxy middleware. Closes the socket cleanly on any failure.
*/
async upgrade(req: IncomingMessage, socket: Socket, head: Buffer): Promise<void> {
+ const timing = requestTiming(req)
const match = this.matchAttachPath(req.url)
if (!match) {
socket.destroy()
@@ -159,7 +161,7 @@ export class BoxliteWsProxyService {
return
}
if (box.autoResume) {
- await this.autoResume.ensureReady(box.id, auth.organization)
+ await this.autoResume.ensureReady(box, auth.organization, undefined, timing)
}
// Opening a WS attach is user activity,
// so the autostop cron does not reap a session that's still connected.
diff --git a/apps/api/src/ci/ci-native-host.spec.ts b/apps/api/src/ci/ci-native-host.spec.ts
index ea637c95a..741534264 100644
--- a/apps/api/src/ci/ci-native-host.spec.ts
+++ b/apps/api/src/ci/ci-native-host.spec.ts
@@ -1,7 +1,7 @@
/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
import { inspectJournal } from '@boxlite-ai/ci-listener/testing'
import { testCapacity } from '@boxlite-ai/ci-listener/testing'
-import { createHash, generateKeyPairSync, randomUUID } from 'node:crypto'
+import { createHash, createHmac, generateKeyPairSync, randomUUID } from 'node:crypto'
import { DataSource, QueryFailedError } from 'typeorm'
import { Logger } from '@nestjs/common'
import {
@@ -9,9 +9,11 @@ import {
ExecutionJournal,
GitHubAppSource,
VerifiedWebhook,
+ verifyWebhook,
ExecutionLease,
ExecutionScope,
} from '@boxlite-ai/ci-listener'
+import { subscribeBusinessEvents } from '../common/utils/business-event.util'
import { CiNativeState } from './ci-native-state'
import { CiNativeHost } from './ci-native-host'
import { CiListenerService } from './ci-listener.service'
@@ -537,6 +539,65 @@ integration('CI native host (Postgres binding and shared inbox)', () => {
job: { id: 50, runId: 40 },
})
})
+ it('records signed Job phases after admission without a worker allocation', async () => {
+ const secret = Buffer.alloc(32, 1)
+ const created_at = '2026-11-01T10:00:00Z'
+ const started_at = '2026-11-01T10:00:05Z'
+ const completed_at = '2026-11-01T10:01:00Z'
+ const signed = (status: string, fields: Record<string, unknown> = {}) => {
+ const raw = Buffer.from(
+ JSON.stringify({
+ action: status,
+ installation: { id: 10 },
+ repository: { id: 30, owner: { id: 20 } },
+ workflow_job: {
+ id: 50,
+ run_id: 40,
+ status,
+ labels: ['boxlite'],
+ created_at,
+ started_at,
+ completed_at,
+ runner_id: status === 'queued' ? null : 768,
+ runner_name: status === 'queued' ? null : 'ci-jit-' + 'a'.repeat(32),
+ ...fields,
+ },
+ }),
+ )
+ const signature = 'sha256=' + createHmac('sha256', secret).update(raw).digest('hex')
+ return {
+ ...verifyWebhook({ raw, signature, event: 'workflow_job', delivery: randomUUID() }, secret)!,
+ application: 'test-app',
+ }
+ }
+ const recorded: Readonly<Record<string, string>>[] = []
+ const stop = subscribeBusinessEvents((event) => recorded.push(event))
+ try {
+ await host.accept(signed('queued'))
+ await host.accept(signed('in_progress'))
+ const completion = signed('completed')
+ expect(await host.accept(completion)).toBe('stored')
+ expect(await host.accept(completion)).toBe('duplicate')
+ expect(recorded.map((e) => [e['event.name'], e['feature.evidence'], e['event.timestamp']])).toEqual([
+ ['cloud.ci.request', undefined, new Date(created_at).toISOString()],
+ ['cloud.feature.use', 'runner_started', new Date(started_at).toISOString()],
+ ['cloud.feature.use', 'runner_completed', new Date(completed_at).toISOString()],
+ ['cloud.feature.use', 'runner_completed', new Date(completed_at).toISOString()],
+ ])
+ expect(new Set(recorded.map((e) => e['event.id'])).size).toBe(4)
+ expect(new Set(recorded.map((e) => e['correlation.id'])).size).toBe(1)
+ expect(recorded[1]).toMatchObject({
+ 'organization.id': org,
+ 'feature.name': 'ci',
+ 'feature.source': 'api',
+ 'ci.job_created_at': new Date(created_at).toISOString(),
+ })
+ expect(JSON.stringify(recorded)).not.toContain('ci-jit-')
+ expect(requests).toEqual([])
+ } finally {
+ stop()
+ }
+ })
it('rejects a conflicting event body without replacing the original receipt', async () => {
const event = notification()
await host.accept(event)
diff --git a/apps/api/src/ci/ci-native-host.ts b/apps/api/src/ci/ci-native-host.ts
index cece351bc..d46e65a21 100644
--- a/apps/api/src/ci/ci-native-host.ts
+++ b/apps/api/src/ci/ci-native-host.ts
@@ -28,6 +28,8 @@ import {
ListenerEvent,
ScaleSetFailure,
} from '@boxlite-ai/ci-listener'
+import { v5 } from 'uuid'
+import { recordBusinessEvent } from '../common/utils/business-event.util'
import { TypedConfigService } from '../config/typed-config.service'
import { CiGitHubService } from './ci-github.service'
import { CiNativeState, CiNativeAuthority } from './ci-native-state'
@@ -326,6 +328,7 @@ export class CiNativeHost implements ListenerHost {
})
}
async accept(notification: VerifiedWebhook): Promise<'stored' | 'duplicate'> {
+ let organization: string | undefined
const captured = {
...notification,
hint: { ...notification.hint, job: notification.hint.job ? { ...notification.hint.job } : null },
@@ -349,11 +352,41 @@ export class CiNativeHost implements ListenerHost {
if (hint.repositoryId !== 0) {
if (!row) throw new ForbiddenException('CI installation is not connected')
await this.store.admit(tx, authority(row), row.app_client_id)
+ organization = row.organization_id
}
return work(tx)
}),
})
- return new ListenerInbox(new ListenerState(database, this.store.namespace)).receive(captured)
+ const result = await new ListenerInbox(new ListenerState(database, this.store.namespace)).receive(captured)
+ const { installationId, repositoryId, job } = captured.hint
+ const { jobTiming, observation } = captured
+ if (organization && job && jobTiming && observation) {
+ try {
+ const common = {
+ organizationId: organization,
+ correlationId: v5(`boxlite:ci-request:${installationId}:${repositoryId}:${job.id}`, v5.URL),
+ occurredAt: new Date(jobTiming.occurredAt),
+ }
+ if (observation.status === 'queued') {
+ recordBusinessEvent({ ...common, name: 'cloud.ci.request', outcome: 'requested' })
+ } else {
+ recordBusinessEvent({
+ ...common,
+ name: 'cloud.feature.use',
+ outcome: 'success',
+ feature: {
+ name: 'ci',
+ evidence: observation.status === 'in_progress' ? 'runner_started' : 'runner_completed',
+ source: 'api',
+ ciJobCreatedAt: new Date(jobTiming.createdAt),
+ },
+ })
+ }
+ } catch {
+ this.logger.warn('Could not record CI webhook analytics')
+ }
+ }
+ return result
}
async close(): Promise<void> {
diff --git a/apps/api/src/common/constants/constants.ts b/apps/api/src/common/constants/constants.ts
index 4d6da329c..7f1f2e648 100644
--- a/apps/api/src/common/constants/constants.ts
+++ b/apps/api/src/common/constants/constants.ts
@@ -5,3 +5,4 @@
*/
export const BOX_EVENT_CHANNEL = 'box.event.channel'
+export const MAX_FEATURE_USAGE_BATCH_SIZE = 100
diff --git a/apps/api/src/common/providers/openfeature-posthog.provider.spec.ts b/apps/api/src/common/providers/openfeature-posthog.provider.spec.ts
new file mode 100644
index 000000000..ebd2b290f
--- /dev/null
+++ b/apps/api/src/common/providers/openfeature-posthog.provider.spec.ts
@@ -0,0 +1,54 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { createServer } from 'node:http'
+import { AddressInfo } from 'node:net'
+import { OpenFeaturePostHogProvider } from './openfeature-posthog.provider'
+import { AnalyticsConsentService } from '../../analytics/services/analytics-consent.service'
+import { AnalyticsService } from '../../analytics/services/analytics.service'
+import { TypedConfigService } from '../../config/typed-config.service'
+
+it('evaluates identified rollouts after refusal without ingesting an exposure event', async () => {
+ const requests: { path: string; body: Record<string, unknown> }[] = []
+ let enabled = true
+ const server = createServer(async (req, res) => {
+ const chunks: Buffer[] = []
+ for await (const chunk of req) chunks.push(chunk)
+ requests.push({ path: req.url!.split('?')[0], body: JSON.parse(Buffer.concat(chunks).toString()) })
+ res.setHeader('Content-Type', 'application/json')
+ res.end(JSON.stringify({ featureFlags: { rollout: enabled }, featureFlagPayloads: {} }))
+ })
+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))
+ const host = 'http://127.0.0.1:' + (server.address() as AddressInfo).port
+ const config: Record<string, string> = { 'posthog.apiKey': 'phc_test', 'posthog.host': host }
+ const consent = Object.create(AnalyticsConsentService.prototype) as AnalyticsConsentService
+ const check = jest.spyOn(consent, 'dispatch').mockResolvedValue(false)
+ const analytics = new AnalyticsService({ get: (key: string) => config[key] } as TypedConfigService, consent)
+ const provider = new OpenFeaturePostHogProvider({
+ apiKey: 'phc_test',
+ clientOptions: { host },
+ reportExposure: (flag, value, user, org) =>
+ analytics.capture(
+ { event: '$feature_flag_called', distinctId: user, properties: { flag, value } },
+ { users: [user], organizations: org ? [org] : [] },
+ ),
+ })
+ try {
+ const context = { targetingKey: 'actor', organizationId: 'organization' }
+ const logger = { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() }
+ for (enabled of [true, false]) {
+ const result = await provider.resolveBooleanEvaluation('rollout', !enabled, context, logger)
+ expect(result.value).toBe(enabled)
+ }
+ await provider.onClose()
+ await analytics.onApplicationShutdown()
+ expect(check).toHaveBeenCalledTimes(2)
+ expect(requests).toHaveLength(2)
+ for (const { path, body } of requests) {
+ expect(['/flags/', '/decide/']).toContain(path)
+ expect(body).toMatchObject({ distinct_id: 'actor', groups: { organization: 'organization' } })
+ }
+ } finally {
+ await provider.onClose()
+ await analytics.onApplicationShutdown()
+ await new Promise<void>((r) => server.close(() => r()))
+ }
+})
diff --git a/apps/api/src/common/providers/openfeature-posthog.provider.ts b/apps/api/src/common/providers/openfeature-posthog.provider.ts
index 3cfbffbb1..0aaf086cd 100644
--- a/apps/api/src/common/providers/openfeature-posthog.provider.ts
+++ b/apps/api/src/common/providers/openfeature-posthog.provider.ts
@@ -14,6 +14,8 @@ export interface OpenFeaturePostHogProviderConfig {
apiKey?: string
/** Optional PostHog client options */
clientOptions?: PostHogOptions
+ /** Route optional analytics through the consent-checked product analytics client. */
+ reportExposure?: (flag: string, value: string | boolean, userId: string, orgId?: string) => void
/** Whether to evaluate flags locally (default: false) */
evaluateLocally?: boolean
}
@@ -27,7 +29,7 @@ export class OpenFeaturePostHogProvider implements Provider {
private readonly evaluateLocally: boolean
private readonly isConfigured: boolean
- constructor(config: OpenFeaturePostHogProviderConfig = {}) {
+ constructor(private readonly config: OpenFeaturePostHogProviderConfig = {}) {
this.evaluateLocally = config.evaluateLocally ?? false
this.isConfigured = !!config.apiKey
@@ -115,7 +117,7 @@ export class OpenFeaturePostHogProvider implements Provider {
const flagContext = this.buildFlagContext(context)
const payload = await this.client.getFeatureFlagPayload(flagKey, targetingKey, undefined, {
onlyEvaluateLocally: this.evaluateLocally,
- sendFeatureFlagEvents: true,
+ sendFeatureFlagEvents: false,
...flagContext,
})
@@ -171,7 +173,7 @@ export class OpenFeaturePostHogProvider implements Provider {
const flagContext = this.buildFlagContext(context)
const flagValue = await this.client.getFeatureFlag(flagKey, targetingKey, {
onlyEvaluateLocally: this.evaluateLocally,
- sendFeatureFlagEvents: true,
+ sendFeatureFlagEvents: false,
...flagContext,
})
@@ -183,6 +185,7 @@ export class OpenFeaturePostHogProvider implements Provider {
}
}
+ this.config.reportExposure?.(flagKey, flagValue, targetingKey, flagContext.groups?.organization)
return {
value: flagValue,
reason: StandardResolutionReasons.TARGETING_MATCH,
diff --git a/apps/api/src/common/utils/business-event.otlp.spec.ts b/apps/api/src/common/utils/business-event.otlp.spec.ts
index 57dbcad1b..427b2f47d 100644
--- a/apps/api/src/common/utils/business-event.otlp.spec.ts
+++ b/apps/api/src/common/utils/business-event.otlp.spec.ts
@@ -59,6 +59,7 @@ describe('recordBusinessEvent through the API logging stack', () => {
expect(record?.attributes).toEqual(
expect.objectContaining({
'event.name': 'box.delete',
+ 'event.id': expect.any(String),
'event.outcome': 'requested',
'correlation.id': 'box-1',
'actor.kind': 'platform',
diff --git a/apps/api/src/common/utils/business-event.util.spec.ts b/apps/api/src/common/utils/business-event.util.spec.ts
index b948c83af..142597af5 100644
--- a/apps/api/src/common/utils/business-event.util.spec.ts
+++ b/apps/api/src/common/utils/business-event.util.spec.ts
@@ -4,7 +4,7 @@
*/
import { Logger } from '@nestjs/common'
-import { recordBusinessEvent, recordOutcomes } from './business-event.util'
+import { recordBusinessEvent, recordOutcomes, subscribeBusinessEvents } from './business-event.util'
import { Context } from '../context/context'
import { PlatformReason } from '../context/platform-reason.enum'
@@ -41,9 +41,68 @@ describe('recordBusinessEvent', () => {
'event.reason': 'auto_delete',
'service.type': 'api',
'event.timestamp': '2026-09-30T08:00:00.000Z',
+ 'event.id': expect.any(String),
})
})
+ it('shares one occurrence ID with observers and keeps separate occurrences distinct', () => {
+ const observed: Readonly<Record<string, string>>[] = []
+ const dispose = subscribeBusinessEvents((attributes) => observed.push(attributes))
+ try {
+ recordBusinessEvent({ name: 'box.start', outcome: 'requested', correlationId: 'box-1' })
+ recordBusinessEvent({ name: 'box.start', outcome: 'success', correlationId: 'box-1' })
+ expect(observed[0]['event.id']).toMatch(/^[0-9a-f-]{36}$/)
+ expect(observed[1]['event.id']).not.toBe(observed[0]['event.id'])
+ expect(logSpy.mock.calls.map(([, attributes]) => attributes)).toEqual(observed)
+ } finally {
+ dispose()
+ }
+ })
+
+ it('preserves source occurrence identity and time', () => {
+ const event = {
+ name: 'box.start' as const,
+ outcome: 'success' as const,
+ correlationId: 'box-1',
+ eventId: '11111111-1111-4111-8111-111111111111',
+ occurredAt: new Date('2026-09-29T08:00:00.000Z'),
+ }
+ recordBusinessEvent(event)
+ expect(logSpy.mock.calls[0][1]).toMatchObject({
+ 'event.id': event.eventId,
+ 'event.timestamp': event.occurredAt.toISOString(),
+ })
+ })
+
+ it('falls back to observation time for an invalid source clock', () => {
+ const event = {
+ name: 'box.start' as const,
+ outcome: 'success' as const,
+ correlationId: 'box-1',
+ occurredAt: new Date(NaN),
+ }
+ expect(() => recordBusinessEvent(event)).not.toThrow()
+ expect(logSpy.mock.calls[0][1]['event.timestamp']).toBe(now.toISOString())
+ })
+
+ it("isolates an observer that attempts to alter another observer's attributes", () => {
+ const mutate = subscribeBusinessEvents((attributes) => {
+ const writable = attributes as Record<string, string>
+ writable['event.name'] = 'user.login'
+ })
+ const observed = jest.fn()
+ const dispose = subscribeBusinessEvents(observed)
+ jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined)
+ try {
+ recordBusinessEvent({ name: 'box.start', outcome: 'success', correlationId: 'box-1' })
+ expect(observed).toHaveBeenCalledWith(expect.objectContaining({ 'event.name': 'box.start' }))
+ expect(Logger.prototype.warn).toHaveBeenCalledWith('Business event analytics capture failed')
+ } finally {
+ mutate()
+ dispose()
+ }
+ })
+
it('omits optional attributes the event does not carry', () => {
recordBusinessEvent({ name: 'user.registration', outcome: 'requested', correlationId: 'user-1' })
@@ -126,6 +185,26 @@ describe('recordOutcomes', () => {
afterEach(() => jest.restoreAllMocks())
+ it('keeps occurrence overrides out of a shared lifecycle input', async () => {
+ const source = {
+ ...event,
+ eventId: '11111111-1111-4111-8111-111111111111',
+ occurredAt: new Date('2000-01-01T00:00:00Z'),
+ }
+ await recordOutcomes(
+ source,
+ async () => 42,
+ () => 'internal',
+ )
+ const attributes = logSpy.mock.calls.map(([, attributes]) => attributes)
+ expect(attributes).toHaveLength(2)
+ expect(new Set(attributes.map((attributes) => attributes['event.id'])).size).toBe(2)
+ for (const observed of attributes) {
+ expect(observed['event.id']).not.toBe(source.eventId)
+ expect(observed['event.timestamp']).not.toBe(source.occurredAt.toISOString())
+ }
+ })
+
it('records requested before the operation and success after it, and returns its result', async () => {
const op = jest.fn(async () => {
expect(logSpy.mock.calls.map(([message]) => message)).toEqual(['user.registration requested'])
@@ -135,6 +214,9 @@ describe('recordOutcomes', () => {
await expect(recordOutcomes(event, op, () => 'internal')).resolves.toBe('created')
expect(op).toHaveBeenCalledTimes(1)
+ const ids = logSpy.mock.calls.map(([, attributes]) => attributes['event.id'])
+ expect(ids).toEqual([expect.any(String), expect.any(String)])
+ expect(new Set(ids).size).toBe(2)
expect(logSpy.mock.calls.map(([message]) => message)).toEqual([
'user.registration requested',
'user.registration success',
diff --git a/apps/api/src/common/utils/business-event.util.ts b/apps/api/src/common/utils/business-event.util.ts
index f89c84ac8..7252d4e50 100644
--- a/apps/api/src/common/utils/business-event.util.ts
+++ b/apps/api/src/common/utils/business-event.util.ts
@@ -4,6 +4,7 @@
*/
import { HttpException, Logger } from '@nestjs/common'
+import { v4 } from 'uuid'
import { getServiceType } from './app-mode'
import { Context } from '../context/context'
@@ -22,9 +23,50 @@ export type BusinessEventName =
| 'api_key.create'
| 'volume.create'
| 'volume.delete'
+ | 'cloud.box.create'
+ | 'cloud.box.start'
+ | 'cloud.box.resume'
+ | 'cloud.ci.request'
+ | 'cloud.feature.use'
+
+export interface BusinessEventFeature {
+ name: 'ssh' | 'tunnel' | 'ci' | 'custom_image' | 'checkpoint'
+ evidence:
+ | 'authenticated_session'
+ | 'established_connection'
+ | 'successful_request'
+ | 'runner_started'
+ | 'runner_completed'
+ | 'started_image'
+ | 'archive_ready'
+ | 'box_restored'
+ source: 'runner' | 'proxy' | 'api'
+ ciJobCreatedAt?: Date
+}
+
+export interface BusinessEventOperation {
+ id: string
+ requestedAt: Date
+ scope: 'rest_api' | 'proxy_api'
+ result?: 'success' | 'service_error' | 'timeout' | 'user_error' | 'cancelled'
+ durationMs?: number
+ boxId?: string
+}
+
+export interface BusinessEventJobTiming {
+ id: string
+ createdAt?: Date | null
+ startedAt?: Date | null
+ completedAt?: Date | null
+}
export interface BusinessEventBase {
name: BusinessEventName
+ eventId?: string
+ occurredAt?: Date
+ job?: Readonly<BusinessEventJobTiming>
+ operation?: Readonly<BusinessEventOperation>
+ feature?: Readonly<BusinessEventFeature>
// User/box/volume id, or a fresh non-secret UUID for an API-key creation attempt.
correlationId: string
// The organization the event belongs to, so its activity can be counted per
@@ -73,7 +115,7 @@ export function mutationFailureType(error: unknown): string {
*/
export function recordBusinessEvent(event: BusinessEvent): void {
const message = `${event.name} ${event.outcome}`
- const attributes = toLogAttributes(event)
+ const attributes = Object.freeze(toLogAttributes(event))
if (event.outcome === 'exception') {
logger.error(message, attributes)
@@ -96,31 +138,39 @@ export function recordBusinessEvent(event: BusinessEvent): void {
* operation that creates it, so only its success can carry it.
*/
export async function recordOutcomes<T>(
- event: BusinessEventBase,
+ event: Omit<BusinessEventBase, 'eventId' | 'occurredAt' | 'job' | 'operation' | 'feature'>,
op: () => Promise<T>,
classifyError: (error: unknown) => string,
organizationOf?: (result: T) => string | undefined,
): Promise<T> {
- recordBusinessEvent({ ...event, outcome: 'requested' })
+ // Occurrence overrides belong to individual emissions, never a whole lifecycle.
+ const lifecycleEvent = {
+ name: event.name,
+ correlationId: event.correlationId,
+ organizationId: event.organizationId,
+ ctx: event.ctx,
+ }
+ recordBusinessEvent({ ...lifecycleEvent, outcome: 'requested' })
let result: T
try {
result = await op()
} catch (error) {
- recordBusinessEvent({ ...event, outcome: 'exception', exceptionType: classifyError(error) })
+ recordBusinessEvent({ ...lifecycleEvent, outcome: 'exception', exceptionType: classifyError(error) })
throw error
}
const organizationId = organizationOf?.(result) ?? event.organizationId
- recordBusinessEvent({ ...event, outcome: 'success', ...(organizationId ? { organizationId } : {}) })
+ recordBusinessEvent({ ...lifecycleEvent, outcome: 'success', ...(organizationId ? { organizationId } : {}) })
return result
}
function toLogAttributes(event: BusinessEvent): Record<string, string> {
const attributes: Record<string, string> = {
'event.name': event.name,
+ 'event.id': event.eventId ?? v4(),
'event.outcome': event.outcome,
'correlation.id': event.correlationId,
'service.type': getServiceType(),
- 'event.timestamp': new Date().toISOString(),
+ 'event.timestamp': isoTimestamp(event.occurredAt) ?? new Date().toISOString(),
}
if (event.organizationId) {
@@ -143,5 +193,51 @@ function toLogAttributes(event: BusinessEvent): Record<string, string> {
attributes['exception.type'] = event.exceptionType
}
+ if (event.operation) {
+ const operation = event.operation
+ attributes['operation.id'] = operation.id
+ attributes['operation.requested_at'] = operation.requestedAt.toISOString()
+ attributes['operation.scope'] = operation.scope
+ attributes['operation.boundary'] = 'cloud_api_to_started'
+ attributes['traffic.kind'] = 'unknown'
+ if (operation.result) attributes['operation.result'] = operation.result
+ if (operation.boxId) attributes['box.id'] = operation.boxId
+ if (
+ typeof operation.durationMs === 'number' &&
+ Number.isFinite(operation.durationMs) &&
+ operation.durationMs >= 0
+ ) {
+ attributes['operation.duration_ms'] = String(operation.durationMs)
+ }
+ }
+
+ if (event.feature) {
+ attributes['feature.name'] = event.feature.name
+ attributes['feature.evidence'] = event.feature.evidence
+ attributes['feature.source'] = event.feature.source
+ if (event.feature.ciJobCreatedAt) attributes['ci.job_created_at'] = event.feature.ciJobCreatedAt.toISOString()
+ }
+
+ if (event.job) {
+ const job = event.job
+ attributes['job.id'] = job.id
+ for (const [key, date] of [
+ ['job.created_at', job.createdAt],
+ ['job.started_at', job.startedAt],
+ ['job.completed_at', job.completedAt],
+ ] as const) {
+ const timestamp = isoTimestamp(date)
+ if (timestamp) attributes[key] = timestamp
+ }
+ if (job.createdAt instanceof Date && job.completedAt instanceof Date) {
+ const duration = job.completedAt.getTime() - job.createdAt.getTime()
+ if (Number.isFinite(duration) && duration >= 0) attributes['job.duration_ms'] = String(duration)
+ }
+ }
+
return attributes
}
+
+function isoTimestamp(date?: Date | null): string | undefined {
+ return date instanceof Date && Number.isFinite(date.getTime()) ? date.toISOString() : undefined
+}
diff --git a/apps/api/src/common/utils/request-timing.util.ts b/apps/api/src/common/utils/request-timing.util.ts
new file mode 100644
index 000000000..1f2c32987
--- /dev/null
+++ b/apps/api/src/common/utils/request-timing.util.ts
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2026 BoxLite AI
+ * SPDX-License-Identifier: AGPL-3.0
+ */
+
+import { RequestHandler } from 'express'
+
+export interface RequestTiming {
+ requestedAt: Date
+ monotonicStart: number
+}
+
+const REQUEST_TIMING = Symbol('cloud_request_timing')
+type TimedRequest = { [REQUEST_TIMING]?: RequestTiming }
+
+export function requestTiming(request?: object): RequestTiming {
+ return (
+ (request as TimedRequest | undefined)?.[REQUEST_TIMING] ?? {
+ requestedAt: new Date(),
+ monotonicStart: performance.now(),
+ }
+ )
+}
+
+/** Capture ingress before parsing and authentication; this performs no I/O. */
+export const captureRequestTiming: RequestHandler = (request, _response, next) => {
+ const timed = request as TimedRequest
+ timed[REQUEST_TIMING] = requestTiming()
+ next()
+}
diff --git a/apps/api/src/config/configuration.ts b/apps/api/src/config/configuration.ts
index ae8837da3..d353d1675 100644
--- a/apps/api/src/config/configuration.ts
+++ b/apps/api/src/config/configuration.ts
@@ -656,6 +656,11 @@ const configuration = {
apiKey: process.env.POSTHOG_API_KEY,
host: process.env.POSTHOG_HOST,
environment: process.env.POSTHOG_ENVIRONMENT,
+ consentBacklogLimit: requiredCount(
+ process.env.POSTHOG_CONSENT_BACKLOG_LIMIT,
+ 1000,
+ 'POSTHOG_CONSENT_BACKLOG_LIMIT',
+ ),
},
oidc: {
clientId: process.env.OIDC_CLIENT_ID || process.env.OID_CLIENT_ID,
diff --git a/apps/api/src/config/posthog-consent-config.spec.ts b/apps/api/src/config/posthog-consent-config.spec.ts
new file mode 100644
index 000000000..5a4a169f8
--- /dev/null
+++ b/apps/api/src/config/posthog-consent-config.spec.ts
@@ -0,0 +1,23 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+describe('PostHog consent backlog configuration', () => {
+ const key = 'POSTHOG_CONSENT_BACKLOG_LIMIT'
+ const load = (value?: string) => {
+ const env = { ...process.env }
+ if (value === undefined) delete env[key]
+ else env[key] = value
+ jest.replaceProperty(process, 'env', env)
+ let limit: number
+ jest.isolateModules(() => {
+ limit = (require('./configuration') as typeof import('./configuration')).configuration.posthog.consentBacklogLimit
+ })
+ return limit!
+ }
+
+ afterEach(() => jest.restoreAllMocks())
+
+ it('defaults to 1000 when the stage omits the setting', () => expect(load()).toBe(1000))
+ it('reads an explicit stage value', () => expect(load('250')).toBe(250))
+ it.each(['0', '-1', '2.5', '3x', '9007199254740992'])('rejects %s at startup', (value) => {
+ expect(() => load(value)).toThrow(key)
+ })
+})
diff --git a/apps/api/src/interceptors/cloud-api-operation.ts b/apps/api/src/interceptors/cloud-api-operation.ts
new file mode 100644
index 000000000..c192e9bb5
--- /dev/null
+++ b/apps/api/src/interceptors/cloud-api-operation.ts
@@ -0,0 +1,143 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { Logger } from '@nestjs/common'
+import type { Request, Response } from 'express'
+import type { AnalyticsService } from '../analytics/services/analytics.service'
+import { isDelegatedMcpRequest } from '../auth/mcp-delegation'
+import { VOLUME_STORAGE_BACKENDS } from '../box/dto/create-volume.dto'
+import { CustomHeaders } from '../common/constants/header.constants'
+import { AuthContextType, isOrganizationAuthContext } from '../common/interfaces/auth-context.interface'
+import { SystemRole } from '../user/enums/system-role.enum'
+
+// Keys are registered Express route templates. Never construct one from the URL.
+const operations = new Map(
+ Object.entries({
+ 'POST /api/v1/boxes': 'box.create',
+ 'DELETE /api/v1/boxes/:boxId': 'box.delete',
+ 'POST /api/v1/boxes/:boxId/start': 'box.start',
+ 'POST /api/v1/boxes/:boxId/stop': 'box.stop',
+ 'PUT /api/v1/boxes/:boxId/network/inbound': 'network.inbound.update',
+ 'PUT /api/v1/boxes/:boxId/network/outbound': 'network.outbound.update',
+ 'POST /api/v1/boxes/:boxId/exec': 'execution.start',
+ 'POST /api/v1/boxes/:boxId/executions/:execId/signal': 'execution.signal',
+ 'DELETE /api/v1/boxes/:boxId/executions/:execId': 'execution.kill',
+ 'PUT /api/v1/boxes/:boxId/files': 'file.upload',
+ 'GET /api/v1/boxes/:boxId/files': 'file.download',
+ 'POST /api/v1/boxes/:boxId/ssh': 'ssh.configure',
+ 'POST /api/v1/boxes/:boxId/ssh/enable': 'ssh.enable',
+ 'DELETE /api/v1/boxes/:boxId/ssh': 'ssh.disable',
+ 'POST /api/v1/boxes/:boxId/network/tunnel': 'tunnel.prepare',
+ 'DELETE /api/v1/boxes/:boxId/network/tunnel': 'tunnel.revoke',
+ 'POST /api/v1/checkpoints': 'checkpoint.create',
+ 'DELETE /api/v1/checkpoints/:key': 'checkpoint.delete',
+ 'POST /api/v1/images/:name/aliases': 'image.alias.create',
+ 'DELETE /api/v1/images/:name/aliases/:alias': 'image.alias.delete',
+ 'DELETE /api/v1/images/:name': 'image.delete',
+ 'POST /api/images/:idOrRef/aliases': 'image.alias.create',
+ 'DELETE /api/images/:idOrRef/aliases/:alias': 'image.alias.delete',
+ 'DELETE /api/images/:idOrRef': 'image.delete',
+ 'POST /api/v1/images/registries': 'registry.create',
+ 'DELETE /api/v1/images/registries/:id': 'registry.delete',
+ 'POST /api/images/registries': 'registry.create',
+ 'PUT /api/images/registries/:id': 'registry.update',
+ 'DELETE /api/images/registries/:id': 'registry.delete',
+ 'POST /api/v1/volumes': 'volume.create',
+ 'DELETE /api/v1/volumes/:volumeId': 'volume.delete',
+ 'POST /api/volumes': 'volume.create',
+ 'DELETE /api/volumes/:volumeId': 'volume.delete',
+ 'POST /api/v1/domains': 'domain.claim',
+ 'PUT /api/v1/domains/:domain/target': 'domain.bind',
+ 'DELETE /api/v1/domains/:domain/target': 'domain.unbind',
+ 'POST /api/organizations/:organizationId/custom-domains': 'custom_domain.create',
+ 'POST /api/organizations/:organizationId/custom-domains/:id/verify': 'custom_domain.verify',
+ 'POST /api/organizations/:organizationId/custom-domains/:id/prepare': 'custom_domain.prepare',
+ 'POST /api/organizations/:organizationId/custom-domains/:id/advance': 'custom_domain.advance',
+ 'DELETE /api/organizations/:organizationId/custom-domains/:id': 'custom_domain.delete',
+ 'POST /api/v1/ci/connect': 'ci.connect.start',
+ 'POST /api/v1/ci/connect/web': 'ci.connect.start',
+ 'POST /api/v1/ci/connect/:id/complete': 'ci.connect.complete',
+ 'POST /api/v1/ci/connect/:id/select': 'ci.connect.select',
+ 'POST /api/v1/ci/connect/:id/installation': 'ci.connect.installation',
+ 'DELETE /api/v1/ci/connect/:id': 'ci.connect.cancel',
+ 'PATCH /api/v1/ci/connections/:id': 'ci.connection.update',
+ 'DELETE /api/v1/ci/connections/:id': 'ci.connection.delete',
+ 'PATCH /api/v1/ci/settings': 'ci.settings.update',
+ 'POST /api/regions': 'region.create',
+ 'PATCH /api/regions/:id': 'region.update',
+ 'DELETE /api/regions/:id': 'region.delete',
+ 'POST /api/regions/:id/regenerate-proxy-api-key': 'region.key.rotate',
+ 'POST /api/box/:boxIdOrName/recover': 'box.recover',
+ 'POST /api/box/:boxIdOrName/attach-tickets': 'box.attach_ticket.create',
+ 'POST /api/api-keys': 'api_key.create',
+ 'DELETE /api/api-keys/:name': 'api_key.delete',
+ 'PATCH /api/organizations/:organizationId/name': 'org.rename',
+ 'PUT /api/organizations/:organizationId/onboarding': 'onboarding.save',
+ 'POST /api/organizations/:organizationId/quickstart/handoffs': 'quickstart.handoff.create',
+ 'PATCH /api/organizations/:organizationId/quickstart/handoffs/:requestId/copied': 'quickstart.handoff.copy',
+ 'POST /api/organizations/:organizationId/coupon-claims': 'coupon.claim.submit',
+ 'PUT /api/organizations/:organizationId/cancellation-feedback': 'billing.feedback.submit',
+ 'POST /api/webhooks/organizations/:organizationId/app-portal-access': 'webhook.portal.open',
+ }),
+)
+const logger = new Logger('CloudApiOperation')
+
+export function observeCloudApiOperation(
+ request: Request & { user?: AuthContextType },
+ response: Response,
+ analytics: AnalyticsService,
+ startedAt: number,
+): void {
+ const path = request.route?.path
+ if (typeof path !== 'string') return
+ let operation = operations.get(request.method + ' ' + path.replace('/api/v1/:prefix/', '/api/v1/'))
+ if (!operation) return
+ const user = request.user
+ if (!user || user.role !== SystemRole.USER || !isOrganizationAuthContext(user)) return
+ const { userId, organizationId, organizationUser } = user
+ if (
+ !userId ||
+ !organizationId ||
+ organizationUser?.userId !== userId ||
+ organizationUser.organizationId !== organizationId
+ )
+ return
+
+ if (operation === 'box.create' && request.body?.checkpoint_id !== undefined) operation = 'checkpoint.restore'
+ const label = request.get(CustomHeaders.SOURCE.name)
+ const source = isDelegatedMcpRequest(request)
+ ? 'mcp'
+ : label === 'sdk' || label === 'dashboard'
+ ? label
+ : 'unattributed'
+ // Proxied handlers can return before the runner has supplied the HTTP result.
+ const finish = () => {
+ response.off('close', close)
+ const status = response.statusCode
+ if (status < 200 || (status >= 300 && status < 400) || status >= 600) return
+ try {
+ const properties: Record<string, string> = {
+ 'api.operation': operation,
+ 'http.status_class': Math.floor(status / 100) + 'xx',
+ 'client.source': source,
+ }
+ if (operation === 'volume.create') {
+ const { storageBackend = 'standard' } = request.body ?? {}
+ if (VOLUME_STORAGE_BACKENDS.includes(storageBackend)) properties['volume.storage_backend'] = storageBackend
+ }
+ analytics.capture(
+ {
+ event: 'cloud.api.operation',
+ distinctId: userId,
+ groups: { organization: organizationId },
+ timestamp: new Date(startedAt),
+ properties,
+ },
+ { users: [userId], organizations: [organizationId] },
+ )
+ } catch {
+ logger.warn('Cloud API operation capture failed')
+ }
+ }
+ const close = () => response.off('finish', finish)
+ response.once('finish', finish)
+ response.once('close', close)
+}
diff --git a/apps/api/src/interceptors/metrics.interceptor.inbound.spec.ts b/apps/api/src/interceptors/metrics.interceptor.inbound.spec.ts
index 1c9f1114b..6ee1ec7ba 100644
--- a/apps/api/src/interceptors/metrics.interceptor.inbound.spec.ts
+++ b/apps/api/src/interceptors/metrics.interceptor.inbound.spec.ts
@@ -39,6 +39,7 @@ describe('MetricsInterceptor inbound mode', () => {
event: 'api_box_inbound_mode_updated',
properties: expect.objectContaining({ box_id: 'box-1', box_inbound_mode: mode }),
}),
+ { users: ['user-1'], organizations: ['org-1'] },
)
})
})
diff --git a/apps/api/src/interceptors/metrics.interceptor.spec.ts b/apps/api/src/interceptors/metrics.interceptor.spec.ts
index 9c0601d34..4438d4fc0 100644
--- a/apps/api/src/interceptors/metrics.interceptor.spec.ts
+++ b/apps/api/src/interceptors/metrics.interceptor.spec.ts
@@ -4,27 +4,33 @@
*/
const mockCapture = jest.fn()
-const mockGroupIdentify = jest.fn()
-jest.mock('posthog-node', () => ({
- PostHog: jest.fn(() => ({
- capture: mockCapture,
- groupIdentify: mockGroupIdentify,
+jest.mock('../analytics/services/consent-bound-posthog', () => ({
+ ConsentBoundPostHog: jest.fn(() => ({
+ deliver: mockCapture,
shutdown: jest.fn(),
on: jest.fn(),
})),
}))
import type { INestApplication } from '@nestjs/common'
-import { ConflictException } from '@nestjs/common'
+import { ConflictException, ValidationPipe } from '@nestjs/common'
import { Test } from '@nestjs/testing'
import type { AddressInfo } from 'net'
+import { request as httpRequest } from 'node:http'
+import { once } from 'node:events'
import { CombinedAuthGuard } from '../auth/combined-auth.guard'
import { AuthenticatedRateLimitGuard } from '../common/guards/authenticated-rate-limit.guard'
import { TypedConfigService } from '../config/typed-config.service'
+import { VolumeController } from '../box/controllers/volume.controller'
+import { VolumeService } from '../box/services/volume.service'
+import { BoxliteVolumeController } from '../boxlite-rest/boxlite-volume.controller'
+import { BoxliteImageController } from '../boxlite-rest/boxlite-image.controller'
import { ImageController } from '../image/controllers/image.controller'
import { ImageCatalogService } from '../image/services/image-catalog.service'
import { OrganizationResourceActionGuard } from '../organization/guards/organization-resource-action.guard'
import { MetricsInterceptor } from './metrics.interceptor'
+import { AnalyticsConsentService } from '../analytics/services/analytics-consent.service'
+import { grantedAnalyticsConsent } from '../../test/granted-analytics-consent'
import { AnalyticsService } from '../analytics/services/analytics.service'
import { AuthGuard } from '@nestjs/passport'
import { of, lastValueFrom } from 'rxjs'
@@ -39,6 +45,7 @@ import { OrGuard } from '../auth/or.guard'
import { UserService } from '../user/user.service'
const ORGANIZATION = { id: 'org-123', imageCountLimit: 20 }
+const volume = { id: 'volume-1', createdAt: new Date(1), updatedAt: new Date(1) }
const CONFIG: Record<string, string> = {
version: '0.0.0-test',
'posthog.apiKey': 'phc_test',
@@ -54,19 +61,26 @@ const CONFIG: Record<string, string> = {
*/
describe('MetricsInterceptor', () => {
let app: INestApplication
- let catalog: { delete: jest.Mock }
+ let catalog: { delete: jest.Mock; deleteAlias: jest.Mock }
beforeEach(async () => {
mockCapture.mockReset()
- mockGroupIdentify.mockReset()
- catalog = { delete: jest.fn().mockResolvedValue(undefined) }
+ catalog = { delete: jest.fn().mockResolvedValue(undefined), deleteAlias: jest.fn().mockResolvedValue(undefined) }
const moduleRef = await Test.createTestingModule({
- controllers: [ImageController, OrganizationController],
+ controllers: [
+ ImageController,
+ OrganizationController,
+ BoxliteImageController,
+ VolumeController,
+ BoxliteVolumeController,
+ ],
providers: [
AnalyticsService,
+ { provide: AnalyticsConsentService, useValue: grantedAnalyticsConsent },
{ provide: TypedConfigService, useValue: { get: (key: string) => CONFIG[key] } },
{ provide: ImageCatalogService, useValue: catalog },
+ { provide: VolumeService, useValue: { create: async () => volume, waitForReady: async () => volume } },
{
provide: OrganizationService,
useValue: {
@@ -89,7 +103,12 @@ describe('MetricsInterceptor', () => {
.overrideGuard(CombinedAuthGuard)
.useValue({
canActivate: (context: any) => {
- context.switchToHttp().getRequest().user = {
+ const req = context.switchToHttp().getRequest()
+ req.user = {
+ role: 'user',
+ organizationUser: req.get('x-test-member')
+ ? { userId: 'user-1', organizationId: ORGANIZATION.id }
+ : undefined,
userId: 'user-1',
organizationId: ORGANIZATION.id,
organization: ORGANIZATION,
@@ -123,6 +142,7 @@ describe('MetricsInterceptor', () => {
app = moduleRef.createNestApplication()
app.setGlobalPrefix('api')
+ app.useGlobalPipes(new ValidationPipe({ transform: true }))
app.useGlobalInterceptors(new MetricsInterceptor(configService, moduleRef.get(AnalyticsService)))
await app.listen(0)
})
@@ -131,6 +151,112 @@ describe('MetricsInterceptor', () => {
await app?.close()
})
+ it.each(['/api/images', '/api/v1/images', '/api/v1/default/images'])(
+ 'tracks removal of an alias through %s with only bounded properties',
+ async (base) => {
+ const address = app.getHttpServer().address() as AddressInfo
+ const response = await fetch(`http://127.0.0.1:${address.port}${base}/private-image/aliases/private-tag`, {
+ method: 'DELETE',
+ headers: { 'x-test-member': '1', 'x-boxlite-source': 'sdk' },
+ })
+ expect(response.status).toBe(204)
+ expect(catalog.deleteAlias).toHaveBeenCalledWith(ORGANIZATION, 'private-image', 'private-tag')
+ expect(mockCapture).toHaveBeenCalledTimes(1)
+ expect(mockCapture.mock.calls[0][0].properties).toEqual({
+ 'api.operation': 'image.alias.delete',
+ environment: 'test',
+ 'client.source': 'sdk',
+ 'http.status_class': '2xx',
+ })
+ },
+ )
+
+ it.each([
+ ['/api/volumes', { name: 'workspace' }, 200, 'standard'],
+ ['/api/v1/volumes', { storageBackend: 'standard' }, 201, 'standard'],
+ ['/api/v1/default/volumes', { storageBackend: 'performance', instance: 'private-instance' }, 201, 'performance'],
+ ['/api/volumes', { name: '/invalid', storageBackend: 'performance' }, 400, 'performance'],
+ ['/api/volumes', { storageBackend: 'private-value' }, 400, undefined],
+ ['/api/volumes', { storageBackend: null }, 400, undefined],
+ ] as const)('records only the requested volume class for POST %s %j', async (path, body, status, backend) => {
+ const address = app.getHttpServer().address() as AddressInfo
+ const response = await fetch(`http://127.0.0.1:${address.port}${path}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-test-member': '1' },
+ body: JSON.stringify(body),
+ })
+ expect(response.status).toBe(status)
+ const events = mockCapture.mock.calls
+ .map(([event]) => event)
+ .filter((event) => event.event === 'cloud.api.operation')
+ expect(events.map((event) => event.properties)).toEqual([
+ {
+ 'api.operation': 'volume.create',
+ environment: 'test',
+ 'client.source': 'unattributed',
+ 'http.status_class': status < 400 ? '2xx' : '4xx',
+ ...(backend && { 'volume.storage_backend': backend }),
+ },
+ ])
+ })
+
+ it('returns the alias response while its PostHog transfer is pending', async () => {
+ let finish!: () => void
+ const pending = new Promise<void>((resolve) => {
+ finish = resolve
+ })
+ mockCapture.mockImplementationOnce(() => pending)
+ try {
+ const address = app.getHttpServer().address() as AddressInfo
+ const response = await fetch(`http://127.0.0.1:${address.port}/api/images/ref/aliases/tag`, {
+ method: 'DELETE',
+ headers: { 'x-test-member': '1' },
+ })
+ expect(response.status).toBe(204)
+ expect(mockCapture).toHaveBeenCalledTimes(1)
+ } finally {
+ finish()
+ }
+ })
+
+ it('drops an interrupted response even when the alias operation later succeeds', async () => {
+ let admitted!: () => void
+ let complete!: () => void
+ const entered = new Promise<void>((resolve) => {
+ admitted = resolve
+ })
+ const pending = new Promise<void>((resolve) => {
+ complete = resolve
+ })
+ catalog.deleteAlias.mockImplementationOnce(() => {
+ admitted()
+ return pending
+ })
+ const server = app.getHttpServer()
+ const incoming = once(server, 'request')
+ const req = httpRequest({
+ port: (server.address() as AddressInfo).port,
+ hostname: '127.0.0.1',
+ path: '/api/images/ref/aliases/tag',
+ method: 'DELETE',
+ headers: { 'x-test-member': '1' },
+ })
+ req.on('error', () => {}) // Destroying the client connection reports ECONNRESET.
+ req.end()
+ const [, response] = await incoming
+ const closed = once(response, 'close')
+ try {
+ await entered
+ req.destroy()
+ await closed
+ } finally {
+ complete()
+ }
+ // Drain the handler microtasks before observing analytics.
+ await new Promise<void>((resolve) => setImmediate(resolve))
+ expect(mockCapture).not.toHaveBeenCalled()
+ })
+
const deleteImage = async (encodedRef: string): Promise<Response> => {
const address = app.getHttpServer().address() as AddressInfo
return fetch(`http://127.0.0.1:${address.port}/api/images/${encodedRef}`, { method: 'DELETE' })
@@ -141,14 +267,17 @@ describe('MetricsInterceptor', () => {
const response = await fetch(`http://127.0.0.1:${address.port}/api/organizations`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ name: 'Example' }),
+ body: JSON.stringify({ name: 'Example', defaultRegionId: 'us' }),
})
expect(response.status).toBe(201)
- expect(mockGroupIdentify).toHaveBeenCalledWith(
+ expect(mockCapture).toHaveBeenCalledWith(
expect.objectContaining({
- groupType: 'organization',
- groupKey: 'new-org',
- properties: expect.objectContaining({ name: 'Example', environment: 'test' }),
+ event: '$groupidentify',
+ properties: expect.objectContaining({
+ $group_type: 'organization',
+ $group_key: 'new-org',
+ $group_set: expect.objectContaining({ name: 'Example', environment: 'test' }),
+ }),
}),
)
expect(mockCapture).toHaveBeenCalledWith(expect.objectContaining({ event: 'api_organization_created' }))
@@ -159,7 +288,7 @@ describe('MetricsInterceptor', () => {
get: (key: string) => (key === missing ? undefined : CONFIG[key]),
getOrThrow: (key: string) => CONFIG[key],
}
- const disabled = new AnalyticsService(config as never)
+ const disabled = new AnalyticsService(config as never, grantedAnalyticsConsent)
const interceptor = new MetricsInterceptor(config as never, disabled)
const next = { handle: jest.fn(() => of('response')) }
const context = {
@@ -169,12 +298,11 @@ describe('MetricsInterceptor', () => {
}
expect(disabled.enabled).toBe(false)
await expect(lastValueFrom(interceptor.intercept(context as never, next))).resolves.toBe('response')
- disabled.capture({ event: 'ignored', distinctId: 'user-1' })
+ disabled.capture({ event: 'ignored', distinctId: 'user-1' }, { users: ['user-1'], organizations: [] })
disabled.groupIdentify({ groupType: 'organization', groupKey: 'ignored' })
await disabled.handleOrganizationCreatedEvent({ id: 'ignored' } as never)
await disabled.onApplicationShutdown()
expect(mockCapture).not.toHaveBeenCalled()
- expect(mockGroupIdentify).not.toHaveBeenCalled()
})
it('captures a removed image under the reference the caller named', async () => {
@@ -200,13 +328,13 @@ describe('MetricsInterceptor', () => {
const response = await deleteImage('quay.io%2Facme%2Fapp')
expect(response.status).toBe(409)
+ expect(JSON.stringify(mockCapture.mock.calls)).not.toContain('still in use by box-1')
expect(mockCapture).toHaveBeenCalledWith(
expect.objectContaining({
event: 'api_image_deletion_failed',
properties: expect.objectContaining({
image_id_or_ref: 'quay.io/acme/app',
status_code: 409,
- error: 'still in use by box-1',
}),
}),
)
diff --git a/apps/api/src/interceptors/metrics.interceptor.ts b/apps/api/src/interceptors/metrics.interceptor.ts
index 2bf6a20e9..8a875d7f2 100644
--- a/apps/api/src/interceptors/metrics.interceptor.ts
+++ b/apps/api/src/interceptors/metrics.interceptor.ts
@@ -6,6 +6,7 @@
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, Logger } from '@nestjs/common'
import { Observable } from 'rxjs'
+import { observeCloudApiOperation } from './cloud-api-operation'
import { tap } from 'rxjs/operators'
import { AnalyticsService } from '../analytics/services/analytics.service'
import { Request } from 'express'
@@ -37,7 +38,6 @@ type CommonCaptureProps = {
error?: string
source: string
sdkVersion?: string
- environment?: string
}
@Injectable()
@@ -59,6 +59,7 @@ export class MetricsInterceptor implements NestInterceptor {
const request = context.switchToHttp().getRequest()
const startTime = Date.now()
+ observeCloudApiOperation(request, context.switchToHttp().getResponse(), this.analytics, startTime)
return next.handle().pipe(
tap({
@@ -96,7 +97,6 @@ export class MetricsInterceptor implements NestInterceptor {
error,
source: Array.isArray(source) ? source[0] : source,
sdkVersion,
- environment: this.configService.get('posthog.environment'),
}
switch (request.method) {
@@ -122,10 +122,11 @@ export class MetricsInterceptor implements NestInterceptor {
)
break
case '/api/organizations/invitations/:invitationId/accept':
- this.captureAcceptInvitation(props, request.params.invitationId)
- break
- case '/api/organizations/invitations/:invitationId/decline':
- this.captureDeclineInvitation(props, request.params.invitationId)
+ if (response.organizationId)
+ this.captureAcceptInvitation(
+ { ...props, organizationId: response.organizationId },
+ request.params.invitationId,
+ )
break
case '/api/organizations':
this.captureCreateOrganization(props, request.body, response)
@@ -270,28 +271,24 @@ export class MetricsInterceptor implements NestInterceptor {
})
}
- private captureDeclineInvitation(props: CommonCaptureProps, invitationId: string) {
- this.capture('api_invitation_declined', props, 'api_invitation_decline_failed', {
- invitation_id: invitationId,
- })
- }
-
private captureCreateOrganization(
props: CommonCaptureProps,
request: CreateOrganizationDto,
response: OrganizationDto,
) {
- this.analytics.groupIdentify({
- groupType: 'organization',
- groupKey: response.id,
- properties: {
- name: request.name,
- created_at: response.createdAt,
- created_by: response.createdBy,
- is_default_for_authenticated_user: response.isDefaultForAuthenticatedUser,
- environment: this.configService.get('posthog.environment'),
+ this.analytics.groupIdentify(
+ {
+ groupType: 'organization',
+ groupKey: response.id,
+ properties: {
+ name: request.name,
+ created_at: response.createdAt,
+ is_default_for_authenticated_user: response.isDefaultForAuthenticatedUser,
+ environment: this.configService.get('posthog.environment'),
+ },
},
- })
+ props.distinctId === 'anonymous' ? [] : [props.distinctId],
+ )
this.capture('api_organization_created', props, 'api_organization_creation_failed', {
organization_id: response.id,
@@ -386,7 +383,6 @@ export class MetricsInterceptor implements NestInterceptor {
) {
this.capture('api_organization_invitation_created', props, 'api_organization_invitation_creation_failed', {
organization_id: organizationId,
- organization_invitation_email: request.email,
organization_invitation_role: request.role,
organization_invitation_assigned_role_ids: request.assignedRoleIds,
organization_invitation_expires_at: request.expiresAt,
@@ -428,8 +424,6 @@ export class MetricsInterceptor implements NestInterceptor {
})
}
- // Delete is the catalog's only mutation — an image enters it by being used,
- // not by being created — so it is the only event there is to capture.
private captureDeleteImage(props: CommonCaptureProps, idOrRef: string) {
this.capture('api_image_deleted', props, 'api_image_deletion_failed', {
image_id_or_ref: idOrRef,
@@ -452,12 +446,20 @@ export class MetricsInterceptor implements NestInterceptor {
}
private capture(event: string, props: CommonCaptureProps, errorEvent?: string, extraProps?: Record<string, any>) {
- this.analytics.capture({
- distinctId: props.distinctId,
- event: props.error ? errorEvent || event : event,
- groups: this.captureCommonGroups(props),
- properties: { ...this.captureCommonProperties(props), ...extraProps },
- })
+ if (props.distinctId === 'anonymous') return
+ const users = [props.distinctId]
+ if (extraProps?.organization_user_id) users.push(extraProps.organization_user_id)
+ const organizations = [props.organizationId, extraProps?.organization_id].filter((id): id is string => !!id)
+ if (!organizations.length) return
+ this.analytics.capture(
+ {
+ distinctId: props.distinctId,
+ event: props.error ? errorEvent || event : event,
+ groups: this.captureCommonGroups(props),
+ properties: { ...this.captureCommonProperties(props), ...extraProps },
+ },
+ { users, organizations },
+ )
}
private captureCommonProperties(props: CommonCaptureProps) {
@@ -465,10 +467,8 @@ export class MetricsInterceptor implements NestInterceptor {
duration_ms: props.durationMs,
status_code: props.statusCode,
user_agent: props.userAgent,
- error: props.error,
source: props.source,
sdk_version: props.sdkVersion,
- environment: props.environment,
boxlite_version: this.version,
}
}
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index 4a1d16308..0e0f498ab 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -46,6 +46,7 @@ import { CiListenerService } from './ci/ci-listener.service'
import { RequestReplayInterceptor } from './boxlite-rest/request-replay.interceptor'
import { RequestReplayPolicy } from './boxlite-rest/request-replay-policy'
import { ReplayValidationPipe } from './common/replay-validation.pipe'
+import { captureRequestTiming } from './common/utils/request-timing.util'
// https options
const httpsEnabled = process.env.CERT_PATH && process.env.CERT_KEY_PATH
@@ -65,6 +66,7 @@ async function bootstrap() {
// after authentication.
bodyParser: false,
})
+ app.use(captureRequestTiming)
installCiWebhookBodyParser(app)
app.useLogger(app.get(PinoLogger))
app.flushLogs()
diff --git a/apps/api/src/migrations/pre-deploy/1795420800000-product-analytics-consent-migration.ts b/apps/api/src/migrations/pre-deploy/1795420800000-product-analytics-consent-migration.ts
new file mode 100644
index 000000000..03a133c4c
--- /dev/null
+++ b/apps/api/src/migrations/pre-deploy/1795420800000-product-analytics-consent-migration.ts
@@ -0,0 +1,16 @@
+import { MigrationInterface, QueryRunner } from 'typeorm'
+
+export class ProductAnalyticsConsent1795420800000 implements MigrationInterface {
+ async up(runner: QueryRunner): Promise<void> {
+ await runner.query(`CREATE TABLE product_analytics_consent (
+ user_id varchar PRIMARY KEY REFERENCES "user"(id) ON DELETE CASCADE,
+ allowed boolean NOT NULL,
+ notice_version integer NOT NULL,
+ decided_at timestamptz NOT NULL DEFAULT clock_timestamp()
+ )`)
+ }
+
+ async down(runner: QueryRunner): Promise<void> {
+ await runner.query('DROP TABLE product_analytics_consent')
+ }
+}
diff --git a/apps/api/src/migrations/pre-deploy/1795996800000-add-signup-claim-migration.ts b/apps/api/src/migrations/pre-deploy/1795996800000-add-signup-claim-migration.ts
new file mode 100644
index 000000000..3eac81c66
--- /dev/null
+++ b/apps/api/src/migrations/pre-deploy/1795996800000-add-signup-claim-migration.ts
@@ -0,0 +1,11 @@
+import { MigrationInterface, QueryRunner } from 'typeorm'
+
+export class AddSignupClaim1795996800000 implements MigrationInterface {
+ async up(runner: QueryRunner): Promise<void> {
+ await runner.query('ALTER TABLE product_analytics_consent ADD COLUMN signup_claimed boolean NOT NULL DEFAULT false')
+ }
+
+ async down(runner: QueryRunner): Promise<void> {
+ await runner.query('ALTER TABLE product_analytics_consent DROP COLUMN signup_claimed')
+ }
+}
diff --git a/apps/api/src/notification/services/notification.service.ts b/apps/api/src/notification/services/notification.service.ts
index 3896760ad..47f7feab7 100644
--- a/apps/api/src/notification/services/notification.service.ts
+++ b/apps/api/src/notification/services/notification.service.ts
@@ -49,16 +49,23 @@ export class NotificationService {
@OnEvent(BoxEvents.STATE_UPDATED)
async handleBoxStateUpdated(event: BoxStateUpdatedEvent) {
+ this.publishBoxTransition(event)
const dto = await this.boxService.toBoxDto(event.box)
this.notificationEmitter.emitBoxStateUpdated(dto, event.oldState, event.newState)
- this.redis.publish(BOX_EVENT_CHANNEL, JSON.stringify(event))
}
@OnEvent(BoxEvents.DESIRED_STATE_UPDATED)
async handleBoxDesiredStateUpdated(event: BoxDesiredStateUpdatedEvent) {
+ this.publishBoxTransition(event)
const dto = await this.boxService.toBoxDto(event.box)
this.notificationEmitter.emitBoxDesiredStateUpdated(dto, event.oldDesiredState, event.newDesiredState)
- this.redis.publish(BOX_EVENT_CHANNEL, JSON.stringify(event))
+ }
+
+ private publishBoxTransition(event: BoxStateUpdatedEvent | BoxDesiredStateUpdatedEvent): void {
+ // Readiness waiters need the state as soon as it is observed, before dashboard metadata is loaded.
+ void this.redis.publish(BOX_EVENT_CHANNEL, JSON.stringify(event)).catch((error) => {
+ this.logger.error('Failed to publish box state for readiness waiters', error)
+ })
}
@OnEvent(VolumeEvents.CREATED)
diff --git a/apps/api/src/user/linked-identity.service.integration.spec.ts b/apps/api/src/user/linked-identity.service.integration.spec.ts
index 23acdfe46..3cf85e655 100644
--- a/apps/api/src/user/linked-identity.service.integration.spec.ts
+++ b/apps/api/src/user/linked-identity.service.integration.spec.ts
@@ -4,8 +4,14 @@
*/
import { randomUUID } from 'node:crypto'
-import type Redis from 'ioredis'
+import { setTimeout as delay } from 'node:timers/promises'
+import { AnalyticsConsentService } from '../analytics/services/analytics-consent.service'
+import { ProductAnalyticsConsent1795420800000 } from '../migrations/pre-deploy/1795420800000-product-analytics-consent-migration'
+import Redis from 'ioredis'
import { DataSource } from 'typeorm'
+import { ConfigService } from '@nestjs/config'
+import { configuration } from '../config/configuration'
+import { TypedConfigService } from '../config/typed-config.service'
import { ApiKey } from '../api-key/api-key.entity'
import { apiKeyValidationCacheKey } from '../common/utils/api-key'
import { CustomNamingStrategy } from '../common/utils/naming-strategy.util'
@@ -44,7 +50,7 @@ describeIfDatabase('LinkedIdentityService.adopt (integration, real Postgres)', (
entities: [User, Organization, OrganizationInvitation, OrganizationRole, OrganizationUser, ApiKey],
namingStrategy: new CustomNamingStrategy(),
synchronize: false,
- extra: { options: `-c search_path=${schemaName},public` },
+ extra: { options: `-c search_path=${schemaName},public`, application_name: schemaName },
}).initialize()
await dataSource.query(`CREATE SCHEMA "${schemaName}"`)
await dataSource.synchronize()
@@ -136,6 +142,43 @@ describeIfDatabase('LinkedIdentityService.adopt (integration, real Postgres)', (
return rows.map((row) => row.roleId)
}
+ it('rechecks the new creator after moving an organization with cached analytics consent', async () => {
+ await user(PRIMARY)
+ await user(SOCIAL)
+ const org = await organization(SOCIAL, 'Example')
+ const client = new Redis({
+ host: process.env.REDIS_HOST ?? '127.0.0.1',
+ port: Number(process.env.REDIS_PORT ?? 6379),
+ keyPrefix: schemaName + ':',
+ lazyConnect: true,
+ maxRetriesPerRequest: 0,
+ commandTimeout: 1000,
+ })
+ const runner = dataSource.createQueryRunner()
+ const migration = new ProductAnalyticsConsent1795420800000()
+ try {
+ await client.connect()
+ await migration.up(runner)
+ const consent = new AnalyticsConsentService(
+ dataSource,
+ client,
+ new TypedConfigService(new ConfigService(configuration)),
+ )
+ await consent.decide(SOCIAL, true)
+ await delay(3)
+ const subjects = { users: [], organizations: [org] }
+ const send = jest.fn(async () => {})
+ expect(await consent.dispatch(subjects, new Date(), send)).toBe(true)
+ await new LinkedIdentityService(dataSource, client).adopt(PRIMARY, SOCIAL)
+ expect(await consent.dispatch(subjects, new Date(), send)).toBe(false)
+ expect(send).toHaveBeenCalledTimes(1)
+ } finally {
+ client.disconnect()
+ await migration.down(runner)
+ await runner.release()
+ }
+ })
+
it('does nothing for a social identity BoxLite never saw', async () => {
await user(PRIMARY)
diff --git a/apps/api/src/user/linked-identity.service.ts b/apps/api/src/user/linked-identity.service.ts
index d0863fbc8..76a5deaea 100644
--- a/apps/api/src/user/linked-identity.service.ts
+++ b/apps/api/src/user/linked-identity.service.ts
@@ -3,6 +3,7 @@
* SPDX-License-Identifier: AGPL-3.0
*/
+import { analyticsConsentCacheKey } from '../analytics/services/analytics-consent.service'
import { Injectable, Logger } from '@nestjs/common'
import { InjectRedis } from '@nestjs-modules/ioredis'
import Redis from 'ioredis'
@@ -53,7 +54,7 @@ export class LinkedIdentityService {
throw new Error(`cannot link ${primaryUserId} to itself`)
}
- const movedKeyHashes = await this.dataSource.transaction(async (em) => {
+ const movedCacheKeys = await this.dataSource.transaction(async (em) => {
// Serialise concurrent adoptions of one secondary, so two links
// racing over the same identity cannot both copy its memberships.
const secondary = await em
@@ -68,17 +69,20 @@ export class LinkedIdentityService {
await this.ensurePrimaryUser(em, primaryUserId, secondary)
const moved = await this.moveMemberships(em, primaryUserId, secondaryUserId)
const keyHashes = await this.moveApiKeys(em, primaryUserId, secondaryUserId)
- await em.query(`UPDATE "organization" SET "createdBy" = $1 WHERE "createdBy" = $2`, [
- primaryUserId,
- secondaryUserId,
- ])
+ const [organizations]: [{ id: string }[], number] = await em.query(
+ 'UPDATE organization SET "createdBy" = $1 WHERE "createdBy" = $2 RETURNING id',
+ [primaryUserId, secondaryUserId],
+ )
this.logger.log(
`Moved ${moved} membership(s) and ${keyHashes.length} API key(s) from ${secondaryUserId} to ${primaryUserId}`,
)
- return keyHashes
+ return [
+ ...keyHashes.map(apiKeyValidationCacheKey),
+ ...organizations.map(({ id }) => analyticsConsentCacheKey('creator', id)),
+ ]
})
- await this.forgetCachedOwners(movedKeyHashes)
+ await this.forgetCachedOwners(movedCacheKeys)
}
/**
@@ -88,15 +92,15 @@ export class LinkedIdentityService {
* commits: any earlier, a request could read the old owner from the
* database and cache it again.
*/
- private async forgetCachedOwners(keyHashes: string[]): Promise<void> {
- if (keyHashes.length === 0) {
+ private async forgetCachedOwners(keys: string[]): Promise<void> {
+ if (keys.length === 0) {
return
}
try {
- await this.redis.del(...keyHashes.map(apiKeyValidationCacheKey))
+ await this.redis.del(...keys)
} catch (error) {
// The entries expire on their own; the move has committed and stands.
- this.logger.error('Could not drop moved API keys from the validation cache:', error)
+ this.logger.error('Could not drop cached owners after account link:', error)
}
}
diff --git a/apps/api/test/granted-analytics-consent.ts b/apps/api/test/granted-analytics-consent.ts
new file mode 100644
index 000000000..95184ea22
--- /dev/null
+++ b/apps/api/test/granted-analytics-consent.ts
@@ -0,0 +1,9 @@
+import type { AnalyticsConsentService, AnalyticsSubjects } from '../src/analytics/services/analytics-consent.service'
+
+/** Existing transport tests exercise eligible events. Database authorization is covered separately. */
+export const grantedAnalyticsConsent = {
+ async dispatch(_subjects: AnalyticsSubjects, _at: Date, send: () => Promise<void>) {
+ await send()
+ return true
+ },
+} as AnalyticsConsentService
diff --git a/apps/dashboard/README.md b/apps/dashboard/README.md
index ed175acd3..481e98b2a 100644
--- a/apps/dashboard/README.md
+++ b/apps/dashboard/README.md
@@ -111,6 +111,18 @@ background refresh; decisions are scoped to identity and organization. Local dis
still uses the existing policy. Cross-browser completion remains a separate server
contract and is not inferred from a saved use case.
+### Product analytics preferences
+
+Registration offers Terms of Service and Privacy Policy links. On first entering the Console, a person can allow product analytics, choose **No thanks**, or continue without answering. Collection starts after an explicit grant. Earlier visits and interactions are discarded. An existing refusal suppresses the card on future visits.
+
+Open **Org → Management → Settings → Privacy Preferences** at `/dashboard/settings?tab=settings` to change **Product analytics**. Each choice covers the signed-in account and organizations it created. A member’s interaction also requires the organization creator’s grant. The Console submits route templates and recognized control actions to the Cloud API. Raw URLs, referral parameters, terminal contents and control text are excluded. Functional feature flags remain available for every choice.
+
+Console analytics sends up to two requests at once and holds up to 16 additional events in memory during rapid interaction. Each queued event keeps its original page and occurrence time. A full queue drops new events. A consent change, an account or organization switch, or leaving the Console clears unsent events.
+
+The Dashboard uses the last confirmed consent while a preference is saving. If the save fails, Settings shows an error and offers a retry. Once the API confirms a withdrawal, collection stops across the account’s organizations in the Console.
+
+See the [first-visit card](review-assets/product-analytics/first-console-visit.png) and [Settings switch](review-assets/product-analytics/settings.png).
+
## Managed checkpoints
**Boxes → Checkpoints** lists reusable disk archives captured from eligible stopped Boxes.
diff --git a/apps/dashboard/project.json b/apps/dashboard/project.json
index b86bdc53b..9c61ca4ea 100644
--- a/apps/dashboard/project.json
+++ b/apps/dashboard/project.json
@@ -3,6 +3,7 @@
"$schema": "../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "dashboard/src",
"projectType": "application",
+ "implicitDependencies": ["shared-contracts"],
"tags": [],
"targets": {
"build": {
diff --git a/apps/dashboard/review-assets/product-analytics/before.png b/apps/dashboard/review-assets/product-analytics/before.png
new file mode 100644
index 000000000..d2cb4f9d7
Binary files /dev/null and b/apps/dashboard/review-assets/product-analytics/before.png differ
diff --git a/apps/dashboard/review-assets/product-analytics/first-console-visit.png b/apps/dashboard/review-assets/product-analytics/first-console-visit.png
new file mode 100644
index 000000000..4a4e3a207
Binary files /dev/null and b/apps/dashboard/review-assets/product-analytics/first-console-visit.png differ
diff --git a/apps/dashboard/review-assets/product-analytics/settings.png b/apps/dashboard/review-assets/product-analytics/settings.png
new file mode 100644
index 000000000..f36de9291
Binary files /dev/null and b/apps/dashboard/review-assets/product-analytics/settings.png differ
diff --git a/apps/dashboard/src/App.test.tsx b/apps/dashboard/src/App.test.tsx
index 249690d43..5bd4fb88e 100644
--- a/apps/dashboard/src/App.test.tsx
+++ b/apps/dashboard/src/App.test.tsx
@@ -149,6 +149,16 @@ describe('App routes', () => {
expect(await renderAt('/dashboard/roles')).toBe('boxes page at /dashboard/boxes')
})
+ it('opens the privacy settings through the organization Settings tab', async () => {
+ expect(await renderAt('/dashboard/settings?tab=settings')).toBe(
+ 'organization page at /dashboard/settings?tab=settings',
+ )
+ })
+
+ it('treats the retired account settings path as unknown', async () => {
+ expect(await renderAt('/dashboard/user/account-settings')).toBe('not found page')
+ })
+
it('redirects the legacy members route to the Organization Member tab', async () => {
expect(await renderAt('/dashboard/members')).toBe('organization page at /dashboard/settings?tab=member')
})
diff --git a/apps/dashboard/src/App.tsx b/apps/dashboard/src/App.tsx
index f1381f32c..0677b60eb 100644
--- a/apps/dashboard/src/App.tsx
+++ b/apps/dashboard/src/App.tsx
@@ -94,10 +94,7 @@ function App() {
useEffect(() => {
if (isAuthenticated && user && posthog?.get_distinct_id() !== user.profile.sub) {
- posthog?.identify(user.profile.sub, {
- email: user.profile.email,
- name: user.profile.name,
- })
+ posthog?.identify(user.profile.sub)
}
if (import.meta.env.PROD && config.pylonAppId && isAuthenticated && user) {
initPylon(config.pylonAppId, {
@@ -112,15 +109,6 @@ function App() {
}
}, [isAuthenticated, user, posthog, config.pylonAppId])
- // Hack for tracking PostHog pageviews in SPAs
- useEffect(() => {
- if (import.meta.env.PROD) {
- posthog?.capture('$pageview', {
- $current_url: window.location.href,
- })
- }
- }, [location, posthog])
-
if (authError && location.pathname !== RoutePath.LOGOUT) return <LandingPage />
return (
@@ -141,10 +129,6 @@ function App() {
<Route path={RoutePath.REDEEM} element={<Redeem />} />
<Route path={RoutePath.DOCS} element={<DocsRedirect />} />
<Route path={RoutePath.SLACK} element={<SlackRedirect />} />
- <Route
- path={RoutePath.ACCOUNT_SETTINGS}
- element={<Navigate to={`${RoutePath.BOXES}${location.search}`} replace />}
- />
<Route
path={RoutePath.DASHBOARD}
element={
diff --git a/apps/dashboard/src/components/Box/CreateBoxDialog.tsx b/apps/dashboard/src/components/Box/CreateBoxDialog.tsx
index c4d0c3288..71177d9d0 100644
--- a/apps/dashboard/src/components/Box/CreateBoxDialog.tsx
+++ b/apps/dashboard/src/components/Box/CreateBoxDialog.tsx
@@ -1239,6 +1239,7 @@ export const CreateBoxDialog = ({
variant="primary"
className="h-11 sm:h-9"
type="button"
+ data-console-action="create_box"
onClick={handleCreate}
disabled={
submitting ||
diff --git a/apps/dashboard/src/components/CheckpointCreateDialog.tsx b/apps/dashboard/src/components/CheckpointCreateDialog.tsx
index 654feb05b..5bedcc6f9 100644
--- a/apps/dashboard/src/components/CheckpointCreateDialog.tsx
+++ b/apps/dashboard/src/components/CheckpointCreateDialog.tsx
@@ -156,7 +156,7 @@ export function CheckpointCreateDialog({ box, onClose }: { box?: Box; onClose: (
<AsciiButton type="button" onClick={onClose} disabled={create.isPending}>
Cancel
</AsciiButton>
- <AsciiButton variant="primary" type="submit" disabled={!canSubmit}>
+ <AsciiButton data-console-action="create_checkpoint" variant="primary" type="submit" disabled={!canSubmit}>
{create.isPending ? 'Creating…' : 'Create Checkpoint'}
</AsciiButton>
</FormDialogFooter>
diff --git a/apps/dashboard/src/components/CiAccountPicker.tsx b/apps/dashboard/src/components/CiAccountPicker.tsx
index 4607f54fe..c7230f01a 100644
--- a/apps/dashboard/src/components/CiAccountPicker.tsx
+++ b/apps/dashboard/src/components/CiAccountPicker.tsx
@@ -124,7 +124,12 @@ export function CiAccountPicker({
Connecting…
</span>
) : (
- <AsciiButton size="sm" disabled={busy !== undefined} onClick={() => void choose(account.account_id)}>
+ <AsciiButton
+ data-console-action="connect_github_account"
+ size="sm"
+ disabled={busy !== undefined}
+ onClick={() => void choose(account.account_id)}
+ >
{account.installed ? (
'Connect'
) : (
diff --git a/apps/dashboard/src/components/CreateApiKeyDialog.tsx b/apps/dashboard/src/components/CreateApiKeyDialog.tsx
index 8f184a302..ab183ef01 100644
--- a/apps/dashboard/src/components/CreateApiKeyDialog.tsx
+++ b/apps/dashboard/src/components/CreateApiKeyDialog.tsx
@@ -45,7 +45,12 @@ export function CreateApiKeyDialog(props: CreateApiKeyDialogProps) {
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
- <AsciiButton variant="primary" title="New API key" className={props.className}>
+ <AsciiButton
+ data-console-action="new_api_key"
+ variant="primary"
+ title="New API key"
+ className={props.className}
+ >
<Plus className="size-4" />
New API key
</AsciiButton>
@@ -476,7 +481,13 @@ function ApiKeyForm({
{result ? 'Done' : 'Close'}
</AsciiButton>
{!result && (
- <AsciiButton variant="primary" type="submit" form="create-api-key-form" disabled={!canSubmit}>
+ <AsciiButton
+ data-console-action="create_api_key"
+ variant="primary"
+ type="submit"
+ form="create-api-key-form"
+ disabled={!canSubmit}
+ >
{submitting ? 'Creating…' : 'Create API key'}
</AsciiButton>
)}
diff --git a/apps/dashboard/src/components/PostHogProviderWrapper.tsx b/apps/dashboard/src/components/PostHogProviderWrapper.tsx
index 9f75f1bed..87cd68da3 100644
--- a/apps/dashboard/src/components/PostHogProviderWrapper.tsx
+++ b/apps/dashboard/src/components/PostHogProviderWrapper.tsx
@@ -5,33 +5,13 @@
*/
import { useConfig } from '@/hooks/useConfig'
-import { usePrivacyConsentStore } from '@/hooks/usePrivacyConsent'
-import { usePostHog } from 'posthog-js/react'
import { PostHogProvider } from 'posthog-js/react'
-import { FC, ReactNode, useEffect } from 'react'
+import { FC, ReactNode } from 'react'
interface PostHogProviderWrapperProps {
children: ReactNode
}
-function PostHogConsentSync() {
- const posthog = usePostHog()
- const analytics = usePrivacyConsentStore((state) => state.preferences.analytics)
- const hasConsented = usePrivacyConsentStore((state) => state.hasConsented)
-
- useEffect(() => {
- if (!posthog || !hasConsented) return
-
- if (analytics) {
- posthog.opt_in_capturing()
- } else {
- posthog.opt_out_capturing()
- }
- }, [posthog, analytics, hasConsented])
-
- return null
-}
-
export const PostHogProviderWrapper: FC<PostHogProviderWrapperProps> = ({ children }) => {
const config = useConfig()
@@ -49,16 +29,23 @@ export const PostHogProviderWrapper: FC<PostHogProviderWrapperProps> = ({ childr
apiKey={config.posthog.apiKey}
options={{
api_host: config.posthog.host,
- opt_out_capturing_by_default: true,
- cookieless_mode: 'on_reject',
- persistence: 'localStorage',
- person_profiles: 'always',
+ persistence: 'memory',
autocapture: false,
capture_pageview: false,
- capture_pageleave: true,
+ capture_pageleave: false,
+ disable_session_recording: true,
+ capture_exceptions: false,
+ capture_performance: false,
+ disable_external_dependency_loading: true,
+ disable_surveys: true,
+ disable_product_tours: true,
+ disable_web_experiments: true,
+ save_referrer: false,
+ store_google: false,
+ // Flag evaluation uses this client. Console events use a separate HTTP sender.
+ before_send: () => null,
}}
>
- <PostHogConsentSync />
{children}
</PostHogProvider>
)
diff --git a/apps/dashboard/src/components/PrivacyPreferencesDialog.tsx b/apps/dashboard/src/components/PrivacyPreferencesDialog.tsx
deleted file mode 100644
index 95ddddcf2..000000000
--- a/apps/dashboard/src/components/PrivacyPreferencesDialog.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright Daytona Platforms Inc.
- * SPDX-License-Identifier: AGPL-3.0
- */
-
-import { ConsentPreferences } from '@/hooks/usePrivacyConsent'
-import { useEffect, useState } from 'react'
-import { Button } from './ui/button'
-import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from './ui/dialog'
-import { ScrollArea } from './ui/scroll-area'
-import { Separator } from './ui/separator'
-import { Switch } from './ui/switch'
-
-type PrivacyPreferencesDialogProps = {
- open: boolean
- onOpenChange: (open: boolean) => void
- preferences: ConsentPreferences
- onSave: (preferences: ConsentPreferences) => void
-}
-
-export function PrivacyPreferencesDialog({ open, onOpenChange, preferences, onSave }: PrivacyPreferencesDialogProps) {
- const [tempPreferences, setTempPreferences] = useState<ConsentPreferences>(preferences)
-
- useEffect(() => {
- if (open) {
- setTempPreferences(preferences)
- }
- }, [open, preferences])
-
- const handleSave = () => {
- onSave(tempPreferences)
- onOpenChange(false)
- }
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-md">
- <DialogHeader>
- <DialogTitle>Privacy Preferences</DialogTitle>
- </DialogHeader>
-
- <DialogDescription>
- Choose which tracking technologies you allow. Essential tracking is always required.
- </DialogDescription>
-
- <ScrollArea fade="mask" className="h-[325px] overflow-auto -mx-5 min-h-0">
- <div className="rounded-md border mx-5">
- <div className="flex items-start justify-between space-x-2 p-3 bg-muted/50">
- <div className="space-y-1">
- <p className="font-medium text-body">Essential</p>
- <p className="text-meta text-muted-foreground">
- Required for login sessions and core functionality. Cannot be disabled.
- </p>
- </div>
- <Switch checked disabled />
- </div>
-
- <Separator />
-
- <div className="flex items-start justify-between space-x-2 p-3">
- <div className="space-y-1">
- <p className="font-medium text-body">Analytics</p>
- <p className="text-meta text-muted-foreground">
- Collects anonymous usage data to help us understand how the product is used and improve it.
- </p>
- </div>
- <Switch
- checked={tempPreferences.analytics}
- onCheckedChange={(checked) => setTempPreferences((prev) => ({ ...prev, analytics: checked }))}
- />
- </div>
-
- <Separator />
-
- <div className="flex items-start justify-between space-x-2 p-3">
- <div className="space-y-1">
- <p className="font-medium text-body">Preferences</p>
- <p className="text-meta text-muted-foreground">
- Remembers your settings like theme and layout across sessions.
- </p>
- </div>
- <Switch
- checked={tempPreferences.preferences}
- onCheckedChange={(checked) => setTempPreferences((prev) => ({ ...prev, preferences: checked }))}
- />
- </div>
-
- <Separator />
-
- <div className="flex items-start justify-between space-x-2 p-3">
- <div className="space-y-1">
- <p className="font-medium text-body">Marketing</p>
- <p className="text-meta text-muted-foreground">
- Used for communications about BoxLite features and updates.
- </p>
- </div>
- <Switch
- checked={tempPreferences.marketing}
- onCheckedChange={(checked) => setTempPreferences((prev) => ({ ...prev, marketing: checked }))}
- />
- </div>
- </div>
- </ScrollArea>
-
- <DialogFooter>
- <Button variant="outline" onClick={() => onOpenChange(false)}>
- Cancel
- </Button>
- <Button onClick={handleSave}>Save Preferences</Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
-}
diff --git a/apps/dashboard/src/components/ProductAnalyticsPreferences.tsx b/apps/dashboard/src/components/ProductAnalyticsPreferences.tsx
new file mode 100644
index 000000000..4fd7308c6
--- /dev/null
+++ b/apps/dashboard/src/components/ProductAnalyticsPreferences.tsx
@@ -0,0 +1,204 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { useAuth } from 'react-oidc-context'
+import { useApi } from '@/hooks/useApi'
+import { useConfig } from '@/hooks/useConfig'
+import { useSelectedOrganization } from '@/hooks/useSelectedOrganization'
+import { useConsoleAnalytics } from '@/hooks/useConsoleAnalytics'
+import { clearSignupSource, takeSignupSource } from '@/lib/signup-attribution'
+import { Button } from '@/components/ui/button'
+import { Switch } from '@/components/ui/switch'
+import { analyticsNoticeVersion, type AnalyticsPreference } from '../../../shared/console-analytics'
+
+type ConsolePreference = AnalyticsPreference & { enabledFrom: string | null }
+type Choice = {
+ allowed: boolean | null | undefined
+ saving: boolean
+ error: string | null
+ save: (allowed: boolean) => void
+ refresh: () => void
+}
+const Preferences = createContext<Choice | null>(null)
+
+export function ProductAnalyticsProvider({ children }: { children: ReactNode }) {
+ const { user, isAuthenticated } = useAuth()
+ const { selectedOrganization } = useSelectedOrganization()
+ const { posthog } = useConfig()
+ const sub = isAuthenticated && user?.profile.sub
+ if (!sub || !selectedOrganization?.id || !posthog?.host || !posthog.apiKey) return children
+ return (
+ <AccountPreference
+ key={JSON.stringify([sub, selectedOrganization.id])}
+ sub={sub}
+ organizationId={selectedOrganization.id}
+ >
+ {children}
+ </AccountPreference>
+ )
+}
+
+function AccountPreference({
+ sub,
+ organizationId,
+ children,
+}: {
+ sub: string
+ organizationId: string
+ children: ReactNode
+}) {
+ const api = useApi()
+ const queryClient = useQueryClient()
+ const [saving, setSaving] = useState(false)
+ const [saveError, setSaveError] = useState<string | null>(null)
+ const writing = useRef(false)
+ const query = useQuery({
+ queryKey: ['product-analytics', sub, organizationId],
+ queryFn: async ({ signal }): Promise<ConsolePreference> => {
+ const http = api.axiosInstance
+ return (await http.get('/analytics/organizations/' + encodeURIComponent(organizationId) + '/consent', { signal }))
+ .data
+ },
+ retry: false,
+ refetchOnMount: 'always',
+ })
+ const allowed = query.data?.allowed
+ useConsoleAnalytics(organizationId, query.isError ? null : query.data?.enabledFrom)
+
+ useEffect(() => {
+ const source = takeSignupSource(sub, query.isError ? undefined : allowed)
+ if (source) void api.axiosInstance.post('/analytics/signup-source', source, { timeout: 2000 }).catch(() => {})
+ }, [api, sub, allowed, query.isError])
+
+ const save = async (next: boolean) => {
+ if (writing.current) return
+ writing.current = true
+ setSaving(true)
+ setSaveError(null)
+ try {
+ const { data: decision } = await api.axiosInstance.put<AnalyticsPreference>('/analytics/consent', {
+ allowed: next,
+ version: analyticsNoticeVersion,
+ })
+ const accountQueries = { queryKey: ['product-analytics', sub] }
+ // Discard consent reads that started before the decision was saved.
+ await queryClient.cancelQueries(accountQueries)
+ if (decision.allowed === false) {
+ clearSignupSource()
+ queryClient.setQueriesData<ConsolePreference>(accountQueries, { ...decision, enabledFrom: null })
+ } else {
+ // A personal grant still needs the organization's creator grant.
+ await queryClient.invalidateQueries(accountQueries)
+ }
+ } catch {
+ setSaveError('Could not confirm your preference. Check your connection and try again.')
+ } finally {
+ setSaving(false)
+ writing.current = false
+ }
+ }
+ return (
+ <Preferences.Provider
+ value={{
+ allowed,
+ saving,
+ save,
+ error: saveError || (query.isError ? 'Could not load your preference.' : null),
+ refresh: () => void query.refetch(),
+ }}
+ >
+ {children}
+ </Preferences.Provider>
+ )
+}
+
+export function AnalyticsConsentCard() {
+ const choice = useContext(Preferences)
+ if (!choice || choice.allowed !== null) return null
+ return (
+ <section
+ data-analytics-preferences
+ aria-labelledby="analytics-card-title"
+ className="mx-4 my-3 max-w-xl border border-border bg-background p-4 sm:mx-5"
+ >
+ <h2 id="analytics-card-title" className="text-body font-semibold">
+ Share usage analytics?
+ </h2>
+ <p className="mt-1 text-body text-muted-foreground">
+ Allow BoxLite to send Console page visits and feature interactions to PostHog to help improve the product. You
+ can turn this off anytime in Settings.
+ </p>
+ <details className="mt-2 text-meta text-muted-foreground">
+ <summary className="cursor-pointer">What this choice covers</summary>Your choice covers your account activity
+ and Cloud activity in organizations you created. Activity linked to another member also needs their permission.
+ </details>
+ <div className="mt-3 flex flex-wrap gap-2">
+ <Button variant="outline" disabled={choice.saving} onClick={() => choice.save(true)}>
+ Allow analytics
+ </Button>
+ <Button variant="outline" disabled={choice.saving} onClick={() => choice.save(false)}>
+ No thanks
+ </Button>
+ </div>
+ {choice.error && (
+ <p role="alert" className="mt-2 text-meta text-destructive">
+ {choice.error}
+ </p>
+ )}
+ </section>
+ )
+}
+
+export function ProductAnalyticsSettings() {
+ const choice = useContext(Preferences)
+ return (
+ <section data-analytics-preferences aria-labelledby="privacy-preferences" className="border border-border p-5">
+ <h2 id="privacy-preferences" className="text-em font-semibold">
+ Privacy Preferences
+ </h2>
+ <div className="mt-4 flex items-start justify-between gap-4">
+ <div>
+ <label htmlFor="product-analytics" className="text-body font-semibold">
+ Product analytics
+ </label>
+ <p id="analytics-scope" className="mt-1 max-w-lg text-meta text-muted-foreground">
+ Share usage with PostHog for your account and the organizations you created. Other members must also agree
+ before their activity is shared.
+ </p>
+ </div>
+ <div className="flex items-center gap-2">
+ <span aria-live="polite" className="text-meta">
+ {!choice
+ ? 'Unavailable'
+ : choice.saving
+ ? 'Saving…'
+ : choice.allowed === undefined
+ ? choice.error
+ ? 'Unavailable'
+ : 'Loading…'
+ : choice.allowed
+ ? 'On'
+ : 'Off'}
+ </span>
+ <Switch
+ id="product-analytics"
+ aria-describedby="analytics-scope"
+ checked={choice?.allowed === true}
+ disabled={!choice || choice.saving || choice.allowed === undefined}
+ onCheckedChange={(value) => choice?.save(value)}
+ />
+ </div>
+ </div>
+ {choice?.error && (
+ <div className="mt-2 flex items-center gap-2">
+ <p role="alert" className="text-meta text-destructive">
+ {choice.error}
+ </p>
+ <Button variant="outline" size="sm" onClick={choice.refresh}>
+ Refresh
+ </Button>
+ </div>
+ )}
+ </section>
+ )
+}
diff --git a/apps/dashboard/src/components/RegistrationGate.tsx b/apps/dashboard/src/components/RegistrationGate.tsx
index ec13bb690..9924b702c 100644
--- a/apps/dashboard/src/components/RegistrationGate.tsx
+++ b/apps/dashboard/src/components/RegistrationGate.tsx
@@ -96,6 +96,15 @@ export function RegistrationGate({ children }: { children: ReactNode }) {
<Button className="mt-6 h-10 w-full" onClick={() => void register()} disabled={!token || submitting}>
{submitting ? 'Creating account…' : 'Create account'}
</Button>
+ <p className="mt-2 text-center text-meta text-muted-foreground">
+ <a className="underline" href="https://boxlite.ai/legal/terms" target="_blank" rel="noopener noreferrer">
+ Terms of Service
+ </a>
+ {' · '}
+ <a className="underline" href="https://boxlite.ai/legal/privacy" target="_blank" rel="noopener noreferrer">
+ Privacy Policy
+ </a>
+ </p>
</>
) : (
<Button onClick={() => void account.refetch()} disabled={account.isFetching}>
diff --git a/apps/dashboard/src/components/billing/PlanComparison.tsx b/apps/dashboard/src/components/billing/PlanComparison.tsx
index 7569e1553..c4f83f04f 100644
--- a/apps/dashboard/src/components/billing/PlanComparison.tsx
+++ b/apps/dashboard/src/components/billing/PlanComparison.tsx
@@ -166,6 +166,7 @@ export function PlanComparison({
className="h-8 w-auto px-3"
variant={cta.disabled ? 'quiet' : 'secondary'}
disabled={!canManage || cta.disabled}
+ data-console-action="select_plan"
onClick={() => navigate(generatePath(RoutePath.BILLING_PLAN_CHANGE, { planId: plan.id }))}
>
{canManage ? cta.label : 'Owner managed'}
diff --git a/apps/dashboard/src/components/billing/WalletSection.integration.test.tsx b/apps/dashboard/src/components/billing/WalletSection.integration.test.tsx
index 219d5af0c..8c75c3e3e 100644
--- a/apps/dashboard/src/components/billing/WalletSection.integration.test.tsx
+++ b/apps/dashboard/src/components/billing/WalletSection.integration.test.tsx
@@ -686,6 +686,7 @@ describe('WalletSection top-up checkout', () => {
expect(topUpButton?.parentElement?.classList.contains('overflow-hidden')).toBe(false)
// The ribbon must not rename the button for assistive technology.
expect(topUpButton?.textContent?.trim()).toBe('Top up →')
+ expect(topUpButton?.getAttribute('data-console-action')).toBe('top_up_wallet')
})
it('shows no discount ribbon without a top-up discount', async () => {
diff --git a/apps/dashboard/src/components/billing/WalletSection.tsx b/apps/dashboard/src/components/billing/WalletSection.tsx
index dd3690259..068186ca0 100644
--- a/apps/dashboard/src/components/billing/WalletSection.tsx
+++ b/apps/dashboard/src/components/billing/WalletSection.tsx
@@ -597,6 +597,7 @@ export function WalletSection({
<div className="relative w-full sm:ml-auto sm:w-auto">
<AsciiButton
variant="primary"
+ data-console-action="top_up_wallet"
onClick={handleTopUpWallet}
disabled={!topUp.enabled || topUpWalletMutation.isPending}
className={cn('inline-flex w-full items-center justify-center gap-2', topUpDiscount && 'pr-14')}
@@ -728,6 +729,7 @@ export function WalletSection({
</div>
</div>
<AsciiButton
+ data-console-action="save_auto_top_up"
onClick={handleSetAutomaticTopUp}
disabled={!cardConnected || saveAutomaticTopUpDisabled || walletQuery.isLoading || !wallet}
className="inline-flex items-center gap-2"
@@ -787,6 +789,7 @@ export function WalletSection({
className="h-9 w-full font-mono text-body sm:w-[200px]"
/>
<AsciiButton
+ data-console-action="redeem_coupon"
onClick={handleRedeemCoupon}
disabled={redeemCouponMutation.isPending}
className="inline-flex shrink-0 items-center gap-2"
diff --git a/apps/dashboard/src/components/ci/CapacitySummary.tsx b/apps/dashboard/src/components/ci/CapacitySummary.tsx
index b22c1e877..07269f616 100644
--- a/apps/dashboard/src/components/ci/CapacitySummary.tsx
+++ b/apps/dashboard/src/components/ci/CapacitySummary.tsx
@@ -164,7 +164,7 @@ export function CapacitySummary({ capacity }: { capacity: CiCapacity }) {
<Button variant="quiet" size="sm" type="button" onClick={() => setOpen(false)} disabled={busy}>
Cancel
</Button>
- <Button size="sm" type="submit" disabled={busy}>
+ <Button size="sm" data-console-action="save_ci_limit" type="submit" disabled={busy}>
{busy ? 'Saving…' : 'Save'}
</Button>
</div>
diff --git a/apps/dashboard/src/components/ci/CiConnectionFlow.test.tsx b/apps/dashboard/src/components/ci/CiConnectionFlow.test.tsx
index e35536006..f5d933e9c 100644
--- a/apps/dashboard/src/components/ci/CiConnectionFlow.test.tsx
+++ b/apps/dashboard/src/components/ci/CiConnectionFlow.test.tsx
@@ -250,6 +250,7 @@ describe('CI browser connection lifecycle', () => {
)
await render()
const connect = button('Connect GitHub')
+ expect(connect.getAttribute('data-console-action')).toBe('connect_github')
await act(async () => connect.click())
try {
expect(button('Cancel')).toBeUndefined()
diff --git a/apps/dashboard/src/components/ci/CiConnectionFlow.tsx b/apps/dashboard/src/components/ci/CiConnectionFlow.tsx
index 002b71359..f5354e955 100644
--- a/apps/dashboard/src/components/ci/CiConnectionFlow.tsx
+++ b/apps/dashboard/src/components/ci/CiConnectionFlow.tsx
@@ -240,6 +240,7 @@ export function CiConnectionFlow({
<AsciiButton
variant="primary"
disabled={starting || !configuration?.web_connect_available}
+ data-console-action="connect_github"
onClick={() => void start()}
>
{starting && <Loader2 className="size-4 animate-spin" />}Connect GitHub
diff --git a/apps/dashboard/src/components/ci/ConnectsPanel.tsx b/apps/dashboard/src/components/ci/ConnectsPanel.tsx
index 41f249b15..19efdcf8c 100644
--- a/apps/dashboard/src/components/ci/ConnectsPanel.tsx
+++ b/apps/dashboard/src/components/ci/ConnectsPanel.tsx
@@ -347,7 +347,7 @@ export function ConnectsPanel() {
<AsciiButton type="button" onClick={() => setEditing(null)} disabled={busy}>
Cancel
</AsciiButton>
- <AsciiButton variant="primary" type="submit" disabled={busy}>
+ <AsciiButton variant="primary" data-console-action="update_ci_connection" type="submit" disabled={busy}>
Update connection
</AsciiButton>
</DialogFooter>
diff --git a/apps/dashboard/src/components/images/ImageCatalog.tsx b/apps/dashboard/src/components/images/ImageCatalog.tsx
index 249647af9..7ff909dea 100644
--- a/apps/dashboard/src/components/images/ImageCatalog.tsx
+++ b/apps/dashboard/src/components/images/ImageCatalog.tsx
@@ -247,6 +247,7 @@ export function ImageCatalog() {
onClick={() =>
image.templateId ? openTemplate(image.templateId) : setNewBoxImage(imageStartRef(image))
}
+ data-console-action="new_box"
title={`New Box from ${imageStartRef(image)}`}
>
New Box
diff --git a/apps/dashboard/src/components/images/RegistriesPanel.tsx b/apps/dashboard/src/components/images/RegistriesPanel.tsx
index 5c5d73e04..102d3de9d 100644
--- a/apps/dashboard/src/components/images/RegistriesPanel.tsx
+++ b/apps/dashboard/src/components/images/RegistriesPanel.tsx
@@ -316,7 +316,7 @@ export function RegistriesPanel() {
disabled={inventory === undefined}
/>
{canWrite && (
- <AsciiButton variant="primary" onClick={() => setFormOpen(true)}>
+ <AsciiButton variant="primary" data-console-action="new_registry" onClick={() => setFormOpen(true)}>
Connect a registry
</AsciiButton>
)}
@@ -513,7 +513,11 @@ export function RegistriesPanel() {
<Button type="button" variant="outline" onClick={closeForm}>
Cancel
</Button>
- <Button type="submit" disabled={saving || createRegistry.isPending || updateRegistry.isPending}>
+ <Button
+ data-console-action={editing ? 'update_registry' : 'connect_registry'}
+ type="submit"
+ disabled={saving || createRegistry.isPending || updateRegistry.isPending}
+ >
{editing ? 'Save changes' : 'Connect'}
</Button>
</DialogFooter>
diff --git a/apps/dashboard/src/components/tests/ProductAnalyticsPreferences.test.tsx b/apps/dashboard/src/components/tests/ProductAnalyticsPreferences.test.tsx
new file mode 100644
index 000000000..c70396507
--- /dev/null
+++ b/apps/dashboard/src/components/tests/ProductAnalyticsPreferences.test.tsx
@@ -0,0 +1,283 @@
+// @vitest-environment jsdom
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { MemoryRouter, Link } from 'react-router-dom'
+import { getByRole, queryByRole } from '@testing-library/dom'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import {
+ AnalyticsConsentCard,
+ ProductAnalyticsProvider,
+ ProductAnalyticsSettings,
+} from '../ProductAnalyticsPreferences'
+import { captureSignupEntry } from '@/lib/signup-attribution'
+import { recordConsoleTabSelection } from '@/hooks/useConsoleAnalytics'
+
+const http = vi.hoisted(() => ({ get: vi.fn(), put: vi.fn(), post: vi.fn() }))
+vi.mock('@/hooks/useApi', () => ({ useApi: () => ({ axiosInstance: http }) }))
+vi.mock('@/hooks/useSelectedOrganization', () => ({
+ useSelectedOrganization: () => ({ selectedOrganization: { id: organizationId } }),
+}))
+vi.mock('react-oidc-context', () => ({
+ useAuth: () => ({ isAuthenticated: true, user: { profile: { sub: 'person' } } }),
+}))
+vi.mock('@/hooks/useConfig', () => ({
+ useConfig: () => ({ posthog: { host: 'https://example.invalid', apiKey: 'phc_test' } }),
+}))
+
+let root: Root
+let host: HTMLDivElement
+let client: QueryClient
+let organizationId: string
+let allowed: boolean | null
+const pause = () => new Promise<void>((r) => setTimeout(r, 5))
+
+async function mount() {
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={client}>
+ <MemoryRouter initialEntries={['/dashboard/boxes?secret=raw-query']}>
+ <ProductAnalyticsProvider>
+ <AnalyticsConsentCard />
+ <ProductAnalyticsSettings />
+ <button data-console-action="new_box">Private project name</button>
+ <Link to="/dashboard/boxes/private-box-id?utm_source=private-referrer">Open private box</Link>
+ <div className="xterm">
+ <button>terminal content</button>
+ </div>
+ </ProductAnalyticsProvider>
+ </MemoryRouter>
+ </QueryClientProvider>,
+ )
+ })
+ await act(pause)
+}
+async function click(name: string, role = 'button') {
+ await act(async () => {
+ getByRole(host, role, { name }).click()
+ await pause()
+ })
+ await act(pause)
+}
+beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ vi.resetAllMocks()
+ organizationId = 'organization'
+ allowed = null
+ http.get.mockImplementation(async () => ({
+ data: { allowed, enabledFrom: allowed ? new Date(0).toISOString() : null },
+ }))
+ http.put.mockImplementation(async (_path, choice) => {
+ allowed = choice.allowed
+ return { data: { allowed, version: 1, decidedAt: new Date().toISOString() } }
+ })
+ http.post.mockResolvedValue({})
+ host = document.createElement('div')
+ document.body.append(host)
+ root = createRoot(host)
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } })
+})
+afterEach(async () => {
+ await act(async () => root.unmount())
+ client.clear()
+ host.remove()
+ localStorage.clear()
+})
+it('starts off, ignores the old browser choice, and sends only subsequent sanitized activity', async () => {
+ localStorage.setItem('privacy_consent_person', JSON.stringify({ analytics: true }))
+ await mount()
+ expect(getByRole(host, 'heading', { name: 'Share usage analytics?' })).toBeTruthy()
+ await click('Private project name')
+ await click('Allow analytics')
+ expect(http.put).toHaveBeenCalledWith('/analytics/consent', { allowed: true, version: 1 })
+ expect(http.post).not.toHaveBeenCalled()
+ await click('terminal content')
+ expect(http.post).not.toHaveBeenCalled()
+ await click('Private project name')
+ await act(async () => recordConsoleTabSelection('view_billing_wallet'))
+ await click('Open private box', 'link')
+ const events = http.post.mock.calls.map(([, e]) => e)
+ expect(events.map((e) => e.event)).toEqual([
+ 'console_control_click',
+ 'console_control_click',
+ 'console_control_click',
+ '$pageview',
+ ])
+ expect(events[0]).toMatchObject({ action: 'new_box', page: '/dashboard/boxes' })
+ expect(events[1]).toMatchObject({ action: 'view_billing_wallet', control: 'tab' })
+ expect(events[2].destination).toBe('/dashboard/boxes/:boxId')
+ expect(events[3].page).toBe('/dashboard/boxes/:boxId')
+ expect(JSON.stringify(events)).not.toMatch(
+ /raw-query|private-box-id|private-referrer|Private project name|terminal content/,
+ )
+ await click('Product analytics', 'switch')
+ expect(http.put).toHaveBeenLastCalledWith('/analytics/consent', { allowed: false, version: 1 })
+ await click('Private project name')
+ expect(http.post).toHaveBeenCalledTimes(4)
+})
+it('saves No thanks, hides the prompt, and leaves product interactions available', async () => {
+ await mount()
+ await click('No thanks')
+ expect(queryByRole(host, 'heading', { name: 'Share usage analytics?' })).toBeNull()
+ expect(getByRole(host, 'switch', { name: 'Product analytics' }).getAttribute('aria-checked')).toBe('false')
+ await click('Open private box', 'link')
+ expect(http.post).not.toHaveBeenCalled()
+})
+it('honors an existing grant on the first admitted view and skips failed preference reads', async () => {
+ allowed = true
+ await mount()
+ expect(http.post).toHaveBeenCalledTimes(1)
+ expect(http.post.mock.calls[0][1]).toMatchObject({ event: '$pageview', page: '/dashboard/boxes' })
+ http.get.mockRejectedValue(Error('offline'))
+ await act(async () => {
+ await client.invalidateQueries()
+ await pause()
+ })
+ await click('Private project name')
+ expect(http.post).toHaveBeenCalledTimes(1)
+})
+
+it('keeps the confirmed grant active when a withdrawal fails and allows a retry', async () => {
+ allowed = true
+ await mount()
+ const alreadySent = http.post.mock.calls.length
+ http.put.mockRejectedValueOnce(new Error('network unavailable'))
+ await click('Product analytics', 'switch')
+ expect(getByRole(host, 'alert').textContent).toContain('Could not confirm your preference')
+ await click('Private project name')
+ expect(http.post).toHaveBeenCalledTimes(alreadySent + 1)
+ expect(getByRole(host, 'switch', { name: 'Product analytics' }).getAttribute('aria-checked')).toBe('true')
+ await click('Product analytics', 'switch')
+ expect(getByRole(host, 'switch', { name: 'Product analytics' }).getAttribute('aria-checked')).toBe('false')
+ expect(queryByRole(host, 'alert')).toBeNull()
+})
+
+it('collects until withdrawal succeeds and stops across cached organizations on acknowledgement', async () => {
+ allowed = true
+ await mount()
+ http.post.mockClear()
+
+ const withdrawal = Promise.withResolvers<void>()
+ http.put.mockImplementationOnce(async () => {
+ await withdrawal.promise
+ allowed = false
+ return { data: { allowed, version: 1, decidedAt: new Date().toISOString() } }
+ })
+ await click('Product analytics', 'switch')
+ await click('Private project name')
+ expect(http.post).toHaveBeenCalledTimes(1)
+
+ organizationId = 'other-org'
+ await mount()
+ const beforeWithdrawal = http.post.mock.calls.length
+
+ // Hold a GET started under the old grant across the acknowledged withdrawal.
+ const oldRead = Promise.withResolvers<void>()
+ http.get.mockImplementationOnce(async () => {
+ await oldRead.promise
+ return { data: { allowed: true, enabledFrom: new Date(0).toISOString() } }
+ })
+ await act(async () => {
+ void client.invalidateQueries()
+ await pause()
+ })
+ await act(async () => {
+ withdrawal.resolve()
+ await pause()
+ oldRead.resolve()
+ await pause()
+ })
+ expect(getByRole(host, 'switch', { name: 'Product analytics' }).getAttribute('aria-checked')).toBe('false')
+ await click('Private project name')
+
+ organizationId = 'organization'
+ await mount()
+ await click('Private project name')
+ expect(http.post).toHaveBeenCalledTimes(beforeWithdrawal)
+})
+
+it('can retry after a failed preference read and keeps a saved refusal off', async () => {
+ allowed = false
+ http.get.mockRejectedValueOnce(new Error('offline'))
+ await mount()
+ expect(getByRole(host, 'alert').textContent).toContain('Could not load your preference')
+ expect(getByRole(host, 'switch', { name: 'Product analytics' }).hasAttribute('disabled')).toBe(true)
+ await click('Refresh')
+ expect(queryByRole(host, 'alert')).toBeNull()
+ expect(queryByRole(host, 'heading', { name: 'Share usage analytics?' })).toBeNull()
+ expect(getByRole(host, 'switch', { name: 'Product analytics' }).getAttribute('aria-checked')).toBe('false')
+ expect(http.post).not.toHaveBeenCalled()
+})
+
+it('queues the destination pageview during a navigation burst and preserves its occurrence time', async () => {
+ allowed = true
+ await mount()
+ http.post.mockClear()
+ const slow = Promise.withResolvers<void>()
+ http.post.mockReturnValueOnce(slow.promise).mockReturnValueOnce(slow.promise)
+ await click('Private project name')
+ await click('Open private box', 'link')
+ expect(http.post).toHaveBeenCalledTimes(2)
+ const beforeDrain = Date.now()
+ await act(async () => {
+ slow.reject(new Error('transport unavailable'))
+ await pause()
+ })
+ expect(http.post).toHaveBeenCalledTimes(3)
+ const pageview = http.post.mock.calls[2][1]
+ expect(pageview).toMatchObject({ event: '$pageview', page: '/dashboard/boxes/:boxId' })
+ expect(Date.parse(pageview.occurredAt)).toBeLessThanOrEqual(beforeDrain)
+})
+
+it('bounds the waiting queue during a stalled transport', async () => {
+ allowed = true
+ await mount()
+ http.post.mockClear()
+ const slow = Promise.withResolvers<void>()
+ http.post.mockReturnValue(slow.promise)
+ const button = getByRole(host, 'button', { name: 'Private project name' })
+ for (let i = 0; i < 30; i++) button.click()
+ expect(http.post).toHaveBeenCalledTimes(2)
+ await act(async () => {
+ slow.resolve()
+ await pause()
+ })
+ expect(http.post).toHaveBeenCalledTimes(18)
+})
+
+it.each(['withdrawal', 'organization switch'])('discards queued interactions on %s', async (change) => {
+ allowed = true
+ await mount()
+ http.post.mockClear()
+ const slow = Promise.withResolvers<void>()
+ http.post.mockReturnValue(slow.promise)
+ await click('Private project name')
+ await click('Open private box', 'link')
+ if (change === 'withdrawal') {
+ await click('Product analytics', 'switch')
+ } else {
+ organizationId = 'other-org'
+ await mount()
+ }
+ const beforeDrain = http.post.mock.calls.length
+ await act(async () => {
+ slow.resolve()
+ await pause()
+ })
+ expect(http.post).toHaveBeenCalledTimes(beforeDrain)
+})
+
+it('sends a pending signup source only after the Settings grant is saved', async () => {
+ window.history.replaceState(null, '', '/#bl_referrer=t.co')
+ captureSignupEntry()
+ await mount()
+ const claims = () => http.post.mock.calls.filter(([route]) => route === '/analytics/signup-source')
+ expect(claims()).toHaveLength(0)
+ http.put.mockRejectedValueOnce(new Error('offline'))
+ await click('Product analytics', 'switch')
+ expect(claims()).toHaveLength(0)
+ await click('Product analytics', 'switch')
+ expect(claims()).toHaveLength(1)
+ expect(claims()[0][1]).toMatchObject({ source: 't.co', kind: 'referrer' })
+})
diff --git a/apps/dashboard/src/components/tests/RegistrationGate.test.tsx b/apps/dashboard/src/components/tests/RegistrationGate.test.tsx
index 062504d84..2a77d0468 100644
--- a/apps/dashboard/src/components/tests/RegistrationGate.test.tsx
+++ b/apps/dashboard/src/components/tests/RegistrationGate.test.tsx
@@ -265,6 +265,9 @@ describe('RegistrationGate', () => {
await render()
expect(businessMount).not.toHaveBeenCalled()
expect(button('Create account').disabled).toBe(true)
+ expect(document.querySelector('a[href="https://boxlite.ai/legal/terms"]')?.textContent).toBe('Terms of Service')
+ expect(document.querySelector('a[href="https://boxlite.ai/legal/privacy"]')?.textContent).toBe('Privacy Policy')
+ expect(document.querySelector('input[type="checkbox"],[role="checkbox"]')).toBeNull()
await click('Complete challenge')
await act(async () => {
button('Create account').click()
diff --git a/apps/dashboard/src/enums/RoutePath.ts b/apps/dashboard/src/enums/RoutePath.ts
index 6721b483d..1bfebb583 100644
--- a/apps/dashboard/src/enums/RoutePath.ts
+++ b/apps/dashboard/src/enums/RoutePath.ts
@@ -8,73 +8,4 @@
* Enum for all route paths in the application
* Use this for consistent route references across the app
*/
-export enum RoutePath {
- // Main routes
- LANDING = '/',
- LOGOUT = '/logout',
- /** Shareable coupon link; see pages/Redeem.tsx. */
- REDEEM = '/redeem',
- DASHBOARD = '/dashboard',
- DOCS = '/docs',
- SLACK = '/slack',
-
- // Dashboard sub-routes
- KEYS = '/dashboard/keys',
- BOXES = '/dashboard/boxes',
- QUICKSTART = '/dashboard/quickstart',
- WELCOME = '/dashboard/welcome',
- BILLING = '/dashboard/billing',
- PRICING = '/dashboard/pricing',
- IMAGES = '/dashboard/images',
- CI = '/dashboard/ci',
- CI_CONNECTS = '/dashboard/ci/connects',
-
- CHECKPOINTS = '/dashboard/checkpoints',
- /** Registries live under Images, as they do in the API. The old top-level path redirects here. */
- IMAGE_REGISTRIES = '/dashboard/images/registries',
- REGISTRIES = '/dashboard/registries',
- VOLUMES = '/dashboard/volumes',
- DOMAINS = '/dashboard/domains',
- LIMITS = '/dashboard/limits',
- BILLING_SPENDING = '/dashboard/billing/spending',
- /** Parent of BILLING_PLAN_CHANGE. Carries no id of its own, so it only redirects. */
- BILLING_PLAN = '/dashboard/billing/plan',
- /** Confirming a switch to `:planId`. Cancelling a subscription outright is not
- * reachable here — it takes a null plan id, which this segment cannot carry. */
- BILLING_PLAN_CHANGE = '/dashboard/billing/plan/:planId',
- BILLING_WALLET = '/dashboard/billing/wallet',
- MEMBERS = '/dashboard/members',
- ROLES = '/dashboard/roles',
- SETTINGS = '/dashboard/settings',
- ONBOARDING = '/dashboard/onboarding',
- AUDIT_LOGS = '/dashboard/audit-logs',
- REGIONS = '/dashboard/regions',
- RUNNERS = '/dashboard/runners',
- EXPERIMENTAL = '/dashboard/experimental',
-
- // User routes
- USER_INVITATIONS = '/dashboard/user/invitations',
- ACCOUNT_SETTINGS = '/dashboard/user/account-settings',
-
- // Webhooks
- WEBHOOKS = '/dashboard/webhooks',
- WEBHOOK_ENDPOINT_DETAILS = '/dashboard/webhooks/:endpointId',
- // Images
- /** `:idOrRef` is a catalog id, or a curated image's short name — neither carries a slash. */
- IMAGE_DETAILS = '/dashboard/images/:idOrRef',
-
- // Boxes
- BOX_DETAILS = '/dashboard/boxes/:boxId',
- BOX_TERMINAL = '/dashboard/boxes/:boxId/terminal',
-
- // Email verification
- EMAIL_VERIFY = '/dashboard/organization/:organizationId/verify-email/:email/:token',
-}
-
-/**
- * Returns only the path segment for dashboard sub-routes
- * Useful for nested routes under the dashboard
- */
-export const getRouteSubPath = (path: RoutePath): string => {
- return path.replace('/dashboard/', '')
-}
+export { RoutePath, getRouteSubPath } from '../../../shared/console-routes'
diff --git a/apps/dashboard/src/hooks/useConsoleAnalytics.ts b/apps/dashboard/src/hooks/useConsoleAnalytics.ts
new file mode 100644
index 000000000..f02257d2b
--- /dev/null
+++ b/apps/dashboard/src/hooks/useConsoleAnalytics.ts
@@ -0,0 +1,109 @@
+import { useLayoutEffect, useRef } from 'react'
+import { matchPath, useLocation } from 'react-router-dom'
+import {
+ consoleActions,
+ consoleControls,
+ consolePages,
+ type ConsoleInteraction,
+} from '../../../shared/console-analytics'
+import { billingTab } from '@/lib/billing-tab'
+import { RoutePath } from '@/enums/RoutePath'
+import { useConfig } from './useConfig'
+import { useApi } from './useApi'
+
+const tabSelections = new EventTarget()
+const routes = [
+ ...consolePages.filter((route) => !route.includes(':')),
+ ...consolePages.filter((route) => route.includes(':')),
+]
+const consolePage = (path: string) => routes.find((route) => matchPath(route, path))
+
+export function recordConsoleTabSelection(action: string) {
+ tabSelections.dispatchEvent(new CustomEvent('select', { detail: action }))
+}
+
+/** Record only transitions and interactions that occur during an active grant. */
+export function useConsoleAnalytics(organizationId: string, enabledFrom: string | null | undefined) {
+ const api = useApi()
+ const { billingApiUrl } = useConfig()
+ const { pathname, search, key } = useLocation()
+ const pending = useRef(0)
+ const waiting = useRef<Array<() => void>>([])
+ const lastView = useRef<{ key: string; at: Date; sent: boolean } | undefined>(undefined)
+
+ // Navigation shares the backlog, but queued events belong to one consent grant.
+ useLayoutEffect(() => {
+ const queue = waiting.current
+ return () => {
+ queue.length = 0
+ }
+ }, [organizationId, enabledFrom])
+
+ useLayoutEffect(() => {
+ const viewKey = JSON.stringify([organizationId, key, pathname])
+ if (lastView.current?.key !== viewKey) lastView.current = { key: viewKey, at: new Date(), sent: false }
+ const view = lastView.current
+ if (enabledFrom === null) view.sent = true
+ const page = consolePage(pathname)
+ if (!page || !enabledFrom || !organizationId) return
+ const send = (event: ConsoleInteraction['event'], at: Date, properties: Partial<ConsoleInteraction> = {}) => {
+ const body: ConsoleInteraction = {
+ event,
+ page,
+ occurredAt: at.toISOString(),
+ ...(page === RoutePath.BILLING && billingApiUrl && { billingTab: billingTab(new URLSearchParams(search)) }),
+ ...properties,
+ }
+ const post = () => {
+ pending.current++
+ void api.axiosInstance
+ .post('/analytics/organizations/' + encodeURIComponent(organizationId) + '/console-events', body, {
+ timeout: 2000,
+ })
+ .catch(() => {})
+ .finally(() => {
+ pending.current--
+ waiting.current.shift()?.()
+ })
+ }
+ if (pending.current < 2) post()
+ else if (waiting.current.length < 16) waiting.current.push(post)
+ }
+ if (!view.sent && view.at.getTime() >= Date.parse(enabledFrom)) {
+ view.sent = true
+ send('$pageview', view.at)
+ }
+ const click = (event: MouseEvent) => {
+ if (
+ !(event.target instanceof Element) ||
+ event.target.closest('[data-analytics-preferences],.xterm,[contenteditable="true"]')
+ )
+ return
+ const target = event.target.closest('button,a[href],[role="button"],[role="menuitem"],[role="tab"]')
+ if (!target) return
+ const control = target.getAttribute('role') ?? target.tagName.toLowerCase()
+ if (!consoleControls.includes(control) || (control === 'tab' && target.closest('[data-console-tab-selections]')))
+ return
+ const action = target.getAttribute('data-console-action')
+ const destination =
+ target instanceof HTMLAnchorElement && target.origin === window.location.origin
+ ? consolePage(target.pathname)
+ : undefined
+ send('console_control_click', new Date(), {
+ control,
+ ...(action && consoleActions.includes(action) && { action }),
+ destination,
+ })
+ }
+ const select = (event: Event) => {
+ const action = (event as CustomEvent<string>).detail
+ if (consoleActions.includes(action)) send('console_control_click', new Date(), { control: 'tab', action })
+ }
+ tabSelections.addEventListener('select', select)
+ document.addEventListener('click', click, true)
+ return () => {
+ tabSelections.removeEventListener('select', select)
+ document.removeEventListener('click', click, true)
+ }
+ }, [api, enabledFrom, billingApiUrl, key, organizationId, pathname, search])
+}
diff --git a/apps/dashboard/src/hooks/usePrivacyConsent.ts b/apps/dashboard/src/hooks/usePrivacyConsent.ts
deleted file mode 100644
index b33a00752..000000000
--- a/apps/dashboard/src/hooks/usePrivacyConsent.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright Daytona Platforms Inc.
- * SPDX-License-Identifier: AGPL-3.0
- */
-
-import { useEffect } from 'react'
-import { useAuth } from 'react-oidc-context'
-import { z } from 'zod'
-import { toast } from 'sonner'
-import { create } from 'zustand'
-import { getLocalStorageItem } from '@/lib/local-storage'
-
-const ConsentPreferencesSchema = z.object({
- necessary: z.boolean(),
- analytics: z.boolean(),
- preferences: z.boolean(),
- marketing: z.boolean(),
-})
-
-export type ConsentPreferences = z.infer<typeof ConsentPreferencesSchema>
-
-const CONSENT_KEY_PREFIX = 'privacy_consent_'
-
-const DEFAULT_PREFERENCES: ConsentPreferences = {
- necessary: true,
- analytics: false,
- preferences: false,
- marketing: false,
-}
-
-interface PrivacyConsentState {
- currentUserSub: string | null
- hasConsented: boolean
- preferences: ConsentPreferences
- init: (userSub: string) => void
- saveConsent: (newPreferences: ConsentPreferences) => void
-}
-
-const usePrivacyConsentStore = create<PrivacyConsentState>()((set, get) => ({
- currentUserSub: null,
- hasConsented: false,
- preferences: DEFAULT_PREFERENCES,
-
- init: (userSub: string) => {
- if (get().currentUserSub === userSub) return
- set({ currentUserSub: userSub })
-
- const consentKey = `${CONSENT_KEY_PREFIX}${userSub}`
- try {
- const saved = getLocalStorageItem(consentKey)
- if (saved) {
- const parsedConsent = ConsentPreferencesSchema.parse(JSON.parse(saved))
- set({ preferences: parsedConsent, hasConsented: true })
- } else {
- set({ preferences: DEFAULT_PREFERENCES, hasConsented: false })
- }
- } catch {
- console.error('Error parsing privacy consent')
- set({ preferences: DEFAULT_PREFERENCES, hasConsented: false })
- }
- },
-
- saveConsent: (newPreferences: ConsentPreferences) => {
- const { currentUserSub } = get()
- if (!currentUserSub) return
-
- const consentKey = `${CONSENT_KEY_PREFIX}${currentUserSub}`
- try {
- localStorage.setItem(consentKey, JSON.stringify(newPreferences))
- set({ preferences: newPreferences, hasConsented: true })
- } catch {
- toast.error('Failed to save privacy preferences. Please try again.')
- }
- },
-}))
-
-export { usePrivacyConsentStore }
-
-export function usePrivacyConsent() {
- const { user } = useAuth()
- const init = usePrivacyConsentStore((state) => state.init)
- const hasConsented = usePrivacyConsentStore((state) => state.hasConsented)
- const preferences = usePrivacyConsentStore((state) => state.preferences)
- const saveConsent = usePrivacyConsentStore((state) => state.saveConsent)
-
- useEffect(() => {
- if (user?.profile?.sub) {
- init(user.profile.sub)
- }
- }, [user?.profile?.sub, init])
-
- return { hasConsented, preferences, saveConsent }
-}
diff --git a/apps/dashboard/src/lib/auth-session.ts b/apps/dashboard/src/lib/auth-session.ts
index 6a2b0cb2d..9f4c1ce41 100644
--- a/apps/dashboard/src/lib/auth-session.ts
+++ b/apps/dashboard/src/lib/auth-session.ts
@@ -3,6 +3,7 @@
* Modified by BoxLite AI, 2025-2026
* SPDX-License-Identifier: AGPL-3.0
*/
+import { clearSignupSource } from './signup-attribution'
import { RoutePath } from '@/enums/RoutePath'
import { CI_CALLBACK_PATH, clearCiConnectSession } from './ci-connect'
import { ORGANIZATION_SESSION_KEY } from './organization-session'
@@ -49,6 +50,7 @@ export function getSignInIntent(): SignInIntent | null {
}
export function markJustLoggedOut(returnTo?: unknown) {
+ clearSignupSource()
clearPendingPlanUpgrade()
sessionStorage.setItem(SIGN_IN_INTENT_KEY, JSON.stringify({ signedOut: true, returnTo: safeReturnTo(returnTo) }))
sessionStorage.removeItem(ORGANIZATION_SESSION_KEY)
diff --git a/apps/dashboard/src/lib/billing-tab.ts b/apps/dashboard/src/lib/billing-tab.ts
new file mode 100644
index 000000000..3bafb1e27
--- /dev/null
+++ b/apps/dashboard/src/lib/billing-tab.ts
@@ -0,0 +1,4 @@
+export function billingTab(params: URLSearchParams) {
+ const tab = params.get('tab')
+ return tab && ['plans', 'usage', 'wallet'].includes(tab) ? tab : 'overview'
+}
diff --git a/apps/dashboard/src/lib/signup-attribution.test.ts b/apps/dashboard/src/lib/signup-attribution.test.ts
new file mode 100644
index 000000000..8488be23c
--- /dev/null
+++ b/apps/dashboard/src/lib/signup-attribution.test.ts
@@ -0,0 +1,99 @@
+// @vitest-environment jsdom
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { captureSignupEntry, takeSignupSource } from './signup-attribution'
+import { signupSourceLifetimeMs } from '../../../shared/signup-attribution'
+
+beforeEach(() => {
+ sessionStorage.clear()
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-01-02T01:00:00Z'))
+})
+afterEach(() => {
+ vi.restoreAllMocks()
+ history.replaceState(null, '', '/')
+ vi.useRealTimers()
+})
+
+function visit(path: string) {
+ history.replaceState(null, '', path)
+ captureSignupEntry()
+}
+
+it('keeps a tagged signup across login and refresh until delayed consent', () => {
+ visit('/?utm_source=X&utm_content=readme&gclid=secret&plan=starter#bl_referrer=t.co')
+ expect(location.search).toBe('?plan=starter')
+ expect(location.hash).toBe('')
+ expect(takeSignupSource('new-user', null)).toBeUndefined()
+ visit('/?code=OIDC&state=opaque')
+ expect(location.search).toBe('?code=OIDC&state=opaque')
+ vi.advanceTimersByTime(signupSourceLifetimeMs - 1)
+ expect(takeSignupSource('new-user', true)).toEqual({
+ source: 'x',
+ kind: 'utm',
+ content: 'readme',
+ enteredAt: '2026-01-02T01:00:00.000Z',
+ })
+ expect(takeSignupSource('new-user', true)).toBeUndefined()
+})
+
+it.each(['x.com', 't.co'])('accepts the observed host %s from an untagged visit', (host) => {
+ visit('/#bl_referrer=' + host)
+ expect(takeSignupSource('user', true)).toMatchObject({ kind: 'referrer', source: host })
+})
+
+it('drops expired evidence, a refused grant, and a candidate bound to a different account', () => {
+ visit('/?ref=docs')
+ vi.advanceTimersByTime(signupSourceLifetimeMs)
+ expect(takeSignupSource('a', true)).toBeUndefined()
+ visit('/?ref=docs')
+ expect(takeSignupSource('a', false)).toBeUndefined()
+ expect(takeSignupSource('a', true)).toBeUndefined()
+ visit('/?ref=docs')
+ expect(takeSignupSource('a', null)).toBeUndefined()
+ expect(takeSignupSource('b', true)).toBeUndefined()
+})
+
+it('keeps only the direct browser referrer hostname until saved consent', () => {
+ const referrer = vi.spyOn(document, 'referrer', 'get').mockReturnValue('https://x.com/post/123?click=private')
+ visit('/dashboard/boxes')
+ expect(takeSignupSource('user', null)).toBeUndefined()
+ referrer.mockReturnValue('https://search.example/')
+ visit('/')
+ expect(takeSignupSource('user', true)).toEqual({
+ source: 'x.com',
+ kind: 'referrer',
+ enteredAt: '2026-01-02T01:00:00.000Z',
+ })
+ expect(takeSignupSource('user', true)).toBeUndefined()
+})
+
+it.each([
+ ['/?utm_source=campaign&ref=partner#bl_referrer=search.example', 'campaign', 'utm'],
+ ['/?ref=partner#bl_referrer=search.example', 'partner', 'ref'],
+ ['/#bl_referrer=search.example', 'search.example', 'referrer'],
+ ['/#bl_referrer=app.boxlite.ai', 't.co', 'referrer'],
+])('resolves %s before using the direct browser referrer', (path, source, kind) => {
+ vi.spyOn(document, 'referrer', 'get').mockReturnValue('https://t.co/short')
+ visit(path)
+ expect(takeSignupSource('user', true)).toMatchObject({ source, kind })
+})
+
+it.each([
+ ['/', ''],
+ ['/', 'https://boxlite.ai/'],
+ ['/', 'https://auth.dev.boxlite.ai/login'],
+ ['/', 'chrome-extension://external.example/index'],
+ ['/?code=oidc&state=opaque', 'https://login.example/'],
+])('ignores an ineligible browser referrer on %s from %s', (path, referrer) => {
+ vi.spyOn(document, 'referrer', 'get').mockReturnValue(referrer)
+ visit(path)
+ expect(takeSignupSource('user', true)).toBeUndefined()
+})
+
+it('leaves unrelated app routes intact and excludes URL-shaped or internal sources', () => {
+ visit('/dashboard/ci?ref=main#section')
+ expect(location.search + location.hash).toBe('?ref=main#section')
+ visit('/?utm_source=https%3A%2F%2Fx.com#bl_referrer=signin.boxlite.ai')
+ expect(takeSignupSource('a', true)).toBeUndefined()
+})
diff --git a/apps/dashboard/src/lib/signup-attribution.ts b/apps/dashboard/src/lib/signup-attribution.ts
new file mode 100644
index 000000000..a7f3c0133
--- /dev/null
+++ b/apps/dashboard/src/lib/signup-attribution.ts
@@ -0,0 +1,119 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { hasAuthParams } from 'react-oidc-context'
+import {
+ campaignLabel,
+ signupSourceLifetimeMs,
+ validSource,
+ type SignupSource,
+} from '../../../shared/signup-attribution'
+
+const key = 'boxlite.signup-source'
+type Entry = { value: SignupSource; subject?: string }
+let expiryTimer: ReturnType<typeof setTimeout> | undefined
+
+export function clearSignupSource() {
+ clearTimeout(expiryTimer)
+ expiryTimer = undefined
+ try {
+ window.sessionStorage.removeItem(key)
+ } catch {
+ // Browsers can disable tab storage.
+ }
+}
+
+function readEntry(): Entry | undefined {
+ const raw = window.sessionStorage.getItem(key)
+ if (!raw) return
+ const entry: Entry = JSON.parse(raw)
+ const value = entry?.value
+ const age = Date.now() - Date.parse(value?.enteredAt)
+ if (
+ !value ||
+ !Number.isFinite(age) ||
+ age < 0 ||
+ age >= signupSourceLifetimeMs ||
+ !validSource(value.source, value.kind)
+ ) {
+ clearSignupSource()
+ return
+ }
+ clearTimeout(expiryTimer)
+ expiryTimer = setTimeout(clearSignupSource, signupSourceLifetimeMs - age)
+ return entry
+}
+
+function referrerHostname(forwarded?: string): string | undefined {
+ if (forwarded && validSource(forwarded, 'referrer')) return forwarded
+ if (!document.referrer || hasAuthParams()) return
+ try {
+ const { protocol, hostname } = new URL(document.referrer)
+ if (protocol !== 'https:' && protocol !== 'http:') return
+ if (hostname !== window.location.hostname && validSource(hostname, 'referrer')) return hostname
+ } catch {
+ // An unparseable referrer provides no signup source.
+ }
+}
+
+// Called before auth or the router reads the URL. Keep OAuth parameters and unrelated anchors intact.
+export function captureSignupEntry() {
+ const url = new URL(window.location.href)
+ if (!['/', '/dashboard', '/dashboard/boxes'].includes(url.pathname)) return
+ const label = (key: string) => {
+ const value = url.searchParams.get(key)
+ return value && campaignLabel.test(value) ? value.toLowerCase() : undefined
+ }
+ const utm = label('utm_source')
+ const ref = label('ref')
+ const fragment = /^#bl_referrer=([a-z0-9.-]+)$/.exec(url.hash)
+ const kind = utm ? 'utm' : ref ? 'ref' : 'referrer'
+ const source = utm || ref || referrerHostname(fragment?.[1])
+ const medium = label('utm_medium')
+ const campaign = label('utm_campaign')
+ const content = label('utm_content')
+ const before = url.href
+ for (const name of [
+ 'utm_source',
+ 'utm_medium',
+ 'utm_campaign',
+ 'utm_content',
+ 'utm_term',
+ 'ref',
+ 'gclid',
+ 'fbclid',
+ 'msclkid',
+ 'twclid',
+ 'li_fat_id',
+ ]) {
+ if (url.searchParams.has(name)) url.searchParams.delete(name)
+ }
+ if (url.hash.startsWith('#bl_referrer=')) url.hash = ''
+ try {
+ if (before !== url.href) window.history.replaceState(window.history.state, '', url)
+ if (readEntry() || !source) return
+ const value: SignupSource = { source, kind, enteredAt: new Date().toISOString(), medium, campaign, content }
+ window.sessionStorage.setItem(key, JSON.stringify({ value }))
+ expiryTimer = setTimeout(clearSignupSource, signupSourceLifetimeMs)
+ } catch {
+ clearSignupSource()
+ }
+}
+
+// Bind a pending tab to its first authenticated account. Consume once, only after a saved grant.
+export function takeSignupSource(subject: string, allowed: boolean | null | undefined): SignupSource | undefined {
+ try {
+ const entry = readEntry()
+ if (!entry) return
+ if (allowed === false || (entry.subject && entry.subject !== subject)) {
+ clearSignupSource()
+ return
+ }
+ if (!allowed) {
+ if (!entry.subject) window.sessionStorage.setItem(key, JSON.stringify({ ...entry, subject }))
+ return
+ }
+ clearSignupSource()
+ return entry.value
+ } catch {
+ clearSignupSource()
+ }
+}
diff --git a/apps/dashboard/src/main.tsx b/apps/dashboard/src/main.tsx
index 8f0df8e27..ce1f06ba6 100644
--- a/apps/dashboard/src/main.tsx
+++ b/apps/dashboard/src/main.tsx
@@ -17,7 +17,9 @@ import { ThemeProvider } from './contexts/ThemeContext'
import './index.css'
import { ConfigProvider } from './providers/ConfigProvider'
import { QueryProvider } from './providers/QueryProvider'
+import { captureSignupEntry } from './lib/signup-attribution'
+captureSignupEntry()
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
async function enableMocking() {
diff --git a/apps/dashboard/src/pages/AccountSettings.tsx b/apps/dashboard/src/pages/AccountSettings.tsx
deleted file mode 100644
index 862a1ce28..000000000
--- a/apps/dashboard/src/pages/AccountSettings.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright 2025 Daytona Platforms Inc.
- * Modified by BoxLite AI, 2025-2026
- * SPDX-License-Identifier: AGPL-3.0
- */
-
-import { PageContent, PageHeader, PageLayout, PageTitle } from '@/components/PageLayout'
-import { PrivacyPreferencesDialog } from '@/components/PrivacyPreferencesDialog'
-import { usePrivacyConsent } from '@/hooks/usePrivacyConsent'
-import { Button } from '@/components/ui/button'
-import { Card, CardContent } from '@/components/ui/card'
-import React, { useState } from 'react'
-import LinkedAccounts from './LinkedAccounts'
-
-const AccountSettings: React.FC<{ linkedAccountsEnabled: boolean }> = ({ linkedAccountsEnabled }) => {
- const { preferences, saveConsent } = usePrivacyConsent()
- const [showPrivacyDialog, setShowPrivacyDialog] = useState(false)
-
- return (
- <PageLayout>
- <PageHeader>
- <PageTitle>Account Settings</PageTitle>
- </PageHeader>
-
- <PageContent>
- <div className="flex flex-col gap-6">
- {linkedAccountsEnabled && <LinkedAccounts />}
-
- <Card>
- <CardContent>
- <div className="flex sm:flex-row flex-col justify-between sm:items-center gap-2">
- <div className="text-body">
- <div className="text-muted-foreground">
- <p className="font-semibold text-foreground">Privacy Preferences</p>
- Manage which tracking technologies are used for analytics and marketing.
- </div>
- </div>
- <Button variant="outline" onClick={() => setShowPrivacyDialog(true)}>
- Manage Preferences
- </Button>
- </div>
- </CardContent>
- </Card>
- </div>
-
- <PrivacyPreferencesDialog
- open={showPrivacyDialog}
- onOpenChange={setShowPrivacyDialog}
- preferences={preferences}
- onSave={saveConsent}
- />
- </PageContent>
- </PageLayout>
- )
-}
-
-export default AccountSettings
diff --git a/apps/dashboard/src/pages/Billing.tsx b/apps/dashboard/src/pages/Billing.tsx
index 130746695..0a9cbc1be 100644
--- a/apps/dashboard/src/pages/Billing.tsx
+++ b/apps/dashboard/src/pages/Billing.tsx
@@ -14,6 +14,7 @@ import { PlanUpgradeReturn } from '@/components/billing/PlanUpgradeReturn'
import { UsageSection } from '@/components/billing/UsageSection'
import { WalletSection } from '@/components/billing/WalletSection'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
+import { billingTab } from '@/lib/billing-tab'
import { RoutePath } from '@/enums/RoutePath'
import { useConfig } from '@/hooks/useConfig'
import { Clock, Cpu, Database, MemoryStick, type LucideIcon } from '@/components/ui/icon'
@@ -93,9 +94,7 @@ function Billing() {
const finishUpgradeReturn = useCallback(() => setPendingUpgrade(null), [])
// Controlled, so the page-level balance warning can send the user to Wallet.
const [searchParams, setSearchParams] = useSearchParams()
- const requestedTab = searchParams.get('tab')
- const tab =
- requestedTab && ['overview', 'plans', 'usage', 'wallet'].includes(requestedTab) ? requestedTab : 'overview'
+ const tab = billingTab(searchParams)
const setTab = (value: string) =>
setSearchParams((previous) => {
const next = new URLSearchParams(previous)
@@ -124,19 +123,19 @@ function Billing() {
</div>
<div className="mt-5 flex items-center gap-3">
<TabsList variant="underline" aria-label="Billing views" className="min-w-0 flex-1 gap-3 sm:gap-6">
- <TabsTrigger value="overview">
+ <TabsTrigger data-console-action="view_billing_overview" value="overview">
<TabIcon name="overview" />
Overview
</TabsTrigger>
- <TabsTrigger value="plans">
+ <TabsTrigger data-console-action="view_billing_plans" value="plans">
<TabIcon name="list" />
Plans
</TabsTrigger>
- <TabsTrigger value="usage">
+ <TabsTrigger data-console-action="view_billing_usage" value="usage">
<TabIcon name="chart" />
Usage
</TabsTrigger>
- <TabsTrigger value="wallet">
+ <TabsTrigger data-console-action="view_billing_wallet" value="wallet">
<TabIcon name="wallet" />
Wallet
</TabsTrigger>
diff --git a/apps/dashboard/src/pages/BillingPlanChange.tsx b/apps/dashboard/src/pages/BillingPlanChange.tsx
index 367cfe6f4..9c6a429a3 100644
--- a/apps/dashboard/src/pages/BillingPlanChange.tsx
+++ b/apps/dashboard/src/pages/BillingPlanChange.tsx
@@ -295,6 +295,7 @@ function BillingPlanChange() {
<AsciiButton
variant="primary"
disabled={pending}
+ data-console-action="confirm_plan_change"
onClick={handleConfirm}
className="inline-flex items-center gap-2"
>
diff --git a/apps/dashboard/src/pages/Boxes.tsx b/apps/dashboard/src/pages/Boxes.tsx
index 87f632e54..6257dae70 100644
--- a/apps/dashboard/src/pages/Boxes.tsx
+++ b/apps/dashboard/src/pages/Boxes.tsx
@@ -739,7 +739,13 @@ const Boxes: React.FC = () => {
updateOnboardingProgress({ boxCreated: true })
}}
>
- <AsciiButton variant="primary" className="h-11 sm:h-9" type="button" title="New Box">
+ <AsciiButton
+ variant="primary"
+ className="h-11 sm:h-9"
+ type="button"
+ title="New Box"
+ data-console-action="new_box"
+ >
<Plus className="size-3.5" strokeWidth={2.4} />
New Box
</AsciiButton>
diff --git a/apps/dashboard/src/pages/Checkpoints.tsx b/apps/dashboard/src/pages/Checkpoints.tsx
index d9248feb5..26f1da2f8 100644
--- a/apps/dashboard/src/pages/Checkpoints.tsx
+++ b/apps/dashboard/src/pages/Checkpoints.tsx
@@ -116,6 +116,7 @@ function CheckpointPage() {
variant="primary"
className="h-11 sm:h-9"
disabled={!canWrite || !capabilities.data?.checkpoints_enabled}
+ data-console-action="new_checkpoint"
onClick={() => setCreateOpen(true)}
>
<Plus className="size-3.5" strokeWidth={1.3} /> New Checkpoint
diff --git a/apps/dashboard/src/pages/CustomDomains.tsx b/apps/dashboard/src/pages/CustomDomains.tsx
index c9e1a32ef..eaf84d5e3 100644
--- a/apps/dashboard/src/pages/CustomDomains.tsx
+++ b/apps/dashboard/src/pages/CustomDomains.tsx
@@ -240,6 +240,7 @@ export default function CustomDomains({
)}
<div className="flex-1" />
<AsciiButton
+ data-console-action="new_custom_domain"
variant="primary"
className="h-11 sm:h-9"
onClick={() => {
@@ -595,6 +596,7 @@ export default function CustomDomains({
<AsciiButton
variant="primary"
type="submit"
+ data-console-action="create_custom_domain"
form="custom-domain-create"
disabled={!canCreate || !formHostname.trim() || busy}
>
@@ -619,7 +621,12 @@ export default function CustomDomains({
) : (
!domain.confirmed &&
domain.phase !== 'superseded' && (
- <AsciiButton variant="primary" disabled={!canCreate || busy} onClick={() => run('verify')}>
+ <AsciiButton
+ variant="primary"
+ disabled={!canCreate || busy}
+ data-console-action="verify_custom_domain"
+ onClick={() => run('verify')}
+ >
{action.isPending
? action.variables?.type === 'verify'
? 'Verifying DNS, please wait…'
diff --git a/apps/dashboard/src/pages/Dashboard.test.tsx b/apps/dashboard/src/pages/Dashboard.test.tsx
index 2daa8b391..e7d3c4e67 100644
--- a/apps/dashboard/src/pages/Dashboard.test.tsx
+++ b/apps/dashboard/src/pages/Dashboard.test.tsx
@@ -7,6 +7,9 @@ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vite
import Dashboard from './Dashboard'
const state = vi.hoisted(() => ({ announcements: {} as Record<string, { text: string }>, shellMounts: 0 }))
+vi.mock('react-oidc-context', () => ({
+ useAuth: () => ({ isAuthenticated: true, user: { profile: { sub: 'member' } } }),
+}))
vi.mock('@/hooks/useConfig', () => ({ useConfig: () => ({ version: 'test', announcements: state.announcements }) }))
vi.mock('@/hooks/useSelectedOrganization', () => ({
useSelectedOrganization: () => ({ selectedOrganization: undefined }),
diff --git a/apps/dashboard/src/pages/Dashboard.tsx b/apps/dashboard/src/pages/Dashboard.tsx
index d3dcc43c5..4dbce63e4 100644
--- a/apps/dashboard/src/pages/Dashboard.tsx
+++ b/apps/dashboard/src/pages/Dashboard.tsx
@@ -6,6 +6,7 @@
import React, { Suspense, useEffect, useMemo, useState } from 'react'
import { matchPath, Outlet, useLocation } from 'react-router-dom'
+import { ProductAnalyticsProvider, AnalyticsConsentCard } from '@/components/ProductAnalyticsPreferences'
import { SetupHeader } from '@/components/SetupLayout'
import { OnboardingEntryGate } from '@/components/OnboardingEntryGate'
import { RoutePath } from '@/enums/RoutePath'
@@ -79,6 +80,7 @@ const Dashboard: React.FC = () => {
{/* Lazy route components (Admin/Billing/Settings/box-details) suspend
here so only the content area shows a fallback — the sidebar/shell
stays mounted across navigation. */}
+ <AnalyticsConsentCard />
<Suspense
fallback={
<div className="space-y-3 p-4 sm:p-5">
@@ -128,7 +130,9 @@ const Dashboard: React.FC = () => {
export default function DashboardEntry() {
return (
<OnboardingEntryGate>
- <Dashboard />
+ <ProductAnalyticsProvider>
+ <Dashboard />
+ </ProductAnalyticsProvider>
</OnboardingEntryGate>
)
}
diff --git a/apps/dashboard/src/pages/Domains.test.tsx b/apps/dashboard/src/pages/Domains.test.tsx
index a08703dbd..08dc914c0 100644
--- a/apps/dashboard/src/pages/Domains.test.tsx
+++ b/apps/dashboard/src/pages/Domains.test.tsx
@@ -5,12 +5,15 @@ import { createRoot, type Root } from 'react-dom/client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import Domains from './Domains'
+import userEvent from '@testing-library/user-event'
+import { useConsoleAnalytics } from '@/hooks/useConsoleAnalytics'
import type { DomainList, HeldDomain } from '@/api/domain-types'
import { MemoryRouter } from 'react-router-dom'
const state = vi.hoisted(() => ({
organizationId: 'org-1',
canManage: true,
+ post: vi.fn().mockResolvedValue({}),
list: vi.fn(),
claim: vi.fn(),
custom: vi.fn(),
@@ -19,7 +22,12 @@ const feedback = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), copy: vi.
vi.mock('sonner', () => ({ toast: { success: feedback.success, error: feedback.error } }))
vi.mock('@/lib/copy-text', () => ({ copyToClipboard: feedback.copy }))
vi.mock('@/hooks/useApi', () => ({
- useApi: () => ({ listDomains: state.list, claimDomain: state.claim, listCustomDomains: state.custom }),
+ useApi: () => ({
+ axiosInstance: { post: state.post },
+ listDomains: state.list,
+ claimDomain: state.claim,
+ listCustomDomains: state.custom,
+ }),
}))
vi.mock('@/hooks/useSelectedOrganization', () => ({
useSelectedOrganization: () => ({
@@ -28,6 +36,18 @@ vi.mock('@/hooks/useSelectedOrganization', () => ({
}),
}))
+vi.mock('@/hooks/useConfig', () => ({
+ useConfig: () => ({ posthog: { host: 'https://events.example', apiKey: 'test' } }),
+}))
+vi.mock('react-oidc-context', () => ({
+ useAuth: () => ({ isAuthenticated: true, user: { profile: { sub: 'member' } } }),
+}))
+
+function TrackedDomains() {
+ useConsoleAnalytics(state.organizationId, new Date(0).toISOString())
+ return <Domains />
+}
+
const list: DomainList = {
domains: [
{
@@ -120,6 +140,7 @@ describe('Domains page', () => {
)!
}
async function openForm() {
+ expect(requestButton().getAttribute('data-console-action')).toBe('new_managed_domain')
await act(async () => requestButton().click())
const input = document.querySelector<HTMLInputElement>('#domain-short-name')!
act(() => {
@@ -161,6 +182,37 @@ describe('Domains page', () => {
expect(state.claim).not.toHaveBeenCalled()
})
+ it('records each Domains tab selection once by keyboard or mouse', async () => {
+ const user = userEvent.setup()
+ act(() =>
+ root.render(
+ <QueryClientProvider client={client}>
+ <MemoryRouter initialEntries={['/dashboard/domains']}>
+ <TrackedDomains />
+ </MemoryRouter>
+ </QueryClientProvider>,
+ ),
+ )
+ await settle()
+ const [managed, custom] = document.querySelectorAll<HTMLButtonElement>('[role="tab"]')
+ await act(async () => {
+ managed.focus()
+ await user.keyboard('{ArrowRight}')
+ })
+ await settle()
+ expect(custom.getAttribute('aria-selected')).toBe('true')
+ await act(async () => {
+ await user.click(managed)
+ await user.click(managed)
+ })
+ expect(managed.getAttribute('aria-selected')).toBe('true')
+ const events = state.post.mock.calls.map(([, event]) => event)
+ expect(events.filter((e) => e.event === 'console_control_click').map((e) => e.action)).toEqual([
+ 'view_custom_domains',
+ 'view_managed_domains',
+ ])
+ })
+
it('lists full names with Box/port, App, and unbound targets', async () => {
await render()
expect(state.list).toHaveBeenCalledWith('org-1')
diff --git a/apps/dashboard/src/pages/Domains.tsx b/apps/dashboard/src/pages/Domains.tsx
index 30238ff6e..f24dcf462 100644
--- a/apps/dashboard/src/pages/Domains.tsx
+++ b/apps/dashboard/src/pages/Domains.tsx
@@ -33,6 +33,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import React, { useState } from 'react'
import { generatePath, Link } from 'react-router-dom'
import { toast } from 'sonner'
+import { recordConsoleTabSelection } from '@/hooks/useConsoleAnalytics'
import { usePageTitle } from '@/hooks/usePageTitle'
import CustomDomains from './CustomDomains'
@@ -80,8 +81,14 @@ function OrganizationDomains({ organizationId, canManage }: { organizationId: st
</p>
</div>
- <Tabs defaultValue="managed" className="min-h-0 flex-1 gap-5">
- <TabsList variant="underline" aria-label="Domain views">
+ <Tabs
+ defaultValue="managed"
+ onValueChange={(tab) =>
+ recordConsoleTabSelection(tab === 'custom' ? 'view_custom_domains' : 'view_managed_domains')
+ }
+ className="min-h-0 flex-1 gap-5"
+ >
+ <TabsList variant="underline" aria-label="Domain views" data-console-tab-selections>
<TabsTrigger value="managed">Managed domain</TabsTrigger>
<TabsTrigger value="custom">Custom domain</TabsTrigger>
</TabsList>
@@ -98,6 +105,7 @@ function OrganizationDomains({ organizationId, canManage }: { organizationId: st
variant="primary"
className="h-11 shrink-0 justify-self-start sm:h-9 sm:justify-self-end"
disabled={!canClaim}
+ data-console-action="new_managed_domain"
onClick={openForm}
>
<Plus className="size-3.5" strokeWidth={2.4} /> Request domain
@@ -324,7 +332,12 @@ function OrganizationDomains({ organizationId, canManage }: { organizationId: st
<AsciiButton disabled={claim.isPending} onClick={() => setOpen(false)}>
Cancel
</AsciiButton>
- <AsciiButton type="submit" variant="primary" disabled={!canClaim || !nameValid || claim.isPending}>
+ <AsciiButton
+ data-console-action="request_managed_domain"
+ type="submit"
+ variant="primary"
+ disabled={!canClaim || !nameValid || claim.isPending}
+ >
{claim.isPending ? 'Requesting…' : 'Request domain'}
</AsciiButton>
</DialogFooter>
diff --git a/apps/dashboard/src/pages/ImageDetails.test.tsx b/apps/dashboard/src/pages/ImageDetails.test.tsx
index 897acc925..081d0f0d9 100644
--- a/apps/dashboard/src/pages/ImageDetails.test.tsx
+++ b/apps/dashboard/src/pages/ImageDetails.test.tsx
@@ -265,6 +265,7 @@ describe('image usage guidance', () => {
describe('pinning and unpinning tags', () => {
it('pins a tag to the version chosen', async () => {
await renderPage()
+ expect(button('Pin a tag')?.getAttribute('data-console-action')).toBe('new_image_tag')
await act(async () => button('Pin a tag')?.click())
await act(async () => typeInto(document.getElementById('pin-tag') as HTMLInputElement, 'stable'))
diff --git a/apps/dashboard/src/pages/ImageDetails.tsx b/apps/dashboard/src/pages/ImageDetails.tsx
index 8482484f8..0cb5645c3 100644
--- a/apps/dashboard/src/pages/ImageDetails.tsx
+++ b/apps/dashboard/src/pages/ImageDetails.tsx
@@ -362,7 +362,11 @@ const ImageDetails: React.FC = () => {
<Button type="button" variant="outline" onClick={() => setPinning(false)}>
Cancel
</Button>
- <Button type="submit" disabled={!tagIsValid || tagTaken || !pinForm.versionId || pinTag.isPending}>
+ <Button
+ data-console-action="pin_image_tag"
+ type="submit"
+ disabled={!tagIsValid || tagTaken || !pinForm.versionId || pinTag.isPending}
+ >
Pin
</Button>
</DialogFooter>
@@ -407,7 +411,11 @@ function TagsSection({
count={`${image.aliases.length} pinned`}
right={
canWrite && (
- <AsciiButton onClick={onPin} disabled={busy || image.versions.length === 0}>
+ <AsciiButton
+ data-console-action="new_image_tag"
+ onClick={onPin}
+ disabled={busy || image.versions.length === 0}
+ >
Pin a tag
</AsciiButton>
)
diff --git a/apps/dashboard/src/pages/OrganizationSettings.test.tsx b/apps/dashboard/src/pages/OrganizationSettings.test.tsx
index a6037ce3d..196c0f408 100644
--- a/apps/dashboard/src/pages/OrganizationSettings.test.tsx
+++ b/apps/dashboard/src/pages/OrganizationSettings.test.tsx
@@ -80,13 +80,20 @@ describe('Organization settings tabs', () => {
})
}
+ it('links directly to Privacy Preferences on the Settings tab', async () => {
+ await renderPage('/dashboard/settings?tab=settings')
+ expect(document.querySelector('[role="tab"][aria-selected="true"]')?.textContent).toBe('Settings')
+ expect(document.getElementById('privacy-preferences')?.textContent).toBe('Privacy Preferences')
+ expect(document.querySelector('label[for="product-analytics"]')?.textContent).toBe('Product analytics')
+ })
+
it('opens General with metadata and loads members only after choosing Members', async () => {
await renderPage()
expect(document.querySelector<HTMLInputElement>('#organization-name')?.value).toBe('Acme')
expect([...document.querySelectorAll('input')].some((input) => input.value === 'org-1')).toBe(true)
expect(mocks.api.organizationsApi.listOrganizationInvitations).not.toHaveBeenCalled()
const tabs = [...document.querySelectorAll<HTMLButtonElement>('[role="tab"]')]
- expect(tabs.map((tab) => tab.textContent)).toEqual(['General', 'Members'])
+ expect(tabs.map((tab) => tab.textContent)).toEqual(['General', 'Members', 'Settings'])
expect(tabs[0].getAttribute('aria-selected')).toBe('true')
await act(async () => tabs[1].dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0 })))
expect(document.querySelector('output')?.textContent).toBe('/dashboard/settings?tab=member')
diff --git a/apps/dashboard/src/pages/OrganizationSettings.tsx b/apps/dashboard/src/pages/OrganizationSettings.tsx
index 2c344f6cf..33fc1da0f 100644
--- a/apps/dashboard/src/pages/OrganizationSettings.tsx
+++ b/apps/dashboard/src/pages/OrganizationSettings.tsx
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: AGPL-3.0
*/
+import { ProductAnalyticsSettings } from '@/components/ProductAnalyticsPreferences'
import { TabIcon } from '@/components/ui/TabIcon'
import { AsciiButton } from '@/components/ascii'
import { ResourceSectionHeading } from '@/components/ResourceLayout'
@@ -142,7 +143,8 @@ const OrganizationSettings: React.FC = () => {
usePageTitle('Organization')
const { selectedOrganization } = useSelectedOrganization()
const [searchParams, setSearchParams] = useSearchParams()
- const tab = searchParams.get('tab') === 'member' ? 'member' : 'general'
+ const selectedTab = searchParams.get('tab')
+ const tab = selectedTab === 'member' || selectedTab === 'settings' ? selectedTab : 'general'
if (searchParams.get('tab') === 'ci') return <Navigate to={RoutePath.CI_CONNECTS} replace />
@@ -158,7 +160,7 @@ const OrganizationSettings: React.FC = () => {
value={tab}
onValueChange={(value) => {
const next = new URLSearchParams(searchParams)
- if (value === 'member') next.set('tab', value)
+ if (value !== 'general') next.set('tab', value)
else next.delete('tab')
setSearchParams(next)
}}
@@ -173,10 +175,14 @@ const OrganizationSettings: React.FC = () => {
<TabIcon name="members" />
Members
</TabsTrigger>
+ <TabsTrigger value="settings">Settings</TabsTrigger>
</TabsList>
<TabsContent value="general" className="pt-6">
<OrganizationGeneral key={selectedOrganization.id} />
</TabsContent>
+ <TabsContent value="settings" className="pt-6">
+ <ProductAnalyticsSettings />
+ </TabsContent>
<TabsContent value="member" className="pt-6">
<OrganizationMembers key={selectedOrganization.id} />
</TabsContent>
diff --git a/apps/dashboard/src/pages/Volumes.test.tsx b/apps/dashboard/src/pages/Volumes.test.tsx
index 25857ed86..efc7d9b59 100644
--- a/apps/dashboard/src/pages/Volumes.test.tsx
+++ b/apps/dashboard/src/pages/Volumes.test.tsx
@@ -10,6 +10,7 @@ import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import Volumes from './Volumes'
+import userEvent from '@testing-library/user-event'
import { toast } from 'sonner'
const READY_VOLUME = {
@@ -210,6 +211,26 @@ describe('Volumes row action "New Box"', () => {
})
}
+ it('records the Volume create action once when Enter submits the name', async () => {
+ const user = userEvent.setup()
+ renderPage()
+ await act(async () => rowAction('New Volume')!.click())
+ const button = rowAction('Create')!
+ expect(button.getAttribute('data-console-action')).toBe('create_volume')
+ const input = document.querySelector<HTMLInputElement>('[aria-label="Volume name"]')!
+ await act(async () => {
+ input.focus()
+ await user.keyboard('{Enter}')
+ })
+ expect(toast.error).toHaveBeenCalledWith('Volume name is required')
+ const clicks = vi.fn()
+ button.addEventListener('click', clicks)
+ await act(async () => user.type(input, 'sample'))
+ await act(async () => user.keyboard('{Enter}'))
+ expect(toast.success).toHaveBeenCalledTimes(1)
+ expect(clicks).toHaveBeenCalledTimes(1)
+ })
+
it.each(['pending_delete', 'deleting', 'error', 'future_state'])(
'keeps %s volume status and action safety visible',
(volumeState) => {
diff --git a/apps/dashboard/src/pages/Volumes.tsx b/apps/dashboard/src/pages/Volumes.tsx
index 26e988027..0b5a99da7 100644
--- a/apps/dashboard/src/pages/Volumes.tsx
+++ b/apps/dashboard/src/pages/Volumes.tsx
@@ -243,6 +243,7 @@ const Volumes: React.FC = () => {
variant="primary"
className="h-11 sm:h-9"
type="button"
+ data-console-action="new_volume"
onClick={() => {
setNewName('')
setNewStorageBackend(CreateVolumeStorageBackendEnum.STANDARD)
@@ -335,6 +336,7 @@ const Volumes: React.FC = () => {
type="button"
// The id, not the name — see the mount-row comment in
// CreateBoxDialog.
+ data-console-action="new_box"
onClick={() => setBoxVolumeId(volume.id)}
title={`Create a box with ${volume.name} mounted`}
>
@@ -383,75 +385,88 @@ const Volumes: React.FC = () => {
<DialogHeader>
<DialogTitle>New Volume</DialogTitle>
</DialogHeader>
- <FormDialogBody>
- {/* This dialog is where someone meets the concept. The backend is
- explicit; the instance is server scheduling, not user input. */}
- <p className="mb-[5px] font-sans text-meta leading-relaxed text-muted-foreground">
- Storage that outlives a box. Mount it into a box to read and write; the data stays once that box is gone,
- and another box can mount it later.
- </p>
- <div className="form-field-label">Name</div>
- <input
- value={newName}
- onChange={(e) => setNewName(e.target.value)}
- onKeyDown={(e) => e.key === 'Enter' && handleCreate()}
- placeholder="subtitle-models"
- aria-label="Volume name"
- aria-invalid={!nameValid}
- className="form-field-input font-mono"
- />
- <div className="mt-4">
- <div className="form-field-label">Volume storage</div>
- <select
- value={selectedStorageBackend}
- onChange={(event) => setNewStorageBackend(event.target.value as CreateVolumeStorageBackendEnum)}
- aria-label="Volume storage"
- className="form-field-input"
- >
- <option value={CreateVolumeStorageBackendEnum.STANDARD} disabled={!objectStorageAvailable}>
- Standard
- </option>
- <option value={CreateVolumeStorageBackendEnum.PERFORMANCE} disabled={!filestoreAvailable}>
- Performance
- </option>
- </select>
- </div>
- {storageCapabilitiesError ? (
- <ResourceErrorNotice
- title="Could not load volume storage options."
- retrying={storageCapabilitiesFetching}
- onRetry={() => void refetchStorageCapabilities()}
+ <form
+ className="flex min-h-0 flex-col"
+ onSubmit={(event) => {
+ event.preventDefault()
+ void handleCreate()
+ }}
+ >
+ <FormDialogBody>
+ {/* This dialog is where someone meets the concept. The backend is
+ explicit; the instance is server scheduling, not user input. */}
+ <p className="mb-[5px] font-sans text-meta leading-relaxed text-muted-foreground">
+ Storage that outlives a box. Mount it into a box to read and write; the data stays once that box is gone,
+ and another box can mount it later.
+ </p>
+ <div className="form-field-label">Name</div>
+ <input
+ value={newName}
+ onChange={(e) => setNewName(e.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' && (!newName.trim() || !nameValid)) {
+ event.preventDefault()
+ void handleCreate()
+ }
+ }}
+ placeholder="subtitle-models"
+ aria-label="Volume name"
+ aria-invalid={!nameValid}
+ className="form-field-input font-mono"
/>
- ) : !objectStorageAvailable && !filestoreAvailable ? (
- <PanelNote>This deployment has no volume storage configured.</PanelNote>
- ) : !filestoreAvailable ? (
- <PanelNote>Performance storage is not configured on this deployment.</PanelNote>
- ) : selectedStorageBackend === CreateVolumeStorageBackendEnum.PERFORMANCE ? (
- <PanelNote>Used to mount this volume into a box. It is ready immediately after creation.</PanelNote>
- ) : (
- <PanelNote>Used to mount this volume into a box. It takes a few seconds to become ready.</PanelNote>
- )}
- </FormDialogBody>
- <DialogFooter>
- <AsciiButton type="button" onClick={() => setCreateOpen(false)}>
- Cancel
- </AsciiButton>
- <AsciiButton
- variant="primary"
- type="button"
- onClick={handleCreate}
- disabled={
- createVolume.isPending ||
- storageCapabilitiesLoading ||
- storageCapabilitiesError ||
- storageUnavailable ||
- !newName.trim() ||
- !nameValid
- }
- >
- {createVolume.isPending ? 'Creating…' : 'Create'}
- </AsciiButton>
- </DialogFooter>
+ <div className="mt-4">
+ <div className="form-field-label">Volume storage</div>
+ <select
+ value={selectedStorageBackend}
+ onChange={(event) => setNewStorageBackend(event.target.value as CreateVolumeStorageBackendEnum)}
+ aria-label="Volume storage"
+ className="form-field-input"
+ >
+ <option value={CreateVolumeStorageBackendEnum.STANDARD} disabled={!objectStorageAvailable}>
+ Standard
+ </option>
+ <option value={CreateVolumeStorageBackendEnum.PERFORMANCE} disabled={!filestoreAvailable}>
+ Performance
+ </option>
+ </select>
+ </div>
+ {storageCapabilitiesError ? (
+ <ResourceErrorNotice
+ title="Could not load volume storage options."
+ retrying={storageCapabilitiesFetching}
+ onRetry={() => void refetchStorageCapabilities()}
+ />
+ ) : !objectStorageAvailable && !filestoreAvailable ? (
+ <PanelNote>This deployment has no volume storage configured.</PanelNote>
+ ) : !filestoreAvailable ? (
+ <PanelNote>Performance storage is not configured on this deployment.</PanelNote>
+ ) : selectedStorageBackend === CreateVolumeStorageBackendEnum.PERFORMANCE ? (
+ <PanelNote>Used to mount this volume into a box. It is ready immediately after creation.</PanelNote>
+ ) : (
+ <PanelNote>Used to mount this volume into a box. It takes a few seconds to become ready.</PanelNote>
+ )}
+ </FormDialogBody>
+ <DialogFooter>
+ <AsciiButton type="button" onClick={() => setCreateOpen(false)}>
+ Cancel
+ </AsciiButton>
+ <AsciiButton
+ variant="primary"
+ type="submit"
+ data-console-action="create_volume"
+ disabled={
+ createVolume.isPending ||
+ storageCapabilitiesLoading ||
+ storageCapabilitiesError ||
+ storageUnavailable ||
+ !newName.trim() ||
+ !nameValid
+ }
+ >
+ {createVolume.isPending ? 'Creating…' : 'Create'}
+ </AsciiButton>
+ </DialogFooter>
+ </form>
</DialogContent>
</Dialog>
diff --git a/apps/dashboard/src/providers/ConfigProvider.tsx b/apps/dashboard/src/providers/ConfigProvider.tsx
index cfeca6211..ec4c58b55 100644
--- a/apps/dashboard/src/providers/ConfigProvider.tsx
+++ b/apps/dashboard/src/providers/ConfigProvider.tsx
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: AGPL-3.0
*/
+import { takeSignupSource } from '@/lib/signup-attribution'
import { completeSignIn, safeReturnTo } from '@/lib/auth-session'
import { queryKeys } from '@/hooks/queries/queryKeys'
import { BoxliteConfiguration } from '@boxlite-ai/api-client'
@@ -70,6 +71,7 @@ export function ConfigProvider(props: Props) {
userStore: new WebStorageStateStore({ store: window.sessionStorage }),
onSigninCallback: (user) => {
if (!user) return
+ if (user.profile?.sub) takeSignupSource(user.profile.sub, undefined)
const state = user.state as { returnTo?: string } | undefined
const targetUrl = safeReturnTo(state?.returnTo)
completeSignIn()
diff --git a/apps/e2e/bootstrap.sh b/apps/e2e/bootstrap.sh
index 17402049b..d17209eec 100755
--- a/apps/e2e/bootstrap.sh
+++ b/apps/e2e/bootstrap.sh
@@ -260,7 +260,7 @@ make dist:c
cp target/release/libboxlite.a sdks/go/libboxlite.a
cd "$REPO/apps/runner"
-CGO_ENABLED=1 go build -o /tmp/boxlite-runner-build ./cmd/runner
+CGO_ENABLED=1 go build -tags boxlite_runner -o /tmp/boxlite-runner-build ./cmd/runner
sudo install -m 0755 /tmp/boxlite-runner-build /usr/local/bin/boxlite-runner
rm -f /tmp/boxlite-runner-build
cd "$REPO"
diff --git a/apps/e2e/build_runner.py b/apps/e2e/build_runner.py
index c8beec07c..4a301279a 100644
--- a/apps/e2e/build_runner.py
+++ b/apps/e2e/build_runner.py
@@ -16,7 +16,7 @@ def build(state):
rebuild = not stamp.exists() or stamp.read_text() != identity
(state / "bin").mkdir(parents=True, exist_ok=True)
subprocess.run(
- ["go", "build", *(["-a"] if rebuild else []), "-tags", "boxlite_dev",
+ ["go", "build", *(["-a"] if rebuild else []), "-tags", "boxlite_dev,boxlite_runner",
"-o", str(state / "bin/runner"), "./cmd/runner"],
cwd=ROOT / "apps/runner", env=dict(os.environ, CGO_ENABLED="1"), check=True)
# Failed builds must never certify a new archive.
diff --git a/apps/e2e/two_sided.sh b/apps/e2e/two_sided.sh
index 8f39001fa..e2257a25a 100755
--- a/apps/e2e/two_sided.sh
+++ b/apps/e2e/two_sided.sh
@@ -28,7 +28,7 @@ build_runner() {
cargo build --release -p boxlite-c >/dev/null 2>&1
cp target/release/libboxlite.a sdks/go/libboxlite.a
cd "$REPO/apps/runner"
- CGO_ENABLED=1 go build -o "$out" ./cmd/runner
+ CGO_ENABLED=1 go build -tags boxlite_runner -o "$out" ./cmd/runner
}
swap_and_restart() {
diff --git a/apps/infra-local/compose/native.py b/apps/infra-local/compose/native.py
index 7d45dd4c3..242f11053 100644
--- a/apps/infra-local/compose/native.py
+++ b/apps/infra-local/compose/native.py
@@ -483,12 +483,10 @@ def _pg_count(cfg: InfraConfig, sql: str) -> int:
# build tags. A table because the three no longer share a shape — the registry
# proxy's module is `image-service`, not its own name.
#
-# The runner links the BoxLite SDK's native lib. Build it with the boxlite_dev
-# tag so it links this worktree's target/debug/libboxlite.a (matching the local
-# sdks/go via go.work) instead of a downloaded prebuilt — otherwise a
-# locally-changed FFI surface fails to link.
+# boxlite_dev links this worktree's native archive; boxlite_runner enables
+# the Runner's private SDK bridge to the Guest.
_GO_BUILDS = {
- "runner": ("runner", "./cmd/runner", ["-tags", "boxlite_dev"]),
+ "runner": ("runner", "./cmd/runner", ["-tags", "boxlite_dev,boxlite_runner"]),
"proxy": ("proxy", "./cmd/proxy", []),
"registry-proxy": ("image-service", "./cmd/registry-proxy", []),
}
diff --git a/apps/infra/deployment/nested-runtime-coverage.test.ts b/apps/infra/deployment/nested-runtime-coverage.test.ts
index 780828040..df67889f3 100644
--- a/apps/infra/deployment/nested-runtime-coverage.test.ts
+++ b/apps/infra/deployment/nested-runtime-coverage.test.ts
@@ -50,7 +50,8 @@ if [[ "$1" == '_ensure-kvm' ]]; then
exit
fi
[[ "$1" == 'coverage:go' ]]
-[[ "$2" == 'GOTEST_FILTER=-count=1 -run NestedVirtualization' ]]
+[[ "$2" == 'GO_SDK_COVERAGE_TAGS=boxlite_runner,boxlite_integration' ]]
+[[ "$3" == "GOTEST_FILTER=-count=1 -run 'NestedVirtualization|SSHUsageConfiguredLocal'" ]]
[[ "$BOXLITE_REQUIRE_NESTED_RUNTIME_TESTS" == '1' ]]
for module in go-sdk gvproxy runner image-service secret-server; do
printf 'mode: %s\\nexample/%s/source.go:2.1,2.2 1 5\\n' "$NESTED_TEST_FOCUSED_MODE" "$module" > "target/coverage/$module.out"
diff --git a/apps/infra/docs/configuration.md b/apps/infra/docs/configuration.md
index ee5090495..41baa7f7e 100644
--- a/apps/infra/docs/configuration.md
+++ b/apps/infra/docs/configuration.md
@@ -157,6 +157,17 @@ The exact key list lives in the manifest; avoid maintaining a second list in a r
Set `DB_POOL_MAX` in the stage store to limit the number of PostgreSQL connections per API instance.
Redeploy the API to deliver the value, for example `25`, through the optional API environment group.
+## PostHog consent backlog
+
+`POSTHOG_CONSENT_BACKLOG_LIMIT` is an optional API setting for AWS and GCP. It defaults to 1,000 messages per API instance and accepts positive whole numbers.
+Only events waiting on an analytics consent cache miss use a slot. Cache hits can send immediately. Each excess cold event increments `posthog_consent_backlog_dropped_total`.
+
+For example, run this from `apps/infra` to store a limit of 250 for dev. The API reads the value on its next deployment.
+
+```bash
+npm run mstage env set -- POSTHOG_CONSENT_BACKLOG_LIMIT=250 --stage dev
+```
+
## Invitation link lifetime
Set `ORGANIZATION_INVITATION_TTL_SECONDS` in the stage store to change the default
diff --git a/apps/infra/mdeploy/test/api-environment.test.ts b/apps/infra/mdeploy/test/api-environment.test.ts
index 044365ab5..c06b090e5 100644
--- a/apps/infra/mdeploy/test/api-environment.test.ts
+++ b/apps/infra/mdeploy/test/api-environment.test.ts
@@ -118,6 +118,8 @@ for (const home of ['aws', 'gcp'] as const) {
for (const [key, value] of [
['DB_POOL_MAX', undefined],
['DB_POOL_MAX', '25'],
+ ['POSTHOG_CONSENT_BACKLOG_LIMIT', undefined],
+ ['POSTHOG_CONSENT_BACKLOG_LIMIT', '250'],
...[undefined, '1', '3', '63'].map((minimum) => ['PLATFORM_SUBDOMAIN_MIN_LENGTH', minimum] as const),
] as const) {
test(`${home} delivers ${key} ${value ?? '(unset)'} from the stage group`, () => {
diff --git a/apps/infra/mstage.env.json b/apps/infra/mstage.env.json
index 9a4a1c160..d409e8c03 100644
--- a/apps/infra/mstage.env.json
+++ b/apps/infra/mstage.env.json
@@ -107,6 +107,7 @@
"OIDC_MANAGEMENT_API_CLIENT_SECRET",
"OIDC_ACCOUNT_LINK_SECRET",
"POSTHOG_API_KEY",
+ "POSTHOG_CONSENT_BACKLOG_LIMIT",
"RUNNER_DISK_EXPANSION_CAP_GIB",
"RUNNER_DISK_EXPANSION_ENABLED",
"SVIX_AUTH_TOKEN",
diff --git a/apps/libs/ci-listener/README.md b/apps/libs/ci-listener/README.md
index d4a6d0478..dc4ad25e8 100644
--- a/apps/libs/ci-listener/README.md
+++ b/apps/libs/ci-listener/README.md
@@ -1017,3 +1017,13 @@ Scopes carry explicit Public and Private decisions. Standalone configuration kee
its Public switch and always permits Private, while hosted policy always permits
Public and requires explicit Private consent. Existing scope hashes are incompatible:
finish cleanup with the old Listener and start a fresh journal before upgrading.
+
+## Hosted CI usage
+
+The hosted API uses GitHub's signed `workflow_job` webhooks after inbox admission for a connected organization.
+A valid BoxLite resource label on `queued` emits `cloud.ci.request`. For an assigned JIT runner,
+`in_progress` and `completed` emit `cloud.feature.use` with `runner_started` and `runner_completed` respectively.
+
+The three phases share an opaque Job correlation ID and use GitHub's phase timestamps.
+Each accepted delivery, including a redelivery, generates a separate observation. Count distinct correlation IDs for unique Jobs.
+Analytics uses the existing organization binding and the signed payload without reading worker allocations, polling GitHub, or writing scheduler state.
diff --git a/apps/libs/ci-listener/src/scale-set-listener.spec.ts b/apps/libs/ci-listener/src/scale-set-listener.spec.ts
index 0e73629f1..ad4e5babc 100644
--- a/apps/libs/ci-listener/src/scale-set-listener.spec.ts
+++ b/apps/libs/ci-listener/src/scale-set-listener.spec.ts
@@ -3,6 +3,7 @@ import { DataSource } from 'typeorm'
import { PostgresStateDatabase, postgresStateTable } from './state/postgres'
import { CredentialSource } from './credentials'
import { GitHubAppSource, GitHubInstallation } from './github-app'
+import { GitHubRequestError } from './github'
import { createHmac, generateKeyPairSync, randomUUID } from 'node:crypto'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
@@ -21,6 +22,8 @@ import { ExecutionLease, ListenerState, StateCheck } from './state/store'
import { ListenerInbox, verifyWebhook } from './webhook'
import { ConfirmedWorkerAbsent, ConfirmedWorkerCreationRejected, WorkerExecutor, WorkerState } from './worker'
+type FixtureScaleSet = { id: number; name: string; labels: unknown[]; runnerGroupId: number }
+
/** Public wire shapes. No external runner or installation is needed by this fixture. */
class ActionsFixture {
readonly repository = { id: 21, name: 'repo', owner: { id: 7, login: 'owner' }, private: true }
@@ -37,7 +40,7 @@ class ActionsFixture {
readonly requests: string[] = []
readonly acquired: number[][] = []
discoverCustom = false
- defaultSet?: { id: number; name: string; labels: unknown[]; runnerGroupId: number }
+ defaultSet?: FixtureScaleSet
labels = ['boxlite']
rejectAcquisition = new Set<number>()
loseRetirementReply = false
@@ -48,7 +51,10 @@ class ActionsFixture {
readonly throttledSets = new Map<number, number>()
rejectNextPoll = false
target = 0
- definition?: { id: number; name: string; labels: unknown[]; runnerGroupId: number }
+ private readonly sets = new Map<number, FixtureScaleSet>()
+ get definition() {
+ return this.sets.get(9)
+ }
installation?: GitHubInstallation
private messages: (object | null)[] = []
idle() {
@@ -143,15 +149,19 @@ class ActionsFixture {
if (method === 'POST') {
if (this.discoverCustom && data.labels.some((label: { name: string }) => label.name === 'boxlite'))
return Response.json((this.defaultSet = { ...data, id: 8 }))
- return Response.json((this.definition = { ...data, id: 9 }))
+ const set = { ...data, id: 9 + this.sets.size }
+ this.sets.set(set.id, set)
+ return Response.json(set)
}
- const sets = [this.definition, this.defaultSet].filter(
+ const sets = [...this.sets.values(), this.defaultSet].filter(
(value) => value && value.name === addr.searchParams.get('name'),
)
return Response.json({ count: sets.length, value: sets })
}
- const setId = Number(path.match(/\/runnerscalesets\/(\d+)$/)?.[1])
- if (method === 'GET' && this.throttledSets.has(setId)) {
+ const setRoute = path.match(/\/runnerscalesets\/(\d+)(\/.*)?$/)
+ const setId = Number(setRoute?.[1])
+ const suffix = setRoute?.[2]
+ if (method === 'GET' && !suffix && this.throttledSets.has(setId)) {
this.throttledSets.set(setId, this.throttledSets.get(setId)! + 1)
return new Response(null, { status: 429, headers: { 'retry-after': '60' } })
}
@@ -174,12 +184,13 @@ class ActionsFixture {
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
})
}
- if (path.endsWith('/runnerscalesets/9') && method === 'GET')
+ const set = this.sets.get(setId)
+ if (set && !suffix && method === 'GET')
return Response.json({
- ...this.definition,
+ ...set,
statistics: { totalAssignedJobs: this.target, totalAcquiredJobs: this.acquiredCount },
})
- if (path.endsWith('/9/sessions') && method === 'POST') {
+ if (set && suffix === '/sessions' && method === 'POST') {
const sessionId = randomUUID()
this.sessions.push(sessionId)
return Response.json({
@@ -189,7 +200,7 @@ class ActionsFixture {
statistics: { totalAssignedJobs: this.target, totalAcquiredJobs: this.initialAcquired },
})
}
- if (method === 'DELETE' && path.includes('/9/sessions/')) return new Response(null, { status: 204 })
+ if (set && method === 'DELETE' && suffix?.startsWith('/sessions/')) return new Response(null, { status: 204 })
if (path === '/messages' && method === 'GET') {
if (this.rejectNextPoll) {
this.rejectNextPoll = false
@@ -233,7 +244,7 @@ class ActionsFixture {
return Response.json({ count: accepted.length, value: accepted })
}
if (path.endsWith('/generatejitconfig')) {
- const runner = { id: 100 + this.runners.size, name: data.name, runnerScaleSetId: 9 }
+ const runner = { id: 100 + this.runners.size, name: data.name, runnerScaleSetId: setId }
this.runners.set(data.name, runner)
return Response.json({ runner, encodedJITConfig: Buffer.from(data.name).toString('base64') })
}
@@ -365,7 +376,11 @@ for (const storage of ['sqlite', 'postgres'])
await pg.query('CREATE SCHEMA ' + schema)
await pg.query(postgresStateTable)
}
- const state = new ListenerState(db ?? new PostgresStateDatabase(pg!), 'test')
+ const pagedRestore =
+ scenario === 'gives every queued specification a turn beyond the session limit' ||
+ scenario === 'recovers an occupied label past a full page of sleeping registrations'
+ const database = db ?? new PostgresStateDatabase(pg!)
+ const state = new ListenerState(database, 'test', pagedRestore ? 1 : undefined)
const journal = new ExecutionJournal(state)
const fixture = new ActionsFixture()
const fetch = jest.spyOn(globalThis, 'fetch').mockImplementation(fixture.fetch.bind(fixture))
@@ -480,6 +495,10 @@ for (const storage of ['sqlite', 'postgres'])
])
}
let started = false
+ // These retries must keep the same execution owner while the GitHub session fails.
+ const retryWithSameOwner =
+ scenario === 'retries an offline assignment after a statless cancellation releases the other candidate' ||
+ scenario === 'requires spare quota to reacquire one of several ambiguous requests'
const start = (queued = true) => {
const controller = new AbortController()
listener = new Listener({
@@ -492,7 +511,7 @@ for (const storage of ['sqlite', 'postgres'])
return { limits: [{ maximum, domain: 'organization' }], checks: policyChecks }
},
},
- timing: { tickMs: 5, leaseMs: 450 },
+ timing: retryWithSameOwner ? { tickMs: 5 } : { tickMs: 5, leaseMs: 450 },
})
const initial = !started
started = true
@@ -964,34 +983,34 @@ for (const storage of ['sqlite', 'postgres'])
expect(fixture.requests).toEqual([])
return
}
- if (
- scenario === 'gives every queued specification a turn beyond the session limit' ||
- scenario === 'recovers an occupied label past a full page of sleeping registrations'
- ) {
- const owner = (await state.acquire(randomUUID(), 600))!
- const key = await journal.define(owner, scope)
+ if (pagedRestore) {
+ // Persist the previous deployment's registrations before the new listener scans for work.
+ const previous = new ListenerState(database, 'test')
+ const owner = (await previous.acquire(randomUUID(), 30_000))!
+ const key = await new ExecutionJournal(previous).define(owner, scope)
const labels = Array.from({ length: 101 }, (_, index) => 'boxlite-1vcpu-1gbmem-' + (index + 1) + 'gbdisk')
const recoveryLabel = [...labels].sort().at(-1)!
const recovering = scenario === 'recovers an occupied label past a full page of sleeping registrations'
- for (const label of labels) {
- await state.commit(owner, [
- {
- key: 'scale-set/' + key.slice(6) + '/' + label,
- expected: null,
- payload: {
- name: 'boxlite-' + randomUUID().replaceAll('-', ''),
- set: null,
- assigned: 0,
- held: recovering && label === recoveryLabel ? 1 : 0,
- pending: recovering && label === recoveryLabel ? [{ id: '123', phase: 'verify' }] : [],
- message: null,
- session: null,
- },
- },
- ])
+ const rows = labels.map((label) => ({
+ key: 'scale-set/' + key.slice(6) + '/' + label,
+ expected: null,
+ payload: {
+ name: 'boxlite-' + randomUUID().replaceAll('-', ''),
+ set: null,
+ assigned: 0,
+ held: recovering && label === recoveryLabel ? 1 : 0,
+ pending: recovering && label === recoveryLabel ? [{ id: '123', phase: 'verify' }] : [],
+ message: null,
+ session: null,
+ },
+ }))
+ await previous.commit(owner, rows.slice(0, 100))
+ await previous.commit(owner, rows.slice(100))
+ if (recovering) {
+ expect(await ScaleSetController.recover(previous, owner)).toEqual(new Map([[key, [recoveryLabel]]]))
}
+ expect(await state.activate()).toBe(true)
if (recovering) {
- expect(await ScaleSetController.recover(state, owner)).toEqual(new Map([[key, [recoveryLabel]]]))
stop = start(false)
await until(() => fixture.requests.includes('GET /messages'))
expect(
@@ -1084,7 +1103,12 @@ for (const storage of ['sqlite', 'postgres'])
fixture.publish(2, 1, [], [{ messageType: 'JobAssigned', runnerRequestId: 123 }])
await until(() => jest.mocked(workers.create).mock.calls.length === 1)
fixture.publish(3, undefined, [], [{ messageType: 'JobCompleted', runnerRequestId: 124 }])
- await until(() => report.mock.calls.some((call) => call[1] === 'scale-set-session'))
+ await until(() =>
+ report.mock.calls.some(
+ ([error, operation]) =>
+ operation === 'scale-set-session' && error instanceof GitHubRequestError && error.status === 429,
+ ),
+ )
expect(await journal.used(scope.organization)).toBe(1)
reject()
await until(() => delivered.size === 1)
diff --git a/apps/libs/ci-listener/src/webhook.spec.ts b/apps/libs/ci-listener/src/webhook.spec.ts
index 6e46e13fd..2a6740fff 100644
--- a/apps/libs/ci-listener/src/webhook.spec.ts
+++ b/apps/libs/ci-listener/src/webhook.spec.ts
@@ -56,6 +56,47 @@ describe('CI shared webhook verification', () => {
it.each([[], ['signed body'], '{}', { length: 1 }, null])('rejects a non-Buffer request body %j', (raw) => {
expect(() => verifyWebhook({ ...signed(), raw: raw as Buffer }, secret)).toThrow('Raw webhook body required')
})
+ it('accepts receipts but omits usage evidence for unassigned, external or malformed job activity', () => {
+ const created_at = '2026-11-24T10:30:00Z'
+ const completed_at = '2026-11-24T10:31:00Z'
+ const parse = (status: string, fields: Record<string, unknown>) =>
+ verifyWebhook(
+ signed({
+ ...payload(),
+ action: status,
+ workflow_job: {
+ ...payload().workflow_job,
+ status,
+ created_at,
+ completed_at,
+ runner_name: 'ci-jit-' + 'f'.repeat(32),
+ runner_id: 42,
+ ...fields,
+ },
+ }),
+ secret,
+ )
+ for (const fields of [
+ { runner_id: null },
+ { runner_name: 'other-runner' },
+ { runner_name: null },
+ { labels: ['ubuntu-latest'] },
+ { labels: ['boxlite', 'boxlite-2vcpu-4gbmem-10gbdisk'] },
+ { created_at: null },
+ { completed_at: 'bad date' },
+ { completed_at: '2026-11-24T10:29:00Z' },
+ ]) {
+ const receipt = parse('completed', fields)
+ expect(receipt?.observation?.status).toBe('completed')
+ expect(receipt?.jobTiming).toBeUndefined()
+ }
+ expect(parse('queued', { created_at: 'bad date' })?.jobTiming).toBeUndefined()
+ expect(parse('in_progress', {})?.jobTiming).toBeUndefined()
+ expect(parse('completed', { labels: ['boxlite-2vcpu-4gbmem-10gbdisk'] })?.jobTiming).toEqual({
+ createdAt: created_at,
+ occurredAt: completed_at,
+ })
+ })
it('verifies original bytes and normalizes a GitHub delivery identifier', () => {
const notification = verifyWebhook(signed(payload(), 'A1234567-1111-2222-3333-444444444444'), secret)!
expect(notification).toMatchObject({
diff --git a/apps/libs/ci-listener/src/webhook.ts b/apps/libs/ci-listener/src/webhook.ts
index 5e0de3ca9..58b4cce33 100644
--- a/apps/libs/ci-listener/src/webhook.ts
+++ b/apps/libs/ci-listener/src/webhook.ts
@@ -86,6 +86,7 @@ export function ciWakeHint(event: string, value: unknown): WakeHint | null {
return { installationId: body.installation.id, accountId: body.installation.account.id, repositoryId: 0, job: null }
}
export interface VerifiedWebhook {
+ jobTiming?: { createdAt: string; occurredAt: string }
observation?: JobObservation
/** Trusted host provenance; verifyWebhook never reads this field from the body. */
application?: string
@@ -94,6 +95,27 @@ export interface VerifiedWebhook {
event: string
hint: WakeHint
}
+const utcTimestamp = (value: unknown): value is string =>
+ typeof value === 'string' &&
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value) &&
+ Number.isFinite(Date.parse(value))
+
+/** Optional analytics evidence. The inbox accepts other signed job observations for scheduling. */
+function jobTiming(job: Record<string, unknown>, observation: JobObservation): VerifiedWebhook['jobTiming'] {
+ const createdAt = job.created_at
+ if (!utcTimestamp(createdAt)) return undefined
+ if (observation.status === 'queued') return { createdAt, occurredAt: createdAt }
+ if (!observation.runner || typeof job.runner_name !== 'string' || !/^ci-jit-[a-f0-9]{32}$/.test(job.runner_name))
+ return undefined
+ const occurredAt = observation.status === 'in_progress' ? job.started_at : job.completed_at
+ if (!utcTimestamp(occurredAt) || Date.parse(occurredAt) < Date.parse(createdAt)) return undefined
+ try {
+ if (parseResourceLabels(observation.labels)) return { createdAt, occurredAt }
+ } catch {
+ // Conflicting resource labels cannot establish BoxLite usage.
+ }
+ return undefined
+}
export function verifyWebhook(
input: { raw: Buffer; signature: string; delivery: string; event: string },
secret: Buffer,
@@ -116,23 +138,22 @@ export function verifyWebhook(
throw new WebhookError(400, 'Invalid webhook JSON')
}
const hint = ciWakeHint(event, value)
- return hint
- ? {
- delivery: input.delivery.toLowerCase(),
- digest: createHash('sha256').update(raw).digest('hex'),
- event,
- hint,
- ...(event === 'workflow_job'
- ? {
- observation: {
- status: (value as { workflow_job: { status: JobObservation['status'] } }).workflow_job.status,
- labels: [...(value as { workflow_job: { labels: string[] } }).workflow_job.labels],
- runner: (value as { workflow_job: { runner_id?: number | null } }).workflow_job.runner_id || null,
- },
- }
- : {}),
- }
- : null
+ if (!hint) return null
+ const verified = {
+ delivery: input.delivery.toLowerCase(),
+ digest: createHash('sha256').update(raw).digest('hex'),
+ event,
+ hint,
+ }
+ if (event !== 'workflow_job') return verified
+ // ciWakeHint validated the signed workflow job before this projection.
+ const job = (value as { workflow_job: Record<string, unknown> }).workflow_job
+ const observation: JobObservation = {
+ status: job.status as JobObservation['status'],
+ labels: job.labels as string[],
+ runner: (job.runner_id as number | undefined) || null,
+ }
+ return { ...verified, observation, jobTiming: jobTiming(job, observation) }
}
/** Both hosts use this inbox. Its database adapter must enforce the live binding in the ingress transaction. */
diff --git a/apps/libs/common-go/pkg/featureusage/reporter.go b/apps/libs/common-go/pkg/featureusage/reporter.go
new file mode 100644
index 000000000..fcda19699
--- /dev/null
+++ b/apps/libs/common-go/pkg/featureusage/reporter.go
@@ -0,0 +1,185 @@
+// Copyright 2026 BoxLite AI
+// SPDX-License-Identifier: AGPL-3.0
+
+// Package featureusage reports Cloud evidence independently of business traffic.
+package featureusage
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync/atomic"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+const QueueCapacity = 1024
+const BatchSize = 100
+
+type Kind string
+
+const (
+ SSH Kind = "ssh"
+ TunnelConnection Kind = "tunnel_connection"
+ TunnelRequest Kind = "tunnel_request"
+)
+
+type Event struct {
+ ID string `json:"id"`
+ BoxID string `json:"boxId"`
+ Kind Kind `json:"kind"`
+ OccurredAt time.Time `json:"occurredAt"`
+}
+
+type Reporter struct {
+ queue chan Event
+ endpoint string
+ token string
+ client *http.Client
+ logger *slog.Logger
+ dropped atomic.Uint64
+ unconfirmed atomic.Uint64
+ stopped atomic.Bool
+}
+
+func NewReporter(baseURL, token string, logger *slog.Logger) (*Reporter, error) {
+ base, err := url.Parse(baseURL)
+ if err != nil || base == nil || (base.Scheme != "http" && base.Scheme != "https") ||
+ base.Host == "" || base.User != nil || base.ForceQuery || base.RawQuery != "" || base.Fragment != "" ||
+ token == "" || strings.ContainsAny(token, "\r\n") {
+ return nil, errors.New("invalid feature usage reporting configuration")
+ }
+ if logger == nil {
+ logger = slog.Default()
+ }
+ transport := &http.Transport{
+ Proxy: http.ProxyFromEnvironment,
+ DialContext: (&net.Dialer{Timeout: 2 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
+ MaxConnsPerHost: 1,
+ MaxIdleConns: 1,
+ IdleConnTimeout: 30 * time.Second,
+ TLSHandshakeTimeout: 2 * time.Second,
+ ResponseHeaderTimeout: 2 * time.Second,
+ }
+ return &Reporter{
+ queue: make(chan Event, QueueCapacity),
+ endpoint: strings.TrimRight(base.String(), "/") + "/telemetry/feature-usage",
+ token: token,
+ logger: logger,
+ client: &http.Client{
+ Transport: transport,
+ Timeout: 2 * time.Second,
+ CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
+ return http.ErrUseLastResponse
+ },
+ },
+ }, nil
+}
+
+// Record only attempts a local enqueue. It performs no network call or retry.
+func (r *Reporter) Record(event Event) bool {
+ if r == nil {
+ return false
+ }
+ if r.stopped.Load() {
+ r.dropped.Add(1)
+ return false
+ }
+ if event.ID == "" {
+ event.ID = uuid.NewString()
+ }
+ if event.OccurredAt.IsZero() {
+ event.OccurredAt = time.Now().UTC()
+ } else {
+ event.OccurredAt = event.OccurredAt.UTC()
+ }
+ select {
+ case r.queue <- event:
+ return true
+ default:
+ r.dropped.Add(1)
+ return false
+ }
+}
+
+func (r *Reporter) Dropped() uint64 { return r.dropped.Load() }
+func (r *Reporter) Unconfirmed() uint64 { return r.unconfirmed.Load() }
+
+// Run has one owner. Delivery and diagnostics happen only on this background loop.
+func (r *Reporter) Run(ctx context.Context) {
+ ticker := time.NewTicker(time.Second)
+ defer ticker.Stop()
+ defer r.client.CloseIdleConnections()
+ batch := make([]Event, 0, BatchSize)
+ defer func() {
+ r.stopped.Store(true)
+ r.dropped.Add(uint64(len(batch) + len(r.queue)))
+ r.logger.Info("Cloud feature usage reporter stopped",
+ "queue_dropped_total", r.Dropped(), "delivery_unconfirmed_total", r.Unconfirmed())
+ }()
+ flush := func() {
+ if len(batch) == 0 {
+ return
+ }
+ if err := r.send(ctx, batch); err != nil {
+ r.unconfirmed.Add(uint64(len(batch)))
+ r.logger.Warn("Cloud feature usage delivery unconfirmed",
+ "error_type", err.Error(), "delivery_unconfirmed_total", r.Unconfirmed())
+ }
+ batch = batch[:0]
+ }
+ var reportedDrops uint64
+ for {
+ if ctx.Err() != nil {
+ return
+ }
+ select {
+ case <-ctx.Done():
+ return
+ case event := <-r.queue:
+ batch = append(batch, event)
+ if len(batch) == BatchSize {
+ flush()
+ }
+ case <-ticker.C:
+ flush()
+ if dropped := r.Dropped(); dropped != reportedDrops {
+ reportedDrops = dropped
+ r.logger.Warn("Cloud feature usage queue dropped events", "queue_dropped_total", dropped)
+ }
+ }
+ }
+}
+
+func (r *Reporter) send(ctx context.Context, events []Event) error {
+ body, err := json.Marshal(struct {
+ Events []Event `json:"events"`
+ }{events})
+ if err != nil {
+ return errors.New("invalid_event")
+ }
+ request, err := http.NewRequestWithContext(ctx, http.MethodPost, r.endpoint, bytes.NewReader(body))
+ if err != nil {
+ return errors.New("invalid_request")
+ }
+ request.Header.Set("Authorization", "Bearer "+r.token)
+ request.Header.Set("Content-Type", "application/json")
+ response, err := r.client.Do(request)
+ if err != nil {
+ return errors.New("transport_error")
+ }
+ defer response.Body.Close()
+ _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4096))
+ if response.StatusCode < 200 || response.StatusCode >= 300 {
+ return errors.New("http_error")
+ }
+ return nil
+}
diff --git a/apps/libs/common-go/pkg/featureusage/reporter_test.go b/apps/libs/common-go/pkg/featureusage/reporter_test.go
new file mode 100644
index 000000000..0f8a4d886
--- /dev/null
+++ b/apps/libs/common-go/pkg/featureusage/reporter_test.go
@@ -0,0 +1,228 @@
+// Copyright 2026 BoxLite AI
+// SPDX-License-Identifier: AGPL-3.0
+
+package featureusage
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+func quietLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
+
+func runReporter(t *testing.T, reporter *Reporter) (context.CancelFunc, <-chan struct{}) {
+ t.Helper()
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan struct{})
+ go func() { defer close(done); reporter.Run(ctx) }()
+ t.Cleanup(func() {
+ cancel()
+ select {
+ case <-done:
+ case <-time.After(3 * time.Second):
+ t.Error("reporter did not stop")
+ }
+ })
+ return cancel, done
+}
+
+func fillBatch(t *testing.T, reporter *Reporter) {
+ t.Helper()
+ for i := 0; i < BatchSize; i++ {
+ if !reporter.Record(Event{BoxID: "AbCdEf123456", Kind: TunnelConnection}) {
+ t.Fatal("unexpected enqueue refusal")
+ }
+ }
+}
+
+func TestReporterBatchesSourceIdentityAndTimestamp(t *testing.T) {
+ received := make(chan []Event, 1)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ if req.URL.Path != "/api/telemetry/feature-usage" || req.Header.Get("Authorization") != "Bearer fixture-token" {
+ t.Error("incorrect authenticated endpoint")
+ }
+ var body struct {
+ Events []Event `json:"events"`
+ }
+ if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ received <- body.Events
+ w.WriteHeader(http.StatusAccepted)
+ }))
+ defer server.Close()
+ reporter, err := NewReporter(server.URL+"/api", "fixture-token", quietLogger())
+ if err != nil {
+ t.Fatal(err)
+ }
+ runReporter(t, reporter)
+ sourceID := uuid.NewString()
+ sourceTime := time.Date(2026, 9, 1, 1, 2, 3, 0, time.UTC)
+ reporter.Record(Event{ID: sourceID, BoxID: "AbCdEf123456", Kind: SSH, OccurredAt: sourceTime})
+ for i := 1; i < BatchSize; i++ {
+ reporter.Record(Event{BoxID: "AbCdEf123456", Kind: TunnelRequest})
+ }
+ select {
+ case events := <-received:
+ if len(events) != BatchSize {
+ t.Fatalf("batch length = %d", len(events))
+ }
+ if events[0].ID != sourceID || !events[0].OccurredAt.Equal(sourceTime) {
+ t.Fatal("source identity/time changed")
+ }
+ if _, err := uuid.Parse(events[1].ID); err != nil {
+ t.Fatal("generated ID is not a UUID")
+ }
+ if events[1].OccurredAt.IsZero() {
+ t.Fatal("missing generated occurrence time")
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("batch was not delivered")
+ }
+}
+
+func TestFullQueueDoesNotWaitForCollector(t *testing.T) {
+ entered := make(chan struct{})
+ release := make(chan struct{})
+ var once sync.Once
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ _, _ = io.Copy(io.Discard, req.Body)
+ once.Do(func() { close(entered) })
+ select {
+ case <-release:
+ case <-req.Context().Done():
+ }
+ w.WriteHeader(http.StatusAccepted)
+ }))
+ defer server.Close()
+ defer close(release)
+ reporter, err := NewReporter(server.URL, "fixture-token", quietLogger())
+ if err != nil {
+ t.Fatal(err)
+ }
+ runReporter(t, reporter)
+ fillBatch(t, reporter)
+ select {
+ case <-entered:
+ case <-time.After(3 * time.Second):
+ t.Fatal("collector did not receive batch")
+ }
+ done := make(chan int, 1)
+ go func() {
+ accepted := 0
+ for i := 0; i < QueueCapacity+1; i++ {
+ if reporter.Record(Event{BoxID: "AbCdEf123456", Kind: TunnelConnection}) {
+ accepted++
+ }
+ }
+ done <- accepted
+ }()
+ select {
+ case accepted := <-done:
+ if accepted != QueueCapacity || reporter.Dropped() != 1 {
+ t.Fatalf("accepted=%d dropped=%d", accepted, reporter.Dropped())
+ }
+ case <-time.After(time.Second):
+ t.Fatal("producer waited for the blocked collector")
+ }
+}
+
+type notificationHandler struct{ failures chan slog.Record }
+
+func (h notificationHandler) Enabled(context.Context, slog.Level) bool { return true }
+func (h notificationHandler) Handle(_ context.Context, record slog.Record) error {
+ if record.Message == "Cloud feature usage delivery unconfirmed" {
+ h.failures <- record.Clone()
+ }
+ return nil
+}
+func (h notificationHandler) WithAttrs([]slog.Attr) slog.Handler { return h }
+func (h notificationHandler) WithGroup(string) slog.Handler { return h }
+
+func TestReporterRejectsRedirectsAndCountsUnconfirmedDelivery(t *testing.T) {
+ var redirected atomic.Int32
+ sink := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { redirected.Add(1); w.WriteHeader(202) }))
+ defer sink.Close()
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ http.Redirect(w, req, sink.URL+"/private-token", http.StatusTemporaryRedirect)
+ }))
+ defer server.Close()
+ failures := make(chan slog.Record, 1)
+ reporter, err := NewReporter(server.URL, "fixture-token", slog.New(notificationHandler{failures}))
+ if err != nil {
+ t.Fatal(err)
+ }
+ runReporter(t, reporter)
+ fillBatch(t, reporter)
+ select {
+ case record := <-failures:
+ if reporter.Unconfirmed() != BatchSize || redirected.Load() != 0 {
+ t.Fatal("delivery was retried or redirect followed")
+ }
+ record.Attrs(func(attr slog.Attr) bool {
+ if attr.Key == "error_type" && attr.Value.String() != "http_error" {
+ t.Errorf("unsafe error category: %v", attr)
+ }
+ return true
+ })
+ case <-time.After(3 * time.Second):
+ t.Fatal("delivery failure was not accounted")
+ }
+}
+
+func TestCancellationStopsBackgroundDelivery(t *testing.T) {
+ entered := make(chan struct{})
+ release := make(chan struct{})
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ _, _ = io.Copy(io.Discard, req.Body)
+ close(entered)
+ select {
+ case <-release:
+ case <-req.Context().Done():
+ }
+ }))
+ defer server.Close()
+ defer close(release)
+ reporter, err := NewReporter(server.URL, "fixture-token", quietLogger())
+ if err != nil {
+ t.Fatal(err)
+ }
+ cancel, done := runReporter(t, reporter)
+ fillBatch(t, reporter)
+ select {
+ case <-entered:
+ case <-time.After(3 * time.Second):
+ t.Fatal("collector did not receive batch")
+ }
+ cancel()
+ select {
+ case <-done:
+ if reporter.Record(Event{BoxID: "AbCdEf123456", Kind: SSH}) {
+ t.Fatal("stopped reporter accepted an event")
+ }
+ case <-time.After(time.Second):
+ t.Fatal("shutdown waited for collector")
+ }
+}
+
+func TestInvalidReportingConfigurationIsSafeToDisable(t *testing.T) {
+ for _, address := range []string{"file:///tmp/private", "http://user:private@collector", "http://collector/?private=value"} {
+ reporter, err := NewReporter(address, "fixture-token", quietLogger())
+ if reporter != nil || err == nil || err.Error() != "invalid feature usage reporting configuration" {
+ t.Fatal("invalid configuration was not sanitized")
+ }
+ if reporter.Record(Event{}) {
+ t.Fatal("disabled reporter accepted an event")
+ }
+ }
+}
diff --git a/apps/proxy/README.md b/apps/proxy/README.md
index 1da69f386..8c51d79b3 100644
--- a/apps/proxy/README.md
+++ b/apps/proxy/README.md
@@ -352,3 +352,12 @@ runs the proxy on port 4000 with the rest of the local stack.
- [`../libs/common-go/pkg/proxy/`](../libs/common-go/pkg/proxy/): shared reverse proxy and stream relay
- Runner side: [`network_tunnel.go`](../runner/pkg/api/controllers/network_tunnel.go) and
[`guest_port_tunnel.go`](../runner/pkg/boxlite/guest_port_tunnel.go)
+
+## Cloud feature usage
+
+After successful guest HTTP forwarding (2xx/3xx or 101), or an accepted CONNECT with a Runner connection,
+Proxy attempts a nonblocking local enqueue. A separate background worker batches observations using the
+existing API URL and Proxy token; no analytics request is awaited by forwarding. A full queue drops evidence.
+The reporter has its own HTTP transport, a two-second upload deadline and no retries or redirects.
+Invalid reporter configuration disables collection without stopping Proxy.
+See [collection and loss boundaries](../api/README.md#cloud-feature-use-evidence).
diff --git a/apps/proxy/pkg/proxy/feature_usage.go b/apps/proxy/pkg/proxy/feature_usage.go
new file mode 100644
index 000000000..2f0409764
--- /dev/null
+++ b/apps/proxy/pkg/proxy/feature_usage.go
@@ -0,0 +1,53 @@
+// Copyright 2026 BoxLite AI
+// SPDX-License-Identifier: AGPL-3.0
+
+package proxy
+
+import (
+ "context"
+ "log/slog"
+ "net/http"
+ "strings"
+
+ "github.com/boxlite-ai/common-go/pkg/featureusage"
+)
+
+func (p *Proxy) startFeatureUsage(ctx context.Context) {
+ if p.apiclient == nil {
+ return
+ }
+ config := p.apiclient.GetConfig()
+ if len(config.Servers) == 0 {
+ return
+ }
+ authorization := config.DefaultHeader["Authorization"]
+ if !strings.HasPrefix(authorization, "Bearer ") {
+ return
+ }
+ reporter, err := featureusage.NewReporter(config.Servers[0].URL, strings.TrimPrefix(authorization, "Bearer "), slog.Default())
+ if err != nil {
+ slog.Warn("Cloud feature usage reporting disabled", "error_type", "invalid_configuration")
+ return
+ }
+ p.featureUsage = reporter
+ go reporter.Run(ctx)
+}
+
+// Only the transport result is observed; no response body is read or delayed.
+type featureUsageTransport struct {
+ next http.RoundTripper
+ reporter *featureusage.Reporter
+ boxID string
+}
+
+func (t featureUsageTransport) RoundTrip(request *http.Request) (*http.Response, error) {
+ response, err := t.next.RoundTrip(request)
+ if err == nil && response != nil {
+ if response.StatusCode == http.StatusSwitchingProtocols {
+ t.reporter.Record(featureusage.Event{BoxID: t.boxID, Kind: featureusage.TunnelConnection})
+ } else if response.StatusCode >= 200 && response.StatusCode < 400 {
+ t.reporter.Record(featureusage.Event{BoxID: t.boxID, Kind: featureusage.TunnelRequest})
+ }
+ }
+ return response, err
+}
diff --git a/apps/proxy/pkg/proxy/feature_usage_test.go b/apps/proxy/pkg/proxy/feature_usage_test.go
new file mode 100644
index 000000000..d9a6c6ef7
--- /dev/null
+++ b/apps/proxy/pkg/proxy/feature_usage_test.go
@@ -0,0 +1,184 @@
+// Copyright 2026 BoxLite AI
+// SPDX-License-Identifier: AGPL-3.0
+
+package proxy
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/boxlite-ai/common-go/pkg/featureusage"
+)
+
+func usageReporter(t *testing.T, endpoint string) *featureusage.Reporter {
+ t.Helper()
+ reporter, err := featureusage.NewReporter(endpoint, "fixture-token", slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return reporter
+}
+
+func TestPreviewForwardsWhileUsageCollectorIsBlocked(t *testing.T) {
+ entered := make(chan []featureusage.Event, 1)
+ release := make(chan struct{})
+ collector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
+ var body struct {
+ Events []featureusage.Event `json:"events"`
+ }
+ if err := json.NewDecoder(request.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ entered <- body.Events
+ select {
+ case <-release:
+ case <-request.Context().Done():
+ }
+ w.WriteHeader(http.StatusAccepted)
+ }))
+ defer collector.Close()
+ defer close(release)
+ reporter := usageReporter(t, collector.URL)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go reporter.Run(ctx)
+ for i := 0; i < featureusage.BatchSize-1; i++ {
+ reporter.Record(featureusage.Event{BoxID: "OtherBox1234", Kind: featureusage.TunnelRequest})
+ }
+ runner := newFakeRunner(t)
+ runner.start()
+ api := newFakeAPI(t, runner, http.StatusNoContent)
+ proxy := newWakeTestProxy(t, runner, api)
+ proxy.featureUsage = reporter
+ type forwardedResult struct {
+ response previewResponse
+ err error
+ }
+ forwarded := make(chan forwardedResult, 1)
+ go func() { response, err := previewGetResult(proxy); forwarded <- forwardedResult{response, err} }()
+ var events []featureusage.Event
+ select {
+ case events = <-entered:
+ case <-time.After(3 * time.Second):
+ t.Fatal("usage collector was not reached")
+ }
+ select {
+ case result := <-forwarded:
+ if result.err != nil {
+ t.Fatal(result.err)
+ }
+ response := result.response
+ if response.Code != 200 || response.Body != "guest-ok" {
+ t.Fatalf("forwarding failed: %#v", response)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("forwarding waited for usage collector")
+ }
+ found := 0
+ for _, event := range events {
+ if event.BoxID == wakeTestBoxID {
+ found++
+ if event.Kind != featureusage.TunnelRequest || event.ID == "" || event.OccurredAt.IsZero() {
+ t.Fatalf("incorrect evidence: %#v", event)
+ }
+ }
+ }
+ if found != 1 {
+ t.Fatalf("usage events for forwarded request = %d", found)
+ }
+}
+
+type usageRoundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f usageRoundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
+ return f(request)
+}
+
+func TestUsageTransportCountsOnlySuccessfulUpstreamEvidence(t *testing.T) {
+ for _, status := range []int{101, 200, 302, 400, 500} {
+ t.Run(fmt.Sprint(status), func(t *testing.T) {
+ reporter := usageReporter(t, "http://collector.invalid")
+ response := &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader("body-unread"))}
+ transport := featureUsageTransport{next: usageRoundTripFunc(func(*http.Request) (*http.Response, error) { return response, nil }), reporter: reporter, boxID: wakeTestBoxID}
+ got, err := transport.RoundTrip(httptest.NewRequest("GET", "http://guest/", nil))
+ if got != response || err != nil {
+ t.Fatal("upstream response changed")
+ }
+ body, _ := io.ReadAll(got.Body)
+ if string(body) != "body-unread" {
+ t.Fatal("usage observer consumed response body")
+ }
+ for i := 0; i < featureusage.QueueCapacity; i++ {
+ reporter.Record(featureusage.Event{BoxID: "OtherBox1234", Kind: featureusage.TunnelRequest})
+ }
+ want := uint64(0)
+ if status == 101 || (status >= 200 && status < 400) {
+ want = 1
+ }
+ if reporter.Dropped() != want {
+ t.Fatalf("observed drops=%d want=%d", reporter.Dropped(), want)
+ }
+ })
+ }
+}
+
+func TestUsageTransportPreservesDialFailure(t *testing.T) {
+ failure := errors.New("private-upstream-error")
+ transport := featureUsageTransport{next: usageRoundTripFunc(func(*http.Request) (*http.Response, error) { return nil, failure })}
+ if response, err := transport.RoundTrip(httptest.NewRequest("GET", "http://guest/", nil)); response != nil || err != failure {
+ t.Fatal("dial failure changed")
+ }
+}
+
+func TestConnectStillStreamsWhenUsageQueueIsFull(t *testing.T) {
+ reporter := usageReporter(t, "http://collector.invalid")
+ for i := 0; i < featureusage.QueueCapacity; i++ {
+ reporter.Record(featureusage.Event{BoxID: "OtherBox1234", Kind: featureusage.TunnelRequest})
+ }
+ runner := newFakeRunner(t)
+ runner.start()
+ api := newFakeAPI(t, runner, http.StatusNoContent)
+ proxy := newWakeTestProxy(t, runner, api)
+ proxy.featureUsage = reporter
+ server := httptest.NewServer(http.HandlerFunc(proxy.handleTunnelConnect))
+ defer server.Close()
+ conn, err := net.Dial("tcp", server.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ conn.SetDeadline(time.Now().Add(3 * time.Second))
+ authority := "3000-d-416243644566313233343536.proxy.test"
+ fmt.Fprintf(conn, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", authority, authority)
+ reader := bufio.NewReader(conn)
+ response, err := http.ReadResponse(reader, &http.Request{Method: http.MethodConnect})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if response.StatusCode != 200 {
+ t.Fatalf("CONNECT status=%d", response.StatusCode)
+ }
+ fmt.Fprint(conn, "GET / HTTP/1.1\r\nHost: guest\r\nConnection: close\r\n\r\n")
+ response, err = http.ReadResponse(reader, &http.Request{Method: http.MethodGet})
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, err := io.ReadAll(response.Body)
+ if err != nil || string(body) != "guest-ok" {
+ t.Fatalf("stream body=%q error=%v", body, err)
+ }
+ if reporter.Dropped() != 1 {
+ t.Fatalf("connection evidence drop=%d", reporter.Dropped())
+ }
+}
diff --git a/apps/proxy/pkg/proxy/get_box_target.go b/apps/proxy/pkg/proxy/get_box_target.go
index 530eb965c..e4bfce4ff 100644
--- a/apps/proxy/pkg/proxy/get_box_target.go
+++ b/apps/proxy/pkg/proxy/get_box_target.go
@@ -158,10 +158,14 @@ func (p *Proxy) forwardToGuest(ctx *gin.Context, boxId string, targetPort uint16
go p.recordPreviewOpen(activityCtx, boxId)
}
return &common_proxy.RequestTarget{
- URL: target,
- Host: forwardedHost,
- Headers: headers,
- Transport: guestCookieTransport{next: p.guestPortTransport},
+ URL: target,
+ Host: forwardedHost,
+ Headers: headers,
+ Transport: featureUsageTransport{
+ next: guestCookieTransport{next: p.guestPortTransport},
+ reporter: p.featureUsage,
+ boxID: boxId,
+ },
ErrorHandler: func(writer http.ResponseWriter, _ *http.Request, err error) {
ctx.Error(guestDialFailure(writer.Header(), err))
},
diff --git a/apps/proxy/pkg/proxy/guest_wake_test.go b/apps/proxy/pkg/proxy/guest_wake_test.go
index c49046174..dd651a5e4 100644
--- a/apps/proxy/pkg/proxy/guest_wake_test.go
+++ b/apps/proxy/pkg/proxy/guest_wake_test.go
@@ -166,6 +166,14 @@ type previewResponse struct {
// previewGet sends one preview request through the proxy's real HTTP handler.
func previewGet(t *testing.T, proxy *Proxy) previewResponse {
t.Helper()
+ response, err := previewGetResult(proxy)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return response
+}
+
+func previewGetResult(proxy *Proxy) (previewResponse, error) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(common_errors.NewErrorMiddleware(func(_ *gin.Context, err error) common_errors.ErrorResponse {
@@ -180,19 +188,19 @@ func previewGet(t *testing.T, proxy *Proxy) previewResponse {
request, err := http.NewRequest(http.MethodGet, server.URL+"/", nil)
if err != nil {
- t.Fatal(err)
+ return previewResponse{}, err
}
request.Host = "3000-d-416243644566313233343536.proxy.test"
response, err := (&http.Client{Timeout: 30 * time.Second}).Do(request)
if err != nil {
- t.Fatal(err)
+ return previewResponse{}, err
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
- t.Fatal(err)
+ return previewResponse{}, err
}
- return previewResponse{Code: response.StatusCode, Header: response.Header, Body: string(body)}
+ return previewResponse{Code: response.StatusCode, Header: response.Header, Body: string(body)}, nil
}
func TestPreviewRequestWakesStoppedBoxAndWaitsForItsService(t *testing.T) {
diff --git a/apps/proxy/pkg/proxy/proxy.go b/apps/proxy/pkg/proxy/proxy.go
index 3abe2cde7..e6f8cb0c9 100644
--- a/apps/proxy/pkg/proxy/proxy.go
+++ b/apps/proxy/pkg/proxy/proxy.go
@@ -27,6 +27,7 @@ import (
common_cache "github.com/boxlite-ai/common-go/pkg/cache"
common_errors "github.com/boxlite-ai/common-go/pkg/errors"
+ "github.com/boxlite-ai/common-go/pkg/featureusage"
common_proxy "github.com/boxlite-ai/common-go/pkg/proxy"
)
@@ -74,6 +75,7 @@ type Proxy struct {
guestPortTransport *http.Transport
wakeGroup singleflight.Group
guestPortGroup singleflight.Group
+ featureUsage *featureusage.Reporter
// wakeDeadlines maps a box being woken to the end of its wake budget, so
// requests that arrive mid-wake join it.
wakeDeadlines sync.Map
@@ -85,6 +87,9 @@ func StartProxy(ctx context.Context, config *config.Config) error {
}
proxy.apiclient = config.ApiClient
+ usageContext, stopUsage := context.WithCancel(ctx)
+ defer stopUsage()
+ proxy.startFeatureUsage(usageContext)
proxy.guestPortTransport = proxy.newGuestPortTransport()
if config.Redis != nil {
diff --git a/apps/proxy/pkg/proxy/tunnel.go b/apps/proxy/pkg/proxy/tunnel.go
index fc2a9fe50..025698e4e 100644
--- a/apps/proxy/pkg/proxy/tunnel.go
+++ b/apps/proxy/pkg/proxy/tunnel.go
@@ -20,6 +20,7 @@ import (
"strings"
"time"
+ "github.com/boxlite-ai/common-go/pkg/featureusage"
common_proxy "github.com/boxlite-ai/common-go/pkg/proxy"
)
@@ -59,6 +60,7 @@ func (p *Proxy) handleTunnelConnect(writer http.ResponseWriter, request *http.Re
return
}
defer clientConn.Close()
+ p.featureUsage.Record(featureusage.Event{BoxID: boxID, Kind: featureusage.TunnelConnection})
if err := common_proxy.ProxyBidirectionalStream(request.Context(), clientConn, runnerConn); err != nil {
slog.WarnContext(request.Context(), "tunnel stream closed with error", "box", boxID, "port", port, "error", err)
diff --git a/apps/runner/README.md b/apps/runner/README.md
index a25336695..ae72d6e3c 100644
--- a/apps/runner/README.md
+++ b/apps/runner/README.md
@@ -43,6 +43,10 @@ Cloud stages deliver process settings through
---
+## SSH authentication evidence
+
+Runner builds set the Go build tag `boxlite_runner` to read accepted SSH sessions through a private native bridge. The collector polls running Cloud boxes and drains the Guest's bounded memory queue using the Runtime's existing session. Empty or stopped boxes stay stopped. Each observation contains only a stable event ID and timestamp.
+
## Regenerating the runner client
With Java 11 or newer available, run `make generate:runner-client` from the
@@ -195,17 +199,17 @@ Path prefix: `/boxes`. Every endpoint here is a thin controller that
calls into `r.Boxlite` (the Go SDK / Rust core). State transitions and
crash handling live in the runtime, not the runner.
-| Method | Path | Controller | Purpose |
-| --- | --- | --- | --- |
-| `POST` | `/boxes` | `Create` | Allocate box, pull/use artifact, return runtime version |
-| `POST` | `/boxes/:id/start` | `Start` | Boot a stopped box (optional auth token + metadata) |
-| `POST` | `/boxes/:id/stop` | `Stop` | Graceful or `force` shutdown |
-| `POST` | `/boxes/:id/destroy` | `Destroy` | Tear down completely |
-| `POST` | `/boxes/:id/recover` | `Recover` | Bring an `error` box back via a named strategy |
-| `POST` | `/boxes/:id/is-recoverable` | `IsRecoverable` | Static check against `common.IsRecoverable(reason)` |
+| Method | Path | Controller | Purpose |
+| ------ | ----------------------------- | ----------------------- | ---------------------------------------------------------------- |
+| `POST` | `/boxes` | `Create` | Allocate box, pull/use artifact, return runtime version |
+| `POST` | `/boxes/:id/start` | `Start` | Boot a stopped box (optional auth token + metadata) |
+| `POST` | `/boxes/:id/stop` | `Stop` | Graceful or `force` shutdown |
+| `POST` | `/boxes/:id/destroy` | `Destroy` | Tear down completely |
+| `POST` | `/boxes/:id/recover` | `Recover` | Bring an `error` box back via a named strategy |
+| `POST` | `/boxes/:id/is-recoverable` | `IsRecoverable` | Static check against `common.IsRecoverable(reason)` |
| `POST` | `/boxes/:id/network-settings` | `UpdateNetworkSettings` | Set the outbound policy (`outboundEnabled` / `outboundAllowNet`) |
-| `POST` | `/boxes/:id/backup` | `CreateBackup` | Kick off async backup; updates `BackupInfoCache` |
-| `GET` | `/boxes/:id` | `Info` | Combined state + backup state + runtime version |
+| `POST` | `/boxes/:id/backup` | `CreateBackup` | Kick off async backup; updates `BackupInfoCache` |
+| `GET` | `/boxes/:id` | `Info` | Combined state + backup state + runtime version |
`Create` and `Recover` take the outbound network policy as
`outboundEnabled` and an `outboundAllowNet` entry list. `outboundEnabled` is
@@ -234,16 +238,16 @@ sidecar**: the controller returns `202`, a goroutine runs the operation,
and the result is recorded in `ArtifactErrorCache` keyed by artifact ref
(or destination ref if pull is mirroring).
-| Method | Path | Controller | Purpose |
-| --- | --- | --- | --- |
-| `POST` | `/artifacts/pull` | `PullArtifact` | Mirror image; optional push to destination registry |
-| `POST` | `/artifacts/build` | `BuildArtifact` | Build from Dockerfile + context hashes |
-| `GET` | `/artifacts/exists` | `ArtifactExists` | Yes/no local cache check |
-| `GET` | `/artifacts/info` | `GetArtifactInfo` | Size, entrypoint, hash — `422` if error cached |
-| `POST` | `/artifacts/remove` | `RemoveArtifact` | Delete local image + clear error cache |
-| `POST` | `/artifacts/tag` | `TagImage` | Re-tag existing local image (deprecated) |
-| `POST` | `/artifacts/inspect` | `InspectArtifactInRegistry` | Remote digest + size lookup |
-| `GET` | `/artifacts/logs` | `GetBuildLogs` | Tail build log file; `follow=true` polls until image exists |
+| Method | Path | Controller | Purpose |
+| ------ | -------------------- | --------------------------- | ----------------------------------------------------------- |
+| `POST` | `/artifacts/pull` | `PullArtifact` | Mirror image; optional push to destination registry |
+| `POST` | `/artifacts/build` | `BuildArtifact` | Build from Dockerfile + context hashes |
+| `GET` | `/artifacts/exists` | `ArtifactExists` | Yes/no local cache check |
+| `GET` | `/artifacts/info` | `GetArtifactInfo` | Size, entrypoint, hash — `422` if error cached |
+| `POST` | `/artifacts/remove` | `RemoveArtifact` | Delete local image + clear error cache |
+| `POST` | `/artifacts/tag` | `TagImage` | Re-tag existing local image (deprecated) |
+| `POST` | `/artifacts/inspect` | `InspectArtifactInRegistry` | Remote digest + size lookup |
+| `GET` | `/artifacts/logs` | `GetBuildLogs` | Tail build log file; `follow=true` polls until image exists |
**Why a separate error cache.** Pull/build are decoupled from the
request, so clients can't see failures via the HTTP response. They poll
@@ -265,15 +269,15 @@ a long-lived bidirectional stdio channel between an SDK client and a
process inside a VM. The endpoints below split create / status / kill
(REST, idempotent) from stdio (`/attach` WebSocket, stateful).
-| Method | Path | Controller | Purpose |
-| --- | --- | --- | --- |
-| `POST` | `exec` | `BoxliteExec` | Create execution; returns `{execution_id}` |
-| `GET` | `executions` | `BoxliteListExecutions` | Live guest inventory, including main; never boots a stopped box |
-| `GET` | `executions/:id/attach` | `BoxliteExecAttach` | WebSocket upgrade; bidirectional stdio + control |
-| `GET` | `executions/:id` | `BoxliteGetExecution` | Status (`running` / `completed`, `exit_code` when done) |
-| `POST` | `executions/:id/signal` | `BoxliteExecSignal` | Send a cooperative signal (whitelist) |
-| `POST` | `executions/:id/resize` | `BoxliteExecResize` | Resize TTY (cols, rows) — TTY-only |
-| `DELETE` | `executions/:id` | `BoxliteExecKill` | Atomic kill + evict |
+| Method | Path | Controller | Purpose |
+| -------- | ----------------------- | ----------------------- | --------------------------------------------------------------- |
+| `POST` | `exec` | `BoxliteExec` | Create execution; returns `{execution_id}` |
+| `GET` | `executions` | `BoxliteListExecutions` | Live guest inventory, including main; never boots a stopped box |
+| `GET` | `executions/:id/attach` | `BoxliteExecAttach` | WebSocket upgrade; bidirectional stdio + control |
+| `GET` | `executions/:id` | `BoxliteGetExecution` | Status (`running` / `completed`, `exit_code` when done) |
+| `POST` | `executions/:id/signal` | `BoxliteExecSignal` | Send a cooperative signal (whitelist) |
+| `POST` | `executions/:id/resize` | `BoxliteExecResize` | Resize TTY (cols, rows) — TTY-only |
+| `DELETE` | `executions/:id` | `BoxliteExecKill` | Atomic kill + evict |
Inventory returns the guest's real `execution_id`, `argv`, `started_at` (Unix
milliseconds), `tty`, and `is_main_session`. Status, signal, resize, kill, and
@@ -430,7 +434,7 @@ Notable properties:
intermediary's idle timeout (CloudFront default 30 s, ALB 60 s,
Heroku 55 s).
- **The close is a handshake.** RFC 6455 §5.5.1 lets an endpoint drop the
- TCP connection only once a Close has been both sent *and received*, so
+ TCP connection only once a Close has been both sent _and received_, so
after its own the server waits for the client's — or for the client to
drop the socket — bounded at 5 s. Dropping it unilaterally strands any
intermediary still relaying the `101`, which an external load balancer
@@ -498,13 +502,13 @@ Completed recovered sessions still use the same retention period. All three
timers for manager-started executions are independently configurable via
environment variables.
-| Trigger | Action | Default | Env var |
-| --- | --- | --- | --- |
-| Age since `created` > cap | atomic kill + evict | 24 h | `BOXLITE_MAX_SESSION_LIFETIME` |
-| `Done` fired ≥ 5 min ago | evict (no signal) | 5 min | (not configurable) |
-| `!Connected` and idle > grace | SIGHUP | 5 min | `BOXLITE_RECONNECT_GRACE` |
-| After SIGHUP, idle > shutdown grace | SIGTERM | 30 s | `BOXLITE_SHUTDOWN_GRACE` |
-| After SIGTERM, idle > shutdown grace | SIGKILL + evict | 30 s | `BOXLITE_SHUTDOWN_GRACE` |
+| Trigger | Action | Default | Env var |
+| ------------------------------------ | ------------------- | ------- | ------------------------------ |
+| Age since `created` > cap | atomic kill + evict | 24 h | `BOXLITE_MAX_SESSION_LIFETIME` |
+| `Done` fired ≥ 5 min ago | evict (no signal) | 5 min | (not configurable) |
+| `!Connected` and idle > grace | SIGHUP | 5 min | `BOXLITE_RECONNECT_GRACE` |
+| After SIGHUP, idle > shutdown grace | SIGTERM | 30 s | `BOXLITE_SHUTDOWN_GRACE` |
+| After SIGTERM, idle > shutdown grace | SIGKILL + evict | 30 s | `BOXLITE_SHUTDOWN_GRACE` |
Reattaching inside the reconnect grace resets `SignaledHUP` and
`SignaledTERM` so a subsequent disconnect starts a fresh clock.
@@ -522,8 +526,8 @@ warning and falls through to `Kill()` immediately. Exercised in
`DELETE /executions/:id` instead; the signal endpoint _needs_ the
atomic kill+evict that DELETE provides.
-| Allowed | Rejected with 400 |
-| --- | --- |
+| Allowed | Rejected with 400 |
+| --------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| 1 (HUP), 2 (INT), 3 (QUIT), 6 (ABRT), 10 (USR1), 12 (USR2), 15 (TERM), 28 (WINCH) | 9 (KILL), 17/19/23 (STOP variants), 18 (CONT), anything else |
STOP/CONT are rejected because they bypass PTY line discipline (so a
@@ -561,11 +565,11 @@ durations, and network counters. All values come from
### 6. Runner info + Prometheus
-| Method | Path | Controller | Purpose |
-| --- | --- | --- | --- |
-| `GET` | `/` | `HealthCheck` | Liveness + version (public) |
-| `GET` | `/info` | `RunnerInfo` | Host metrics + service health + version |
-| `GET` | `/metrics` | promhttp | Prometheus scrape endpoint |
+| Method | Path | Controller | Purpose |
+| ------ | ---------- | ------------- | --------------------------------------- |
+| `GET` | `/` | `HealthCheck` | Liveness + version (public) |
+| `GET` | `/info` | `RunnerInfo` | Host metrics + service health + version |
+| `GET` | `/metrics` | promhttp | Prometheus scrape endpoint |
`/info` combines:
@@ -581,12 +585,12 @@ the counters maintained in `pkg/common/` (operation counts, etc.).
### 7. Guest SSH
-| Method | Path | Controller | Purpose |
-| --- | --- | --- | --- |
-| `POST` | `/v1/boxes/:boxId/ssh` | `BoxliteSSHConfigure` | Strict `SshConfig` parse → one `SSH().Configure` on a running box |
-| `POST` | `/v1/boxes/:boxId/ssh/enable` | `BoxliteSSHEnable` | Enable saved configuration on a running box; otherwise `409` |
-| `GET` | `/v1/boxes/:boxId/ssh` | `BoxliteSSHStatus` | `SshStatus`; stopped boxes answer disabled from persisted state |
-| `DELETE` | `/v1/boxes/:boxId/ssh` | `BoxliteSSHDisable` | Disable on a running box; otherwise `409`. Repeatable while running; never boots |
+| Method | Path | Controller | Purpose |
+| -------- | ----------------------------- | --------------------- | -------------------------------------------------------------------------------- |
+| `POST` | `/v1/boxes/:boxId/ssh` | `BoxliteSSHConfigure` | Strict `SshConfig` parse → one `SSH().Configure` on a running box |
+| `POST` | `/v1/boxes/:boxId/ssh/enable` | `BoxliteSSHEnable` | Enable saved configuration on a running box; otherwise `409` |
+| `GET` | `/v1/boxes/:boxId/ssh` | `BoxliteSSHStatus` | `SshStatus`; stopped boxes answer disabled from persisted state |
+| `DELETE` | `/v1/boxes/:boxId/ssh` | `BoxliteSSHDisable` | Disable on a running box; otherwise `409`. Repeatable while running; never boots |
- **Running-state checks.** Configure on a box observed as not running answers
`409 invalid_state`; the API resumes a box first when its policy allows. The
@@ -1124,42 +1128,42 @@ the API, which matches everything infra provisions today.
All routes are gated by `Bearer <BOXLITE_RUNNER_TOKEN>` except `/` and
the Swagger UI (development only).
-| Method | Path | Purpose |
-| --- | --- | --- |
-| `GET` | `/` | Health check (public) |
-| `GET` | `/info` | Runner metrics + service health |
-| `GET` | `/metrics` | Prometheus scrape |
-| `POST` | `/boxes` | Create box |
-| `GET` | `/boxes/:id` | Box info (state + backup state + runtime version) |
-| `POST` | `/boxes/:id/start` | Start |
-| `POST` | `/boxes/:id/stop` | Stop (graceful or `force`) |
-| `POST` | `/boxes/:id/destroy` | Destroy |
-| `POST` | `/boxes/:id/backup` | Async backup |
-| `POST` | `/boxes/:id/recover` | Recover from error state |
-| `POST` | `/boxes/:id/is-recoverable` | Check whether an error reason is recoverable |
-| `POST` | `/boxes/:id/network-settings` | Update the outbound policy |
-| `POST` | `/artifacts/pull` | Async pull (mirror + optional push) |
-| `POST` | `/artifacts/build` | Async build |
-| `GET` | `/artifacts/exists` | Local existence check |
-| `GET` | `/artifacts/info` | Image info; `422` if cached error |
-| `POST` | `/artifacts/remove` | Delete image + clear error cache |
-| `POST` | `/artifacts/tag` | Re-tag (deprecated) |
-| `POST` | `/artifacts/inspect` | Remote digest + size |
-| `GET` | `/artifacts/logs` | Stream build log (`follow=true` polls until image exists) |
-| `POST` | `/v1/boxes/:boxId/exec` | Create execution |
-| `GET` | `/v1/boxes/:boxId/executions` | Live guest inventory (including main), without booting |
-| `GET` | `/v1/boxes/:boxId/executions/:execId` | Execution status |
-| `DELETE` | `/v1/boxes/:boxId/executions/:execId` | Kill + evict |
-| `GET` | `/v1/boxes/:boxId/executions/:execId/attach` | WebSocket stdio + control |
-| `POST` | `/v1/boxes/:boxId/executions/:execId/signal` | Cooperative signal (whitelist) |
-| `POST` | `/v1/boxes/:boxId/executions/:execId/resize` | Resize TTY |
-| `PUT` | `/v1/boxes/:boxId/files?path=<dest>` | Upload tar |
-| `GET` | `/v1/boxes/:boxId/files?path=<src>` | Download tar |
-| `GET` | `/v1/boxes/:boxId/metrics` | Per-box metrics |
-| `POST` | `/v1/boxes/:boxId/ssh` | Configure guest SSH once; running boxes only |
-| `POST` | `/v1/boxes/:boxId/ssh/enable` | Enable saved guest SSH configuration on a running box; otherwise `409`; never boots |
-| `GET` | `/v1/boxes/:boxId/ssh` | Guest SSH status; never boots |
-| `DELETE` | `/v1/boxes/:boxId/ssh` | Disable guest SSH on a running box; otherwise `409`; never boots |
+| Method | Path | Purpose |
+| -------- | -------------------------------------------- | ----------------------------------------------------------------------------------- |
+| `GET` | `/` | Health check (public) |
+| `GET` | `/info` | Runner metrics + service health |
+| `GET` | `/metrics` | Prometheus scrape |
+| `POST` | `/boxes` | Create box |
+| `GET` | `/boxes/:id` | Box info (state + backup state + runtime version) |
+| `POST` | `/boxes/:id/start` | Start |
+| `POST` | `/boxes/:id/stop` | Stop (graceful or `force`) |
+| `POST` | `/boxes/:id/destroy` | Destroy |
+| `POST` | `/boxes/:id/backup` | Async backup |
+| `POST` | `/boxes/:id/recover` | Recover from error state |
+| `POST` | `/boxes/:id/is-recoverable` | Check whether an error reason is recoverable |
+| `POST` | `/boxes/:id/network-settings` | Update the outbound policy |
+| `POST` | `/artifacts/pull` | Async pull (mirror + optional push) |
+| `POST` | `/artifacts/build` | Async build |
+| `GET` | `/artifacts/exists` | Local existence check |
+| `GET` | `/artifacts/info` | Image info; `422` if cached error |
+| `POST` | `/artifacts/remove` | Delete image + clear error cache |
+| `POST` | `/artifacts/tag` | Re-tag (deprecated) |
+| `POST` | `/artifacts/inspect` | Remote digest + size |
+| `GET` | `/artifacts/logs` | Stream build log (`follow=true` polls until image exists) |
+| `POST` | `/v1/boxes/:boxId/exec` | Create execution |
+| `GET` | `/v1/boxes/:boxId/executions` | Live guest inventory (including main), without booting |
+| `GET` | `/v1/boxes/:boxId/executions/:execId` | Execution status |
+| `DELETE` | `/v1/boxes/:boxId/executions/:execId` | Kill + evict |
+| `GET` | `/v1/boxes/:boxId/executions/:execId/attach` | WebSocket stdio + control |
+| `POST` | `/v1/boxes/:boxId/executions/:execId/signal` | Cooperative signal (whitelist) |
+| `POST` | `/v1/boxes/:boxId/executions/:execId/resize` | Resize TTY |
+| `PUT` | `/v1/boxes/:boxId/files?path=<dest>` | Upload tar |
+| `GET` | `/v1/boxes/:boxId/files?path=<src>` | Download tar |
+| `GET` | `/v1/boxes/:boxId/metrics` | Per-box metrics |
+| `POST` | `/v1/boxes/:boxId/ssh` | Configure guest SSH once; running boxes only |
+| `POST` | `/v1/boxes/:boxId/ssh/enable` | Enable saved guest SSH configuration on a running box; otherwise `409`; never boots |
+| `GET` | `/v1/boxes/:boxId/ssh` | Guest SSH status; never boots |
+| `DELETE` | `/v1/boxes/:boxId/ssh` | Disable guest SSH on a running box; otherwise `409`; never boots |
---
@@ -1275,3 +1279,15 @@ Omission retains the one-core default; explicit zero, non-finite values, and exc
The HTTP and v2 job paths preserve the number through the Go SDK; recovery validates it before destroying the old Box.
Fractional Linux allocations use the Runtime's cgroup quota and rounded-up guest topology, with its existing best-effort membership behavior.
Upgrade all Runners and matching native libraries before enabling fractional creation in the API, including migration destinations.
+
+## Cloud feature usage
+
+Runner drains accepted SSH authentication evidence only from running Cloud Boxes, using an independent native handle per read.
+Its background collector polls every five seconds, reads at most 64 Boxes per round with four workers,
+and applies a one-second deadline to each read. Larger inventories rotate between rounds.
+No read starts a VM. Older Guests are skipped with a diagnostic; the local SDK never uploads analytics automatically.
+
+The shared reporter uses the existing API URL and Runner token. It enqueues locally without waiting,
+then sends batches over its own HTTP transport. Full queues drop observations; shutdown cancels collection
+before closing the native client. Invalid reporter configuration disables telemetry without stopping Runner.
+See [collection, loss boundaries and query semantics](../api/README.md#cloud-feature-use-evidence).
diff --git a/apps/runner/cmd/runner/main.go b/apps/runner/cmd/runner/main.go
index aeb74fcf9..b32675630 100644
--- a/apps/runner/cmd/runner/main.go
+++ b/apps/runner/cmd/runner/main.go
@@ -12,9 +12,11 @@ import (
"os/signal"
"path/filepath"
"strings"
+ "sync"
"syscall"
"time"
+ "github.com/boxlite-ai/common-go/pkg/featureusage"
"github.com/boxlite-ai/common-go/pkg/log"
"github.com/boxlite-ai/common-go/pkg/telemetry"
"github.com/boxlite-ai/runner/cmd/runner/config"
@@ -23,6 +25,7 @@ import (
"github.com/boxlite-ai/runner/internal/diskresize"
"github.com/boxlite-ai/runner/internal/memorymonitor"
"github.com/boxlite-ai/runner/internal/metrics"
+ "github.com/boxlite-ai/runner/internal/sshusage"
"github.com/boxlite-ai/runner/pkg/api"
"github.com/boxlite-ai/runner/pkg/backend"
blclient "github.com/boxlite-ai/runner/pkg/boxlite"
@@ -109,6 +112,9 @@ func run() int {
logger.Info("BoxLite runtime initialized")
+ stopSSHUsage := startSSHUsage(ctx, cfg, boxliteClient, logger)
+ defer stopSSHUsage()
+
boxService := services.NewBoxService(logger, boxliteClient)
boxSyncService := services.NewBoxSyncService(services.BoxSyncServiceConfig{
@@ -313,6 +319,34 @@ func run() int {
}
}
+// Stop both workers before the Runner closes the native BoxLite client.
+func startSSHUsage(ctx context.Context, cfg *config.Config, source sshusage.Source, logger *slog.Logger) func() {
+ if cfg.BoxliteApiUrl == "" || cfg.ApiToken == "" {
+ return func() {}
+ }
+ reporter, err := featureusage.NewReporter(cfg.BoxliteApiUrl, cfg.ApiToken, logger)
+ if err != nil {
+ logger.Warn("Cloud feature usage reporting disabled")
+ return func() {}
+ }
+
+ ctx, cancel := context.WithCancel(ctx)
+ var running sync.WaitGroup
+ running.Add(2)
+ go func() {
+ defer running.Done()
+ reporter.Run(ctx)
+ }()
+ go func() {
+ defer running.Done()
+ sshusage.New(source, reporter.Record, logger).Run(ctx)
+ }()
+ return func() {
+ cancel()
+ running.Wait()
+ }
+}
+
// buildBoxliteClientConfig keeps startup policy mapping separate from runtime
// construction, so configuration can be checked without starting the server.
func buildBoxliteClientConfig(cfg *config.Config, logger *slog.Logger) blclient.ClientConfig {
diff --git a/apps/runner/cmd/runner/ssh_usage_test.go b/apps/runner/cmd/runner/ssh_usage_test.go
new file mode 100644
index 000000000..b1d148022
--- /dev/null
+++ b/apps/runner/cmd/runner/ssh_usage_test.go
@@ -0,0 +1,62 @@
+// Copyright 2026 BoxLite AI
+// SPDX-License-Identifier: AGPL-3.0
+
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ boxlite "github.com/boxlite-ai/boxlite/sdks/go"
+ "github.com/boxlite-ai/common-go/pkg/featureusage"
+ "github.com/boxlite-ai/runner/cmd/runner/config"
+)
+
+type sshEvidence struct{}
+
+func (sshEvidence) ListInfo(context.Context) ([]boxlite.BoxInfo, error) {
+ return []boxlite.BoxInfo{{ID: "native", Name: "CloudBox1234", Running: true}}, nil
+}
+func (sshEvidence) TakeSSHUsage(context.Context, string) (*boxlite.SSHUsageBatch, error) {
+ return &boxlite.SSHUsageBatch{Events: []boxlite.SSHUsageEvent{{ID: "event-1", OccurredAtMS: 1234}}}, nil
+}
+
+func TestSSHUsageStartupDeliversEvidenceThroughReporter(t *testing.T) {
+ received := make(chan []featureusage.Event, 1)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != "/telemetry/feature-usage" || r.Header.Get("Authorization") != "Bearer test-token" {
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
+ }
+ var batch struct{ Events []featureusage.Event }
+ if err := json.NewDecoder(r.Body).Decode(&batch); err != nil {
+ t.Error(err)
+ }
+ w.WriteHeader(http.StatusNoContent)
+ received <- batch.Events
+ }))
+ defer server.Close()
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ stop := startSSHUsage(context.Background(), &config.Config{BoxliteApiUrl: server.URL, ApiToken: "test-token"}, sshEvidence{}, logger)
+ defer stop()
+ select {
+ case events := <-received:
+ if len(events) != 1 || events[0].ID != "event-1" || events[0].BoxID != "CloudBox1234" || events[0].Kind != featureusage.SSH || events[0].OccurredAt.UnixMilli() != 1234 {
+ t.Fatalf("reported events: %v", events)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("runner did not upload the SSH usage batch")
+ }
+}
+
+func TestSSHUsageStartupDisablesInvalidOrAbsentConfiguration(t *testing.T) {
+ for _, cfg := range []config.Config{{}, {BoxliteApiUrl: "invalid", ApiToken: "test-token"}} {
+ stop := startSSHUsage(context.Background(), &cfg, nil, slog.Default())
+ stop()
+ }
+}
diff --git a/apps/runner/internal/sshusage/collector.go b/apps/runner/internal/sshusage/collector.go
new file mode 100644
index 000000000..0f3cd99ea
--- /dev/null
+++ b/apps/runner/internal/sshusage/collector.go
@@ -0,0 +1,161 @@
+// Copyright 2026 BoxLite AI
+// SPDX-License-Identifier: AGPL-3.0
+
+// Package sshusage drains guest evidence exclusively from a background loop.
+package sshusage
+
+import (
+ "context"
+ "log/slog"
+ "math"
+ "sort"
+ "sync"
+ "time"
+
+ boxlite "github.com/boxlite-ai/boxlite/sdks/go"
+ "github.com/boxlite-ai/common-go/pkg/featureusage"
+)
+
+const (
+ pollInterval = 5 * time.Second
+ maxBoxes = 64
+ workers = 4
+)
+
+type Source interface {
+ ListInfo(context.Context) ([]boxlite.BoxInfo, error)
+ TakeSSHUsage(context.Context, string) (*boxlite.SSHUsageBatch, error)
+}
+
+type Collector struct {
+ source Source
+ record func(featureusage.Event) bool
+ logger *slog.Logger
+ cursor string
+ unavailable map[string]bool
+ drops map[string]uint64
+ listFailed bool
+}
+
+func New(source Source, record func(featureusage.Event) bool, logger *slog.Logger) *Collector {
+ return &Collector{source: source, record: record, logger: logger, unavailable: make(map[string]bool), drops: make(map[string]uint64)}
+}
+
+func (c *Collector) Run(ctx context.Context) {
+ timer := time.NewTicker(pollInterval)
+ defer timer.Stop()
+ for {
+ if ctx.Err() != nil {
+ return
+ }
+ c.poll(ctx)
+ select {
+ case <-ctx.Done():
+ return
+ case <-timer.C:
+ }
+ }
+}
+
+type observation struct {
+ box boxlite.BoxInfo
+ batch *boxlite.SSHUsageBatch
+ err error
+}
+
+func (c *Collector) poll(ctx context.Context) {
+ boxes, err := c.source.ListInfo(ctx)
+ if err != nil {
+ if !c.listFailed {
+ c.logger.WarnContext(ctx, "SSH usage listing unavailable")
+ }
+ c.listFailed = true
+ return
+ }
+ c.listFailed = false
+ active := boxes[:0]
+ present := make(map[string]bool)
+ for _, box := range boxes {
+ if box.Running && cloudBoxID(box.Name) {
+ active = append(active, box)
+ present[box.ID] = true
+ }
+ }
+ for id := range c.unavailable {
+ if !present[id] {
+ delete(c.unavailable, id)
+ }
+ }
+ for id := range c.drops {
+ if !present[id] {
+ delete(c.drops, id)
+ }
+ }
+ sort.Slice(active, func(i, j int) bool { return active[i].ID < active[j].ID })
+ if len(active) == 0 {
+ return
+ }
+ start := sort.Search(len(active), func(i int) bool { return active[i].ID > c.cursor })
+ if start == len(active) {
+ start = 0
+ }
+ count := min(len(active), maxBoxes)
+ jobs := make(chan boxlite.BoxInfo, count)
+ results := make(chan observation, count)
+ for i := 0; i < count; i++ {
+ jobs <- active[(start+i)%len(active)]
+ }
+ c.cursor = active[(start+count-1)%len(active)].ID
+ close(jobs)
+ var group sync.WaitGroup
+ for range min(workers, count) {
+ group.Add(1)
+ go func() {
+ defer group.Done()
+ for box := range jobs {
+ if ctx.Err() != nil {
+ return
+ }
+ callCtx, cancel := context.WithTimeout(ctx, time.Second)
+ batch, err := c.source.TakeSSHUsage(callCtx, box.ID)
+ cancel()
+ results <- observation{box: box, batch: batch, err: err}
+ }
+ }()
+ }
+ group.Wait()
+ close(results)
+ for result := range results {
+ id := result.box.ID
+ if result.err != nil || result.batch == nil {
+ if !c.unavailable[id] && ctx.Err() == nil {
+ c.logger.WarnContext(ctx, "SSH usage unavailable", "boxId", result.box.Name)
+ }
+ c.unavailable[id] = true
+ continue
+ }
+ delete(c.unavailable, id)
+ if result.batch.DroppedTotal != c.drops[id] {
+ c.logger.WarnContext(ctx, "Guest SSH usage buffer dropped observations", "boxId", result.box.Name, "droppedTotal", result.batch.DroppedTotal)
+ c.drops[id] = result.batch.DroppedTotal
+ }
+ for _, event := range result.batch.Events {
+ if event.OccurredAtMS > math.MaxInt64 {
+ continue
+ }
+ c.record(featureusage.Event{ID: event.ID, BoxID: result.box.Name, Kind: featureusage.SSH, OccurredAt: time.UnixMilli(int64(event.OccurredAtMS)).UTC()})
+ }
+ }
+}
+
+func cloudBoxID(value string) bool {
+ if len(value) != 12 {
+ return false
+ }
+ for _, char := range value {
+ if !(char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z' || char >= '0' && char <= '9') {
+ return false
+ }
+ }
+ return true
+}
diff --git a/apps/runner/internal/sshusage/collector_test.go b/apps/runner/internal/sshusage/collector_test.go
new file mode 100644
index 000000000..e765b57b4
--- /dev/null
+++ b/apps/runner/internal/sshusage/collector_test.go
@@ -0,0 +1,173 @@
+// Copyright 2026 BoxLite AI
+// SPDX-License-Identifier: AGPL-3.0
+package sshusage
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "math"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ boxlite "github.com/boxlite-ai/boxlite/sdks/go"
+ "github.com/boxlite-ai/common-go/pkg/featureusage"
+)
+
+type source struct {
+ listErr error
+ boxes []boxlite.BoxInfo
+ take func(context.Context, string) (*boxlite.SSHUsageBatch, error)
+}
+
+func (s source) ListInfo(context.Context) ([]boxlite.BoxInfo, error) {
+ return append([]boxlite.BoxInfo(nil), s.boxes...), s.listErr
+}
+func (s source) TakeSSHUsage(ctx context.Context, id string) (*boxlite.SSHUsageBatch, error) {
+ return s.take(ctx, id)
+}
+func logger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
+
+func TestPollPreservesGuestEvidenceAndCloudIdentity(t *testing.T) {
+ var calls []string
+ var got []featureusage.Event
+ timestamp := time.Now().Add(-time.Minute).Truncate(time.Millisecond)
+ c := New(source{
+ boxes: []boxlite.BoxInfo{{ID: "native-id", Name: "CloudBox1234", Running: true}, {ID: "stopped", Name: "Stopped12345"}, {ID: "local", Name: "local-box", Running: true}},
+ take: func(_ context.Context, id string) (*boxlite.SSHUsageBatch, error) {
+ calls = append(calls, id)
+ return &boxlite.SSHUsageBatch{Events: []boxlite.SSHUsageEvent{{ID: "source-uuid", OccurredAtMS: uint64(timestamp.UnixMilli())}}}, nil
+ },
+ }, func(event featureusage.Event) bool { got = append(got, event); return true }, logger())
+ c.poll(context.Background())
+ if len(calls) != 1 || calls[0] != "native-id" {
+ t.Fatalf("unexpected native reads: %v", calls)
+ }
+ if len(got) != 1 || got[0].BoxID != "CloudBox1234" || got[0].ID != "source-uuid" || got[0].Kind != featureusage.SSH || !got[0].OccurredAt.Equal(timestamp) {
+ t.Fatalf("source evidence changed: %#v", got)
+ }
+}
+
+func TestPollBoundsWorkersAndRotatesAcrossBoxes(t *testing.T) {
+ boxes := make([]boxlite.BoxInfo, 70)
+ for i := range boxes {
+ boxes[i] = boxlite.BoxInfo{ID: fmt.Sprintf("%03d", i), Name: fmt.Sprintf("Box%09d", i), Running: true}
+ }
+ var active, maxActive atomic.Int32
+ var mu sync.Mutex
+ seen := make(map[string]bool)
+ c := New(source{boxes: boxes, take: func(ctx context.Context, id string) (*boxlite.SSHUsageBatch, error) {
+ now := active.Add(1)
+ for {
+ old := maxActive.Load()
+ if now <= old || maxActive.CompareAndSwap(old, now) {
+ break
+ }
+ }
+ defer active.Add(-1)
+ time.Sleep(time.Millisecond)
+ mu.Lock()
+ seen[id] = true
+ mu.Unlock()
+ return &boxlite.SSHUsageBatch{}, nil
+ }}, func(featureusage.Event) bool { return false }, logger())
+ c.poll(context.Background())
+ if len(seen) != maxBoxes {
+ t.Fatalf("poll scanned %d boxes", len(seen))
+ }
+ c.poll(context.Background())
+ if len(seen) != len(boxes) || maxActive.Load() > workers {
+ t.Fatalf("seen=%d concurrency=%d", len(seen), maxActive.Load())
+ }
+}
+
+func TestPollDeadlineShutdownAndFailures(t *testing.T) {
+ entered := make(chan time.Duration, 1)
+ c := New(source{boxes: []boxlite.BoxInfo{{ID: "native", Name: "CloudBox1234", Running: true}}, take: func(ctx context.Context, _ string) (*boxlite.SSHUsageBatch, error) {
+ deadline, _ := ctx.Deadline()
+ entered <- time.Until(deadline)
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }}, func(featureusage.Event) bool { t.Error("failed read produced evidence"); return false }, logger())
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ done := make(chan struct{})
+ go func() { defer close(done); c.Run(ctx) }()
+ select {
+ case budget := <-entered:
+ if budget <= 0 || budget > time.Second {
+ t.Errorf("read budget=%v", budget)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("collector never started a read")
+ }
+ cancel()
+ select {
+ case <-done:
+ case <-time.After(time.Second):
+ t.Fatal("collector blocked shutdown")
+ }
+}
+
+func TestPollRecoversAfterInventoryAndGuestFailures(t *testing.T) {
+ var logs bytes.Buffer
+ var events []featureusage.Event
+ var batch *boxlite.SSHUsageBatch
+ src := &source{
+ listErr: errors.New("inventory offline"),
+ boxes: []boxlite.BoxInfo{
+ {ID: "native", Name: "CloudBox1234", Running: true},
+ {ID: "other", Name: "CloudBox123!", Running: true},
+ },
+ take: func(_ context.Context, id string) (*boxlite.SSHUsageBatch, error) {
+ if id != "native" {
+ t.Errorf("drained unexpected box %q", id)
+ }
+ return batch, nil
+ },
+ }
+ record := func(event featureusage.Event) bool {
+ events = append(events, event)
+ return true
+ }
+ c := New(src, record, slog.New(slog.NewTextHandler(&logs, nil)))
+ poll := func() { c.poll(context.Background()) }
+ poll()
+ poll()
+ src.listErr = nil
+ poll()
+ poll()
+ batch = &boxlite.SSHUsageBatch{DroppedTotal: 2, Events: []boxlite.SSHUsageEvent{
+ {ID: "invalid-time", OccurredAtMS: math.MaxUint64},
+ {ID: "accepted", OccurredAtMS: 1234},
+ }}
+ poll()
+ if len(events) != 1 || events[0].ID != "accepted" || events[0].OccurredAt.UnixMilli() != 1234 {
+ t.Fatalf("recovered observations: %v", events)
+ }
+ batch.Events = nil
+ poll()
+ batch = nil
+ poll()
+ src.boxes[0].Running = false
+ poll()
+ src.boxes[0].Running = true
+ poll()
+ batch = &boxlite.SSHUsageBatch{DroppedTotal: 2}
+ poll()
+ for message, want := range map[string]int{
+ "SSH usage listing unavailable": 1,
+ "SSH usage unavailable": 3,
+ "Guest SSH usage buffer dropped observations": 2,
+ } {
+ if got := strings.Count(logs.String(), message); got != want {
+ t.Errorf("%s: got %d warnings, want %d", message, got, want)
+ }
+ }
+}
diff --git a/apps/runner/packaging/dev-artifact.Dockerfile b/apps/runner/packaging/dev-artifact.Dockerfile
index dc679baf6..9359102b3 100644
--- a/apps/runner/packaging/dev-artifact.Dockerfile
+++ b/apps/runner/packaging/dev-artifact.Dockerfile
@@ -60,7 +60,7 @@ ARG VERSION_IDENTITY
RUN test -n "${BUILD_REF}" \
&& test -n "${VERSION}" \
&& test -n "${VERSION_IDENTITY}" \
- && CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -C apps \
+ && CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -C apps -tags boxlite_runner \
-ldflags "-X 'github.com/boxlite-ai/runner/internal.Version=${VERSION_IDENTITY}'" \
-o /tmp/boxlite-runner \
./runner/cmd/runner/ \
diff --git a/apps/runner/pkg/boxlite/client.go b/apps/runner/pkg/boxlite/client.go
index 64c96abc2..b273c0b0a 100644
--- a/apps/runner/pkg/boxlite/client.go
+++ b/apps/runner/pkg/boxlite/client.go
@@ -1026,6 +1026,17 @@ func (c *Client) ListInfo(ctx context.Context) ([]boxlite.BoxInfo, error) {
return c.listPublicBoxes(ctx)
}
+// TakeSSHUsage borrows its own native handle, so telemetry cannot evict or
+// close a business operation's cached handle. This read never boots the box.
+func (c *Client) TakeSSHUsage(ctx context.Context, nativeID string) (*boxlite.SSHUsageBatch, error) {
+ box, err := c.runtime.Get(ctx, nativeID)
+ if err != nil {
+ return nil, err
+ }
+ defer box.Close()
+ return box.SSH().RunnerTakeUsage(ctx)
+}
+
// GetBox retrieves a box handle from cache or fetches it from the runtime.
func (c *Client) GetBox(ctx context.Context, boxId string) (*boxlite.Box, error) {
return c.getOrFetchBox(ctx, boxId)
diff --git a/apps/runner/pkg/boxlite/ssh_test.go b/apps/runner/pkg/boxlite/ssh_test.go
index ad3dbdcca..eb2656cc3 100644
--- a/apps/runner/pkg/boxlite/ssh_test.go
+++ b/apps/runner/pkg/boxlite/ssh_test.go
@@ -11,6 +11,7 @@ import (
"fmt"
"io"
"net"
+ "net/http"
"os"
"os/exec"
"path/filepath"
@@ -24,6 +25,32 @@ import (
"github.com/boxlite-ai/runner/pkg/models/enums"
)
+func TestSSHUsageBorrowsAnIndependentHandle(t *testing.T) {
+ client := checkpointRESTClient(t, func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.Method == http.MethodGet && r.URL.Path == "/v1/boxes/native" {
+ _, _ = io.WriteString(w, checkpointWireBox("native", "CloudBox1234", "Running", "alpine"))
+ return
+ }
+ http.NotFound(w, r)
+ })
+ cached, err := client.GetBox(t.Context(), "native")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = client.TakeSSHUsage(t.Context(), "native")
+ var sdkErr *boxlite.Error
+ if !errors.As(err, &sdkErr) || sdkErr.Code != boxlite.ErrUnsupported {
+ t.Fatalf("native-only drain on REST: %v", err)
+ }
+ if _, err := cached.Info(t.Context()); err != nil {
+ t.Fatalf("usage drain invalidated the business handle: %v", err)
+ }
+ if _, err := client.TakeSSHUsage(t.Context(), "missing"); !boxlite.IsNotFound(err) {
+ t.Fatalf("missing native box: %v", err)
+ }
+}
+
const sshGuestPort = 2222
// newSSHTestBox creates a box through the runner client and waits for want.
diff --git a/apps/runner/project.json b/apps/runner/project.json
index 626345ebc..5297b3594 100644
--- a/apps/runner/project.json
+++ b/apps/runner/project.json
@@ -10,7 +10,7 @@
"options": {
"main": "{projectRoot}/cmd/runner/main.go",
"outputPath": "dist/apps/runner",
- "flags": ["-ldflags \"-X 'github.com/boxlite-ai/runner/internal.Version=$VERSION'\""]
+ "flags": ["-tags=boxlite_runner", "-ldflags \"-X 'github.com/boxlite-ai/runner/internal.Version=$VERSION'\""]
},
"dependsOn": ["check-version-env"],
"inputs": [
@@ -21,7 +21,7 @@
],
"configurations": {
"development": {
- "flags": ["-tags=boxlite_dev", "-ldflags \"-X 'github.com/boxlite-ai/runner/internal.Version=$VERSION'\""]
+ "flags": ["-tags=boxlite_dev,boxlite_runner", "-ldflags \"-X 'github.com/boxlite-ai/runner/internal.Version=$VERSION'\""]
}
}
},
@@ -34,7 +34,7 @@
"GOARCH": "amd64",
"GOOS": "linux"
},
- "flags": ["-ldflags \"-X 'github.com/boxlite-ai/runner/internal.Version=$VERSION'\""]
+ "flags": ["-tags=boxlite_runner", "-ldflags \"-X 'github.com/boxlite-ai/runner/internal.Version=$VERSION'\""]
},
"dependsOn": ["check-version-env"],
"inputs": [
@@ -48,7 +48,7 @@
"executor": "nx:run-commands",
"options": {
"cwd": ".",
- "command": "go run -tags boxlite_dev {projectRoot}/cmd/runner/main.go"
+ "command": "go run -tags boxlite_dev,boxlite_runner {projectRoot}/cmd/runner/main.go"
},
"configurations": {
"production": {}
@@ -64,7 +64,7 @@
"executor": "nx:run-commands",
"options": {
"cwd": "{projectRoot}",
- "command": "go test -tags boxlite_dev ./..."
+ "command": "go test -tags boxlite_dev,boxlite_runner ./..."
}
},
"lint": {
diff --git a/apps/shared/console-analytics.ts b/apps/shared/console-analytics.ts
new file mode 100644
index 000000000..47169516e
--- /dev/null
+++ b/apps/shared/console-analytics.ts
@@ -0,0 +1,54 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { RoutePath } from './console-routes'
+
+export const consolePages = Object.values(RoutePath).filter((page) => page.startsWith('/dashboard/'))
+export const consoleActions = [
+ 'confirm_plan_change',
+ 'connect_github',
+ 'connect_github_account',
+ 'connect_registry',
+ 'create_api_key',
+ 'create_box',
+ 'create_checkpoint',
+ 'create_custom_domain',
+ 'create_volume',
+ 'new_api_key',
+ 'new_box',
+ 'new_checkpoint',
+ 'new_custom_domain',
+ 'new_image_tag',
+ 'new_managed_domain',
+ 'new_registry',
+ 'new_volume',
+ 'pin_image_tag',
+ 'redeem_coupon',
+ 'request_managed_domain',
+ 'save_auto_top_up',
+ 'save_ci_limit',
+ 'select_plan',
+ 'top_up_wallet',
+ 'update_ci_connection',
+ 'update_registry',
+ 'verify_custom_domain',
+ 'view_billing_overview',
+ 'view_billing_plans',
+ 'view_billing_usage',
+ 'view_billing_wallet',
+ 'view_custom_domains',
+ 'view_managed_domains',
+]
+export const billingTabs = ['overview', 'plans', 'usage', 'wallet']
+export const consoleControls = ['a', 'button', 'menuitem', 'tab']
+export const analyticsNoticeVersion = 1
+
+export type AnalyticsPreference = { allowed: boolean | null; version: number; decidedAt: string | null }
+
+export type ConsoleInteraction = {
+ event: '$pageview' | 'console_control_click'
+ page: RoutePath
+ occurredAt: string
+ control?: string
+ destination?: RoutePath
+ action?: string
+ billingTab?: string
+}
diff --git a/apps/shared/console-routes.ts b/apps/shared/console-routes.ts
new file mode 100644
index 000000000..7291b0dac
--- /dev/null
+++ b/apps/shared/console-routes.ts
@@ -0,0 +1,79 @@
+/**
+ * Copyright 2025 Daytona Platforms Inc.
+ * Modified by BoxLite AI, 2025-2026
+ * SPDX-License-Identifier: AGPL-3.0
+ */
+
+/**
+ * Enum for all route paths in the application
+ * Use this for consistent route references across the app
+ */
+export enum RoutePath {
+ // Main routes
+ LANDING = '/',
+ LOGOUT = '/logout',
+ /** Shareable coupon link; see pages/Redeem.tsx. */
+ REDEEM = '/redeem',
+ DASHBOARD = '/dashboard',
+ DOCS = '/docs',
+ SLACK = '/slack',
+
+ // Dashboard sub-routes
+ KEYS = '/dashboard/keys',
+ BOXES = '/dashboard/boxes',
+ QUICKSTART = '/dashboard/quickstart',
+ WELCOME = '/dashboard/welcome',
+ BILLING = '/dashboard/billing',
+ PRICING = '/dashboard/pricing',
+ IMAGES = '/dashboard/images',
+ CI = '/dashboard/ci',
+ CI_CONNECTS = '/dashboard/ci/connects',
+
+ CHECKPOINTS = '/dashboard/checkpoints',
+ /** Registries live under Images, as they do in the API. The old top-level path redirects here. */
+ IMAGE_REGISTRIES = '/dashboard/images/registries',
+ REGISTRIES = '/dashboard/registries',
+ VOLUMES = '/dashboard/volumes',
+ DOMAINS = '/dashboard/domains',
+ LIMITS = '/dashboard/limits',
+ BILLING_SPENDING = '/dashboard/billing/spending',
+ /** Parent of BILLING_PLAN_CHANGE. Carries no id of its own, so it only redirects. */
+ BILLING_PLAN = '/dashboard/billing/plan',
+ /** Confirming a switch to `:planId`. Cancelling a subscription outright is not
+ * reachable here — it takes a null plan id, which this segment cannot carry. */
+ BILLING_PLAN_CHANGE = '/dashboard/billing/plan/:planId',
+ BILLING_WALLET = '/dashboard/billing/wallet',
+ MEMBERS = '/dashboard/members',
+ ROLES = '/dashboard/roles',
+ SETTINGS = '/dashboard/settings',
+ ONBOARDING = '/dashboard/onboarding',
+ AUDIT_LOGS = '/dashboard/audit-logs',
+ REGIONS = '/dashboard/regions',
+ RUNNERS = '/dashboard/runners',
+ EXPERIMENTAL = '/dashboard/experimental',
+
+ // User routes
+ USER_INVITATIONS = '/dashboard/user/invitations',
+
+ // Webhooks
+ WEBHOOKS = '/dashboard/webhooks',
+ WEBHOOK_ENDPOINT_DETAILS = '/dashboard/webhooks/:endpointId',
+ // Images
+ /** `:idOrRef` is a catalog id, or a curated image's short name — neither carries a slash. */
+ IMAGE_DETAILS = '/dashboard/images/:idOrRef',
+
+ // Boxes
+ BOX_DETAILS = '/dashboard/boxes/:boxId',
+ BOX_TERMINAL = '/dashboard/boxes/:boxId/terminal',
+
+ // Email verification
+ EMAIL_VERIFY = '/dashboard/organization/:organizationId/verify-email/:email/:token',
+}
+
+/**
+ * Returns only the path segment for dashboard sub-routes
+ * Useful for nested routes under the dashboard
+ */
+export const getRouteSubPath = (path: RoutePath): string => {
+ return path.replace('/dashboard/', '')
+}
diff --git a/apps/shared/project.json b/apps/shared/project.json
new file mode 100644
index 000000000..0758eac15
--- /dev/null
+++ b/apps/shared/project.json
@@ -0,0 +1,6 @@
+{
+ "name": "shared-contracts",
+ "$schema": "../node_modules/nx/schemas/project-schema.json",
+ "sourceRoot": "shared",
+ "projectType": "library"
+}
diff --git a/apps/shared/signup-attribution.ts b/apps/shared/signup-attribution.ts
new file mode 100644
index 000000000..b3cdf2fd8
--- /dev/null
+++ b/apps/shared/signup-attribution.ts
@@ -0,0 +1,22 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+
+export const signupSourceLifetimeMs = 24 * 60 * 60 * 1000
+export const campaignLabel = /^[a-z0-9][a-z0-9_-]{0,63}$/i
+export const sourceHostname = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/
+
+export function validSource(source: string, kind: SignupSource['kind']): boolean {
+ if (typeof source !== 'string') return false
+ if (kind === 'referrer') {
+ return sourceHostname.test(source) && source !== 'boxlite.ai' && !source.endsWith('.boxlite.ai')
+ }
+ return (kind === 'utm' || kind === 'ref') && campaignLabel.test(source)
+}
+
+export interface SignupSource {
+ source: string
+ kind: 'utm' | 'ref' | 'referrer'
+ enteredAt: string
+ medium?: string
+ campaign?: string
+ content?: string
+}
diff --git a/docs/contributing/architecture/platform/api.md b/docs/contributing/architecture/platform/api.md
index ba0cd8771..7234f6660 100644
--- a/docs/contributing/architecture/platform/api.md
+++ b/docs/contributing/architecture/platform/api.md
@@ -1612,7 +1612,7 @@ is unset; the same document carries PostHog's key and host to the browser.
| Box admission | [`commerce-box-limit.service.ts`](../../../../apps/api/src/boxlite-rest/commerce-box-limit.service.ts) | `billingApiUrl` | 2 server-side reads on Commerce: `GET /plan` and `GET /organization/{organizationId}/plan`, bearer `USAGE_EXPORT_TOKEN`, used by hosted CREATE BOX. |
| Usage export | [`api/src/usage/services`](../../../../apps/api/src/usage/services/), hand-written | `usageExport.url` | 2 routes on the same Commerce service, server-side: `POST /internal/usage-events` and `POST /internal/allocation-snapshot`, bearer `USAGE_EXPORT_TOKEN`, which must equal Commerce's `USAGE_INGEST_TOKEN`. |
| Internal state reads | [`box-billing-state.service.ts`](../../../../apps/api/src/box/services/box-billing-state.service.ts) | `usageExport.url` | `GET /internal/billing-states`, server-side bearer `USAGE_EXPORT_TOKEN`. |
-| PostHog | `posthog-js` in the dashboard; `posthog-node` in the API | `posthog.apiKey`, `posthog.host` | Browser product analytics; server-side `api_*` operation events from the global metrics interceptor, two `groupIdentify` calls, and feature-flag evaluation. |
+| PostHog | `posthog-js` in the dashboard; `posthog-node` in the API | `posthog.apiKey`, `posthog.host` | Browser analytics; legacy `api_*` captures; shared business and [Cloud readiness events](../../../../apps/api/README.md#cloud-readiness-metrics); organization grouping; feature flags. Shared events also reach OTLP. |
| Pylon | [`App.tsx`](../../../../apps/dashboard/src/App.tsx) widget, production builds only | `pylonAppId` | Outbound support-chat widget; it registers no route here. |
The analytics client is generated from
diff --git a/make/coverage.mk b/make/coverage.mk
index 3aff51c15..0234e596a 100644
--- a/make/coverage.mk
+++ b/make/coverage.mk
@@ -88,16 +88,18 @@ coverage\:vmm\:boot: _ensure-kvm _ensure-vmm-kernel $(VMM_BALLOON_INIT) $(VMM_DI
-p boxlite-vmm --lib --run-ignored only --test-threads=1 -E 'test(boot::tests::)'
@cargo llvm-cov report $(COVERAGE_REPORT_ARGS) --lcov --output-path target/coverage/lcov.info
+GO_SDK_COVERAGE_TAGS ?= boxlite_runner
+
# Go's reports include every package, including packages with no tests.
coverage\:go:
@$(MAKE) dev:go GO_CARGO_FEATURES="--features test-support"
@mkdir -p target/coverage
@rc=0; \
- (cd sdks/go && $(GO_DEV_ENV) go test -a -count=1 -tags $(GO_DEV_TAGS),boxlite_agent_test -covermode=atomic -coverpkg=./... \
+ (cd sdks/go && $(GO_DEV_ENV) go test -a -count=1 -tags $(GO_DEV_TAGS),boxlite_agent_test,$(GO_SDK_COVERAGE_TAGS) -covermode=atomic -coverpkg=./... \
-coverprofile="$(PROJECT_ROOT)/target/coverage/go-sdk.out" $(GOTEST_FILTER) ./...) || rc=$$?; \
(cd src/deps/libgvproxy-sys/gvproxy-bridge && go test -covermode=atomic -coverpkg=./... \
-coverprofile="$(PROJECT_ROOT)/target/coverage/gvproxy.out" $(GOTEST_FILTER) ./...) || rc=$$?; \
- (cd apps/runner && $(GO_DEV_ENV) GOFLAGS=-tags=$(GO_DEV_TAGS) go test -covermode=atomic -coverpkg=./... \
+ (cd apps/runner && $(GO_DEV_ENV) GOFLAGS=-tags=$(GO_DEV_TAGS),boxlite_runner go test -covermode=atomic -coverpkg=./... \
-coverprofile="$(PROJECT_ROOT)/target/coverage/runner.out" $(GOTEST_FILTER) ./...) || rc=$$?; \
(cd apps/image-service && go test -covermode=atomic -coverpkg=./... \
-coverprofile="$(PROJECT_ROOT)/target/coverage/image-service.out" $(GOTEST_FILTER) ./...) || rc=$$?; \
diff --git a/make/help.mk b/make/help.mk
index 4b21d21d5..bc1e350a6 100644
--- a/make/help.mk
+++ b/make/help.mk
@@ -103,7 +103,7 @@ help:
@echo " make test:integration:node - Run Node.js SDK integration tests (requires VM)"
@echo " make test:all:node - Run all Node.js SDK tests"
@echo " make test:unit:go - Run Go SDK unit tests"
- @echo " make test:integration:go - Run Go SDK archive round-trip test (requires VM, FILTER=<pattern>)"
+ @echo " make test:integration:go - Run Go SDK archive and SSH usage integration tests (requires virtualization, FILTER=<pattern>)"
@echo " make test:integration:go:agents - Compare Go, C and Rust OpenCode agent behavior (requires VM)"
@echo " make test:integration:go:agents:parity - Run Go equivalents of the Rust agent VM scenarios"
@echo " make test:integration:runner - Run runner native archive recovery tests (FILTER=<pattern>)"
@@ -121,6 +121,7 @@ help:
@echo " make test:apps:ci-listener - Run shared CI state contracts (optional local PostgreSQL)"
@echo " make test:apps:github-ci-runner - Run standalone Listener boundary tests"
+ @echo " make test:apps:feature-usage - Run shared feature reporter tests (FILTER=<pattern>)"
@echo " make test:apps:proxy - Run proxy unit tests (FILTER=<pattern>)"
@echo " make test:apps:secret-server - Run Secret Server Go tests with the race detector"
@echo " make test:apps:secret-server:credential-api - Test the pinned credential API with Secret Server"
diff --git a/make/quality.mk b/make/quality.mk
index 4d2c3a8cb..e455ddcb9 100644
--- a/make/quality.mk
+++ b/make/quality.mk
@@ -203,6 +203,7 @@ lint\:c:
done
fmt\:go:
+ @cd apps/libs/common-go && gofmt -w pkg/featureusage
@echo "🔧 Formatting Go code..."
@cd sdks/go && gofmt -w .
@cd src/deps/libgvproxy-sys/gvproxy-bridge && gofmt -w .
diff --git a/make/test.mk b/make/test.mk
index 5c07d3175..3d97c9b32 100644
--- a/make/test.mk
+++ b/make/test.mk
@@ -8,6 +8,7 @@ PHONY_TARGETS += test\:apps\:mbuild
PHONY_TARGETS += test\:apps\:proxy test\:apps\:dashboard
PHONY_TARGETS += test\:apps\:mdeploy test\:e2e\:drivers
PHONY_TARGETS += test\:apps\:ci-listener
+PHONY_TARGETS += test\:apps\:feature-usage
PHONY_TARGETS += _local-registry
PHONY_TARGETS += _guest-boot-probe
PHONY_TARGETS += test\:apps\:infra\:mdeploy test\:apps\:infra\:mstage
@@ -732,11 +733,11 @@ test\:unit\:go:
@$(MAKE) dev:go GO_CARGO_FEATURES="--features test-support"
@cd sdks/go && $(GO_DEV_ENV) go test -a -count=1 -tags $(GO_DEV_TAGS),boxlite_agent_test $(GOTEST_RACE) -v $(GOTEST_FILTER) ./...
-# Native Go archive import/export tests require a supported host.
-# Keep them in the VM-capable integration workflow, outside hosted unit coverage.
+# The native runtime constructor requires host virtualization for archive and SSH usage tests.
test\:integration\:go: dev\:go
- @echo "🧪 Running Go SDK archive integration test (requires VM)..."
- @cd sdks/go && go test -count=1 -tags=boxlite_dev,boxlite_integration -v $(GOTEST_FILTER) ./integration/archive
+ @echo "🧪 Running Go SDK archive and SSH usage integration tests..."
+ @cd sdks/go && $(GO_DEV_ENV) go test -count=1 -tags=$(GO_DEV_TAGS),boxlite_integration -v $(GOTEST_FILTER) ./integration/archive
+ @cd sdks/go && $(GO_DEV_ENV) go test -count=1 -tags=$(GO_DEV_TAGS),boxlite_runner,boxlite_integration -v $(if $(FILTER),$(GOTEST_FILTER),-run TestSSHUsage) .
# Go SDK full suite.
test\:all\:go:
@@ -812,11 +813,11 @@ test\:apps\:github-ci-runner: _ensure-apps-deps
test\:apps\:runner: dev\:go
@echo "🧪 Running runner Go tests..."
- @cd apps/runner && go test -tags boxlite_dev $(GOTEST_RACE) ./... $(GOTEST_FILTER)
+ @cd apps/runner && $(GO_DEV_ENV) go test -tags $(GO_DEV_TAGS),boxlite_runner $(GOTEST_RACE) ./... $(GOTEST_FILTER)
PHONY_TARGETS += test\:integration\:runner
test\:integration\:runner: dev\:go
- @cd apps/runner && go test -count=1 -tags boxlite_dev,boxlite_integration ./pkg/boxlite $(GOTEST_FILTER)
+ @cd apps/runner && $(GO_DEV_ENV) go test -count=1 -tags $(GO_DEV_TAGS),boxlite_runner,boxlite_integration ./pkg/boxlite $(GOTEST_FILTER)
test\:apps\:proxy:
@cd apps/proxy && go test ./... $(GOTEST_FILTER)
@@ -824,6 +825,8 @@ test\:apps\:proxy:
PHONY_TARGETS += test\:apps\:secret-server
test\:apps\:secret-server:
@cd apps/secret-server && GOWORK=off go test -race ./... $(GOTEST_FILTER)
+test\:apps\:feature-usage:
+ @cd apps/libs/common-go && go test ./pkg/featureusage $(GOTEST_FILTER)
PHONY_TARGETS += run\:apps\:secret-server
run\:apps\:secret-server:
diff --git a/sdks/c/README.md b/sdks/c/README.md
index 53b80353e..96831a74e 100644
--- a/sdks/c/README.md
+++ b/sdks/c/README.md
@@ -98,6 +98,7 @@ The C SDK provides two API styles:
- Advanced features (volumes, networking, etc.)
Both APIs support:
+
- ✅ Structured error handling (error codes + messages)
- ✅ OCI container images
- ✅ Hardware-accelerated VMs (KVM/Hypervisor.framework)
@@ -118,6 +119,7 @@ The existing `boxlite_options_add_secret()` remains ABI-compatible, but its
headerless secret is rejected at creation. Use the plural function above.
### Core Features
+
- **C-compatible FFI bindings** (`cdylib`, `staticlib`)
- **Auto-generated header file** (`include/boxlite.h`)
- **Structured error handling** - Error codes + detailed messages
@@ -126,6 +128,7 @@ headerless secret is rejected at creation. Use the plural function above.
- **Typed configuration** - Builder-style options and typed result structs
### Advanced Features
+
- **Box lifecycle management** - Create, start, stop, restart, remove
- **Persistent boxes** - Cross-process reattachment
- **Performance metrics** - Runtime and per-box statistics
@@ -139,11 +142,13 @@ headerless secret is rejected at creation. Use the plural function above.
### Prerequisites
**macOS:**
+
- Apple Silicon (ARM64) or Intel x86_64
- macOS 11.0+ (Big Sur or later)
- Xcode Command Line Tools
**Linux:**
+
- x86_64 or ARM64 architecture
- KVM support (check: `kvm-ok` or `lsmod | grep kvm`)
- GCC or Clang
@@ -464,12 +469,14 @@ void boxlite_simple_free(CBoxliteSimple* box);
```
#### When to Use Simple API
+
- ✅ Quick prototypes and scripts
- ✅ Single-box applications
- ✅ Buffered output is acceptable
- ✅ Standard resource limits (2 CPUs, 512 MB)
#### When to Use Native API Instead
+
- ❌ Need streaming output callbacks
- ❌ Custom volumes or networking
- ❌ Multi-box orchestration
@@ -961,16 +968,16 @@ For the full API reference with detailed parameter tables and code examples, see
The `examples/c/` directory contains 8 examples:
-| Example | Description |
-|---------|-------------|
-| `simple_api_demo.c` | Quick start with Simple API |
-| `execute.c` | Command execution with streaming output |
-| `shutdown.c` | Runtime shutdown with multiple boxes |
-| `01_lifecycle.c` | Complete box lifecycle (create/stop/restart/remove) |
-| `02_list_boxes.c` | Discovery, introspection, ID prefix lookup |
-| `03_streaming_output.c` | Real-time output handling with callbacks |
-| `04_error_handling.c` | Error codes, retry logic, graceful degradation |
-| `05_metrics.c` | Runtime and per-box metrics |
+| Example | Description |
+| ----------------------- | --------------------------------------------------- |
+| `simple_api_demo.c` | Quick start with Simple API |
+| `execute.c` | Command execution with streaming output |
+| `shutdown.c` | Runtime shutdown with multiple boxes |
+| `01_lifecycle.c` | Complete box lifecycle (create/stop/restart/remove) |
+| `02_list_boxes.c` | Discovery, introspection, ID prefix lookup |
+| `03_streaming_output.c` | Real-time output handling with callbacks |
+| `04_error_handling.c` | Error codes, retry logic, graceful degradation |
+| `05_metrics.c` | Runtime and per-box metrics |
### Building and Running Examples
@@ -1016,6 +1023,7 @@ make
### Common Patterns
**String output:**
+
```c
char* id = boxlite_box_id(box);
printf("ID: %s\n", id);
@@ -1023,6 +1031,7 @@ boxlite_free_string(id); // MUST free
```
**Error handling:**
+
```c
CBoxliteError error = {0};
BoxliteErrorCode code = boxlite_simple_new(..., &error);
@@ -1033,6 +1042,7 @@ if (code != Ok) {
```
**Execution results:**
+
```c
CBoxliteExecResult* result;
boxlite_simple_run(..., &result, &error);
@@ -1065,6 +1075,7 @@ leaks -atExit -- ./my_app
### Best Practices
**Safe: One runtime, multiple threads**
+
```c
CBoxliteRuntime* runtime = NULL;
CBoxliteError error = {0};
@@ -1086,6 +1097,7 @@ boxlite_options_free(opts2);
```
**Unsafe: Sharing box handle across threads**
+
```c
CBoxHandle* box = NULL;
boxlite_create_box(runtime, opts, &box, &error);
@@ -1098,6 +1110,7 @@ boxlite_execute(box, &cmd2, ...); // UNSAFE
```
**Safe: Per-thread boxes**
+
```c
void* thread_func(void* arg) {
CBoxliteRuntime* runtime = (CBoxliteRuntime*)arg;
@@ -1130,27 +1143,30 @@ Callbacks are invoked on the **calling thread**. Do not block in callbacks.
### Supported Platforms
-| Platform | Architecture | Status | Requirements |
-|----------|-------------|--------|--------------|
-| macOS | ARM64 (Apple Silicon) | ✅ Full support | macOS 11.0+, Hypervisor.framework |
-| macOS | x86_64 (Intel) | ❌ Not supported | N/A |
-| Linux | x86_64 | ✅ Full support | KVM enabled |
-| Linux | ARM64 (aarch64) | ✅ Full support | KVM enabled |
-| Windows | Any | ❌ Not supported | Use WSL2 |
+| Platform | Architecture | Status | Requirements |
+| -------- | --------------------- | ---------------- | --------------------------------- |
+| macOS | ARM64 (Apple Silicon) | ✅ Full support | macOS 11.0+, Hypervisor.framework |
+| macOS | x86_64 (Intel) | ❌ Not supported | N/A |
+| Linux | x86_64 | ✅ Full support | KVM enabled |
+| Linux | ARM64 (aarch64) | ✅ Full support | KVM enabled |
+| Windows | Any | ❌ Not supported | Use WSL2 |
### Platform-Specific Notes
**macOS:**
+
- Requires Hypervisor.framework (built-in on macOS 11.0+)
- Intel Macs are not supported
- Dylib search paths: use `install_name_tool` or `DYLD_LIBRARY_PATH`
**Linux:**
+
- Requires KVM kernel module: `sudo modprobe kvm kvm_intel` (or `kvm_amd`)
- Check support: `kvm-ok` or `lsmod | grep kvm`
- Library search paths: use `LD_LIBRARY_PATH` or `ldconfig`
**Windows:**
+
- Use WSL2 (Windows Subsystem for Linux 2)
- Follow Linux instructions inside WSL2
@@ -1161,6 +1177,7 @@ Callbacks are invoked on the **calling thread**. Do not block in callbacks.
### Unreleased
**Breaking Changes:**
+
- `boxlite_options_add_volume` is renamed `boxlite_options_add_bind_mount`, and
the new `boxlite_options_add_managed_volume` mounts a managed volume by its
server-assigned id or its name. The two mount origins are distinct: a host
@@ -1200,12 +1217,14 @@ Callbacks are invoked on the **calling thread**. Do not block in callbacks.
the upload and caps it at 512 MiB.
Before:
+
```c
boxlite_options_add_volume(opts, "/host/data", "/data", 0);
boxlite_volume_create(handle, on_created, user_data, &err);
```
After:
+
```c
/* host bind (local runtime) */
boxlite_options_add_bind_mount(opts, "/host/data", "/data", 0);
@@ -1217,22 +1236,26 @@ boxlite_volume_create(handle, NULL, on_created, user_data, &err); /* unnamed */
```
Before:
+
```c
boxlite_options_add_port(opts, 80, 8080); /* guest, host */
```
After:
+
```c
boxlite_options_add_port(opts, 8080, 80, BoxlitePortProtocolTcp, NULL); /* host, guest */
```
Before:
+
```c
CBoxInfo *info = NULL;
boxlite_box_info(box, &info, &error);
```
After:
+
```c
boxlite_box_info(box, on_info, user_data, &error);
while (!request_done) {
@@ -1241,6 +1264,7 @@ while (!request_done) {
```
Before:
+
```c
boxlite_copy_in_start(handle, "/dst", BoxliteCopySourceKindDir, copy_cb, user_data, &error);
int32_t kind;
@@ -1248,6 +1272,7 @@ CBoxCopyOutStream *out = boxlite_copy_out_start(handle, "/src", &kind, &error);
```
After:
+
```c
boxlite_copy_in_start(handle, "/dst", copy_cb, user_data, &error);
CBoxCopyOutStream *out = boxlite_copy_out_start(handle, "/src", &error);
@@ -1256,6 +1281,7 @@ CBoxCopyOutStream *out = boxlite_copy_out_start(handle, "/src", &error);
### From 0.1.x to 0.2.0
**Breaking Changes:**
+
- Simple API added (new feature, backward compatible)
- Error handling enhanced (new `CBoxliteError` struct, backward compatible with old API)
@@ -1266,6 +1292,7 @@ CBoxCopyOutStream *out = boxlite_copy_out_start(handle, "/src", &error);
**1. Simple use cases → Simple API**
Before (0.1.x):
+
```c
char* error = NULL;
CBoxliteRuntime* runtime = boxlite_runtime_new(NULL, &error);
@@ -1276,6 +1303,7 @@ boxlite_runtime_free(runtime);
```
After (0.2.0):
+
```c
CBoxliteSimple* box;
CBoxliteError error = {0};
@@ -1291,6 +1319,7 @@ boxlite_simple_free(box);
**2. Error handling → Structured errors**
Before:
+
```c
char* error = NULL;
if (!runtime) {
@@ -1300,6 +1329,7 @@ if (!runtime) {
```
After:
+
```c
CBoxliteError error = {0};
if (code != Ok) {
@@ -1324,6 +1354,7 @@ if (code != Ok) {
**Error:** `dyld: Library not loaded: @rpath/libboxlite.dylib`
**Solution:**
+
```bash
# macOS: Add RPATH to executable
install_name_tool -add_rpath /path/to/lib my_app
@@ -1337,6 +1368,7 @@ export LD_LIBRARY_PATH=/path/to/lib:$LD_LIBRARY_PATH
**Error:** `Failed to create box: Image error: ...`
**Solutions:**
+
1. Check internet connection (for image pull)
2. Verify image name: `"alpine:3.19"` (not `alpine:3.19` without quotes)
3. Check disk space: `df -h ~/.boxlite`
@@ -1347,6 +1379,7 @@ export LD_LIBRARY_PATH=/path/to/lib:$LD_LIBRARY_PATH
**Error:** `UnsupportedEngine` or `kvm: Permission denied`
**Solutions:**
+
```bash
# Check KVM support
kvm-ok
@@ -1368,11 +1401,13 @@ newgrp kvm
### Memory Leaks
**Run valgrind:**
+
```bash
valgrind --leak-check=full --show-leak-kinds=all ./my_app
```
**Common causes:**
+
- Not freeing strings: `boxlite_box_id()`
- Not freeing errors: `boxlite_error_free()`
- Not freeing results: `boxlite_result_free()` and typed list/info structs
@@ -1380,6 +1415,7 @@ valgrind --leak-check=full --show-leak-kinds=all ./my_app
### High Memory Usage
**Check box count:**
+
```c
CRuntimeMetrics metrics = {0};
CBoxliteError error = {0};
@@ -1388,6 +1424,7 @@ printf("Running boxes: %d\n", metrics.num_running_boxes);
```
**Reduce memory per box:**
+
```c
// Simple API: Can't configure (uses defaults)
// Use native API instead:
@@ -1399,11 +1436,13 @@ boxlite_options_set_memory(opts, 256);
### Command Hangs
**Possible causes:**
+
1. Command waiting for input (use non-interactive commands)
2. Large output without callback (output buffer full)
3. Deadlock in callback function
**Solutions:**
+
- Use streaming callback for large output
- Don't block in callbacks
- Set command timeout (future feature)
@@ -1436,12 +1475,14 @@ boxlite/src/runtime/
### Development
**Rebuilding Header:**
+
```bash
cargo build -p boxlite-c
# Outputs: sdks/c/include/boxlite.h
```
**Adding New Functions:**
+
1. Add implementation to the appropriate file in `sdks/c/src/`
2. Add the exported C symbol in the same domain module
3. Rebuild: `cargo build -p boxlite-c`
diff --git a/sdks/c/cbindgen.toml b/sdks/c/cbindgen.toml
index 818debbc3..91da38559 100644
--- a/sdks/c/cbindgen.toml
+++ b/sdks/c/cbindgen.toml
@@ -22,7 +22,7 @@ parse_deps = false
# the names must remain exported.
[export]
include = ["BoxliteDomainTargetType", "CAgentSendMode"]
-exclude = ["boxlite_go_drain_subscription", "sockaddr_storage", "boxlite_test_agents_new", "boxlite_test_agents_wait_pending", "boxlite_test_agents_wait_queue", "boxlite_test_agents_free_counts", "boxlite_test_agents_event_frees", "boxlite_test_agents_barrier", "boxlite_test_agents_install"]
+exclude = ["boxlite_internal_runner_ssh_take_usage", "CBoxSshUsageCb", "boxlite_go_drain_subscription", "sockaddr_storage", "boxlite_test_agents_new", "boxlite_test_agents_wait_pending", "boxlite_test_agents_wait_queue", "boxlite_test_agents_free_counts", "boxlite_test_agents_event_frees", "boxlite_test_agents_barrier", "boxlite_test_agents_install"]
[export.rename]
sockaddr_storage = "struct sockaddr_storage"
diff --git a/sdks/c/src/event_queue.rs b/sdks/c/src/event_queue.rs
index 084684a08..0e3aa4a6b 100644
--- a/sdks/c/src/event_queue.rs
+++ b/sdks/c/src/event_queue.rs
@@ -107,6 +107,10 @@ pub(crate) type CBoxGetOrCreateBoxFn =
/// Box export completion.
pub type CBoxExportCb = Option<extern "C" fn(*mut c_char, *mut crate::CBoxliteError, *mut c_void)>;
+/// Owns the usage JSON on success; release it with `boxlite_free_string`.
+pub type CBoxSshUsageCb =
+ Option<extern "C" fn(*mut c_char, *mut crate::CBoxliteError, *mut c_void)>;
+pub(crate) type CBoxSshUsageFn = extern "C" fn(*mut c_char, *mut crate::CBoxliteError, *mut c_void);
pub(crate) type CBoxExportFn = extern "C" fn(*mut c_char, *mut crate::CBoxliteError, *mut c_void);
/// Runtime import completion.
@@ -443,6 +447,11 @@ pub enum RuntimeEvent {
user_data: usize,
result: Result<CString, BoxliteError>,
},
+ SshUsage {
+ cb: CBoxSshUsageFn,
+ user_data: usize,
+ result: Result<CString, BoxliteError>,
+ },
RuntimeImport {
cb: CRuntimeImportFn,
user_data: usize,
diff --git a/sdks/c/src/runtime.rs b/sdks/c/src/runtime.rs
index ff95656c8..737b6d865 100644
--- a/sdks/c/src/runtime.rs
+++ b/sdks/c/src/runtime.rs
@@ -646,6 +646,11 @@ unsafe fn dispatch_event(event: RuntimeEvent) {
cb,
user_data,
result,
+ }
+ | RuntimeEvent::SshUsage {
+ cb,
+ user_data,
+ result,
} => dispatch_string_event(result, user_data, cb),
RuntimeEvent::RuntimeImport {
cb,
diff --git a/sdks/c/src/ssh.rs b/sdks/c/src/ssh.rs
index be652eda4..c5f1a377b 100644
--- a/sdks/c/src/ssh.rs
+++ b/sdks/c/src/ssh.rs
@@ -14,14 +14,62 @@ use boxlite::{SshConfig, SshStatus};
use crate::CBoxHandle;
use crate::error::{BoxliteErrorCode, FFIError, null_pointer_error, write_error};
use crate::event_queue::{
- CBoxSshConfigureCb, CBoxSshDisableCb, CBoxSshEnableCb, CBoxSshStatusCb, OwnedFfiPtr,
- RuntimeEvent, push_event,
+ CBoxSshConfigureCb, CBoxSshDisableCb, CBoxSshEnableCb, CBoxSshStatusCb, CBoxSshUsageCb,
+ OwnedFfiPtr, RuntimeEvent, push_event,
};
/// A rejected configure body reports this constant, mirroring the REST
/// handler: serde's message can quote the caller's key material.
const INVALID_CONFIG: &str = "invalid SSH configuration";
+/// Drain accepted SSH authentication evidence from an existing local guest.
+/// Never starts a box or sends analytics. The guest RPC has a one-second budget.
+/// REST runtimes and guests without this RPC report Unsupported asynchronously.
+///
+/// # Safety
+///
+/// `handle` must be a live box handle and `cb` must be non-null. The callback
+/// owns the returned JSON and must free it with `boxlite_free_string`.
+/// The error is borrowed during the callback. `user_data` and `cb` must remain
+/// valid until dispatch or queue disposal, as for `boxlite_box_ssh_status`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn boxlite_internal_runner_ssh_take_usage(
+ handle: *mut CBoxHandle,
+ cb: CBoxSshUsageCb,
+ user_data: *mut c_void,
+ out_error: *mut FFIError,
+) -> BoxliteErrorCode {
+ let cb = crate::unwrap_cb_or_return!(cb, out_error);
+ if handle.is_null() {
+ unsafe { write_error(out_error, null_pointer_error("handle")) };
+ return BoxliteErrorCode::InvalidArgument;
+ }
+ let handle = unsafe { &*handle };
+ let lite = handle.handle.clone();
+ let queue = handle.queue.clone();
+ let user_data = user_data as usize;
+ handle.tokio_rt.spawn(async move {
+ let result = lite.ssh().runner_take_usage().await.and_then(|batch| {
+ let json = serde_json::to_string(&batch).map_err(|_| {
+ boxlite::BoxliteError::Internal("SSH usage serialization failed".into())
+ })?;
+ CString::new(json).map_err(|_| {
+ boxlite::BoxliteError::Internal("SSH usage serialization failed".into())
+ })
+ });
+ push_event(
+ &queue,
+ RuntimeEvent::SshUsage {
+ cb,
+ user_data,
+ result,
+ },
+ )
+ .await;
+ });
+ BoxliteErrorCode::Ok
+}
+
/// Guest SSH listener state as observed by one call; carries no credentials.
///
/// The callback that receives it by pointer owns it, nested strings included,
diff --git a/sdks/c/src/tests/ssh.rs b/sdks/c/src/tests/ssh.rs
index fd7b77883..b444191b8 100644
--- a/sdks/c/src/tests/ssh.rs
+++ b/sdks/c/src/tests/ssh.rs
@@ -161,6 +161,37 @@ extern "C" fn record_status(status: *mut CSshStatus, error: *mut FFIError, user_
}
}
+extern "C" fn record_unsupported_usage(
+ json: *mut c_char,
+ error: *mut FFIError,
+ user_data: *mut c_void,
+) {
+ assert!(json.is_null());
+ unsafe {
+ let delivery = &mut *user_data.cast::<Delivery>();
+ delivery.code = Some((*error).code);
+ }
+}
+
+#[test]
+fn ssh_usage_on_rest_reports_unsupported_via_drain() {
+ let box_ = SshBox::on_rest_server(&[BOX_RUNNING]);
+ let delivery = box_.deliver(|user_data, error| unsafe {
+ boxlite_internal_runner_ssh_take_usage(
+ box_.box_handle,
+ Some(record_unsupported_usage),
+ user_data,
+ error,
+ )
+ });
+ assert_eq!(delivery.code, Some(BoxliteErrorCode::Unsupported));
+ assert_eq!(
+ box_.requests_received().len(),
+ 1,
+ "only the initial box lookup reaches REST"
+ );
+}
+
/// Drain until `ready` holds; panics with `what` after ~20s.
fn drain_until(runtime: *mut RuntimeHandle, what: &str, ready: impl Fn() -> bool) {
let mut error = FFIError::default();
@@ -651,6 +682,23 @@ fn null_pointers_and_callbacks_are_refused_before_queueing() {
unsafe { boxlite_box_ssh_status(ptr::null_mut(), None, ptr::null_mut(), &mut error) };
check("status: null callback", code, &error, "cb is null");
+ let mut error = FFIError::default();
+ let code = unsafe {
+ boxlite_internal_runner_ssh_take_usage(
+ ptr::null_mut(),
+ Some(record_unsupported_usage),
+ ptr::null_mut(),
+ &mut error,
+ )
+ };
+ check("usage: null handle", code, &error, "handle is null");
+
+ let mut error = FFIError::default();
+ let code = unsafe {
+ boxlite_internal_runner_ssh_take_usage(ptr::null_mut(), None, ptr::null_mut(), &mut error)
+ };
+ check("usage: null callback", code, &error, "cb is null");
+
let mut error = FFIError::default();
let code = unsafe {
boxlite_box_ssh_disable(
diff --git a/sdks/go/README.md b/sdks/go/README.md
index 6c4059c6d..3ab0554c8 100644
--- a/sdks/go/README.md
+++ b/sdks/go/README.md
@@ -269,15 +269,15 @@ if err != nil {
fmt.Println(pull.Reference, pull.ConfigDigest, pull.LayerCount)
```
-| Method | Local runtime | REST runtime |
-|--------|---------------|--------------|
-| `Pull` | Pulls into the cache | `ErrUnsupported`: creating a box pulls |
-| `List` | One row per cached reference | Catalog alias and digest references |
-| `Get` | The cache entries under the name | The catalog entry with its versions |
-| `Remove` | Forgets the name; layers stay | Removes the catalog entry; `ErrInvalidState` while a box can boot from it |
-| `Usage` | `ErrUnsupported` | `ImageUsage{Count, Limit, KnownBytes}` |
-| `CreateAlias` | `ErrUnsupported` | Creates a new alias; existing names conflict |
-| `DeleteAlias` | `ErrUnsupported` | Removes only the named alias |
+| Method | Local runtime | REST runtime |
+| ------------- | -------------------------------- | ------------------------------------------------------------------------- |
+| `Pull` | Pulls into the cache | `ErrUnsupported`: creating a box pulls |
+| `List` | One row per cached reference | Catalog alias and digest references |
+| `Get` | The cache entries under the name | The catalog entry with its versions |
+| `Remove` | Forgets the name; layers stay | Removes the catalog entry; `ErrInvalidState` while a box can boot from it |
+| `Usage` | `ErrUnsupported` | `ImageUsage{Count, Limit, KnownBytes}` |
+| `CreateAlias` | `ErrUnsupported` | Creates a new alias; existing names conflict |
+| `DeleteAlias` | `ErrUnsupported` | Removes only the named alias |
`Get` and `Remove` take an image name such as `"docker.io/library/alpine"`. A
reference with a tag or digest fails with `ErrInvalidArgument`, since a remove
@@ -330,10 +330,10 @@ if err := registries.Remove(ctx, login.ID); err != nil {
}
```
-| Method | Returns or fails with |
-|--------|-----------------------|
-| `List` | Every login, oldest first |
-| `Create` | The login; `ErrAlreadyExists` while one is held for the same registry and prefix |
+| Method | Returns or fails with |
+| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `List` | Every login, oldest first |
+| `Create` | The login; `ErrAlreadyExists` while one is held for the same registry and prefix |
| `Remove` | `ErrInvalidState` naming the boxes while one pulls through it; `ErrNotFound` for an unknown id; `ErrInvalidArgument` for an id that is not a UUID |
The password is sent once and never returned: `RegistryCredential` has no
diff --git a/sdks/go/bridge_callback.go b/sdks/go/bridge_callback.go
index 12bb399e0..173f159e4 100644
--- a/sdks/go/bridge_callback.go
+++ b/sdks/go/bridge_callback.go
@@ -112,22 +112,26 @@ func goBoxliteOnCreateBox(box *C.CBoxHandle, errPtr *C.CBoxliteError, userData u
//export goBoxliteOnBoxExport
func goBoxliteOnBoxExport(archivePath *C.char, errPtr *C.CBoxliteError, userData unsafe.Pointer) {
+ deliverOwnedString(archivePath, errPtr, userData)
+}
+
+func deliverOwnedString(value *C.char, errPtr *C.CBoxliteError, userData unsafe.Pointer) {
h := ptrToHandle(userData)
if h == 0 {
- freeBoxliteStringPayload(&archivePath)
+ freeBoxliteStringPayload(&value)
return
}
- if !claimOrFreePayload(h, &archivePath, freeBoxliteStringPayload) {
+ if !claimOrFreePayload(h, &value, freeBoxliteStringPayload) {
return
}
defer h.Delete()
ch, ok := h.Value().(chan handleResult[*C.char])
if !ok {
- freeBoxliteStringPayload(&archivePath)
+ freeBoxliteStringPayload(&value)
return
}
- ch <- handleResult[*C.char]{value: archivePath, err: errorFromCError(errPtr)}
+ ch <- handleResult[*C.char]{value: value, err: errorFromCError(errPtr)}
}
//export goBoxliteOnRuntimeImport
diff --git a/sdks/go/runner_ssh_usage.go b/sdks/go/runner_ssh_usage.go
new file mode 100644
index 000000000..6fa4e7416
--- /dev/null
+++ b/sdks/go/runner_ssh_usage.go
@@ -0,0 +1,94 @@
+//go:build boxlite_runner
+
+package boxlite
+
+/*
+#include "bridge.h"
+
+typedef void (*RunnerSSHUsageCallback)(char*, CBoxliteError*, void*);
+extern enum BoxliteErrorCode boxlite_internal_runner_ssh_take_usage(
+ CBoxHandle*, RunnerSSHUsageCallback, void*, CBoxliteError*);
+extern void goBoxliteOnSSHUsage(char*, CBoxliteError*, void*);
+static inline RunnerSSHUsageCallback cbSSHUsage(void) { return goBoxliteOnSSHUsage; }
+*/
+import "C"
+import (
+ "context"
+ "encoding/json"
+ "runtime/cgo"
+ "unsafe"
+)
+
+// SSHUsageEvent is one accepted authentication, without keys or login names.
+type SSHUsageEvent struct {
+ ID string `json:"id"`
+ OccurredAtMS uint64 `json:"occurred_at_ms"`
+}
+
+// SSHUsageBatch drains the guest's bounded, volatile evidence buffer.
+// DroppedTotal counts buffer overflow or contention since guest startup.
+type SSHUsageBatch struct {
+ Events []SSHUsageEvent `json:"events"`
+ DroppedTotal uint64 `json:"dropped_total"`
+}
+
+// RunnerTakeUsage reads and removes local guest evidence without starting the box.
+// Only an explicit caller reads it; the SDK never sends it to an analytics service.
+// A failed or canceled drain may lose evidence. REST runtimes and older guests
+// return ErrUnsupported; a stopped or configured local box returns an empty batch.
+func (s *SSH) RunnerTakeUsage(ctx context.Context) (*SSHUsageBatch, error) {
+ if s == nil || s.box == nil || s.box.runtime == nil {
+ return nil, errBoxClosed
+ }
+ rt := s.box.runtime
+ select {
+ case <-rt.closing:
+ return nil, ErrRuntimeClosed
+ default:
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ rt.ensureDrainRunning()
+ boxHandle, unlock, err := s.box.acquire()
+ if err != nil {
+ return nil, err
+ }
+ result := make(chan handleResult[*C.char], 1)
+ handle := registerHandleForDispatch(cgo.NewHandle(result))
+ var cerr C.CBoxliteError
+ code := C.boxlite_internal_runner_ssh_take_usage(boxHandle, C.cbSSHUsage(), handleToPtr(handle), &cerr)
+ unlock()
+ if code != C.Ok {
+ deleteHandleForDispatch(handle)
+ return nil, freeError(&cerr)
+ }
+ dispose := func(value *C.char) {
+ if value != nil {
+ freeBoxliteString(value)
+ }
+ }
+ select {
+ case completed := <-result:
+ defer dispose(completed.value)
+ if completed.err != nil {
+ return nil, completed.err
+ }
+ var batch SSHUsageBatch
+ if err := json.Unmarshal([]byte(cString(completed.value)), &batch); err != nil {
+ return nil, &Error{Code: ErrInternal, Message: "invalid SSH usage response"}
+ }
+ return &batch, nil
+ case <-ctx.Done():
+ abandonOwnedResult(result, handle, dispose)
+ return nil, ctx.Err()
+ case <-rt.closing:
+ abandonOwnedResult(result, handle, dispose)
+ return nil, ErrRuntimeClosed
+ }
+}
+
+//export goBoxliteOnSSHUsage
+func goBoxliteOnSSHUsage(json *C.char, errPtr *C.CBoxliteError, userData unsafe.Pointer) {
+ deliverOwnedString(json, errPtr, userData)
+}
diff --git a/sdks/go/ssh_usage_integration_test.go b/sdks/go/ssh_usage_integration_test.go
new file mode 100644
index 000000000..fa2065539
--- /dev/null
+++ b/sdks/go/ssh_usage_integration_test.go
@@ -0,0 +1,32 @@
+//go:build boxlite_runner && boxlite_dev && boxlite_integration
+
+package boxlite
+
+import (
+ "context"
+ "testing"
+)
+
+func TestSSHUsageConfiguredLocalBoxReturnsOwnedEmptyBatchWithoutBoot(t *testing.T) {
+ rt, err := NewRuntime(WithHomeDir(t.TempDir()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rt.Close()
+ box, err := rt.Create(context.Background(), "alpine:latest", WithName("usage-idle"), WithAutoRemove(false))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer box.Close()
+ batch, err := box.SSH().RunnerTakeUsage(context.Background())
+ if err != nil || batch == nil || len(batch.Events) != 0 || batch.DroppedTotal != 0 {
+ t.Fatalf("batch=%v err=%v", batch, err)
+ }
+ info, err := box.Info(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Running || info.PID != 0 {
+ t.Fatalf("usage observation booted the Box: %#v", info)
+ }
+}
diff --git a/sdks/go/ssh_usage_test.go b/sdks/go/ssh_usage_test.go
new file mode 100644
index 000000000..b56cbf952
--- /dev/null
+++ b/sdks/go/ssh_usage_test.go
@@ -0,0 +1,112 @@
+//go:build boxlite_runner && boxlite_dev
+
+package boxlite
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "testing"
+ "time"
+)
+
+func TestSSHUsageRESTIsUnsupportedWithoutHTTPRequest(t *testing.T) {
+ server := newSSHServer(t)
+ box := server.box(t)
+ batch, err := box.SSH().RunnerTakeUsage(context.Background())
+ var native *Error
+ if batch != nil || !errors.As(err, &native) || native.Code != ErrUnsupported {
+ t.Fatalf("batch=%v err=%v", batch, err)
+ }
+ if len(server.received()) != 0 {
+ t.Fatal("local evidence attempted a REST request")
+ }
+}
+
+func TestSSHUsageWaitsForHandleOwnership(t *testing.T) {
+ box := newSSHServer(t).box(t)
+ box.mu.Lock()
+ entered := make(chan struct{})
+ result := make(chan error, 1)
+ go func() {
+ close(entered)
+ _, err := box.SSH().RunnerTakeUsage(context.Background())
+ result <- err
+ }()
+ <-entered
+ select {
+ case err := <-result:
+ box.mu.Unlock()
+ t.Fatalf("usage completed while the handle was exclusively locked: %v", err)
+ case <-time.After(200 * time.Millisecond):
+ }
+ box.mu.Unlock()
+ var native *Error
+ if err := waitForSSH(t, result, "usage after releasing the lock"); !errors.As(err, &native) || native.Code != ErrUnsupported {
+ t.Fatalf("REST usage: %v", err)
+ }
+}
+
+func TestSSHUsageRejectsCanceledAndClosedHandles(t *testing.T) {
+ server := newSSHServer(t)
+ box := server.box(t)
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if _, err := box.SSH().RunnerTakeUsage(ctx); !errors.Is(err, context.Canceled) {
+ t.Fatal(err)
+ }
+ box.Close()
+ if _, err := box.SSH().RunnerTakeUsage(context.Background()); !IsInvalidState(err) {
+ t.Fatal(err)
+ }
+ var ssh *SSH
+ if _, err := ssh.RunnerTakeUsage(context.Background()); !IsInvalidState(err) {
+ t.Fatal(err)
+ }
+}
+
+// Signal when TakeUsage has submitted the native operation and selects a completion.
+type usageWaitContext struct {
+ context.Context
+ waiting chan struct{}
+ once sync.Once
+}
+
+func (ctx *usageWaitContext) Done() <-chan struct{} {
+ ctx.once.Do(func() { close(ctx.waiting) })
+ return ctx.Context.Done()
+}
+
+func TestSSHUsagePendingDrainObservesCancellationAndShutdown(t *testing.T) {
+ for _, shutdown := range []bool{false, true} {
+ name := "cancel"
+ if shutdown {
+ name = "runtime close"
+ }
+ t.Run(name, func(t *testing.T) {
+ box := newSSHServer(t).box(t)
+ box.runtime.stopDrain()
+ parent, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ ctx := &usageWaitContext{Context: parent, waiting: make(chan struct{})}
+ done := make(chan error, 1)
+ go func() { _, err := box.SSH().RunnerTakeUsage(ctx); done <- err }()
+ waitForSSH(t, ctx.waiting, "native submission")
+ want := context.Canceled
+ if shutdown {
+ if err := box.runtime.Close(); err != nil {
+ t.Fatal(err)
+ }
+ want = ErrRuntimeClosed
+ if _, err := box.SSH().RunnerTakeUsage(t.Context()); !errors.Is(err, ErrRuntimeClosed) {
+ t.Fatalf("already closed runtime: %v", err)
+ }
+ } else {
+ cancel()
+ }
+ if err := waitForSSH(t, done, "pending usage drain"); !errors.Is(err, want) {
+ t.Fatalf("pending drain: got %v, want %v", err, want)
+ }
+ })
+ }
+}
diff --git a/src/boxlite/src/lib.rs b/src/boxlite/src/lib.rs
index 0c5487375..13cca05a1 100644
--- a/src/boxlite/src/lib.rs
+++ b/src/boxlite/src/lib.rs
@@ -63,7 +63,9 @@ pub use litebox::{
MountHandle, MountInfo, MountRequest, MountState, SyncExecResult, collect_sync_execution,
validate_sync_exec,
};
-pub use litebox::{SshAccount, SshCaConfig, SshConfig, SshHandle, SshStatus};
+pub use litebox::{
+ SshAccount, SshCaConfig, SshConfig, SshHandle, SshStatus, SshUsageBatch, SshUsageEvent,
+};
pub use metrics::{BoxMetrics, RuntimeMetrics};
pub use runtime::advanced_options::{
AdvancedBoxOptions, ContainerCapabilities, HealthCheckOptions, NetworkRateLimit,
diff --git a/src/boxlite/src/litebox/box_impl.rs b/src/boxlite/src/litebox/box_impl.rs
index 6872e3888..25d144c38 100644
--- a/src/boxlite/src/litebox/box_impl.rs
+++ b/src/boxlite/src/litebox/box_impl.rs
@@ -1971,6 +1971,10 @@ impl crate::runtime::backend::BoxBackend for BoxImpl {
BoxImpl::ssh_status(self).await
}
+ async fn ssh_take_usage(&self) -> BoxliteResult<crate::SshUsageBatch> {
+ BoxImpl::ssh_take_usage(self).await
+ }
+
async fn ssh_disable(&self) -> BoxliteResult<SshStatus> {
BoxImpl::ssh_disable(self).await
}
diff --git a/src/boxlite/src/litebox/mod.rs b/src/boxlite/src/litebox/mod.rs
index 957518986..212cffd70 100644
--- a/src/boxlite/src/litebox/mod.rs
+++ b/src/boxlite/src/litebox/mod.rs
@@ -42,7 +42,9 @@ pub use network::{
};
pub use resize::ResizeOptions;
pub use snapshot::SnapshotHandle;
-pub use ssh::{SshAccount, SshCaConfig, SshConfig, SshHandle, SshStatus};
+pub use ssh::{
+ SshAccount, SshCaConfig, SshConfig, SshHandle, SshStatus, SshUsageBatch, SshUsageEvent,
+};
pub use state::{BoxResources, BoxState, BoxStatus, HealthState, HealthStatus};
pub(crate) use box_impl::SharedBoxImpl;
diff --git a/src/boxlite/src/litebox/ssh.rs b/src/boxlite/src/litebox/ssh.rs
index e630268ee..d6afd1996 100644
--- a/src/boxlite/src/litebox/ssh.rs
+++ b/src/boxlite/src/litebox/ssh.rs
@@ -10,6 +10,20 @@ use crate::runtime::backend::BoxBackend;
// Allow guest cleanup plus communication and scheduling overhead after startup.
const SSH_TIMEOUT: Duration = Duration::from_secs(DRAIN_TIMEOUT.as_secs() + 5);
+// Background collection must yield quickly to lifecycle changes.
+const SSH_USAGE_TIMEOUT: Duration = Duration::from_secs(1);
+
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SshUsageBatch {
+ pub events: Vec<SshUsageEvent>,
+ pub dropped_total: u64,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SshUsageEvent {
+ pub id: String,
+ pub occurred_at_ms: u64,
+}
enum StartupPolicy {
AllowStart,
@@ -131,6 +145,13 @@ impl fmt::Debug for SshHandle {
}
impl SshHandle {
+ /// Drain bounded local authentication evidence without starting a Box.
+ /// No network reporting is initiated; a Cloud collector owns delivery.
+ #[doc(hidden)]
+ pub async fn runner_take_usage(&self) -> BoxliteResult<SshUsageBatch> {
+ self.backend.ssh_take_usage().await
+ }
+
/// Retain the backend without starting it; the backend decides SSH support.
pub(super) fn new(backend: Arc<dyn BoxBackend>) -> Self {
Self { backend }
@@ -162,6 +183,40 @@ impl SshHandle {
/// Local SSH control policy; `BoxBackend` forwards to these verbatim.
impl BoxImpl {
+ pub(crate) async fn ssh_take_usage(&self) -> BoxliteResult<SshUsageBatch> {
+ if self.shutdown_token.is_cancelled() {
+ return Err(BoxliteError::Stopped(
+ "SSH usage: runtime is shutting down".into(),
+ ));
+ }
+ let Some(session) = self.existing_ssh_session()? else {
+ return Ok(SshUsageBatch::default());
+ };
+ tokio::select! {
+ biased;
+ _ = self.shutdown_token.cancelled() => Err(BoxliteError::Stopped("SSH usage: runtime is shutting down".into())),
+ result = tokio::time::timeout(SSH_USAGE_TIMEOUT, async {
+ let response = session.ssh().await?.take_usage().await.map_err(|status| {
+ if status.code() == tonic::Code::Unimplemented {
+ BoxliteError::Unsupported("SSH usage is unavailable on this guest".into())
+ } else {
+ map_tonic_err("usage", *status)
+ }
+ })?;
+ if response.events.len() > proto::ssh_usage::SSH_USAGE_CAPACITY ||
+ response.events.iter().any(|event| event.id.len() != 36 || uuid::Uuid::parse_str(&event.id).is_err() || event.occurred_at_ms > i64::MAX as u64) {
+ return Err(BoxliteError::Rpc("SSH usage: invalid observation batch".into()));
+ }
+ Ok(SshUsageBatch {
+ events: response.events.into_iter().map(|event| SshUsageEvent {
+ id: event.id, occurred_at_ms: event.occurred_at_ms,
+ }).collect(),
+ dropped_total: response.dropped_total,
+ })
+ }) => result.unwrap_or_else(|_| Err(BoxliteError::Rpc("SSH usage collection timed out".into()))),
+ }
+ }
+
pub(crate) async fn ssh_configure(&self, config: SshConfig) -> BoxliteResult<SshStatus> {
self.run_ssh(
"configure",
diff --git a/src/boxlite/src/litebox/ssh_tests.rs b/src/boxlite/src/litebox/ssh_tests.rs
index 7895aa8cd..797d9c251 100644
--- a/src/boxlite/src/litebox/ssh_tests.rs
+++ b/src/boxlite/src/litebox/ssh_tests.rs
@@ -14,6 +14,7 @@ use tonic::{Request, Response, Status};
#[derive(Default)]
struct Mock {
+ usage: Mutex<proto::SshUsageResponse>,
requests: Mutex<Vec<&'static str>>,
config: Mutex<Option<proto::SshConfig>>,
updates: Mutex<Vec<(Option<bool>, Option<proto::SshConfig>)>>,
@@ -59,6 +60,14 @@ struct MockService(Arc<Mock>);
#[tonic::async_trait]
impl proto::Ssh for MockService {
+ async fn take_usage(
+ &self,
+ _: Request<proto::SshUsageRequest>,
+ ) -> Result<Response<proto::SshUsageResponse>, Status> {
+ self.0.reply("usage").await?;
+ Ok(Response::new(self.0.usage.lock().unwrap().clone()))
+ }
+
/// Capture the decoded configuration so assertions cover the serialization boundary.
async fn control(
&self,
@@ -392,6 +401,12 @@ async fn ssh_observation_does_not_start_idle_boxes() {
f.backend.runtime.shutdown_token.child_token(),
));
let ssh = SshHandle::new(backend.clone());
+ let usage = ssh.runner_take_usage().await;
+ if matches!(status, BoxStatus::Configured | BoxStatus::Stopped) {
+ assert!(usage.unwrap().events.is_empty());
+ } else {
+ assert!(matches!(usage, Err(BoxliteError::InvalidState(_))));
+ }
for operation in [1, 2, 3] {
let result = operate(ssh.clone(), operation).await;
if operation == 1 && matches!(status, BoxStatus::Configured | BoxStatus::Stopped) {
@@ -425,6 +440,76 @@ async fn ssh_observation_does_not_start_idle_boxes() {
assert!(f.mock.requests.lock().unwrap().is_empty());
}
+/// Source metadata crosses the real portal RPC without modification.
+#[tokio::test]
+async fn ssh_usage_source_metadata_and_validation() {
+ let f = fixture().await;
+ let event = proto::SshUsageEvent {
+ id: uuid::Uuid::new_v4().to_string(),
+ occurred_at_ms: 1_800_000_000_123,
+ };
+ *f.mock.usage.lock().unwrap() = proto::SshUsageResponse {
+ events: vec![event.clone()],
+ dropped_total: 3,
+ };
+ let batch = f.ssh.runner_take_usage().await.unwrap();
+ assert_eq!(batch.events[0].id, event.id);
+ assert_eq!(batch.events[0].occurred_at_ms, event.occurred_at_ms);
+ assert_eq!(batch.dropped_total, 3);
+ for events in [
+ vec![event.clone(); proto::ssh_usage::SSH_USAGE_CAPACITY + 1],
+ vec![proto::SshUsageEvent {
+ id: "invalid".into(),
+ ..event.clone()
+ }],
+ vec![proto::SshUsageEvent {
+ occurred_at_ms: u64::MAX,
+ ..event.clone()
+ }],
+ ] {
+ f.mock.usage.lock().unwrap().events = events;
+ assert!(matches!(
+ f.ssh.runner_take_usage().await,
+ Err(BoxliteError::Rpc(_))
+ ));
+ }
+ *f.mock.error.lock().unwrap() = Some(tonic::Code::Unimplemented);
+ assert!(matches!(
+ f.ssh.runner_take_usage().await,
+ Err(BoxliteError::Unsupported(_))
+ ));
+}
+
+/// A blocked drain exits on its own budget or runtime shutdown without retry.
+#[tokio::test]
+async fn ssh_usage_timeout_and_shutdown() {
+ for cancel in [false, true] {
+ let f = fixture().await;
+ *f.mock.block.lock().unwrap() = true;
+ let ssh = f.ssh.clone();
+ let call = tokio::spawn(async move { ssh.runner_take_usage().await });
+ f.mock.entered.notified().await;
+ if cancel {
+ f.backend.shutdown_token.cancel();
+ } else {
+ tokio::time::pause();
+ tokio::time::advance(Duration::from_secs(1)).await;
+ }
+ let error = tokio::time::timeout(Duration::from_millis(100), call)
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap_err();
+ if cancel {
+ assert!(matches!(error, BoxliteError::Stopped(_)));
+ } else {
+ assert!(matches!(error, BoxliteError::Rpc(_)));
+ tokio::time::resume();
+ }
+ assert_eq!(*f.mock.requests.lock().unwrap(), vec!["usage"]);
+ }
+}
+
/// An attached or recovered VM serves SSH without initializing its main command.
#[tokio::test]
async fn ssh_observation_uses_existing_vm_without_container_start() {
diff --git a/src/boxlite/src/portal/connection/tests.rs b/src/boxlite/src/portal/connection/tests.rs
index c3fb0e2cd..4f2239941 100644
--- a/src/boxlite/src/portal/connection/tests.rs
+++ b/src/boxlite/src/portal/connection/tests.rs
@@ -10,6 +10,13 @@ struct Control;
#[tonic::async_trait]
impl Ssh for Control {
+ async fn take_usage(
+ &self,
+ _: Request<boxlite_shared::SshUsageRequest>,
+ ) -> Result<Response<boxlite_shared::SshUsageResponse>, Status> {
+ Ok(Response::new(boxlite_shared::SshUsageResponse::default()))
+ }
+
async fn control(
&self,
_: Request<SshControlRequest>,
diff --git a/src/boxlite/src/portal/interfaces/ssh.rs b/src/boxlite/src/portal/interfaces/ssh.rs
index 8e6b63fdd..6533ab72d 100644
--- a/src/boxlite/src/portal/interfaces/ssh.rs
+++ b/src/boxlite/src/portal/interfaces/ssh.rs
@@ -8,6 +8,17 @@ pub(crate) struct SshInterface {
}
impl SshInterface {
+ pub(crate) async fn take_usage(
+ &mut self,
+ ) -> Result<proto::SshUsageResponse, Box<tonic::Status>> {
+ Ok(self
+ .client
+ .take_usage(proto::SshUsageRequest {})
+ .await
+ .map_err(Box::new)?
+ .into_inner())
+ }
+
/// Reuse an established guest channel; connection setup belongs to the session.
pub(crate) fn new(channel: Channel) -> Self {
Self {
diff --git a/src/boxlite/src/runtime/backend.rs b/src/boxlite/src/runtime/backend.rs
index ada0e349b..206c17168 100644
--- a/src/boxlite/src/runtime/backend.rs
+++ b/src/boxlite/src/runtime/backend.rs
@@ -226,6 +226,12 @@ pub(crate) trait BoxBackend: Send + Sync + Any {
/// Read the guest's SSH state without starting the box.
async fn ssh_status(&self) -> BoxliteResult<SshStatus>;
+ async fn ssh_take_usage(&self) -> BoxliteResult<crate::SshUsageBatch> {
+ Err(BoxliteError::Unsupported(
+ "SSH usage requires a local runtime".into(),
+ ))
+ }
+
/// Stop the guest's SSH listener without starting the box.
async fn ssh_disable(&self) -> BoxliteResult<SshStatus>;
}
diff --git a/src/guest/src/service/ssh/control.rs b/src/guest/src/service/ssh/control.rs
index b22e575f9..16bf38a78 100644
--- a/src/guest/src/service/ssh/control.rs
+++ b/src/guest/src/service/ssh/control.rs
@@ -4,6 +4,13 @@ use tonic::{Request, Response, Status};
#[tonic::async_trait]
impl Ssh for GuestServer {
+ async fn take_usage(
+ &self,
+ _request: Request<boxlite_shared::SshUsageRequest>,
+ ) -> Result<Response<boxlite_shared::SshUsageResponse>, Status> {
+ Ok(Response::new(self.ssh_manager.take_usage()))
+ }
+
async fn control(
&self,
request: Request<SshControlRequest>,
diff --git a/src/guest/src/service/ssh/mod.rs b/src/guest/src/service/ssh/mod.rs
index d321c23b2..60b1c46d6 100644
--- a/src/guest/src/service/ssh/mod.rs
+++ b/src/guest/src/service/ssh/mod.rs
@@ -100,6 +100,7 @@ impl SshConfig {
/// Serializes control operations and retains timed-out cleanup until it finishes.
pub(crate) struct SshManager {
+ usage: boxlite_shared::ssh_usage::SshUsageBuffer,
guest: OnceLock<Weak<GuestServer>>,
state: Mutex<SshState>,
connection_permits: Arc<tokio::sync::Semaphore>,
@@ -122,6 +123,7 @@ use tests::ActivationGate;
impl Default for SshManager {
fn default() -> Self {
Self {
+ usage: boxlite_shared::ssh_usage::SshUsageBuffer::default(),
guest: OnceLock::new(),
state: Mutex::new(SshState::default()),
connection_permits: Arc::new(tokio::sync::Semaphore::new(limits::MAX_CONNECTIONS)),
@@ -130,6 +132,23 @@ impl Default for SshManager {
}
impl SshManager {
+ pub(crate) fn record_usage(&self) {
+ let occurred_at_ms = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis()
+ .try_into()
+ .unwrap_or(u64::MAX);
+ self.usage.try_record(boxlite_shared::SshUsageEvent {
+ id: uuid::Uuid::new_v4().to_string(),
+ occurred_at_ms,
+ });
+ }
+
+ pub(crate) fn take_usage(&self) -> boxlite_shared::SshUsageResponse {
+ self.usage.take()
+ }
+
pub(crate) fn guest(&self) -> Option<Arc<GuestServer>> {
self.guest.get().and_then(Weak::upgrade)
}
diff --git a/src/guest/src/service/ssh/server.rs b/src/guest/src/service/ssh/server.rs
index f09c4be28..7c5a3db52 100644
--- a/src/guest/src/service/ssh/server.rs
+++ b/src/guest/src/service/ssh/server.rs
@@ -80,6 +80,7 @@ impl SshConnection {
};
self.permissions = identity.permissions;
if let Some(authenticated) = self.authenticated.take() {
+ self.guest.ssh_manager.record_usage();
let _ = authenticated.send(());
}
Auth::Accept
@@ -844,6 +845,10 @@ mod tests {
raw.auth_publickey("root", ca.public_key()).await.unwrap(),
Auth::reject()
);
+ assert!(
+ guest.ssh_manager.take_usage().events.is_empty(),
+ "probes and denied identities are not usage"
+ );
assert_eq!(
raw.auth_publickey("root", user.public_key()).await.unwrap(),
Auth::Accept
@@ -851,6 +856,15 @@ mod tests {
assert!(raw.permissions.pty && raw.permissions.port_forwarding);
assert!(!raw.permissions.agent_forwarding && !raw.permissions.x11_forwarding);
assert_eq!(committed.try_recv(), Ok(()));
+ let usage = guest.ssh_manager.take_usage();
+ assert_eq!(usage.events.len(), 1);
+ assert!(uuid::Uuid::parse_str(&usage.events[0].id).is_ok());
+ assert!(usage.events[0].occurred_at_ms > 0);
+ raw.auth_publickey("root", user.public_key()).await.unwrap();
+ assert!(
+ guest.ssh_manager.take_usage().events.is_empty(),
+ "one observation per authenticated connection"
+ );
let (tx, mut committed) = oneshot::channel();
let mut certified = SshConnection::new(
@@ -876,10 +890,11 @@ mod tests {
assert!(certified.permissions.pty);
assert!(!certified.permissions.port_forwarding);
assert_eq!(committed.try_recv(), Ok(()));
+ assert_eq!(guest.ssh_manager.take_usage().events.len(), 1);
let (tx, mut committed) = oneshot::channel();
let mut cancelled = SshConnection::new(
- guest,
+ guest.clone(),
certified.authorizer.clone(),
tx,
Arc::new(super::super::TaskGroup::default()),
diff --git a/src/shared/proto/boxlite/v1/service.proto b/src/shared/proto/boxlite/v1/service.proto
index e6132167e..5502e7050 100644
--- a/src/shared/proto/boxlite/v1/service.proto
+++ b/src/shared/proto/boxlite/v1/service.proto
@@ -76,6 +76,18 @@ service Ssh {
// Apply supplied fields; absent fields retain their current desired values.
// With neither field supplied, query live status without initialization or writes.
rpc Control(SshControlRequest) returns (SshControlResponse);
+ // Drain bounded local authentication observations; never starts a Box.
+ rpc TakeUsage(SshUsageRequest) returns (SshUsageResponse);
+}
+
+message SshUsageRequest {}
+message SshUsageEvent {
+ string id = 1;
+ uint64 occurred_at_ms = 2;
+}
+message SshUsageResponse {
+ repeated SshUsageEvent events = 1;
+ uint64 dropped_total = 2;
}
// Command execution
diff --git a/src/shared/src/lib.rs b/src/shared/src/lib.rs
index e13055371..0b1b57250 100644
--- a/src/shared/src/lib.rs
+++ b/src/shared/src/lib.rs
@@ -30,6 +30,7 @@ pub type BoxByteStream =
pub mod constants;
pub mod errors;
pub mod layout;
+pub mod ssh_usage;
pub mod tar;
pub mod transport;
diff --git a/src/shared/src/ssh_usage.rs b/src/shared/src/ssh_usage.rs
new file mode 100644
index 000000000..330a39ac8
--- /dev/null
+++ b/src/shared/src/ssh_usage.rs
@@ -0,0 +1,96 @@
+//! Bounded local SSH evidence; producers never wait for the collector.
+
+use crate::{SshUsageEvent, SshUsageResponse};
+use std::collections::VecDeque;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::Mutex;
+
+pub const SSH_USAGE_CAPACITY: usize = 128;
+
+#[derive(Debug)]
+pub struct SshUsageBuffer {
+ events: Mutex<VecDeque<SshUsageEvent>>,
+ dropped: AtomicU64,
+}
+
+impl Default for SshUsageBuffer {
+ fn default() -> Self {
+ Self {
+ events: Mutex::new(VecDeque::with_capacity(SSH_USAGE_CAPACITY)),
+ dropped: AtomicU64::new(0),
+ }
+ }
+}
+
+impl SshUsageBuffer {
+ /// Full or contended buffers drop the observation rather than delaying SSH.
+ pub fn try_record(&self, event: SshUsageEvent) -> bool {
+ if let Ok(mut events) = self.events.try_lock() {
+ if events.len() < SSH_USAGE_CAPACITY {
+ events.push_back(event);
+ return true;
+ }
+ }
+ self.dropped.fetch_add(1, Ordering::Relaxed);
+ false
+ }
+
+ /// Called by a background collector; retains the allocated queue capacity.
+ pub fn take(&self) -> SshUsageResponse {
+ let mut events = self
+ .events
+ .lock()
+ .unwrap_or_else(|error| error.into_inner());
+ SshUsageResponse {
+ events: events.drain(..).collect(),
+ dropped_total: self.dropped.load(Ordering::Relaxed),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::{mpsc, Arc};
+ use std::time::Duration;
+
+ fn event(sequence: u64) -> SshUsageEvent {
+ SshUsageEvent {
+ id: sequence.to_string(),
+ occurred_at_ms: sequence,
+ }
+ }
+
+ #[test]
+ fn ssh_usage_capacity_drops_and_drain_preserves_source_order() {
+ let buffer = SshUsageBuffer::default();
+ for sequence in 0..SSH_USAGE_CAPACITY as u64 {
+ assert!(buffer.try_record(event(sequence)));
+ }
+ assert!(!buffer.try_record(event(999)));
+ let batch = buffer.take();
+ assert_eq!(batch.events.len(), SSH_USAGE_CAPACITY);
+ assert_eq!(batch.dropped_total, 1);
+ assert_eq!(batch.events[0].id, "0");
+ assert_eq!(
+ batch.events[SSH_USAGE_CAPACITY - 1].occurred_at_ms,
+ (SSH_USAGE_CAPACITY - 1) as u64
+ );
+ assert!(buffer.take().events.is_empty());
+ assert!(buffer.try_record(event(1000)));
+ }
+
+ #[test]
+ fn ssh_usage_contention_never_waits_for_the_consumer() {
+ let buffer = Arc::new(SshUsageBuffer::default());
+ let consumer = buffer.events.lock().unwrap();
+ let (sent, received) = mpsc::channel();
+ let producer = buffer.clone();
+ let task = std::thread::spawn(move || sent.send(producer.try_record(event(1))).unwrap());
+ let result = received.recv_timeout(Duration::from_secs(1));
+ drop(consumer);
+ task.join().unwrap();
+ assert!(!result.expect("producer waited for consumer"));
+ assert_eq!(buffer.take().dropped_total, 1);
+ }
+}