The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(api): make request replay a shared hosted API capability (#2760)
Vitus3ddf4a8880be
diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 449239e18..0279b8e6f 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -938,6 +938,8 @@ jobs:cache-dependency-path: "apps/yarn.lock"- name: Install app dependenciesrun: "yarn install --immutable"+ - name: Install isolated Redis test dependency+ run: sudo apt-get update && sudo apt-get install -y redis-server- name: Run API unit testsrun: "yarn nx run api:test --coverage --skip-nx-cache"- name: Run shared and standalone CI Listener testsdiff --git a/apps/api/README.md b/apps/api/README.mdindex 5cfba4b90..45f9527c6 100644--- a/apps/api/README.md+++ b/apps/api/README.md@@ -177,6 +177,94 @@ schema and drops it afterward; it skips without `DB_HOST`. Authentication guardsand enrichment dependencies are replaced in this harness, so it does not establishcredential-policy enforcement or deployed infrastructure behavior.+## Request idempotency and replay++Hosted `/api/v1` writes returning finite JSON or empty responses honour an optional+`Idempotency-Key` UUID header through `RequestReplayInterceptor`, after authentication,+organization membership, and resource permissions. New write routes are covered automatically;+controllers do not opt in or manage reservations. Requests without the header execute normally.+File transfers, WebSocket upgrades, and public or private tunnel preparation reject the header before+their operation begins. Organization invitations retain their separate transactional replay, including+their declared MCP `Idempotency-Key` input.++For example, retrying `POST /boxes` with the same key and input returns the original Box ID+and creation response even after quota fills or the Box changes state. Object key order is+ignored; target parameters, query values, arrays, types, explicit null, and absent bodies matter.+Equivalent organization-prefixed routes share identity after the prefix is authorized.++Hosted Box API errors expose `code` and `message` at the top level; local runtime errors+nest these fields under `error`. Both use the shared OpenAPI `ErrorResponse` definition.+The mismatch, pending, and unknown status/code pairs follow [E2B's idempotent creation contract](https://docs.e2b.dev/sandbox/idempotency).++| Condition | Response |+| --- | --- |+| Original success recorded | Original status, serialized bytes, Content-Type and Location |+| Invalid or duplicate key, or a keyed request body with a non-JSON content type | `400` |+| Same key with changed business input | `409 idempotency_request_mismatch` |+| Original owner still active | `409 idempotency_in_progress` |+| Outcome cannot be confirmed | `422 idempotency_outcome_unknown`; no redispatch |+| Reservation storage unavailable | `503 idempotency_storage_unavailable`; no dispatch |++Records expire 24 hours after first use. Heartbeats and retries preserve this absolute deadline.+Only trusted validation or proven pre-effect admission errors make the same key retryable.+Submitted work, downstream errors, disconnects, and unclassified exceptions retain the fence;+the original owner can still record a late success. Never automatically switch keys after unknown.+The response representation is limited to 1 MiB. Oversized responses and interrupted runner+responses retain unknown. Records store the response, request fingerprint, and trusted resource+metadata so audit entries for the original request and its replays identify the same resource.+Cookie, CORS, authentication, and tracking headers belong to the current request.++Replay uses a dedicated Redis connection with one-second connection and command deadlines,+and no offline command queue or command resend. It requires `maxmemory-policy=noeviction`,+which it checks with `INFO memory`. The ElastiCache and Memorystore stacks set this policy.++```mermaid+sequenceDiagram+ participant Client+ participant API+ participant Redis+ Client->>API: Send keyed write+ API->>Redis: Send claim with owner token+ API-->>Client: Deadline expires, 503 before dispatch+ API->>Redis: Queue cleanup on the same connection+ Note over Redis: Redis resumes and processes the claim before cleanup+ alt Token still owns a fresh reservation+ Redis->>Redis: Delete reservation+ else Token still owns a reclaimed reservation+ Redis->>Redis: Restore retryable state with original fingerprint and expiry+ else Owner differs or a response exists+ Note over Redis: Preserve the current record+ end+```++Capacity refusal rejects new keyed work before dispatch. Success delivery does not wait for+response persistence; a retry in that short window receives 409. Redis loss, expiration, or+manual deletion ends the guarantee. `GET /config` advertises `PT24H` and served operation IDs.+MCP forwards the same key and business input; wait options only control result observation.++Deployment must drain keyed writes, replace every API replica, then reopen traffic. A rollback+must retain the shared reader/fence or stop the affected writes; a version that ignores valid+keys cannot safely receive retries.++Run `make test:apps:api TEST_FILES='request-replay|volume-access.guard|image-admission.service|box.service.spec'`+with `REDIS_HOST/REDIS_PORT` for HTTP replay, Redis ownership, runner proxy, authorization and refund regressions.+The suite focuses on shared replay boundaries rather than repeating every business resource's persistence tests.+Missing Redis configuration skips integration tests and does not establish the contract.+The capacity test requires a local `redis-server` executable to start an isolated noeviction instance.+Install it before running the replay integration suite; a missing executable fails that test.++Cross-replica assertions wait for the exact record to become complete: receiving the owner's+HTTP success alone does not establish that Redis has stored it. Transport tests cover keyed file+rejection and WebSocket attachment before side effects; existing guard tests cover trusted resource ownership.+Storage fault regressions hold a real Redis reservation past the caller deadline and verify its release;+corrupt records, oversized responses and unsafe eviction policies retain the request fence or reject dispatch.+The concurrent HTTP test observes a renewed owner heartbeat before retrying on another replica.+Disconnect tests confirm that an unfinished owner remains fenced and can publish its late response;+failed outcome persistence also keeps retries from dispatching the business operation again.++A Box rejected at its creation limit refunds exactly one cold-pull charge to the window that paid it.+Refunds preserve the window's expiry; an expired ticket cannot debit a replacement window.+## Registration email policyWith protection enabled, new OIDC identities register through `POST /api/auth/register`,diff --git a/apps/api/src/audit/interceptors/audit.interceptor.ts b/apps/api/src/audit/interceptors/audit.interceptor.tsindex 01ca166d0..e398816ba 100644--- a/apps/api/src/audit/interceptors/audit.interceptor.ts+++ b/apps/api/src/audit/interceptors/audit.interceptor.ts@@ -116,7 +116,11 @@ export class AuditInterceptor implements NestInterceptor {const result = await firstValueFrom(next.handle())const organizationId = this.resolveOrganizationId(auditContext, request, result)- const targetId = this.resolveTargetId(auditContext, request, result)+ if (!request[AUDIT_TARGET_ID] && auditContext.targetIdFromResult && result) {+ const resultTargetId = this.normalizeTargetId(auditContext.targetIdFromResult(result))+ if (resultTargetId) request[AUDIT_TARGET_ID] = resultTargetId+ }+ const targetId = this.resolveTargetId(auditContext, request)const statusCode = response.statusCode || HttpStatus.NO_CONTENTif (!completeResponse) await this.recordHandlerSuccess(auditLog, organizationId, targetId, statusCode)@@ -215,16 +219,10 @@ export class AuditInterceptor implements NestInterceptor {/*** Resolves the identifier of the target resource from the initial request or the response object.*- * Prioritizes resolving the ID from the response object as the request may not include a unique resource identifier (e.g. delete box by name).+ * A resource ID resolved by the handler or its result takes precedence over the request target.*/- private resolveTargetId(auditContext: AuditContext, request: RequestWithUser, result?: any): string | null {+ private resolveTargetId(auditContext: AuditContext, request: RequestWithUser): string | null {if (request[AUDIT_TARGET_ID]) return request[AUDIT_TARGET_ID]- if (auditContext.targetIdFromResult && result) {- const targetId = this.normalizeTargetId(auditContext.targetIdFromResult(result))- if (targetId) {- return targetId- }- }if (auditContext.targetIdFromRequest) {const targetId = this.normalizeTargetId(auditContext.targetIdFromRequest(request))diff --git a/apps/api/src/box/errors/box-creation-limit.error.ts b/apps/api/src/box/errors/box-creation-limit.error.tsindex 371cb1cde..0f236436d 100644--- a/apps/api/src/box/errors/box-creation-limit.error.ts+++ b/apps/api/src/box/errors/box-creation-limit.error.ts@@ -4,6 +4,7 @@*/import { HttpException, HttpStatus } from '@nestjs/common'+import { noEffect } from '../../common/replay-no-effect'export const BOX_CREATION_LIMIT_EXCEEDED_CODE = 'resource_exhausted'export const BOX_CREATION_ADMISSION_UNAVAILABLE_CODE = 'upstream_unavailable'@@ -18,6 +19,7 @@ export class BoxCreationLimitExceededError extends HttpException {HttpStatus.TOO_MANY_REQUESTS,)this.name = 'BoxCreationLimitExceededError'+ noEffect(this)}}diff --git a/apps/api/src/box/guards/volume-access.guard.spec.ts b/apps/api/src/box/guards/volume-access.guard.spec.tsindex 08fc2bb82..b18a99f39 100644--- a/apps/api/src/box/guards/volume-access.guard.spec.ts+++ b/apps/api/src/box/guards/volume-access.guard.spec.ts@@ -2,6 +2,10 @@ import { ExecutionContext, NotFoundException } from '@nestjs/common'import { EntityNotFoundError } from 'typeorm'import { VolumeAccessGuard } from './volume-access.guard'import { VolumeService } from '../services/volume.service'+import { randomUUID } from 'node:crypto'+import { Request } from 'express'+import { BoxRequestReplayService, ReplayResponse } from '../../boxlite-rest/box-request-replay.service'+import { replayIdentity, REPLAY_ONLY, REPLAY_RESOURCE } from '../../boxlite-rest/request-replay-policy'describe('VolumeAccessGuard', () => {const volumeId = 'volume-1'@@ -83,4 +87,100 @@ describe('VolumeAccessGuard', () => {await expect(guard.canActivate(context)).rejects.toBeInstanceOf(NotFoundException)})++ function replayGuard(completed?: ReplayResponse, error: Error = new EntityNotFoundError('Volume', { id: volumeId })) {+ const key = randomUUID()+ const request = {+ method: 'DELETE',+ originalUrl: `/api/v1/volumes/${volumeId}`,+ path: `/api/v1/volumes/${volumeId}`,+ route: { path: '/api/v1/volumes/:volumeId' },+ params: { volumeId },+ query: {},+ headers: { 'idempotency-key': key },+ rawHeaders: ['Idempotency-Key', key],+ user: { organizationId: 'org-1', userId: 'user-1' },+ }+ const peekCompleted = jest.fn().mockResolvedValue(completed)+ const getOrganizationId = jest.fn().mockRejectedValue(error)+ const guard = new VolumeAccessGuard(+ { getOrganizationId } as unknown as VolumeService,+ { peekCompleted } as unknown as BoxRequestReplayService,+ )+ const context = { switchToHttp: () => ({ getRequest: () => request }) } as ExecutionContext+ return { guard, context, request, peekCompleted, getOrganizationId, key }+ }++ it('uses completed trusted ownership only for the exact current request', async () => {+ const completed = { status: 204, body: '', resource: { id: volumeId, organizationId: 'org-1' } }+ const { guard, context, request, peekCompleted, key } = replayGuard(completed)+ const identity = replayIdentity(request as unknown as Request)+ await expect(guard.canActivate(context)).resolves.toBe(true)+ expect(peekCompleted).toHaveBeenCalledWith('org-1', 'user-1', identity.operation, key, identity.fingerprint)+ expect(Reflect.get(request, REPLAY_ONLY)).toBe(true)+ expect(Reflect.get(request, REPLAY_RESOURCE)).toEqual(completed.resource)+ })++ it('never replays an absent volume without a key or through a read route', async () => {+ for (const keyed of [false, true]) {+ const { guard, context, request, peekCompleted } = replayGuard()+ if (!keyed) {+ request.headers = {} as typeof request.headers+ request.rawHeaders = []+ } else request.method = 'GET'+ await expect(guard.canActivate(context)).rejects.toBeInstanceOf(NotFoundException)+ expect(peekCompleted).not.toHaveBeenCalled()+ }+ })++ it('authorizes a named volume from current ownership rather than stored replay evidence', async () => {+ const { guard, context, request, peekCompleted, getOrganizationId } = replayGuard()+ const named = request as unknown as Request+ named.params = { name: 'named-volume' }+ getOrganizationId.mockResolvedValue('org-1')+ await expect(guard.canActivate(context)).resolves.toBe(true)+ expect(getOrganizationId).toHaveBeenCalledWith({ name: 'named-volume', organizationId: 'org-1' })+ expect(peekCompleted).not.toHaveBeenCalled()+ expect(Reflect.get(request, REPLAY_RESOURCE)).toBeUndefined()+ })++ it.each([+ undefined,+ { status: 204, body: '' },+ { status: 204, body: '', resource: { id: 'another-volume', organizationId: 'org-1' } },+ { status: 204, body: '', resource: { id: volumeId, organizationId: 'another-org' } },+ ])('denies absent or mismatched trusted ownership: %p', async (completed) => {+ const { guard, context, request } = replayGuard(completed)+ await expect(guard.canActivate(context)).rejects.toBeInstanceOf(NotFoundException)+ expect(Reflect.get(request, REPLAY_ONLY)).toBeUndefined()+ })++ it('does not consult replay storage for database failures', async () => {+ const { guard, context, peekCompleted } = replayGuard(+ { status: 204, body: '', resource: { id: volumeId, organizationId: 'org-1' } },+ new Error('database unavailable'),+ )+ await expect(guard.canActivate(context)).rejects.toBeInstanceOf(NotFoundException)+ expect(peekCompleted).not.toHaveBeenCalled()+ })++ it('records ownership only after the current resource belongs to the organization', async () => {+ const { guard, context, request, getOrganizationId, peekCompleted } = replayGuard()+ getOrganizationId.mockResolvedValueOnce('org-1')+ await expect(guard.canActivate(context)).resolves.toBe(true)+ expect(Reflect.get(request, REPLAY_RESOURCE)).toEqual({ id: volumeId, organizationId: 'org-1' })+ expect(peekCompleted).not.toHaveBeenCalled()+ })++ it('never replaces a cross-organization denial with completed evidence', async () => {+ const { guard, context, request, getOrganizationId, peekCompleted } = replayGuard({+ status: 204,+ body: '',+ resource: { id: volumeId, organizationId: 'org-1' },+ })+ getOrganizationId.mockResolvedValueOnce('another-org')+ await expect(guard.canActivate(context)).rejects.toBeInstanceOf(NotFoundException)+ expect(Reflect.get(request, REPLAY_RESOURCE)).toBeUndefined()+ expect(peekCompleted).not.toHaveBeenCalled()+ })})diff --git a/apps/api/src/box/guards/volume-access.guard.ts b/apps/api/src/box/guards/volume-access.guard.tsindex 505daae74..dcf5ae2ee 100644--- a/apps/api/src/box/guards/volume-access.guard.ts+++ b/apps/api/src/box/guards/volume-access.guard.ts@@ -3,34 +3,86 @@* Modified by BoxLite AI, 2025-2026* SPDX-License-Identifier: AGPL-3.0*/-import { Injectable, CanActivate, ExecutionContext, ForbiddenException, NotFoundException } from '@nestjs/common'+import {+ Injectable,+ CanActivate,+ ExecutionContext,+ ForbiddenException,+ NotFoundException,+ Optional,+} from '@nestjs/common'import { OrganizationAuthContext } from '../../common/interfaces/auth-context.interface'import { SystemRole } from '../../user/enums/system-role.enum'import { VolumeService } from '../services/volume.service'import { EntityNotFoundError } from 'typeorm'+import { Request } from 'express'+import { BoxRequestReplayService, ReplayResource } from '../../boxlite-rest/box-request-replay.service'+import {+ replayIdentity,+ replayPolicy,+ REPLAY_ONLY,+ REPLAY_RESOURCE,+ validateReplayKey,+} from '../../boxlite-rest/request-replay-policy'++type ReplayVolumeRequest = Request & {+ user?: OrganizationAuthContext+ [REPLAY_ONLY]?: boolean+ [REPLAY_RESOURCE]?: ReplayResource+}+@Injectable()export class VolumeAccessGuard implements CanActivate {- constructor(private readonly volumeService: VolumeService) {}+ constructor(+ private readonly volumeService: VolumeService,+ @Optional() private readonly requestReplay?: BoxRequestReplayService,+ ) {}async canActivate(context: ExecutionContext): Promise<boolean> {- const request = context.switchToHttp().getRequest()+ const request = context.switchToHttp().getRequest<ReplayVolumeRequest>()- const volumeId = request.params.volumeId || request.params.id- const volumeName = request.params.name+ const id = request.params.volumeId || request.params.id+ const volumeId = typeof id === 'string' ? id : undefined+ const volumeName = typeof request.params.name === 'string' ? request.params.name : undefinedif (!volumeId && !volumeName) {throw new NotFoundException(`Volume not found`)}- const authContext: OrganizationAuthContext = request.user+ const authContext = request.user as OrganizationAuthContexttry {- const params = volumeId ? { id: volumeId } : { name: volumeName, organizationId: authContext.organizationId }+ const params = volumeId+ ? { id: volumeId }+ : { name: volumeName ?? '', organizationId: authContext.organizationId }const volumeOrganizationId = await this.volumeService.getOrganizationId(params)if (authContext.role !== SystemRole.ADMIN && volumeOrganizationId !== authContext.organizationId) {throw new ForbiddenException('Request organization ID does not match resource organization ID')}+ if (volumeId) request[REPLAY_RESOURCE] = { id: volumeId, organizationId: volumeOrganizationId }} catch (error) {+ if (error instanceof EntityNotFoundError && this.requestReplay && volumeId) {+ const route = String(request.route?.path ?? request.path)+ const key = validateReplayKey(request)+ if (key && replayPolicy(request.method, route) === 'supported') {+ const { operation, fingerprint } = replayIdentity(request)+ const completed = await this.requestReplay.peekCompleted(+ authContext.organizationId,+ authContext.userId,+ operation,+ key,+ fingerprint,+ )+ if (+ completed?.resource?.id === volumeId &&+ completed.resource.organizationId === authContext.organizationId+ ) {+ request[REPLAY_ONLY] = true+ request[REPLAY_RESOURCE] = completed.resource+ return true+ }+ }+ }if (request.method === 'DELETE' && request.query?.force === 'true' && error instanceof EntityNotFoundError) {return true}diff --git a/apps/api/src/box/services/box.service.spec.ts b/apps/api/src/box/services/box.service.spec.tsindex bec3839f3..43f831a86 100644--- a/apps/api/src/box/services/box.service.spec.ts+++ b/apps/api/src/box/services/box.service.spec.ts@@ -10,6 +10,7 @@ import { BoxState } from '../enums/box-state.enum'import { BoxDesiredState } from '../enums/box-desired-state.enum'import { RunnerState } from '../enums/runner-state.enum'import { BadRequestError } from '../../exceptions/bad-request.exception'+import { BoxCreationLimitExceededError } from '../errors/box-creation-limit.error'import { BoxEvents } from '../constants/box-events.constants'import Redis from 'ioredis'import { Repository } from 'typeorm'@@ -22,6 +23,8 @@ import { CreateBoxDto as RestCreateBoxDto } from '../../boxlite-rest/dto/create-import { createBoxToCreateBox } from '../../boxlite-rest/mappers/box-to-box.mapper'import { Context } from '../../common/context/context'import { OrganizationService } from '../../organization/services/organization.service'+import { CreateBoxDto } from '../dto/create-box.dto'+import { Organization } from '../../organization/entities/organization.entity'import { SecretServerClient } from './secret-server-client'import { createServer } from 'node:http'import { AddressInfo } from 'node:net'@@ -899,9 +902,9 @@ describe('BoxService inbound defaults', () => {*/describe('cold-pull budget', () => {function withRealAdmission(resolved: object, overrides: Record<string, unknown> = {}) {- const redis = { incr: jest.fn().mockResolvedValue(1), expire: jest.fn(), ttl: jest.fn() }+ const redis = { eval: jest.fn().mockResolvedValue([1, 'gen-1', 60000]) }const images = { exists: jest.fn().mockResolvedValue(true), count: jest.fn().mockResolvedValue(0) }- const { service } = makeCreateService({+ const { service, boxRepository } = makeCreateService({imageAdmissionService: new ImageAdmissionService(redis as unknown as Redis,images as unknown as Repository<Image>,@@ -910,7 +913,7 @@ describe('BoxService inbound defaults', () => {imageResolverService: { resolve: jest.fn().mockResolvedValue(resolved) },...overrides,})- return { service, redis }+ return { service, redis, boxRepository }}let allowlistBefore: string | undefined@@ -937,7 +940,7 @@ describe('BoxService inbound defaults', () => {Context.user(),)- expect(redis.incr).not.toHaveBeenCalled()+ expect(redis.eval).not.toHaveBeenCalled()})/**@@ -959,7 +962,7 @@ describe('BoxService inbound defaults', () => {),).rejects.toThrow(/limit of 20 images/)- expect(redis.incr).not.toHaveBeenCalled()+ expect(redis.eval).not.toHaveBeenCalled()})/** A volume the create names but cannot have refuses it after resolution. */@@ -981,7 +984,7 @@ describe('BoxService inbound defaults', () => {),).rejects.toThrow(/no such volume/)- expect(redis.incr).not.toHaveBeenCalled()+ expect(redis.eval).not.toHaveBeenCalled()})it.each([@@ -998,7 +1001,7 @@ describe('BoxService inbound defaults', () => {),).rejects.toThrow(BadRequestError)- expect(redis.incr).not.toHaveBeenCalled()+ expect(redis.eval).not.toHaveBeenCalled()})it('spends none on a create no runner can take', async () => {@@ -1015,13 +1018,12 @@ describe('BoxService inbound defaults', () => {),).rejects.toThrow(/no runner/)- expect(redis.incr).not.toHaveBeenCalled()+ expect(redis.eval).not.toHaveBeenCalled()})it('inserts no box when the budget refuses the create', async () => {- const { service, redis } = withRealAdmission({ ref: 'quay.io/acme/app:v1', isOrgOwned: true })- redis.incr.mockResolvedValue(7)- redis.ttl.mockResolvedValue(30)+ const { service, redis, boxRepository } = withRealAdmission({ ref: 'quay.io/acme/app:v1', isOrgOwned: true })+ redis.eval.mockResolvedValue([7, 'gen-1', 30000])await expect(service.create(@@ -1031,7 +1033,44 @@ describe('BoxService inbound defaults', () => {),).rejects.toThrow(/Too many image pulls/)- expect((service as any).boxRepository.insert).not.toHaveBeenCalled()+ expect(boxRepository.insert).not.toHaveBeenCalled()+ })++ it('refunds the charged generation when the box limit refuses insertion', async () => {+ const { service, redis, boxRepository } = withRealAdmission({ ref: 'quay.io/acme/app:v1', isOrgOwned: true })+ redis.eval.mockResolvedValueOnce([1, 'gen-7', 60000]).mockResolvedValueOnce(0)+ boxRepository.insert.mockRejectedValue(new BoxCreationLimitExceededError(3, 3))++ await expect(+ service.create(+ plainToInstance(CreateBoxDto, { name: 'over-limit-box', image: 'quay.io/acme/app:v1' }),+ plainToInstance(Organization, { id: 'org-1' }),+ Context.user(),+ ),+ ).rejects.toThrow(BoxCreationLimitExceededError)++ expect(redis.eval.mock.calls[1].slice(1)).toEqual([+ 2,+ 'image:coldpull:org-1',+ 'image:coldpull:org-1:gen',+ 'gen-7',+ 1,+ ])+ })++ it('does not refund when spending fails before returning a ticket', async () => {+ const { service, redis, boxRepository } = withRealAdmission({ ref: 'quay.io/acme/app:v1', isOrgOwned: true })+ redis.eval.mockRejectedValueOnce(new Error('connection dropped'))++ await expect(+ service.create(+ plainToInstance(CreateBoxDto, { name: 'broken-pipe-box', image: 'quay.io/acme/app:v1' }),+ plainToInstance(Organization, { id: 'org-1' }),+ Context.user(),+ ),+ ).rejects.toThrow('connection dropped')+ expect(redis.eval).toHaveBeenCalledTimes(1)+ expect(boxRepository.insert).not.toHaveBeenCalled()})it('spends one on a ref the catalog has not seen', async () => {@@ -1043,7 +1082,7 @@ describe('BoxService inbound defaults', () => {Context.user(),)- expect(redis.incr).toHaveBeenCalledTimes(1)+ expect(redis.eval).toHaveBeenCalledTimes(1)})})diff --git a/apps/api/src/box/services/box.service.ts b/apps/api/src/box/services/box.service.tsindex 9b697e77b..1aede8782 100644--- a/apps/api/src/box/services/box.service.ts+++ b/apps/api/src/box/services/box.service.ts@@ -36,9 +36,10 @@ import { GetRunnerParams, RunnerService } from './runner.service'import { BoxExitCodeService } from './box-exit-code.service'import { BoxError } from '../../exceptions/box-error.exception'import { BadRequestError } from '../../exceptions/bad-request.exception'+import { BoxCreationLimitExceededError } from '../errors/box-creation-limit.error'import { Cron, CronExpression } from '@nestjs/schedule'import { BOX_WARM_POOL_UNASSIGNED_ORGANIZATION } from '../constants/box.constants'-import { ImageAdmissionService } from '../../image/services/image-admission.service'+import { ImageAdmissionService, type ColdPullTicket } from '../../image/services/image-admission.service'import { ImagePreparationService } from '../../image/services/image-preparation.service'import { ImagePullFailureService } from '../../image/services/image-pull-failure.service'import { ImageResolverService } from '../../image/services/image-resolver.service'@@ -503,8 +504,14 @@ export class BoxService {// before the insert: it has no way to give a slot back, so a create its// own input or placement refuses must not spend one. Only the box limit// and a name collision, which the insert itself settles, come after it.+ // The limit is one of those, so a create it refuses hands its unit back+ // — with the ticket the spend returned, so the refund can only touch+ // the window that was actually charged. The replay layer marks the+ // rejection retryable, and retries must not drain the organization's+ // cold-pull window without a box to show for it.+ let coldPullTicket: ColdPullTicket | undefinedconst insertedBox = await this.persistOnAvailableRunner(box, { regions: [region.id], boxClass }, async () => {- await this.imageAdmissionService.spendColdPullBudget(organization, resolvedImage)+ coldPullTicket = await this.imageAdmissionService.spendColdPullBudget(organization, resolvedImage)const insert = () =>options.onPersist? this.boxRepository.insert(box, options.maxCreatedBoxes, options.onPersist)@@ -515,6 +522,11 @@ export class BoxService {box.name = namereturn insert()})+ }).catch(async (error: unknown) => {+ if (error instanceof BoxCreationLimitExceededError && coldPullTicket) {+ await this.imageAdmissionService.refundColdPullBudget(organization, resolvedImage, coldPullTicket)+ }+ throw error})recordBoxRequested('box.create', insertedBox, ctx)diff --git a/apps/api/src/boxlite-rest/admin-api.spec.ts b/apps/api/src/boxlite-rest/admin-api.spec.tsindex 4f396998b..eb372e33f 100644--- a/apps/api/src/boxlite-rest/admin-api.spec.ts+++ b/apps/api/src/boxlite-rest/admin-api.spec.ts@@ -294,12 +294,12 @@ describe('Admin API HTTP contract', () => {expect((await call('GET', `/organizations/invites?pageToken=${encodeURIComponent(token)}`)).status).toBe(400)expect(invites.findPage).not.toHaveBeenCalled()})- it.each([400, 401, 403, 404, 409, 422, 429, 500, 503])('uses the shared Box error schema for %s', async (status) => {+ it.each([400, 401, 403, 404, 409, 422, 429, 500, 503])('uses the Admin error schema for %s', async (status) => {members.findPage.mockRejectedValueOnce(new HttpException('Request refused', status))const response = await call('GET', '/organizations/users')expect(response.status).toBe(status)const body = await response.json()- const validate = ajv.getSchema('https://contract.test/box.openapi.yaml#/components/schemas/ErrorResponse')!+ const validate = ajv.getSchema(`${specId}#/components/schemas/ErrorResponse`)!expect(validate(body) ? [] : validate.errors).toEqual([])expect(body.error.message).toBe('Request refused')})diff --git a/apps/api/src/boxlite-rest/admin-openapi.spec.ts b/apps/api/src/boxlite-rest/admin-openapi.spec.tsindex a6b9e4245..0dea4548a 100644--- a/apps/api/src/boxlite-rest/admin-openapi.spec.ts+++ b/apps/api/src/boxlite-rest/admin-openapi.spec.ts@@ -63,5 +63,7 @@ describe('Admin API error contract', () => {const body = json.mock.calls[0][0]expect(validate(body)).toBe(true)expect(validate({ error: { message: body.error.message } })).toBe(false)+ // Hosted Box APIs send a flat error; Admin clients never receive that shape.+ expect(validate({ statusCode: status, error: 'Conflict', message: body.error.message })).toBe(false)})})diff --git a/apps/api/src/boxlite-rest/box-request-replay.service.spec.ts b/apps/api/src/boxlite-rest/box-request-replay.service.spec.tsnew file mode 100644index 000000000..060ad8e2b--- /dev/null+++ b/apps/api/src/boxlite-rest/box-request-replay.service.spec.ts@@ -0,0 +1,253 @@+/// <reference lib="es2024.promise" />+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */+import { createHash, randomUUID } from 'node:crypto'+import { once } from 'node:events'+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { spawn } from 'node:child_process'+import { setImmediate as nextTurn } from 'node:timers/promises'+import Redis from 'ioredis'+import { BoxRequestReplayService } from './box-request-replay.service'++const integration = process.env.REDIS_HOST ? describe : describe.skip+integration('Replay Redis ownership and storage failures', () => {+ const org = randomUUID()+ let redis: Redis+ let service: BoxRequestReplayService+ beforeAll(async () => {+ redis = new Redis({+ host: process.env.REDIS_HOST,+ port: Number(process.env.REDIS_PORT || 6379),+ username: process.env.REDIS_USERNAME || undefined,+ password: process.env.REDIS_PASSWORD || undefined,+ })+ await redis.ping()+ service = new BoxRequestReplayService(redis)+ })+ afterAll(async () => {+ service.onModuleDestroy()+ const keys = await redis.keys(`replay:${org}:*`)+ if (keys.length) await redis.del(...keys)+ await redis.quit()+ })+ const session = (key: string) => service.session(org, 'u', 'op', key, 'fingerprint')+ const record = (key: string) => `replay:${org}:u:op:${createHash('sha256').update(key).digest('hex')}`++ it('rejects stale owners and preserves absolute retention through unknown and late completion', async () => {+ const key = randomUUID()+ const stale = await session(key)+ await stale.markRetryable()+ const owner = await session(key)+ const ttl = await redis.pttl(record(key))+ await stale.complete({ status: 201, body: 'stale' })+ await expect(session(key)).rejects.toMatchObject({ status: 409 })+ await owner.markUnknown()+ await owner.heartbeat()+ await expect(session(key)).rejects.toMatchObject({ status: 422 })+ await owner.complete({ status: 201, body: 'original' })+ expect((await session(key)).response?.body).toBe('original')+ expect(await redis.pttl(record(key))).toBeLessThanOrEqual(ttl)+ await redis.hset(record(key), 'response', 'invalid-json')+ await expect(session(key)).rejects.toMatchObject({ status: 422 })+ await redis.del(record(key))+ expect((await session(key)).isOwner).toBe(true)+ })++ it('retains corrupt and oversized outcomes while allowing only completed-resource lookups', async () => {+ const key = randomUUID()+ const owner = await session(key)+ expect(await service.peekCompleted(org, 'u', 'op', key, 'fingerprint')).toBeUndefined()+ await owner.complete({ status: 201, body: 'x'.repeat(1024 * 1024) })+ await expect(session(key)).rejects.toMatchObject({ status: 422 })+ for (const response of [+ null,+ { status: 500, body: '' },+ { status: 201, body: '', headers: { cookie: 'secret' } },+ { status: 201, body: '', resource: { id: 'volume' } },+ { status: 201, body: '', encoding: 'utf16' },+ { status: 201, body: '', auditTargetId: { id: 'box' } },+ ]) {+ await redis.hset(record(key), 'response', JSON.stringify(response))+ expect(await service.peekCompleted(org, 'u', 'op', key, 'fingerprint')).toBeUndefined()+ }+ await redis.hset(+ record(key),+ 'response',+ JSON.stringify({ status: 204, body: '', resource: { id: 'v', organizationId: org } }),+ )+ expect(await service.peekCompleted(org, 'u', 'op', key, 'fingerprint')).toMatchObject({+ status: 204,+ resource: { id: 'v' },+ })+ const replay = await session(key)+ expect(replay.isOwner).toBe(false)+ await replay.complete({ status: 204, body: '' })+ await replay.markUnknown()+ const unkeyed = await service.session(org, 'u', 'op', undefined, 'fingerprint')+ expect(unkeyed.isOwner).toBe(false)+ await unkeyed.heartbeat()+ })++ it('releases a reservation arriving after the caller deadline', async () => {+ const key = randomUUID()+ const delayed = new BoxRequestReplayService(redis)+ const resume = Promise.withResolvers<void>()+ const stored = Promise.withResolvers<void>()+ const settled = Promise.withResolvers<void>()+ const connection = redis.duplicate()+ const evaluate = connection.eval.bind(connection)+ jest.spyOn(connection, 'eval').mockImplementationOnce(async (...args: Parameters<Redis['eval']>) => {+ const result = await evaluate(...args)+ stored.resolve()+ await resume.promise+ return result+ })+ const cleanup = jest.spyOn(connection, 'eval')+ Object.assign(delayed, { ready: async () => connection })+ try {+ const pending = delayed.session(org, 'u', 'op', key, 'fingerprint')+ await stored.promise+ await expect(pending).rejects.toMatchObject({ status: 503 })+ cleanup.mockImplementationOnce(async (...args: Parameters<Redis['eval']>) => {+ try {+ return await evaluate(...args)+ } finally {+ settled.resolve()+ }+ })+ resume.resolve()+ await settled.promise+ expect(await redis.exists(record(key))).toBe(0)+ expect((await session(key)).isOwner).toBe(true)+ } finally {+ resume.resolve()+ await connection.quit()+ }+ })++ it('never sends a reservation after readiness has already timed out', async () => {+ const ready = Promise.withResolvers<Redis>()+ const settled = Promise.withResolvers<void>()+ const evaluate = jest.fn(async () => ['owner'])+ const slow = new BoxRequestReplayService(redis)+ Object.assign(slow, {+ ready: () => ready.promise.finally(settled.resolve),+ })+ await expect(slow.session(org, 'u', 'op', randomUUID(), 'fp')).rejects.toMatchObject({ status: 503 })+ // This is an in-process stand-in for the connection, not external data.+ const connection = { eval: evaluate } as unknown as Redis+ ready.resolve(connection)+ await settled.promise+ await nextTurn()+ expect(evaluate).not.toHaveBeenCalled()+ slow.onModuleDestroy()+ })++ async function withIsolatedRedis(run: (client: Redis) => Promise<void>): Promise<void> {+ const directory = await mkdtemp(join(tmpdir(), 'replay-capacity-'))+ const socket = join(directory, 'redis.sock')+ const server = spawn(+ 'redis-server',+ ['--port', '0', '--unixsocket', socket, '--save', '', '--appendonly', 'no', '--maxmemory-policy', 'noeviction'],+ { stdio: ['ignore', 'pipe', 'pipe'] },+ )+ const ready = Promise.withResolvers<void>()+ server.stdout.on('data', (chunk: Buffer) => {+ if (chunk.toString().includes('Ready to accept connections')) ready.resolve()+ })+ server.once('error', ready.reject)+ let isolated: Redis | undefined+ server.once('exit', (code) => ready.reject(new Error(`Test Redis exited with code ${code}`)))+ try {+ await ready.promise+ isolated = new Redis({ path: socket })+ await run(isolated)+ } finally {+ await isolated?.quit()+ if (server.pid && server.exitCode === null && server.signalCode === null) {+ const exited = once(server, 'exit')+ server.kill()+ await exited+ }+ await rm(directory, { recursive: true, force: true })+ }+ }++ it('replays with a Redis user that cannot run CONFIG', async () => {+ await withIsolatedRedis(async (isolated) => {+ await isolated.acl('SETUSER', 'replay', 'on', '>test-password', '~*', '+@all', '-config')+ const client = isolated.duplicate({ username: 'replay', password: 'test-password', lazyConnect: true })+ const engine = new BoxRequestReplayService(client)+ const key = randomUUID()+ try {+ const owner = await engine.session(org, 'u', 'op', key, 'fp')+ await owner.complete({ status: 201, body: 'original' })+ const replay = await engine.session(org, 'u', 'op', key, 'fp')+ expect(replay.response).toMatchObject({ status: 201, body: 'original' })+ } finally {+ engine.onModuleDestroy()+ client.disconnect()+ }+ })+ })++ it.each(['new', 'retryable'])('releases a %s reservation after a real Redis command timeout', async (state) => {+ await withIsolatedRedis(async (isolated) => {+ const engine = new BoxRequestReplayService(isolated)+ const reserve = (key: string, fingerprint = 'fp') => engine.session(org, 'u', 'op', key, fingerprint)+ try {+ const warm = await reserve(randomUUID())+ const key = randomUUID()+ if (state === 'retryable') {+ const previous = await reserve(key)+ await previous.markRetryable()+ await isolated.expire(record(key), 60)+ }+ await isolated.call('CLIENT', 'PAUSE', '1500', 'ALL')+ await expect(reserve(key)).rejects.toMatchObject({ status: 503 })+ // Redis resumes before the heartbeat is queued on the same connection as the abandoned claim.+ await isolated.ping()+ await warm.heartbeat()+ if (state === 'retryable') {+ await expect(reserve(key, 'changed')).rejects.toMatchObject({+ status: 409,+ response: { code: 'idempotency_request_mismatch' },+ })+ } else {+ expect(await isolated.exists(record(key))).toBe(0)+ }+ expect((await reserve(key)).isOwner).toBe(true)+ if (state === 'retryable') expect(await isolated.pttl(record(key))).toBeLessThan(60_000)+ } finally {+ engine.onModuleDestroy()+ }+ })+ })++ it('refuses capacity without discarding an existing execution fence', async () => {+ await withIsolatedRedis(async (isolated) => {+ await isolated.config('SET', 'maxmemory-policy', 'allkeys-lru')+ const unsafe = new BoxRequestReplayService(isolated)+ try {+ await expect(unsafe.session(org, 'u', 'op', randomUUID(), 'fp')).rejects.toMatchObject({ status: 503 })+ } finally {+ unsafe.onModuleDestroy()+ }+ await isolated.config('SET', 'maxmemory-policy', 'noeviction')+ const engine = new BoxRequestReplayService(isolated)+ try {+ const key = randomUUID()+ expect((await engine.session(org, 'u', 'op', key, 'fp')).isOwner).toBe(true)+ await isolated.config('SET', 'maxmemory', '1')+ await expect(engine.session(org, 'u', 'op', randomUUID(), 'fp')).rejects.toMatchObject({ status: 503 })+ await expect(engine.session(org, 'u', 'op', key, 'fp')).rejects.toMatchObject({ status: 409 })+ } finally {+ engine.onModuleDestroy()+ }+ })+ })+})diff --git a/apps/api/src/boxlite-rest/box-request-replay.service.ts b/apps/api/src/boxlite-rest/box-request-replay.service.tsnew file mode 100644index 000000000..6ee624eb0--- /dev/null+++ b/apps/api/src/boxlite-rest/box-request-replay.service.ts@@ -0,0 +1,337 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */+import { HttpException, HttpStatus, Inject, Injectable, Logger, OnModuleDestroy } from '@nestjs/common'+import { getRedisConnectionToken } from '@nestjs-modules/ioredis'+import type Redis from 'ioredis'+import { createHash, randomUUID } from 'node:crypto'++const RECORD_TTL_SECONDS = 24 * 60 * 60+export const REPLAY_COMMAND_TIMEOUT_MS = 1_000+export const REPLAY_HEARTBEAT_MS = 1_000+const COMPLETION_DEADLINE_MS = 5_000+export const REPLAY_MAX_RESPONSE_BYTES = 1024 * 1024++export interface ReplayResource {+ id: string+ organizationId: string+}+export interface ReplayResponse {+ status: number+ body: string+ encoding?: 'base64'+ headers?: Record<string, string>+ resource?: ReplayResource+ auditTargetId?: string+}+interface ReplayReservation {+ key: string+ owner: string+}+interface ReplayOptions {+ replayOnly?: boolean+}++/** Only the HTTP entry owns this handle. Unknown outcomes keep their fence; late success may still complete. */+export class ReplaySession {+ constructor(+ readonly response: ReplayResponse | undefined,+ private readonly reservation: ReplayReservation | undefined,+ private readonly redis: Redis | undefined,+ ) {}++ get isOwner(): boolean {+ return this.reservation !== undefined+ }++ async complete(response: ReplayResponse): Promise<void> {+ if (!this.reservation || !this.redis) return+ const serialized = JSON.stringify(response)+ if (Buffer.byteLength(serialized) > REPLAY_MAX_RESPONSE_BYTES) {+ await this.markUnknown()+ return+ }+ await this.redis.eval(COMPLETE_SCRIPT, 1, this.reservation.key, this.reservation.owner, serialized)+ }++ async markRetryable(): Promise<void> {+ await this.update('retryable')+ }+ async markUnknown(): Promise<void> {+ await this.update('unknown')+ }+ async heartbeat(): Promise<void> {+ await this.update('heartbeat')+ }++ private async update(state: string): Promise<void> {+ if (!this.reservation || !this.redis) return+ await this.redis.eval(UPDATE_SCRIPT, 1, this.reservation.key, this.reservation.owner, state)+ }+}++// Redis time and absolute expiry are shared by replicas. Neither heartbeat nor reclaim extends retention.+const RESERVE_SCRIPT = `+local fp = redis.call('HGET', KEYS[1], 'fingerprint')+if redis.call('EXISTS', KEYS[1]) == 0 then+ if ARGV[4] == 'peek' or ARGV[4] == 'replay-only' then return {'unknown'} end+ local now = redis.call('TIME')+ local now_ms = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000)+ redis.call('HSET', KEYS[1], 'fingerprint', ARGV[1], 'owner', ARGV[2],+ 'state', 'pending', 'expected_response_at', tostring(now_ms + ${COMPLETION_DEADLINE_MS}))+ local ok = redis.pcall('EXPIRE', KEYS[1], ARGV[3])+ if type(ok) == 'table' and ok.err then+ redis.call('DEL', KEYS[1])+ return redis.error_reply('idempotency: failed to set retention')+ end+ return {'owner'}+end+if fp ~= ARGV[1] then return {'mismatch'} end+local body = redis.call('HGET', KEYS[1], 'response')+if body then return {'replay', body} end+if ARGV[4] == 'peek' or ARGV[4] == 'replay-only' then return {'unknown'} end+local state = redis.call('HGET', KEYS[1], 'state')+local now = redis.call('TIME')+local now_ms = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000)+if state == 'retryable' then+ redis.call('HSET', KEYS[1], 'owner', ARGV[2], 'state', 'pending', 'reclaimed', '1',+ 'expected_response_at', tostring(now_ms + ${COMPLETION_DEADLINE_MS}))+ return {'owner'}+end+if state == 'unknown' then return {'unknown'} end+local deadline = tonumber(redis.call('HGET', KEYS[1], 'expected_response_at') or '0')+if now_ms >= deadline then return {'unknown'} end+return {'pending'}+`+const COMPLETE_SCRIPT = `+if redis.call('HGET', KEYS[1], 'owner') ~= ARGV[1] then return 0 end+local state = redis.call('HGET', KEYS[1], 'state')+if state and state ~= 'pending' and state ~= 'unknown' then return 0 end+if redis.call('HEXISTS', KEYS[1], 'response') == 1 then return 0 end+redis.call('HSET', KEYS[1], 'response', ARGV[2], 'state', 'complete')+return 1+`+const UPDATE_SCRIPT = `+if redis.call('HGET', KEYS[1], 'owner') ~= ARGV[1] then return 0 end+if redis.call('HEXISTS', KEYS[1], 'response') == 1 then return 0 end+if ARGV[2] == 'heartbeat' then+ if redis.call('HGET', KEYS[1], 'state') ~= 'pending' then return 0 end+ local now = redis.call('TIME')+ local now_ms = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000)+ redis.call('HSET', KEYS[1], 'expected_response_at', tostring(now_ms + ${COMPLETION_DEADLINE_MS}))+else+ redis.call('HSET', KEYS[1], 'state', ARGV[2])+ if ARGV[2] == 'retryable' then redis.call('HDEL', KEYS[1], 'owner') end+end+return 1+`+const RELEASE_IF_OWNER_SCRIPT = `+if redis.call('HGET', KEYS[1], 'owner') ~= ARGV[1] then return 0 end+if redis.call('HEXISTS', KEYS[1], 'response') == 1 then return 0 end+if redis.call('HEXISTS', KEYS[1], 'reclaimed') == 0 then return redis.call('DEL', KEYS[1]) end+redis.call('HSET', KEYS[1], 'state', 'retryable')+redis.call('HDEL', KEYS[1], 'owner')+return 1+`++function recordKey(organizationId: string, subjectId: string, operation: string, requestId: string): string {+ return `replay:${organizationId}:${subjectId}:${operation}:${createHash('sha256').update(requestId).digest('hex')}`+}++function storedResponse(raw: string): ReplayResponse | undefined {+ try {+ const value: unknown = JSON.parse(raw)+ if (!value || typeof value !== 'object' || !('status' in value) || !('body' in value)) return undefined+ if (typeof value.status !== 'number' || value.status < 200 || value.status >= 300 || typeof value.body !== 'string')+ return undefined+ if ('encoding' in value && value.encoding !== 'base64') return undefined+ if (+ 'headers' in value &&+ (!value.headers ||+ typeof value.headers !== 'object' ||+ Object.entries(value.headers).some(+ ([key, item]) => !['content-type', 'location'].includes(key) || typeof item !== 'string',+ ))+ )+ return undefined+ if (+ 'resource' in value &&+ (!value.resource ||+ typeof value.resource !== 'object' ||+ !('id' in value.resource) ||+ !('organizationId' in value.resource) ||+ typeof value.resource.id !== 'string' ||+ typeof value.resource.organizationId !== 'string')+ )+ return undefined+ if ('auditTargetId' in value && typeof value.auditTargetId !== 'string') return undefined+ // Every optional field was validated above; this is the persisted response boundary.+ return value as ReplayResponse+ } catch {+ return undefined+ }+}++@Injectable()+export class BoxRequestReplayService implements OnModuleDestroy {+ private readonly logger = new Logger(BoxRequestReplayService.name)+ private connection?: Redis+ private connecting?: Promise<Redis>+ private policyChecked = false+ private readonly noOpSession = new ReplaySession(undefined, undefined, undefined)++ constructor(@Inject(getRedisConnectionToken()) private readonly redis: Redis) {}++ onModuleDestroy(): void {+ this.connection?.disconnect()+ }++ async session(+ organizationId: string,+ subjectId: string,+ operation: string,+ requestId: string | undefined,+ fingerprint: string,+ options: ReplayOptions = {},+ ): Promise<ReplaySession> {+ if (!requestId) return this.noOpSession+ const key = recordKey(organizationId, subjectId, operation, requestId)+ const owner = randomUUID()+ const { result, connection } = await this.reserve(+ key,+ owner,+ fingerprint,+ options.replayOnly ? 'replay-only' : 'reserve',+ )+ if (result[0] === 'owner') return new ReplaySession(undefined, { key, owner }, connection)+ if (result[0] === 'replay') {+ const response = storedResponse(result[1])+ if (response) return new ReplaySession(response, undefined, undefined)+ this.logger.warn(`Corrupt replay record for ${operation}; retaining fence`)+ }+ if (result[0] === 'mismatch')+ throw new HttpException(+ { message: 'Idempotency-Key was already used with a different request', code: 'idempotency_request_mismatch' },+ HttpStatus.CONFLICT,+ )+ if (result[0] === 'pending')+ throw new HttpException(+ {+ message: 'The original request has not recorded a response yet. Retry with the same Idempotency-Key.',+ code: 'idempotency_in_progress',+ },+ HttpStatus.CONFLICT,+ )+ throw new HttpException(+ {+ message:+ 'The original request has no recorded response and its outcome is unknown. This request was not executed again.',+ code: 'idempotency_outcome_unknown',+ },+ HttpStatus.UNPROCESSABLE_ENTITY,+ )+ }++ async peekCompleted(+ organizationId: string,+ subjectId: string,+ operation: string,+ requestId: string,+ fingerprint: string,+ ): Promise<ReplayResponse | undefined> {+ const { result } = await this.reserve(+ recordKey(organizationId, subjectId, operation, requestId),+ '',+ fingerprint,+ 'peek',+ )+ return result[0] === 'replay' ? storedResponse(result[1]) : undefined+ }++ private async reserve(+ key: string,+ owner: string,+ fingerprint: string,+ mode: 'reserve' | 'replay-only' | 'peek',+ ): Promise<{ result: string[]; connection: Redis }> {+ let timer: NodeJS.Timeout | undefined+ let abandoned = false+ const deadline = new Promise<never>((_resolve, reject) => {+ timer = setTimeout(() => {+ abandoned = true+ reject(new Error('Replay reservation deadline exceeded'))+ }, REPLAY_COMMAND_TIMEOUT_MS)+ })+ const claim = async () => {+ const connection = await this.ready()+ if (abandoned) throw new Error('Replay reservation deadline exceeded')+ try {+ const result = await connection.eval(RESERVE_SCRIPT, 1, key, fingerprint, owner, RECORD_TTL_SECONDS, mode)+ if (abandoned) throw new Error('Replay reservation deadline exceeded')+ if (!Array.isArray(result) || result.some((item) => typeof item !== 'string'))+ throw new Error('Invalid replay storage result')+ return { result: result as string[], connection }+ } catch (error) {+ if (mode === 'reserve') {+ // An ioredis timeout rejects the promise, but Redis can still execute EVAL.+ // Queue owner-checked cleanup behind the claim on the same connection.+ void connection.eval(RELEASE_IF_OWNER_SCRIPT, 1, key, owner).catch(() => {+ this.logger.warn('Failed to release an undispatched replay reservation')+ })+ }+ throw error+ }+ }+ try {+ return await Promise.race([claim(), deadline])+ } catch (error) {+ throw this.unavailable(error)+ } finally {+ clearTimeout(timer)+ }+ }++ private async ready(): Promise<Redis> {+ if (this.connecting) return this.connecting+ if (this.policyChecked && this.connection?.status === 'ready') return this.connection+ if (!this.connection) {+ this.connection = this.redis.duplicate({+ lazyConnect: true,+ commandTimeout: REPLAY_COMMAND_TIMEOUT_MS,+ connectTimeout: REPLAY_COMMAND_TIMEOUT_MS,+ maxRetriesPerRequest: 0,+ enableOfflineQueue: false,+ autoResendUnfulfilledCommands: false,+ retryStrategy: null,+ })+ this.connection.on('error', () => undefined)+ }+ const connection = this.connection+ this.connecting = (async () => {+ try {+ if (connection.status === 'wait' || connection.status === 'end') await connection.connect()+ const memory = await connection.info('memory')+ if (!/^maxmemory_policy:noeviction\r?$/m.test(memory))+ throw new Error('Replay Redis requires maxmemory-policy=noeviction')+ this.policyChecked = true+ return connection+ } catch (error) {+ this.policyChecked = false+ throw this.unavailable(error)+ } finally {+ this.connecting = undefined+ }+ })()+ return this.connecting+ }++ private unavailable(error: unknown): HttpException {+ this.logger.warn('Replay storage unavailable; request not dispatched')+ return new HttpException(+ { message: 'Request replay storage is unavailable', code: 'idempotency_storage_unavailable' },+ HttpStatus.SERVICE_UNAVAILABLE,+ { cause: error },+ )+ }+}diff --git a/apps/api/src/boxlite-rest/boxlite-box.controller.ts b/apps/api/src/boxlite-rest/boxlite-box.controller.tsindex 2b80d528c..bc38b472a 100644--- a/apps/api/src/boxlite-rest/boxlite-box.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-box.controller.ts@@ -17,7 +17,6 @@ import {HttpCode,UseGuards,UsePipes,- ValidationPipe,Logger,Res,Req,@@ -51,6 +50,8 @@ import { Audit, AUDIT_TARGET_ID, MASKED_AUDIT_VALUE, TypedRequest } from '../audimport { AuditAction } from '../audit/enums/audit-action.enum'import { AuditTarget } from '../audit/enums/audit-target.enum'import { CommerceBoxLimitService } from './commerce-box-limit.service'+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'@@ -77,7 +78,7 @@ const CHECKPOINT_BOX_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$///// `whitelist` alone only strips unknown fields; `forbidNonWhitelisted` is what// turns a stripped field into a 400. Both are required.-@UsePipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))+@UsePipes(new ReplayValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))@ApiBearerAuth()export class BoxliteBoxController {private readonly logger = new Logger(BoxliteBoxController.name)@@ -136,15 +137,7 @@ export class BoxliteBoxController {if (dto.checkpoint_id !== undefined) {return this.createBoxFromCheckpoint(authContext, dto, ctx, request)}-- // Attaching a managed volume grants the box read/write access to its data,- // so it is authorized independently of WRITE_BOXES: the caller must hold the- // volume permissions too. WRITE_BOXES alone must not reach another key's- // volumes (GHSA-2qqv-7cwv-mj8h).- if (dto.volumes?.length) {- this.assertCanAttachVolumes(authContext)- }-+ if (dto.volumes?.length) this.assertCanAttachVolumes(authContext)const organization = authContext.organizationconst createBoxDto = createBoxToCreateBox(dto)const maxCreatedBoxes = await this.commerceBoxLimitService.resolveMaxCreatedBoxes(organization.id)@@ -203,15 +196,17 @@ export class BoxliteBoxController {.filter(([field, value]) => value !== undefined && field !== 'checkpoint_id' && field !== 'name').map(([field]) => field)if (overrides.includes('image')) {- throw new BadRequestException('checkpoint_id and image are mutually exclusive')+ throw noEffect(new BadRequestException('checkpoint_id and image are mutually exclusive'))}if (overrides.length) {- throw new BadRequestException(- `A box created from a checkpoint inherits its settings; only name may be set, remove: ${overrides.join(', ')}`,+ throw noEffect(+ new BadRequestException(+ `A box created from a checkpoint inherits its settings; only name may be set, remove: ${overrides.join(', ')}`,+ ),)}if (dto.name !== undefined && (typeof dto.name !== 'string' || !CHECKPOINT_BOX_NAME.test(dto.name))) {- throw new BadRequestException('Invalid box name')+ throw noEffect(new BadRequestException('Invalid box name'))}const maxCreatedBoxes = await this.commerceBoxLimitService.resolveMaxCreatedBoxes(authContext.organizationId)@@ -247,7 +242,7 @@ export class BoxliteBoxController {private assertCanAttachVolumes(authContext: OrganizationAuthContext): void {const required = [OrganizationResourcePermission.READ_VOLUMES, OrganizationResourcePermission.WRITE_VOLUMES]if (!hasOrganizationResourcePermissions(authContext, required)) {- throw new ForbiddenException(`Attaching a volume requires: ${required.join(', ')}`)+ throw noEffect(new ForbiddenException(`Attaching a volume requires: ${required.join(', ')}`))}}diff --git a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.ts b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.tsindex 5f2910f40..003eca7ee 100644--- a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.ts@@ -10,12 +10,10 @@ import {Get,HttpCode,Param,- ParseBoolPipe,Post,Query,UseGuards,UsePipes,- ValidationPipe,} from '@nestjs/common'import { ApiExcludeController } from '@nestjs/swagger'import { IsIn, IsOptional, IsString, Matches, MaxLength, MinLength, ValidateIf } from 'class-validator'@@ -27,6 +25,7 @@ import { AuthContext } from '../common/decorators/auth-context.decorator'import { OrganizationAuthContext } from '../common/interfaces/auth-context.interface'import { Checkpoint } from '../box/entities/checkpoint.entity'import { CheckpointService } from '../box/services/checkpoint.service'+import { ReplayParseBoolPipe, ReplayValidationPipe } from '../common/replay-validation.pipe'class CreateCheckpointRequest {@IsString() @MinLength(1) @MaxLength(128) source_box_id: string@@ -39,7 +38,7 @@ class CreateCheckpointRequest {@Controller(['v1/checkpoints', 'v1/:prefix/checkpoints'])@ApiExcludeController()@UseGuards(CombinedAuthGuard, OrganizationResourceActionGuard)-@UsePipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))+@UsePipes(new ReplayValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))export class BoxliteCheckpointController {constructor(private readonly checkpoints: CheckpointService) {}@@ -76,10 +75,10 @@ export class BoxliteCheckpointController {async remove(@AuthContext() auth: OrganizationAuthContext,@Param('key') key: string,- @Query('force', new DefaultValuePipe(false), ParseBoolPipe) force: unknown,+ @Query('force', new DefaultValuePipe(false), ReplayParseBoolPipe) force: unknown,) {// Boolean metatype coercion would turn an invalid query into false before- // ParseBoolPipe can reject it. Let that pipe validate the original value.+ // ReplayParseBoolPipe can reject it. Let that pipe validate the original value.await this.checkpoints.remove(auth.organizationId, key, force === true)}}diff --git a/apps/api/src/boxlite-rest/boxlite-config.controller.ts b/apps/api/src/boxlite-rest/boxlite-config.controller.tsindex af389949a..c6ac0d79f 100644--- a/apps/api/src/boxlite-rest/boxlite-config.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-config.controller.ts@@ -8,13 +8,17 @@ import { Controller, Get, Optional } from '@nestjs/common'import { ApiTags, ApiExcludeController } from '@nestjs/swagger'import { TypedConfigService } from '../config/typed-config.service'import { isVolumeStorageConfigured } from '../box/stores/volume-bucket.store'+import { REPLAY_LIFETIME, RequestReplayPolicy } from './request-replay-policy'// Spec-first surface: the contract is openapi/box.openapi.yaml.@ApiExcludeController()@ApiTags('BoxLite REST')@Controller('v1')export class BoxliteConfigController {- constructor(@Optional() private readonly config?: TypedConfigService) {}+ constructor(+ @Optional() private readonly config?: TypedConfigService,+ @Optional() private readonly replayPolicy?: RequestReplayPolicy,+ ) {}@Get('config')getConfig() {@@ -35,6 +39,8 @@ export class BoxliteConfigController {inbound_update_enabled: true,private_tunnels_enabled: true,exec_user_enabled: true,+ idempotency_key_lifetime: REPLAY_LIFETIME,+ idempotency_operations: this.replayPolicy?.operations() ?? [],},}}diff --git a/apps/api/src/boxlite-rest/boxlite-domain.controller.ts b/apps/api/src/boxlite-rest/boxlite-domain.controller.tsindex 938ece15f..e402c242b 100644--- a/apps/api/src/boxlite-rest/boxlite-domain.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-domain.controller.ts@@ -21,7 +21,6 @@ import {Req,UseGuards,UsePipes,- ValidationPipe,} from '@nestjs/common'import { ApiExcludeController } from '@nestjs/swagger'import { CombinedAuthGuard } from '../auth/combined-auth.guard'@@ -34,6 +33,7 @@ import { BoxService } from '../box/services/box.service'import { HeldDomain, HeldDomains, DomainService } from '../box/services/domain.service'import { DomainTargetDto } from './dto/domain-target.dto'import { ClaimDomainDto } from './dto/claim-domain.dto'+import { ReplayValidationPipe } from '../common/replay-validation.pipe'type RestDomain = HeldDomain@@ -54,7 +54,7 @@ type RestDomainList = {@Controller(['v1/domains', 'v1/:prefix/domains'])@ApiExcludeController()@UseGuards(CombinedAuthGuard, OrganizationResourceActionGuard)-@UsePipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))+@UsePipes(new ReplayValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))export class BoxliteDomainController {constructor(private readonly domainService: DomainService,diff --git a/apps/api/src/boxlite-rest/boxlite-invitation.controller.ts b/apps/api/src/boxlite-rest/boxlite-invitation.controller.tsindex d845231d9..7779cd29c 100644--- a/apps/api/src/boxlite-rest/boxlite-invitation.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-invitation.controller.ts@@ -18,7 +18,6 @@ import {Query,UseGuards,UsePipes,- ValidationPipe,} from '@nestjs/common'import { ApiExcludeController } from '@nestjs/swagger'import { isUUID } from 'class-validator'@@ -39,6 +38,7 @@ import { OrganizationActionGuard } from '../organization/guards/organization-actimport { OrganizationInvitationService } from '../organization/services/organization-invitation.service'import { CreateInvitationDto } from './dto/create-invitation.dto'import { AdminPageQuery, adminNextPage } from './dto/admin-page-query.dto'+import { ReplayValidationPipe } from '../common/replay-validation.pipe'type RestInvitation = {type: 'invite'@@ -54,7 +54,7 @@ type RestInvitation = {@Controller('v1/organizations/invites')@ApiExcludeController()@UseGuards(CombinedAuthGuard, AuthenticatedRateLimitGuard, OrganizationActionGuard)-@UsePipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))+@UsePipes(new ReplayValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))export class BoxliteInvitationController {constructor(private readonly organizationInvitationService: OrganizationInvitationService) {}diff --git a/apps/api/src/boxlite-rest/boxlite-member.controller.ts b/apps/api/src/boxlite-rest/boxlite-member.controller.tsindex b0fc95169..18ad1b7d3 100644--- a/apps/api/src/boxlite-rest/boxlite-member.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-member.controller.ts@@ -3,7 +3,7 @@* SPDX-License-Identifier: AGPL-3.0*/-import { Controller, Delete, Get, HttpCode, Param, Query, UseGuards, UsePipes, ValidationPipe } from '@nestjs/common'+import { Controller, Delete, Get, HttpCode, Param, Query, UseGuards, UsePipes } from '@nestjs/common'import { ApiExcludeController } from '@nestjs/swagger'import { CombinedAuthGuard } from '../auth/combined-auth.guard'import { AuthenticatedRateLimitGuard } from '../common/guards/authenticated-rate-limit.guard'@@ -20,6 +20,7 @@ import { OrganizationResourcePermission } from '../organization/enums/organizatiimport { OrganizationActionGuard } from '../organization/guards/organization-action.guard'import { OrganizationUserService } from '../organization/services/organization-user.service'import { AdminPageQuery, adminNextPage } from './dto/admin-page-query.dto'+import { ReplayValidationPipe } from '../common/replay-validation.pipe'type RestMember = {type: 'user'@@ -34,7 +35,7 @@ type RestMember = {@Controller('v1/organizations/users')@ApiExcludeController()@UseGuards(CombinedAuthGuard, AuthenticatedRateLimitGuard, OrganizationActionGuard)-@UsePipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))+@UsePipes(new ReplayValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))export class BoxliteMemberController {constructor(private readonly organizationUserService: OrganizationUserService) {}diff --git a/apps/api/src/boxlite-rest/boxlite-openapi.spec.ts b/apps/api/src/boxlite-rest/boxlite-openapi.spec.tsindex 1cc816fac..c8f189002 100644--- a/apps/api/src/boxlite-rest/boxlite-openapi.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-openapi.spec.ts@@ -3,11 +3,13 @@* SPDX-License-Identifier: AGPL-3.0*/+import { ArgumentsHost, HttpException } from '@nestjs/common'import Ajv2020 from 'ajv/dist/2020'import addFormats from 'ajv-formats'import { readFileSync } from 'node:fs'import { resolve } from 'node:path'import { parse } from 'yaml'+import { AllExceptionsFilter } from '../filters/all-exceptions.filter'import { ImageCatalogService } from '../image/services/image-catalog.service'import { RegistriesService } from '../registry/services/registries.service'import { BoxliteCheckpointController } from './boxlite-checkpoint.controller'@@ -21,7 +23,7 @@ const spec = parse(readFileSync(resolve(__dirname, '../../../../openapi/box.open// standard JSON Schema semantics required by this OAS 3.1 document.const jsonSchema = JSON.parse(JSON.stringify(spec, (key, value) => (key === 'nullable' ? undefined : value)))const ajv = addFormats(new Ajv2020({ strict: false, allErrors: true }))-ajv.addSchema({ components: jsonSchema.components }, 'box-api')+ajv.addSchema({ components: jsonSchema.components, paths: jsonSchema.paths }, 'box-api')function validator(name: string) {const validate = ajv.getSchema(`box-api#/components/schemas/${name}`)@@ -262,3 +264,46 @@ describe('Box API JSON Schema nullability', () => {},)})++describe('Hosted replay error contract', () => {+ type Operation = {+ operationId: string+ parameters?: { $ref?: string }[]+ responses: Record<string, { $ref?: string }>+ }+ const writes = Object.entries(spec.paths).flatMap(([path, item]) =>+ Object.entries(item as Record<string, Operation>)+ .filter(([, op]) => op.parameters?.some((p) => p.$ref === '#/components/parameters/idempotencyKey'))+ .map(([method, op]) => ({ path, method, op })),+ )++ it.each([+ [400, undefined],+ [409, 'idempotency_in_progress'],+ [409, 'idempotency_request_mismatch'],+ [422, 'idempotency_outcome_unknown'],+ [503, 'idempotency_storage_unavailable'],+ ] as const)('documents the hosted %i response (%s) for every keyed write', async (status, code) => {+ const json = jest.fn()+ const url = '/api/v1/volumes'+ const host = {+ switchToHttp: () => ({+ getRequest: () => ({ path: url, url }),+ getResponse: () => ({ status: () => ({ json }) }),+ }),+ } as ArgumentsHost+ const filter = new AllExceptionsFilter({} as never)+ await filter.catch(new HttpException({ message: 'Request refused', code }, status), host)+ const [body] = json.mock.calls[0]++ expect(writes.map(({ op }) => op.operationId)).toContain('createVolume')+ for (const { path, method, op } of writes) {+ const escapedPath = path.replace(/~/g, '~0').replace(/\//g, '~1')+ const ref = op.responses[status]?.$ref ?? `#/paths/${escapedPath}/${method}/responses/${status}`+ const validate = ajv.getSchema(`box-api${ref}/content/application~1json/schema`)+ if (!validate) throw new Error(`${op.operationId} has no response schema for ${status}`)+ if (!validate(body)) throw new Error(`${op.operationId} ${status}: ${ajv.errorsText(validate.errors)}`)+ expect(validate({ ...body, code: 123 })).toBe(false)+ }+ })+})diff --git a/apps/api/src/boxlite-rest/boxlite-proxy.controller.spec.ts b/apps/api/src/boxlite-rest/boxlite-proxy.controller.spec.tsindex 9747de1b4..aed2df3b0 100644--- a/apps/api/src/boxlite-rest/boxlite-proxy.controller.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-proxy.controller.spec.ts@@ -10,6 +10,7 @@ import { HTTP_CODE_METADATA, METHOD_METADATA, PATH_METADATA, ROUTE_ARGS_METADATAimport { Reflector } from '@nestjs/core'import { createProxyMiddleware } from 'http-proxy-middleware'import { BoxliteProxyController } from './boxlite-proxy.controller'+import { hasNoEffect } from '../common/replay-no-effect'import { Context } from '../common/context/context'import { RequiredOrganizationResourcePermissions } from '../organization/decorators/required-organization-resource-permissions.decorator'import { OrganizationResourcePermission } from '../organization/enums/organization-resource-permission.enum'@@ -46,12 +47,12 @@ function makeHarness() {prepare: jest.fn().mockResolvedValue({ isPublic: true, token: null }),revoke: jest.fn().mockResolvedValue(undefined),}- const controller = new (BoxliteProxyController as any)(- boxService,- runnerService,- autoResume,- tunnelService,- ) as BoxliteProxyController+ const controller = new BoxliteProxyController(+ boxService as never,+ runnerService as never,+ autoResume as never,+ tunnelService as never,+ )return { controller, boxService, autoResume, tunnelService }}@@ -140,8 +141,8 @@ describe('BoxliteProxyController', () => {const proxyHandler = jest.fn()jest.mocked(createProxyMiddleware).mockReturnValue(proxyHandler as never)const { controller, boxService } = makeHarness()- const req = { url: '/api/v1/boxes/public-box/exec' }- const res = {}+ const req = { url: '/api/v1/boxes/public-box/exec', method: 'POST' }+ const res = new EventEmitter()const next = jest.fn()await controller.proxyExec(activeAuth as never, 'public-box', req as never, res as never, next)@@ -153,6 +154,24 @@ describe('BoxliteProxyController', () => {expect(proxyHandler).toHaveBeenCalledWith(req, res, next)})+ it('marks an admission refusal before auto-resume and dispatch as no-effect', async () => {+ jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)+ const { controller, boxService, autoResume } = makeHarness()+ boxService.findOneByIdOrName.mockResolvedValue({+ id: 'box-uuid',+ runnerId: 'runner-1',+ autoResume: false,+ state: 'stopped',+ desiredState: 'stopped',+ })+ const error = await controller+ .proxyExec(activeAuth as never, 'public-box', { method: 'POST' } as never, new EventEmitter() as never, jest.fn())+ .catch((error: unknown) => error)+ expect(error).toMatchObject({ status: 409 })+ expect(hasNoEffect(error)).toBe(true)+ expect(autoResume.ensureReady).not.toHaveBeenCalled()+ expect(createProxyMiddleware).not.toHaveBeenCalled()+ })it('lists a stopped box without resuming it or extending its idle lifetime', async () => {jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)const { controller, boxService, autoResume } = makeHarness()@@ -407,9 +426,11 @@ describe('BoxliteProxyController', () => {const { controller, autoResume } = makeHarness()autoResume.ensureReady.mockRejectedValue(new Error('start failed'))- await expect(- controller.proxyExec(activeAuth as never, 'public-box', { url: '/exec' } as never, {} as never, jest.fn()),- ).rejects.toThrow('start failed')+ const error = await controller+ .proxyExec(activeAuth as never, 'public-box', { url: '/exec' } as never, {} as never, jest.fn())+ .catch((error: unknown) => error)+ expect(error).toMatchObject({ message: 'start failed' })+ expect(hasNoEffect(error)).toBe(false)expect(proxyHandler).not.toHaveBeenCalled()})diff --git a/apps/api/src/boxlite-rest/boxlite-proxy.controller.ts b/apps/api/src/boxlite-rest/boxlite-proxy.controller.tsindex 45d73a8ad..d5e658aef 100644--- a/apps/api/src/boxlite-rest/boxlite-proxy.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-proxy.controller.ts@@ -20,15 +20,12 @@ import {Logger,NotFoundException,ConflictException,- ForbiddenException,HttpCode,HttpStatus,- ParseIntPipe,Post,Query,Body,Header,- ValidationPipe,} from '@nestjs/common'import { ApiTags, ApiBearerAuth, ApiExcludeController } from '@nestjs/swagger'import { createProxyMiddleware, fixRequestBody, Options } from 'http-proxy-middleware'@@ -51,6 +48,9 @@ import { PrepareTunnelDto } from '../box/dto/tunnel.dto'import { requestContext, UserContext } from '../common/decorators/user-context.decorator'import { Context } from '../common/context/context'import { recordBusinessEvent, recordOutcomes } from '../common/utils/business-event.util'+import { noEffect } from '../common/replay-no-effect'+import { ReplayParseIntPipe, ReplayValidationPipe } from '../common/replay-validation.pipe'+import { trackReplayUpstream } from './request-replay-response'type ProxyActivityPolicy = { activity: boolean; autoResume: boolean }const USER_OPERATION: ProxyActivityPolicy = { activity: true, autoResume: true }@@ -442,9 +442,9 @@ export class BoxliteProxyController {async proxyNetworkTunnel(@AuthContext() authContext: OrganizationAuthContext,@Param('boxId') boxId: string,- @Query('port', ParseIntPipe) port: number,+ @Query('port', ReplayParseIntPipe) port: number,@UserContext() ctx: Context,- @Body(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true })) options: PrepareTunnelDto = {},+ @Body(new ReplayValidationPipe({ whitelist: true, forbidNonWhitelisted: true })) options: PrepareTunnelDto = {},@Req() request?: Request,) {// findOneByIdOrName already 404s for a missing/destroyed box.@@ -502,7 +502,7 @@ export class BoxliteProxyController {async revokeNetworkTunnel(@AuthContext() authContext: OrganizationAuthContext,@Param('boxId') boxId: string,- @Query('port', ParseIntPipe) port: number,+ @Query('port', ReplayParseIntPipe) port: number,@Req() request?: Request,): Promise<void> {const box = await this.boxService.findOneByIdOrName(boxId, authContext.organizationId)@@ -558,7 +558,14 @@ export class BoxliteProxyController {res.once('error', stop)}- opts?.admit?.(box, boxId)+ // Only this local admission check proves that neither auto-resume nor+ // runner dispatch has begun. An error after ensureReady may follow a start.+ try {+ opts?.admit?.(box, boxId)+ } catch (error) {+ if (error instanceof Error) throw noEffect(error)+ throw error+ }if (policy.autoResume && box.autoResume) {await this.autoResume.ensureReady(box.id, authContext.organization, opts?.admit)@@ -582,10 +589,11 @@ export class BoxliteProxyController {ws: opts?.ws ?? false,pathRewrite: () => targetPathForRunnerBox(box.id),on: {- proxyReq: (proxyReq: any, originalReq: any) => {+ proxyReq: (proxyReq, originalReq) => {proxyReq.setHeader('Authorization', `Bearer ${runner.apiKey}`)fixRequestBody(proxyReq, originalReq)},+ proxyRes: trackReplayUpstream,},proxyTimeout: opts?.proxyTimeoutMs ?? 5 * 60 * 1000,}diff --git a/apps/api/src/boxlite-rest/boxlite-registry.controller.ts b/apps/api/src/boxlite-rest/boxlite-registry.controller.tsindex 9cddcbb9d..13ec45569 100644--- a/apps/api/src/boxlite-rest/boxlite-registry.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-registry.controller.ts@@ -3,7 +3,7 @@* SPDX-License-Identifier: AGPL-3.0*/-import { Body, Controller, Delete, Get, HttpCode, Param, ParseUUIDPipe, Post, UseGuards } from '@nestjs/common'+import { Body, Controller, Delete, Get, HttpCode, Param, Post, UseGuards } from '@nestjs/common'import { ApiExcludeController } from '@nestjs/swagger'import { Audit, TypedRequest } from '../audit/decorators/audit.decorator'import { AuditAction } from '../audit/enums/audit-action.enum'@@ -18,6 +18,7 @@ import { OrganizationResourceActionGuard } from '../organization/guards/organizaimport { RegistryCredential } from '../registry/entities/registry-credential.entity'import { RegistriesService } from '../registry/services/registries.service'import { CreateRegistryDto } from './dto/create-registry.dto'+import { ReplayParseUUIDPipe } from '../common/replay-validation.pipe'type RestRegistryCredential = {id: string@@ -87,7 +88,7 @@ export class BoxliteRegistryController {})async remove(@AuthContext() authContext: OrganizationAuthContext,- @Param('id', ParseUUIDPipe) id: string,+ @Param('id', ReplayParseUUIDPipe) id: string,): Promise<void> {await this.registries.delete(authContext.organizationId, id)}diff --git a/apps/api/src/boxlite-rest/boxlite-rest-routing.spec.ts b/apps/api/src/boxlite-rest/boxlite-rest-routing.spec.tsindex 303699b47..604eb02b8 100644--- a/apps/api/src/boxlite-rest/boxlite-rest-routing.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-rest-routing.spec.ts@@ -32,6 +32,7 @@ import { BoxliteRegistryController } from './boxlite-registry.controller'import { RegistriesService } from '../registry/services/registries.service'import { CommerceBoxLimitService } from './commerce-box-limit.service'import { AUDIT_CONTEXT_KEY, AuditContext } from '../audit/decorators/audit.decorator'+import { RequestReplayPolicy } from './request-replay-policy'jest.mock('http-proxy-middleware', () => ({createProxyMiddleware: jest.fn(),@@ -95,7 +96,7 @@ describe('BoxLite REST routing', () => {}async function startApp(controllers: any[], providers: any[]) {- const moduleRef = await Test.createTestingModule({ controllers, providers })+ const moduleRef = await Test.createTestingModule({ controllers, providers: [RequestReplayPolicy, ...providers] })// The proxy controller is here only for its routes. Mock whatever it// injects, so a constructor dependency added later (#1723 added// TunnelService) cannot stop these routing tests from building.diff --git a/apps/api/src/boxlite-rest/boxlite-rest.module.ts b/apps/api/src/boxlite-rest/boxlite-rest.module.tsindex 8f467e10a..47bd312ba 100644--- a/apps/api/src/boxlite-rest/boxlite-rest.module.ts+++ b/apps/api/src/boxlite-rest/boxlite-rest.module.ts@@ -37,6 +37,7 @@ import { BoxliteMemberController } from './boxlite-member.controller'import { BoxliteInvitationController } from './boxlite-invitation.controller'import { BoxliteDomainController } from './boxlite-domain.controller'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'@@ -50,6 +51,7 @@ import { BoxliteCheckpointController } from './boxlite-checkpoint.controller'ImageModule,RegistryModule,AuditModule,+ RequestReplayModule,],controllers: [BoxliteCheckpointController,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.tsindex b96b37373..a7bdb4c98 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@@ -134,6 +134,29 @@ describe('BoxliteWsProxyService', () => {)})+ it.each(['', 'not-a-uuid', '9521e865-87b5-4ad9-8ed7-818ee4f182d4'])(+ 'rejects any replay key %p before authentication, tickets, or guest effects',+ async (key) => {+ const harness = buildAuthHarness()+ const req = authRequest('blk_live_test')+ req.headers['idempotency-key'] = key+ const socket = { write: jest.fn(), destroy: jest.fn() }+ const proxyHandler = jest.mocked(createProxyMiddleware).mock.results.at(-1)?.value+ const consume = jest.spyOn(harness.attachTickets, 'consume')++ await (harness.service as unknown as BoxliteWsProxyService).upgrade(req, socket as never, Buffer.alloc(0))++ expect(socket.write).toHaveBeenCalledWith(expect.stringContaining('400 Bad Request'))+ expect(socket.destroy).toHaveBeenCalled()+ expect(harness.apiKeyService.getApiKeyByValue).not.toHaveBeenCalled()+ expect(consume).not.toHaveBeenCalled()+ expect(harness.boxService.findOneByIdOrName).not.toHaveBeenCalled()+ expect(harness.autoResume.ensureReady).not.toHaveBeenCalled()+ expect(harness.audit.createLog).not.toHaveBeenCalled()+ expect(proxyHandler.upgrade).not.toHaveBeenCalled()+ },+ )+it('does not upgrade the websocket when strict AutoResume fails', async () => {const harness = buildAuthHarness()const { service, apiKeyService, organizationUserService, autoResume } = harnessdiff --git a/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.ts b/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.tsindex ca25f3407..7ebe4967f 100644--- a/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.ts+++ b/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.ts@@ -130,10 +130,15 @@ export class BoxliteWsProxyService {return}+ if (req.headers['idempotency-key'] !== undefined) {+ this.respondAndClose(socket, 400, 'Bad Request')+ return+ }// Browsers cannot set `Authorization` on a WebSocket; they send a ticket.const auth = req.headers['authorization']? await this.authenticate(req, match.tenant): await this.authenticateTicket(req, match)+if (!auth) {this.respondAndClose(socket, 401, 'Unauthorized')returndiff --git a/apps/api/src/boxlite-rest/request-replay-discovery.integration.spec.ts b/apps/api/src/boxlite-rest/request-replay-discovery.integration.spec.tsnew file mode 100644index 000000000..bff5da0ea--- /dev/null+++ b/apps/api/src/boxlite-rest/request-replay-discovery.integration.spec.ts@@ -0,0 +1,142 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */++import express from 'express'+import type { Request } from 'express'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { parse } from 'yaml'+import { McpDelegation } from '../auth/mcp-delegation'+import { McpCatalog } from '../mcp/mcp-catalog'+import { McpDispatcher } from '../mcp/mcp-dispatcher'+import { servedOperations } from '../mcp/mcp-routes'+import { BoxliteConfigController } from './boxlite-config.controller'+import { assertReplaySupported, replayPolicy, RequestReplayPolicy } from './request-replay-policy'++jest.mock('http-proxy-middleware', () => ({ createProxyMiddleware: jest.fn(() => ({ upgrade: jest.fn() })) }))++const box = parse(readFileSync(resolve(__dirname, '../../../../openapi/box.openapi.yaml'), 'utf8'))+const admin = parse(readFileSync(resolve(__dirname, '../../../../openapi/admin.openapi.yaml'), 'utf8'))+const catalog = new McpCatalog({ box, admin, dashboard: {}, delegable: () => true, served: () => true })+const key = '017f22e2-79b0-7cc3-98c4-dc0c0c07398f'++describe('hosted replay discovery and production requests', () => {+ it.each(['startExecution', 'createInvite'])(+ '%s preserves inputs with and without the optional header',+ async (id) => {+ const operation = catalog.get(id)!+ expect(operation.params).toContainEqual({ name: 'Idempotency-Key', in: 'header', required: false })+ const seen: { method: string; url: string; body: unknown; key?: string }[] = []+ const app = express()+ app.use(express.json())+ app.use((req, res) => {+ seen.push({+ method: req.method,+ url: req.originalUrl,+ body: req.body,+ key: req.headers['idempotency-key'] as string,+ })+ res.status(201).json({ id: 'original-result' })+ })+ const dispatcher = new McpDispatcher(+ { httpAdapter: { getInstance: () => app } } as never,+ new McpDelegation(),+ {} as never,+ )+ const args = Object.fromEntries(+ operation.params.filter((param) => param.in === 'path').map((param) => [param.name, 'org/target']),+ )+ const body = id === 'startExecution' ? { cmd: ['echo', 'hello'] } : { email: '[email protected]' }+ const request = { headers: {}, user: { organizationId: 'org', userId: 'user' } } as unknown as Request+ try {+ await dispatcher.call(operation, { ...args, body }, request)+ await dispatcher.call(operation, { ...args, body, 'Idempotency-Key': key }, request)+ expect(seen).toHaveLength(2)+ expect(seen[0]).toEqual({+ method: operation.method.toUpperCase(),+ url: operation.path.replace(/\{[^}]+\}/g, 'org%2Ftarget'),+ body,+ key: undefined,+ })+ expect(seen[1]).toEqual({ ...seen[0], key })+ } finally {+ await dispatcher.onModuleDestroy()+ }+ },+ )++ it('advertises exactly registered replay writes in config and MCP', () => {+ const app = express()+ const registeredIds = [+ 'bindDomain',+ 'claimDomain',+ 'configureSsh',+ 'createBox',+ 'createCheckpoint',+ 'createImageAlias',+ 'createRegistry',+ 'createVolume',+ 'deleteImageAlias',+ 'disableSsh',+ 'enableSsh',+ 'killExecution',+ 'removeBox',+ 'removeCheckpoint',+ 'removeImage',+ 'removeRegistry',+ 'removeVolume',+ 'resizeExecution',+ 'revokeTunnel',+ 'signalExecution',+ 'startBox',+ 'startExecution',+ 'stopBox',+ 'unbindDomain',+ 'updateInboundNetwork',+ 'updateOutboundNetwork',+ ]+ const operations = registeredIds.map((id) => catalog.get(id)!)+ expect(operations.every((op) => replayPolicy(op.method, op.path, op.webSocket) === 'supported')).toBe(true)+ for (const op of operations) {+ app[op.method as 'post'](op.path.replace(/\{([^}]+)\}/g, ':$1'), (_req, res) => res.end())+ expect(op.inputSchema).toMatchObject({ properties: { 'Idempotency-Key': { type: 'string', format: 'uuid' } } })+ }+ const policy = new RequestReplayPolicy()+ policy.configure(app, box)+ const config = new BoxliteConfigController(undefined, policy).getConfig().capabilities+ expect(config.idempotency_key_lifetime).toBe('PT24H')+ expect(config.idempotency_operations.sort()).toEqual(operations.map((op) => op.operationId).sort())+ const served = servedOperations(app as never, () => false)+ const actual = new McpCatalog({ box, admin: {}, dashboard: {}, delegable: () => true, served })+ expect(+ actual+ .all()+ .map((op) => op.operationId)+ .sort(),+ ).toEqual(config.idempotency_operations)+ expect(actual.get('createSnapshot')).toBeUndefined()+ for (const id of ['getBox', 'uploadFiles', 'prepareTunnel', 'attachExecution']) {+ expect(catalog.get(id)!.inputSchema.properties).not.toHaveProperty('Idempotency-Key')+ }+ expect(box.components.parameters.idempotencyKey.schema.default).toBeUndefined()+ })+ it('rejects keyed file transfers before transport dispatch', () => {+ expect(() => assertReplaySupported('GET', '/api/v1/boxes/b/files', { 'idempotency-key': key })).toThrow()+ expect(() => assertReplaySupported('POST', '/api/v1/boxes', { 'idempotency-key': key })).not.toThrow()+ expect(() => assertReplaySupported('GET', '/api/v1/boxes/b/files', {})).not.toThrow()+ })++ it('discovers wildcard write routes and refuses writes without operation IDs', () => {+ const app = express()+ app.use((_req, _res, next) => next())+ app.all('/api/v1/probe', (_req, res) => res.end())+ const policy = new RequestReplayPolicy()+ policy.configure(app, { paths: { '/probe': { post: { operationId: 'probe' }, get: {} } } })+ expect(policy.operations()).toEqual(['probe'])+ expect(() => policy.configure(app, { paths: { '/probe': { post: {} } } })).toThrow('Missing operationId')+ policy.configure({}, {})+ expect(policy.operations()).toEqual([])+ })+})diff --git a/apps/api/src/boxlite-rest/request-replay-policy.ts b/apps/api/src/boxlite-rest/request-replay-policy.tsnew file mode 100644index 000000000..78a6bb894--- /dev/null+++ b/apps/api/src/boxlite-rest/request-replay-policy.ts@@ -0,0 +1,128 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */+import { BadRequestException, Injectable } from '@nestjs/common'+import { isUUID } from 'class-validator'+import { createHash } from 'node:crypto'+import type { IncomingHttpHeaders } from 'node:http'+import type { Request } from 'express'+import { routeShape } from '../mcp/mcp-routes'++export const REPLAY_LIFETIME = 'PT24H'+export const REPLAY_ONLY = Symbol('replay-only')+export const REPLAY_RESOURCE = Symbol('replay-resource')+const WRITES: Record<string, true> = { POST: true, PUT: true, PATCH: true, DELETE: true }++function canonicalRoute(path: string): string {+ return path.replace(/\/(?:\:prefix|\{prefix\})(?=\/)/, '').replace(/\/$/, '')+}++export function replayPolicy(+ method: string,+ path: string,+ webSocket = false,+): 'supported' | 'excluded' | 'outside' | 'read' {+ const route = canonicalRoute(path).split('?')[0]+ if (!/^\/(?:api\/)?v1(?:\/|$)/.test(route)) return 'outside'+ if (/\/v1\/organizations(?:\/|$)/.test(route)) return 'outside'+ if (webSocket || /\/attach(?:\/|$)/.test(route)) return 'excluded'+ if (/\/files(?:\/|$)/.test(route) || (method.toUpperCase() === 'POST' && /\/network\/tunnel$/.test(route)))+ return 'excluded'+ if (!WRITES[method.toUpperCase()]) return 'read'+ return 'supported'+}++export function validateReplayKey(req: Pick<Request, 'headers' | 'rawHeaders'>): string | undefined {+ const raw = req.rawHeaders ?? []+ let count = 0+ for (let index = 0; index < raw.length; index += 2) if (raw[index].toLowerCase() === 'idempotency-key') count+++ const key = req.headers['idempotency-key']+ if (key === undefined && count === 0) return undefined+ if (count > 1 || typeof key !== 'string' || !isUUID(key))+ throw new BadRequestException('Idempotency-Key must be a single UUID')+ return key+}++/** Called before a stream or upgrade can reach its business handler. */+export function assertReplaySupported(method: string, path: string, headers: IncomingHttpHeaders): void {+ if (+ headers['idempotency-key'] !== undefined &&+ replayPolicy(method, path, /\/attach(?:\?|$)/.test(path)) === 'excluded'+ ) {+ throw new BadRequestException('Idempotency-Key is not supported for this operation')+ }+}++function stable(value: unknown): string {+ if (value === undefined) return 'undefined'+ if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`+ if (value !== null && typeof value === 'object') {+ return `{${Object.entries(value)+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))+ .map(([key, item]) => `${JSON.stringify(key)}:${stable(item)}`)+ .join(',')}}`+ }+ return JSON.stringify(value)+}++export function replayIdentity(req: Request): { operation: string; fingerprint: string } {+ const route = canonicalRoute(String(req.route?.path ?? req.path))+ const method = req.method.toUpperCase()+ const shape = routeShape(route)+ const operation =+ method === 'POST' && shape === '/api/v1/boxes'+ ? 'createBox'+ : method === 'POST' && shape === '/api/v1/boxes/*/exec'+ ? 'startExecution'+ : `${method} ${shape}`+ const params = Object.fromEntries(Object.entries(req.params ?? {}).filter(([key]) => key !== 'prefix'))+ const fingerprint = `v2:${createHash('sha256')+ .update(stable([method, params, req.query, req.body]))+ .digest('hex')}`+ return { operation, fingerprint }+}++/** Discovery describes registered routes; it never decides whether a new write is protected. */+@Injectable()+export class RequestReplayPolicy {+ private supportedOperations: string[] = []++ configure(expressApp: unknown, document: { paths?: object }): void {+ // Express exposes its registered router layers without a public structural type.+ const app = expressApp as {+ router?: { stack?: { route?: { path: string | string[]; methods: Record<string, boolean> } }[] }+ }+ const layers = app.router?.stack ?? []+ const routes = new Set<string>()+ for (const { route } of layers) {+ if (!route) continue+ for (const path of [route.path].flat())+ for (const [method, enabled] of Object.entries(route.methods)) {+ if (enabled)+ routes.add(`${method === '_all' ? '*' : method.toUpperCase()} ${routeShape(canonicalRoute(path))}`)+ }+ }+ const ids = new Set<string>()+ for (const [path, item] of Object.entries(document.paths ?? {})) {+ const route = `/api/v1${canonicalRoute(path)}`+ for (const [method, operation] of Object.entries(item as object)) {+ if (!this.supports(method, route)) continue+ const shape = routeShape(route)+ if (!routes.has(`${method.toUpperCase()} ${shape}`) && !routes.has(`* ${shape}`)) continue+ const id =+ operation && typeof operation === 'object' && 'operationId' in operation ? operation.operationId : undefined+ if (typeof id !== 'string' || !id) throw new Error(`Missing operationId for replay operation ${method} ${path}`)+ ids.add(id)+ }+ }+ this.supportedOperations = [...ids].sort()+ }++ supports(method: string, path: string, webSocket = false): boolean {+ return replayPolicy(method, path, webSocket) === 'supported'+ }+ operations(): string[] {+ return [...this.supportedOperations]+ }+}diff --git a/apps/api/src/boxlite-rest/request-replay-proxy.integration.spec.ts b/apps/api/src/boxlite-rest/request-replay-proxy.integration.spec.tsnew file mode 100644index 000000000..ee1d067ab--- /dev/null+++ b/apps/api/src/boxlite-rest/request-replay-proxy.integration.spec.ts@@ -0,0 +1,288 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */++import { createHash, randomUUID } from 'node:crypto'+import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'+import type { AddressInfo } from 'node:net'+import { once } from 'node:events'+import { setTimeout as delay } from 'node:timers/promises'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { parse } from 'yaml'+import type { Request } from 'express'+import { Socket } from 'node:net'+import { getRedisConnectionToken } from '@nestjs-modules/ioredis'+import { ExecutionContext, INestApplication } from '@nestjs/common'+import { Test } from '@nestjs/testing'+import Redis from 'ioredis'+import { CombinedAuthGuard } from '../auth/combined-auth.guard'+import { OrganizationResourceActionGuard } from '../organization/guards/organization-resource-action.guard'+import { BoxService } from '../box/services/box.service'+import { RunnerService } from '../box/services/runner.service'+import { BoxAutoResumeService } from '../box/services/box-auto-resume.service'+import { TunnelService } from '../box/services/tunnel.service'+import { BoxliteProxyController } from './boxlite-proxy.controller'+import { BoxRequestReplayService } from './box-request-replay.service'+import { RequestReplayInterceptor } from './request-replay.interceptor'+import { HttpAdapterHost } from '@nestjs/core'+import { McpDispatcher } from '../mcp/mcp-dispatcher'+import { McpCatalog } from '../mcp/mcp-catalog'+import { McpDelegation } from '../auth/mcp-delegation'+import { BoxliteWsProxyService } from './boxlite-ws-proxy.service'++jest.mock('http-proxy-middleware', () =>+ process.getBuiltinModule('node:module').createRequire(__filename)('http-proxy-middleware'),+)+const describeWithRedis = process.env.REDIS_HOST ? describe : describe.skip++describeWithRedis('Request replay through the production HTTP runner proxy', () => {+ const organizationId = `proxy-replay-${randomUUID()}`+ const caller = {+ userId: 'proxy-user',+ email: '[email protected]',+ role: 'user',+ organizationId,+ organization: { id: organizationId },+ }+ let redis: Redis+ let app: INestApplication+ let runner: Server+ let base: string+ let reply: (req: IncomingMessage, res: ServerResponse) => void+ let dispatcher: McpDispatcher | undefined+ let runnerCalls = 0+ const boxService = {+ findOneByIdOrName: jest.fn(async (id: string) => ({+ id,+ organizationId,+ runnerId: 'runner',+ autoResume: false,+ state: 'started',+ desiredState: 'started',+ })),+ updateLastActivityAt: jest.fn(async () => undefined),+ }+ const autoResume = { ensureReady: jest.fn(async () => undefined) }++ beforeAll(async () => {+ redis = new Redis({+ host: process.env.REDIS_HOST,+ port: Number(process.env.REDIS_PORT || 6379),+ username: process.env.REDIS_USERNAME || undefined,+ password: process.env.REDIS_PASSWORD || undefined,+ })+ await redis.ping()+ runner = createServer((req, res) => {+ req.resume()+ req.on('end', () => {+ runnerCalls+++ reply(req, res)+ })+ })+ runner.listen(0, '127.0.0.1')+ await once(runner, 'listening')+ const runnerUrl = `http://127.0.0.1:${(runner.address() as AddressInfo).port}`+ const module = await Test.createTestingModule({+ controllers: [BoxliteProxyController],+ providers: [+ BoxRequestReplayService,+ RequestReplayInterceptor,+ { provide: getRedisConnectionToken(), useValue: redis },+ { provide: BoxService, useValue: boxService },+ { provide: RunnerService, useValue: { findOne: async () => ({ apiUrl: runnerUrl, apiKey: 'runner-secret' }) } },+ { provide: BoxAutoResumeService, useValue: autoResume },+ { provide: TunnelService, useValue: {} },+ ],+ })+ .useMocker(() => ({}))+ .overrideGuard(CombinedAuthGuard)+ .useValue({+ canActivate: (context: ExecutionContext) => {+ const req = context.switchToHttp().getRequest<Request>()+ if (req.headers['x-boxlite-mcp-delegation']) return new CombinedAuthGuard().canActivate(context)+ req.user = caller+ return true+ },+ })+ .overrideGuard(OrganizationResourceActionGuard)+ .useValue({ canActivate: () => true })+ .compile()+ app = module.createNestApplication()+ app.setGlobalPrefix('api')+ app.useGlobalInterceptors(app.get(RequestReplayInterceptor))+ await app.listen(0, '127.0.0.1')+ base = await app.getUrl()+ })++ beforeEach(() => {+ runnerCalls = 0+ jest.clearAllMocks()+ reply = (_req, res) => {+ res.writeHead(201, { 'Content-Type': 'application/json', Location: '/executions/original-execution' })+ res.end('{ "execution_id": "original-execution" }\n')+ }+ })++ afterAll(async () => {+ await dispatcher?.onModuleDestroy()+ await app?.close()+ if (runner) {+ runner.closeAllConnections()+ const closed = once(runner, 'close')+ runner.close()+ await closed+ }+ if (redis) {+ const keys = await redis.keys(`replay:${organizationId}:*`)+ if (keys.length) await redis.del(...keys)+ await redis.quit()+ }+ })++ const send = (method: string, path: string, key: string, body?: unknown) =>+ fetch(`${base}/api/v1/boxes/${path}`, {+ method,+ headers: { 'Idempotency-Key': key, ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },+ body: body === undefined ? undefined : JSON.stringify(body),+ })++ async function waitForState(key: string, expected = ['complete']) {+ const deadline = Date.now() + 2_000+ while (Date.now() < deadline) {+ const hash = createHash('sha256').update(key).digest('hex')+ const keys = await redis.keys(`replay:${organizationId}:*:${hash}`)+ const states = await Promise.all(keys.map((record) => redis.hget(record, 'state')))+ if (states.some((state) => state !== null && expected.includes(state))) return+ await delay(5)+ }+ throw new Error(`The proxy response did not reach replay state ${expected.join(' or ')}`)+ }++ it.each([+ ['POST', 'exec', 201, { command: '/bin/echo', args: ['hello'] }],+ ['POST', 'executions/e1/signal', 204, { signal: 'TERM' }],+ ] as const)('replays %s %s status %s without another runner operation', async (method, suffix, status, body) => {+ if (status === 204) reply = (_req, res) => res.writeHead(204).end()+ const boxId = randomUUID()+ const key = randomUUID()+ const path = `${boxId}/${suffix}`+ const first = await send(method, path, key, body)+ const originalBody = await first.text()+ expect(first.status).toBe(status)+ expect(originalBody).toBe(status === 204 ? '' : '{ "execution_id": "original-execution" }\n')+ // A successful response can reach the client before its bounded Redis write finishes.+ await waitForState(key)+ const retry = await send(method, path, key, body)+ expect(retry.status).toBe(status)+ expect(await retry.text()).toBe(originalBody)+ expect(retry.headers.get('content-type')).toBe(first.headers.get('content-type'))+ expect(retry.headers.get('location')).toBe(first.headers.get('location'))+ expect(runnerCalls).toBe(1)+ })+ it('shares the execution result between production MCP dispatch and a direct REST retry', async () => {+ const operation = new McpCatalog({+ box: parse(readFileSync(resolve(__dirname, '../../../../openapi/box.openapi.yaml'), 'utf8')),+ admin: {},+ dashboard: {},+ delegable: () => true,+ served: () => true,+ }).get('startExecution')!+ const boxId = randomUUID()+ const key = randomUUID()+ const body = { command: '/bin/echo', args: ['cross-transport'] }+ dispatcher = new McpDispatcher(app.get(HttpAdapterHost), new McpDelegation(), {} as BoxliteWsProxyService)+ const mcpRequest = { user: caller, headers: {}, socket: new Socket() } as unknown as Request+ const original = await dispatcher.call(operation, { box_id: boxId, 'Idempotency-Key': key, body }, mcpRequest)+ expect(original.status).toBe(201)+ expect(original.json).toEqual({ execution_id: 'original-execution' })+ await waitForState(key)+ const retry = await send('POST', `${boxId}/exec`, key, body)+ expect(retry.status).toBe(201)+ expect(await retry.json()).toEqual(original.json)+ expect(runnerCalls).toBe(1)+ })++ it('keeps a downstream failure behind the unknown fence', async () => {+ const status = 503+ reply = (_req, res) => {+ res.writeHead(status, { 'Content-Type': 'application/json' })+ res.end('{"error":"downstream"}')+ }+ const key = randomUUID()+ const path = `${randomUUID()}/exec`+ const first = await send('POST', path, key, { command: 'effect' })+ expect(first.status).toBe(status)+ await first.text()+ await waitForState(key, ['unknown'])+ const retry = await send('POST', path, key, { command: 'effect' })+ expect(retry.status).toBe(422)+ expect(await retry.json()).toMatchObject({ code: 'idempotency_outcome_unknown' })+ expect(runnerCalls).toBe(1)+ })++ it('fences a runner disconnect after a partial success response', async () => {+ let upstream: ServerResponse | undefined+ reply = (_req, res) => {+ upstream = res+ res.writeHead(201, { 'Content-Type': 'application/json' })+ res.write('{"execution_id":')+ }+ const key = randomUUID()+ const path = `${randomUUID()}/exec`+ const body = { command: 'effect' }+ try {+ const first = await send('POST', path, key, body)+ expect(first.status).toBe(201)+ upstream?.destroy()+ await Promise.allSettled([first.text()])+ await waitForState(key, ['complete', 'unknown'])+ const retry = await send('POST', path, key, body)+ expect(retry.status).toBe(422)+ expect(await retry.json()).toMatchObject({ code: 'idempotency_outcome_unknown' })+ expect(runnerCalls).toBe(1)+ } finally {+ upstream?.destroy()+ }+ })++ it('rejects keyed file downloads before runner dispatch', async () => {+ const response = await send('GET', `${randomUUID()}/files?path=/tmp/file`, randomUUID())+ expect(response.status).toBe(400)+ await response.text()+ expect(boxService.findOneByIdOrName).not.toHaveBeenCalled()+ expect(autoResume.ensureReady).not.toHaveBeenCalled()+ expect(runnerCalls).toBe(0)+ })++ it('rejects keyed WebSockets for tenant organizations before effects', async () => {+ // Generic keys are covered by the WS service suite; this tenant resembles an API route prefix.+ const effect = jest.fn()+ const dependency = { getApiKeyByValue: effect, findOne: effect, consume: effect, createLog: effect }+ const service = new BoxliteWsProxyService(+ dependency as never,+ dependency as never,+ dependency as never,+ boxService as never,+ dependency as never,+ autoResume as never,+ dependency as never,+ undefined,+ dependency as never,+ dependency as never,+ )+ const socket = { write: jest.fn(), destroy: jest.fn() }+ const request = {+ url: `/api/v1/organizations/boxes/${randomUUID()}/executions/e1/attach?ticket=unused`,+ headers: { 'idempotency-key': randomUUID() },+ } as unknown as IncomingMessage+ await service.upgrade(request, socket as never, Buffer.alloc(0))+ expect(socket.write).toHaveBeenCalledWith(expect.stringContaining('400 Bad Request'))+ expect(socket.destroy).toHaveBeenCalled()+ expect(effect).not.toHaveBeenCalled()+ expect(boxService.findOneByIdOrName).not.toHaveBeenCalled()+ expect(autoResume.ensureReady).not.toHaveBeenCalled()+ expect(runnerCalls).toBe(0)+ })+})diff --git a/apps/api/src/boxlite-rest/request-replay-response.ts b/apps/api/src/boxlite-rest/request-replay-response.tsnew file mode 100644index 000000000..43b416872--- /dev/null+++ b/apps/api/src/boxlite-rest/request-replay-response.ts@@ -0,0 +1,105 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */+import type { IncomingMessage, ServerResponse } from 'node:http'+import type { Response } from 'express'+import { ReplayResponse, REPLAY_MAX_RESPONSE_BYTES } from './box-request-replay.service'++const replayUpstreams = new WeakMap<ServerResponse, IncomingMessage | undefined>()++export function trackReplayUpstream(+ upstream: IncomingMessage,+ _request: IncomingMessage,+ response: ServerResponse,+): void {+ if (replayUpstreams.has(response)) replayUpstreams.set(response, upstream)+}++/** Side-channel capture: forwarding keeps Node's exact callback, return value and backpressure behavior. */+export function captureReplayResponse(+ response: Response,+ complete: (result: ReplayResponse) => void,+ unknown: () => void,+ stopHeartbeat: () => void,+): () => void {+ const write = response.write+ const end = response.end+ let chunks: Buffer[] = []+ let size = 0+ let overflow = false+ let ended = false+ let closed = false++ const collect = (chunk: unknown, encoding: unknown): void => {+ if (overflow || chunk === undefined || chunk === null || typeof chunk === 'function') return+ const bytesEncoding = typeof encoding === 'string' ? (encoding as BufferEncoding) : undefined+ const length =+ typeof chunk === 'string'+ ? Buffer.byteLength(chunk, bytesEncoding)+ : chunk instanceof Uint8Array+ ? chunk.byteLength+ : undefined+ if (length === undefined || size + length > Math.floor(((REPLAY_MAX_RESPONSE_BYTES - 4096) * 3) / 4)) {+ overflow = true+ chunks = []+ return+ }+ const bytes = typeof chunk === 'string' ? Buffer.from(chunk, bytesEncoding) : Buffer.from(chunk as Uint8Array)+ size += length+ chunks.push(bytes)+ }+ const cleanup = (): void => {+ if (response.write === wrappedWrite) response.write = write+ if (response.end === wrappedEnd) response.end = end+ response.off('close', onClose)+ response.off('error', onClose)+ replayUpstreams.delete(response)+ chunks = []+ stopHeartbeat()+ }+ const onClose = (): void => {+ if (ended || closed) return+ closed = true+ stopHeartbeat()+ unknown()+ // Keep the owner capture until end: a still-running handler may confirm late success.+ }+ const wrappedWrite: typeof response.write = function (chunk: unknown, ...args: unknown[]): boolean {+ collect(chunk, args[0])+ // Node overloads are runtime-equivalent; forwarding must retain the original arguments.+ return Reflect.apply(write, response, [chunk, ...args])+ }+ const wrappedEnd: typeof response.end = function (...args: unknown[]): Response {+ if (!ended) {+ ended = true+ collect(args[0], args[1])+ const status = response.statusCode+ const headers: Record<string, string> = {}+ for (const name of ['content-type', 'location']) {+ const value = response.getHeader(name)+ if (typeof value === 'string') headers[name] = value+ }+ const upstream = replayUpstreams.get(response)+ // A proxy error can end the downstream response after a partial upstream 2xx.+ if (+ status >= 200 &&+ status < 300 &&+ !overflow &&+ !headers['content-type']?.includes('text/event-stream') &&+ (!upstream || upstream.complete)+ ) {+ const body = status === 204 ? '' : Buffer.concat(chunks, size).toString('base64')+ complete({ status, body, encoding: 'base64', headers })+ } else unknown()+ cleanup()+ }+ return Reflect.apply(end, response, args)+ }+ replayUpstreams.set(response, undefined)+ response.write = wrappedWrite+ response.end = wrappedEnd+ response.once('close', onClose)+ response.once('error', onClose)+ return cleanup+}diff --git a/apps/api/src/boxlite-rest/request-replay.integration.spec.ts b/apps/api/src/boxlite-rest/request-replay.integration.spec.tsnew file mode 100644index 000000000..0948cda51--- /dev/null+++ b/apps/api/src/boxlite-rest/request-replay.integration.spec.ts@@ -0,0 +1,393 @@+/// <reference lib="es2024.promise" />+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */+import { createHash, randomUUID } from 'node:crypto'+import { setTimeout as delay } from 'node:timers/promises'+import { request as httpRequest } from 'node:http'+import Redis from 'ioredis'+import { getRedisConnectionToken } from '@nestjs-modules/ioredis'+import {+ BadRequestException,+ Body,+ ClassSerializerInterceptor,+ Controller,+ HttpCode,+ INestApplication,+ Param,+ Post,+ Res,+ UseInterceptors,+ UsePipes,+} from '@nestjs/common'+import { Test } from '@nestjs/testing'+import { Exclude } from 'class-transformer'+import { IsString } from 'class-validator'+import type { Request, Response, NextFunction } from 'express'+import { BoxRequestReplayService, REPLAY_MAX_RESPONSE_BYTES } from './box-request-replay.service'+import { RequestReplayInterceptor } from './request-replay.interceptor'+import { ReplayParseIntPipe, ReplayValidationPipe } from '../common/replay-validation.pipe'+import { BoxCreationLimitExceededError } from '../box/errors/box-creation-limit.error'+import { Audit } from '../audit/decorators/audit.decorator'+import { AuditAction } from '../audit/enums/audit-action.enum'+import { AuditTarget } from '../audit/enums/audit-target.enum'+import { AuditInterceptor } from '../audit/interceptors/audit.interceptor'+import { AuditService } from '../audit/services/audit.service'+import { AllExceptionsFilter } from '../filters/all-exceptions.filter'++class Input {+ @IsString() value!: string+}+class PublicResult {+ readonly id = randomUUID()+ @Exclude() secret = 'private'+}+let effects = 0+let quota = false+let entered = Promise.withResolvers<void>()+let release = Promise.withResolvers<void>()+@Controller(['v1/probe/:target', 'v1/:prefix/probe/:target'])+class ProbeController {+ @Post()+ create(@Body() body: unknown) {+ return { id: ++effects, body }+ }+ @Post('slow')+ async slow() {+ effects+++ entered.resolve()+ await release.promise+ return { id: randomUUID() }+ }+ @Post('quota')+ admitted() {+ if (quota) throw new BoxCreationLimitExceededError(3, 3)+ return this.create({})+ }+ @Post('failure')+ submitted() {+ effects+++ throw new BadRequestException('effect committed before failure')+ }+ @Post('validate')+ @UsePipes(new ReplayValidationPipe({ transform: true }))+ validate(@Body() body: Input) {+ return this.create(body)+ }+ @Post('count/:count')+ count(@Param('count', ReplayParseIntPipe) count: number) {+ return this.create({ count })+ }+ @Post('dto')+ @Audit({ action: AuditAction.CREATE, targetType: AuditTarget.BOX, targetIdFromResult: (result) => result.id })+ @UseInterceptors(ClassSerializerInterceptor)+ dto() {+ effects+++ return new PublicResult()+ }+ @Post('empty')+ @HttpCode(204)+ empty() {+ effects+++ }+ @Post('large')+ large(@Res() res: Response) {+ effects+++ res.json({ value: 'x'.repeat(REPLAY_MAX_RESPONSE_BYTES) })+ }+}++@Controller('v1/boxes')+class VolumeWriteController {+ @Post()+ create() {+ return { id: ++effects }+ }+}++const integration = process.env.REDIS_HOST ? describe : describe.skip+integration('Replay HTTP contract with shared Redis', () => {+ const org = randomUUID()+ const apps: INestApplication[] = []+ const bases: string[] = []+ let redis: Redis+ const services: BoxRequestReplayService[] = []+ const audit = {+ createLog: jest.fn(async () => ({ id: randomUUID() })),+ updateLog: jest.fn(async () => undefined),+ }+ beforeAll(async () => {+ redis = new Redis({+ host: process.env.REDIS_HOST,+ port: Number(process.env.REDIS_PORT || 6379),+ username: process.env.REDIS_USERNAME || undefined,+ password: process.env.REDIS_PASSWORD || undefined,+ })+ await redis.ping()+ for (let i = 0; i < 2; i++) {+ const module = await Test.createTestingModule({+ controllers: [ProbeController, VolumeWriteController],+ providers: [+ AuditInterceptor,+ BoxRequestReplayService,+ { provide: getRedisConnectionToken(), useValue: redis },+ { provide: AuditService, useValue: audit },+ ],+ }).compile()+ services.push(module.get(BoxRequestReplayService))+ const app = module.createNestApplication()+ app.setGlobalPrefix('api')+ app.use((req: Request & { user?: unknown }, res: Response, next: NextFunction) => {+ req.user = {+ organizationId: req.headers['x-org'] ?? org,+ userId: req.headers['x-user'] ?? 'user',+ role: 'user',+ }+ res.setHeader('x-request-id', randomUUID())+ next()+ })+ app.useGlobalInterceptors(+ app.get(AuditInterceptor),+ new RequestReplayInterceptor(module.get(BoxRequestReplayService)),+ )+ app.useGlobalFilters(new AllExceptionsFilter({} as never))+ await app.listen(0, '127.0.0.1')+ apps.push(app)+ bases.push(await app.getUrl())+ }+ })+ afterAll(async () => {+ release.resolve()+ for (const app of apps) await app.close()+ if (redis) {+ const keys = await redis.keys(`replay:${org}:*`)+ if (keys.length) await redis.del(...keys)+ await redis.quit()+ }+ })+ const send = async (+ key?: string,+ path = 'probe/target',+ body: unknown = {},+ replica = 0,+ headers: Record<string, string> = {},+ ) => {+ const response = await fetch(`${bases[replica]}/api/v1/${path}`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ ...(key === undefined ? {} : { 'Idempotency-Key': key }),+ ...headers,+ },+ body: JSON.stringify(body),+ })+ return { status: response.status, text: await response.text(), headers: response.headers }+ }+ async function completed(key: string) {+ const digest = createHash('sha256').update(key).digest('hex')+ const deadline = Date.now() + 3000+ do {+ const keys = await redis.keys(`replay:${org}:*:${digest}`)+ if (keys.length && (await redis.hget(keys[0], 'state')) === 'complete') return+ await delay(5)+ } while (Date.now() < deadline)+ throw new Error('Response persistence did not complete')+ }++ it('replays canonical input across aliases and rejects changed input without another effect', async () => {+ const key = randomUUID()+ const before = effects+ const original = await send(key, 'probe/target', { b: 2, a: [1, null] })+ expect(original.status).toBe(201)+ await completed(key)+ const retry = await send(key, `${org}/probe/target`, { a: [1, null], b: 2 }, 1)+ expect(retry.text).toBe(original.text)+ expect(retry.headers.get('x-request-id')).not.toBe(original.headers.get('x-request-id'))+ for (const [path, body] of [+ ['probe/other', { b: 2, a: [1, null] }],+ ['probe/target?force=true', { b: 2, a: [1, null] }],+ ['probe/target', { b: 2, a: [null, 1] }],+ ] as const) {+ const mismatch = await send(key, path, body)+ expect(mismatch.status).toBe(409)+ expect(JSON.parse(mismatch.text)).toMatchObject({+ code: 'idempotency_request_mismatch',+ message: 'Idempotency-Key was already used with a different request',+ })+ }+ expect((await send(key, 'probe/target', { b: 2, a: [1, null] }, 1)).text).toBe(original.text)+ expect(effects).toBe(before + 1)+ expect((await send(key, 'probe/target', {}, 0, { 'x-user': 'other' })).status).toBe(201)+ expect((await send(key, 'foreign/probe/target')).status).toBe(403)+ })++ it('passes unkeyed writes through and rejects malformed keys before effects', async () => {+ const before = effects+ expect((await send()).status).toBe(201)+ expect((await send()).status).toBe(201)+ for (const key of ['', 'invalid', `${randomUUID()}, ${randomUUID()}`]) {+ expect((await send(key)).status).toBe(400)+ }+ expect(effects).toBe(before + 2)+ })++ it('rejects unauthenticated callers, unauthorized volumes and non-JSON keyed bodies before effects', async () => {+ const before = effects+ expect((await send(randomUUID(), 'probe/target', {}, 0, { 'x-user': '' })).status).toBe(403)+ expect((await send(randomUUID(), 'boxes', { volumes: [{ id: 'private-volume' }] })).status).toBe(403)+ const response = await fetch(`${bases[0]}/api/v1/probe/target`, {+ method: 'POST',+ headers: { 'Idempotency-Key': randomUUID(), 'Content-Type': 'text/plain' },+ body: 'opaque',+ })+ expect(response.status).toBe(400)+ expect(effects).toBe(before)+ })++ it('keeps a disconnected owner fenced until its late response is recorded', async () => {+ entered = Promise.withResolvers<void>()+ release = Promise.withResolvers<void>()+ const key = randomUUID()+ const request = httpRequest(`${bases[0]}/api/v1/probe/target/slow`, {+ method: 'POST',+ headers: { 'Idempotency-Key': key, 'Content-Type': 'application/json' },+ })+ request.on('error', () => undefined)+ request.end('{}')+ await entered.promise+ try {+ request.destroy()+ const deadline = Date.now() + 3000+ while ((await send(key, 'probe/target/slow', {}, 1)).status !== 422) {+ if (Date.now() >= deadline) throw new Error('Disconnected owner was not fenced')+ await delay(5)+ }+ release.resolve()+ await completed(key)+ expect((await send(key, 'probe/target/slow', {}, 1)).status).toBe(201)+ } finally {+ request.destroy()+ release.resolve()+ }+ })++ it('preserves the fence when recording an error fails', async () => {+ const original = services[0].session.bind(services[0])+ const spy = jest.spyOn(services[0], 'session').mockImplementationOnce(async (...args) => {+ const owner = await original(...args)+ jest.spyOn(owner, 'markUnknown').mockRejectedValueOnce(new Error('Redis unavailable'))+ return owner+ })+ const key = randomUUID()+ try {+ expect((await send(key, 'probe/target/failure')).status).toBe(400)+ expect((await send(key, 'probe/target/failure')).status).toBe(409)+ } finally {+ spy.mockRestore()+ }+ })++ it('rejects malformed numeric input without fencing a later identical attempt', async () => {+ const key = randomUUID()+ const before = effects+ expect((await send(key, 'probe/target/count/invalid')).status).toBe(400)+ expect((await send(key, 'probe/target/count/invalid')).status).toBe(400)+ expect((await send(randomUUID(), 'probe/target/count/3')).status).toBe(201)+ expect(effects).toBe(before + 1)+ })++ it('holds one owner across replicas and records its late success', async () => {+ entered = Promise.withResolvers<void>()+ release = Promise.withResolvers<void>()+ const key = randomUUID()+ const before = effects+ const owner = send(key, 'probe/target/slow')+ await entered.promise+ try {+ const pending = await send(key, 'probe/target/slow', {}, 1)+ expect(pending.status).toBe(409)+ expect(JSON.parse(pending.text)).toMatchObject({ code: 'idempotency_in_progress' })+ const hash = createHash('sha256').update(key).digest('hex')+ const [record] = await redis.keys(`replay:${org}:*:${hash}`)+ const initial = await redis.hget(record, 'expected_response_at')+ const deadline = Date.now() + 3000+ while ((await redis.hget(record, 'expected_response_at')) === initial) {+ if (Date.now() >= deadline) throw new Error('Owner heartbeat did not renew its deadline')+ await delay(10)+ }+ expect((await send(key, 'probe/target/slow', {}, 1)).status).toBe(409)+ release.resolve()+ const original = await owner+ await completed(key)+ expect((await send(key, 'probe/target/slow', {}, 1)).text).toBe(original.text)+ expect(effects).toBe(before + 1)+ } finally {+ release.resolve()+ await owner+ }+ })++ it('allows proven admission rejection to retry but fences a post-effect 400', async () => {+ const key = randomUUID()+ quota = true+ expect((await send(key, 'probe/target/quota')).status).toBe(429)+ quota = false+ expect((await send(key, 'probe/target/quota')).status).toBe(201)+ await completed(key)+ quota = true+ expect((await send(key, 'probe/target/quota')).status).toBe(201)+ quota = false+ const failedKey = randomUUID()+ const before = effects+ expect((await send(failedKey, 'probe/target/failure')).status).toBe(400)+ const unknown = await send(failedKey, 'probe/target/failure')+ expect(unknown.status).toBe(422)+ expect(JSON.parse(unknown.text)).toMatchObject({ code: 'idempotency_outcome_unknown' })+ expect(effects).toBe(before + 1)+ const invalid = randomUUID()+ expect((await send(invalid, 'probe/target/validate', { value: 1 })).status).toBe(400)+ expect((await send(invalid, 'probe/target/validate', { value: 1 })).status).toBe(400)+ })++ it.each(['dto', 'empty'])('preserves serialized %s responses', async (suffix) => {+ const key = randomUUID()+ const before = effects+ const original = await send(key, `probe/target/${suffix}`)+ expect(original.status).toBe(suffix === 'empty' ? 204 : 201)+ await completed(key)+ const retry = await send(key, `probe/target/${suffix}`, {}, 1)+ expect(retry.status).toBe(original.status)+ expect(retry.text).toBe(original.text)+ expect(retry.text).not.toContain('secret')+ expect(effects).toBe(before + 1)+ })++ it('audits the same created resource on a replay from another replica', async () => {+ audit.createLog.mockClear()+ audit.updateLog.mockClear()+ const key = randomUUID()+ const original = await send(key, 'probe/target/dto')+ expect(original.status).toBe(201)+ const { id } = JSON.parse(original.text)+ expect(id).toEqual(expect.any(String))+ await completed(key)+ const retry = await send(key, 'probe/target/dto', {}, 1)+ expect(retry.status).toBe(201)+ const [first, replay] = audit.createLog.mock.results+ expect(audit.updateLog.mock.calls).toEqual([+ [(await first.value).id, expect.objectContaining({ targetId: id }), expect.any(Number)],+ [(await replay.value).id, expect.objectContaining({ targetId: id }), expect.any(Number)],+ ])+ })++ it('forwards an oversized success while keeping its unknown fence', async () => {+ const key = randomUUID()+ const before = effects+ const first = await send(key, 'probe/target/large')+ expect(first.status).toBe(201)+ expect(first.text.length).toBeGreaterThan(REPLAY_MAX_RESPONSE_BYTES)+ expect((await send(key, 'probe/target/large')).status).toBe(422)+ expect(effects).toBe(before + 1)+ })+})diff --git a/apps/api/src/boxlite-rest/request-replay.interceptor.ts b/apps/api/src/boxlite-rest/request-replay.interceptor.tsnew file mode 100644index 000000000..58b9cbaf8--- /dev/null+++ b/apps/api/src/boxlite-rest/request-replay.interceptor.ts@@ -0,0 +1,167 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */+import {+ BadRequestException,+ CallHandler,+ ExecutionContext,+ ForbiddenException,+ Injectable,+ Logger,+ NestInterceptor,+ OnModuleDestroy,+ StreamableFile,+} from '@nestjs/common'+import type { Request, Response } from 'express'+import { catchError, Observable, of } from 'rxjs'+import { BoxRequestReplayService, ReplayResource, REPLAY_HEARTBEAT_MS } from './box-request-replay.service'+import { replayIdentity, replayPolicy, REPLAY_ONLY, REPLAY_RESOURCE, validateReplayKey } from './request-replay-policy'+import { captureReplayResponse } from './request-replay-response'+import { OrganizationAuthContext } from '../common/interfaces/auth-context.interface'+import { hasOrganizationResourcePermissions } from '../organization/guards/organization-resource-action.guard'+import { OrganizationResourcePermission } from '../organization/enums/organization-resource-permission.enum'+import { hasNoEffect } from '../common/replay-no-effect'+import { AUDIT_TARGET_ID } from '../audit/decorators/audit.decorator'+import { RESPONSE_PASSTHROUGH_METADATA, ROUTE_ARGS_METADATA } from '@nestjs/common/constants'+import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum'++type ReplayRequest = Request & {+ user?: OrganizationAuthContext+ [AUDIT_TARGET_ID]?: string+ [REPLAY_ONLY]?: boolean+ [REPLAY_RESOURCE]?: ReplayResource+}++@Injectable()+export class RequestReplayInterceptor implements NestInterceptor, OnModuleDestroy {+ private readonly logger = new Logger(RequestReplayInterceptor.name)+ private readonly active = new Set<() => void>()+ constructor(private readonly service: BoxRequestReplayService) {}+ onModuleDestroy(): void {+ for (const cleanup of this.active) cleanup()+ this.active.clear()+ }++ async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {+ if (context.getType() !== 'http') return next.handle()+ const req = context.switchToHttp().getRequest<ReplayRequest>()+ const route = String(req.route?.path ?? req.path)+ const policy = replayPolicy(req.method, route)+ if (policy === 'outside' || policy === 'read') return next.handle()+ const key = validateReplayKey(req)+ if (!key) return next.handle()+ if (policy === 'excluded') throw new BadRequestException('Idempotency-Key is not supported for this operation')+ const user = req.user+ if (!user?.organizationId || !user.userId) throw new ForbiddenException('Organization authentication required')+ const prefix = req.params?.prefix+ if (prefix && prefix !== 'default' && prefix !== user.organizationId)+ throw new ForbiddenException('Request prefix does not match organization')+ const identity = replayIdentity(req)+ if (+ identity.operation === 'createBox' &&+ Array.isArray(req.body?.volumes) &&+ req.body.volumes.length &&+ !hasOrganizationResourcePermissions(user, [+ OrganizationResourcePermission.READ_VOLUMES,+ OrganizationResourcePermission.WRITE_VOLUMES,+ ])+ ) {+ throw new ForbiddenException('Attaching a managed volume requires: read:volumes, write:volumes')+ }+ if (+ (Number(req.headers['content-length']) > 0 || req.headers['transfer-encoding']) &&+ req.headers['content-type']?.split(';')[0] !== 'application/json'+ )+ throw new BadRequestException('Idempotency-Key requires a JSON request body')+ const session = await this.service.session(+ user.organizationId,+ user.userId,+ identity.operation,+ key,+ identity.fingerprint,+ { replayOnly: req[REPLAY_ONLY] },+ )+ const response = context.switchToHttp().getResponse<Response>()+ if (session.response) {+ const stored = session.response+ if (stored.auditTargetId) req[AUDIT_TARGET_ID] = stored.auditTargetId+ response.status(stored.status)+ for (const [name, value] of Object.entries(stored.headers ?? { 'content-type': 'application/json' }))+ response.setHeader(name, value)+ // Nest writes ordinary return values itself; @Res/@Next handlers own their response.+ const metadata: Record<string, unknown> =+ Reflect.getMetadata(ROUTE_ARGS_METADATA, context.getClass(), context.getHandler().name) ?? {}+ const passthrough = Reflect.getMetadata(+ RESPONSE_PASSTHROUGH_METADATA,+ context.getClass(),+ context.getHandler().name,+ )+ const handled =+ !passthrough &&+ Object.keys(metadata).some((key) =>+ [RouteParamtypes.RESPONSE, RouteParamtypes.NEXT].includes(Number(key.split(':')[0])),+ )+ const body =+ stored.status === 204 ? undefined : Buffer.from(stored.body, stored.encoding === 'base64' ? 'base64' : 'utf8')+ if (handled) {+ response.end(body)+ return of(undefined)+ }+ return of(body === undefined ? undefined : new StreamableFile(body))+ }+ const logFailure = (error: unknown): void =>+ this.logger.warn(+ `Failed to save replay outcome for ${identity.operation}: ${error instanceof Error ? error.message : 'storage error'}`,+ )+ let stopped = false+ let beating = false+ const timer = setInterval(() => {+ if (beating || stopped) return+ beating = true+ void session+ .heartbeat()+ .catch(logFailure)+ .finally(() => {+ beating = false+ })+ }, REPLAY_HEARTBEAT_MS)+ timer.unref()+ const stop = (): void => {+ stopped = true+ clearInterval(timer)+ this.active.delete(cleanup)+ }+ let cleanup!: () => void+ const captureCleanup = captureReplayResponse(+ response,+ (result) => {+ void session+ .complete({ ...result, resource: req[REPLAY_RESOURCE], auditTargetId: req[AUDIT_TARGET_ID] })+ .catch(logFailure)+ this.active.delete(cleanup)+ },+ () => {+ void session.markUnknown().catch(logFailure)+ },+ stop,+ )+ cleanup = () => {+ captureCleanup()+ this.active.delete(cleanup)+ }+ this.active.add(cleanup)+ return next.handle().pipe(+ catchError(async (error: unknown) => {+ cleanup()+ try {+ if (hasNoEffect(error)) await session.markRetryable()+ else await session.markUnknown()+ } catch (storageError) {+ logFailure(storageError)+ }+ throw error+ }),+ )+ }+}diff --git a/apps/api/src/boxlite-rest/request-replay.module.ts b/apps/api/src/boxlite-rest/request-replay.module.tsnew file mode 100644index 000000000..c24157e48--- /dev/null+++ b/apps/api/src/boxlite-rest/request-replay.module.ts@@ -0,0 +1,15 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */+import { Global, Module } from '@nestjs/common'+import { BoxRequestReplayService } from './box-request-replay.service'+import { RequestReplayInterceptor } from './request-replay.interceptor'+import { RequestReplayPolicy } from './request-replay-policy'++@Global()+@Module({+ providers: [BoxRequestReplayService, RequestReplayInterceptor, RequestReplayPolicy],+ exports: [BoxRequestReplayService, RequestReplayInterceptor, RequestReplayPolicy],+})+export class RequestReplayModule {}diff --git a/apps/api/src/ci/ci-native-workers.spec.ts b/apps/api/src/ci/ci-native-workers.spec.tsindex 073ae821e..1eb5901ea 100644--- a/apps/api/src/ci/ci-native-workers.spec.ts+++ b/apps/api/src/ci/ci-native-workers.spec.ts@@ -478,7 +478,10 @@ integration('CI native workers (shared lease, actual PostgreSQL and HTTP)', () =const { host, config, row } = await prepared()let started = 0const admission = new ImageAdmissionService(- { incr: async () => ++started, expire: async () => 1, ttl: async () => 60 } as any,+ {+ eval: async (script: string) =>+ String(script).includes("redis.call('INCR', KEYS[1])") ? [++started, 'gen-1', 60000] : started - 1,+ } as any,{} as any,{} as any,)diff --git a/apps/api/src/common/replay-no-effect.ts b/apps/api/src/common/replay-no-effect.tsnew file mode 100644index 000000000..fc58ae098--- /dev/null+++ b/apps/api/src/common/replay-no-effect.ts@@ -0,0 +1,15 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */+/** Server-only proof that an exception occurred before the requested business effect. */+export const REPLAY_NO_EFFECT = Symbol('replay-no-effect')++export function noEffect<T extends Error>(error: T): T {+ Object.defineProperty(error, REPLAY_NO_EFFECT, { value: true })+ return error+}++export function hasNoEffect(error: unknown): boolean {+ return error instanceof Error && REPLAY_NO_EFFECT in error && error[REPLAY_NO_EFFECT] === true+}diff --git a/apps/api/src/common/replay-validation.pipe.ts b/apps/api/src/common/replay-validation.pipe.tsnew file mode 100644index 000000000..1d2a544a8--- /dev/null+++ b/apps/api/src/common/replay-validation.pipe.ts@@ -0,0 +1,57 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */+import {+ ArgumentMetadata,+ Injectable,+ ParseBoolPipe,+ ParseIntPipe,+ ParseUUIDPipe,+ ValidationPipe,+} from '@nestjs/common'+import { noEffect } from './replay-no-effect'++@Injectable()+export class ReplayValidationPipe extends ValidationPipe {+ async transform(value: unknown, metadata: ArgumentMetadata): Promise<unknown> {+ try {+ return await super.transform(value, metadata)+ } catch (error) {+ throw error instanceof Error ? noEffect(error) : error+ }+ }+}++@Injectable()+export class ReplayParseBoolPipe extends ParseBoolPipe {+ async transform(value: string | boolean, metadata: ArgumentMetadata): Promise<boolean> {+ try {+ return await super.transform(value, metadata)+ } catch (error) {+ throw error instanceof Error ? noEffect(error) : error+ }+ }+}++@Injectable()+export class ReplayParseIntPipe extends ParseIntPipe {+ async transform(value: string, metadata: ArgumentMetadata): Promise<number> {+ try {+ return await super.transform(value, metadata)+ } catch (error) {+ throw error instanceof Error ? noEffect(error) : error+ }+ }+}++@Injectable()+export class ReplayParseUUIDPipe extends ParseUUIDPipe {+ async transform(value: string, metadata: ArgumentMetadata): Promise<string> {+ try {+ return await super.transform(value, metadata)+ } catch (error) {+ throw error instanceof Error ? noEffect(error) : error+ }+ }+}diff --git a/apps/api/src/image/services/image-admission.service.spec.ts b/apps/api/src/image/services/image-admission.service.spec.tsindex 34cb121ae..764fe6b3d 100644--- a/apps/api/src/image/services/image-admission.service.spec.ts+++ b/apps/api/src/image/services/image-admission.service.spec.ts@@ -4,6 +4,11 @@*/import { HttpStatus } from '@nestjs/common'+import { spawn, type ChildProcess } from 'node:child_process'+import { once } from 'node:events'+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'import Redis from 'ioredis'import { BadRequestError } from '../../exceptions/bad-request.exception'import { IsNull, Repository } from 'typeorm'@@ -14,7 +19,7 @@ import { ImageCountLimitReachedError } from '../errors/image-admission.error'import { ImageAdmissionService } from './image-admission.service'import { ResolvedImage } from './image-resolver.service'-type RedisMock = { incr: jest.Mock; expire: jest.Mock; ttl: jest.Mock }+type RedisMock = { eval: jest.Mock }type ImageRepositoryMock = { exists: jest.Mock; count: jest.Mock }/** What the resolver answers for a ref the catalog has never seen. */@@ -38,9 +43,7 @@ describe('ImageAdmissionService', () => {beforeEach(() => {process.env.BOXLITE_IMAGE_REGISTRY_ALLOWLIST = 'quay.io,gcr.io'redis = {- incr: jest.fn().mockResolvedValue(1),- expire: jest.fn().mockResolvedValue(1),- ttl: jest.fn().mockResolvedValue(60),+ eval: jest.fn().mockResolvedValue([1, 'gen-1', 60000]),}images = {exists: jest.fn().mockResolvedValue(false),@@ -85,7 +88,7 @@ describe('ImageAdmissionService', () => {isOrgOwned: false,})expect(images.exists).not.toHaveBeenCalled()- expect(redis.incr).not.toHaveBeenCalled()+ expect(redis.eval).not.toHaveBeenCalled()// Nor asked about logins: a login for the curated image's whole host must// not be able to take the curated path over.expect(credentials.routesThroughProxy).not.toHaveBeenCalled()@@ -169,18 +172,25 @@ describe('ImageAdmissionService', () => {isOrgOwned: true,imageId: 'image-1',})- expect(redis.incr).not.toHaveBeenCalled()+ expect(redis.eval).not.toHaveBeenCalled()})it('sets the window on the first pull of a window', async () => {await service.spendColdPullBudget(organization, CATALOG_MISS)- expect(redis.expire).toHaveBeenCalledWith('image:coldpull:org-1', 60)+ expect(redis.eval.mock.calls[0].slice(1)).toEqual([+ 3,+ 'image:coldpull:org-1',+ 'image:coldpull:org-1:gen',+ 'image:coldpull:org-1:genseq',+ 60,+ 6,+ ])})it('does not reset the window on later pulls', async () => {- redis.incr.mockResolvedValue(2)+ redis.eval.mockResolvedValue([2, 'gen-1', 59000])await service.spendColdPullBudget(organization, CATALOG_MISS)- expect(redis.expire).not.toHaveBeenCalled()+ expect(redis.eval).toHaveBeenCalledTimes(1)})/**@@ -189,8 +199,7 @@ describe('ImageAdmissionService', () => {* the shape this has to produce.*/it('reports how long to wait when the budget is spent', async () => {- redis.incr.mockResolvedValue(7)- redis.ttl.mockResolvedValue(42)+ redis.eval.mockResolvedValue([7, 'gen-1', 42000])const error = await service.spendColdPullBudget(organization, CATALOG_MISS).catch((e) => e)@@ -205,8 +214,7 @@ describe('ImageAdmissionService', () => {* the window makes the limit look like it changes size between requests.*/it('names the window length, not the time left in it', async () => {- redis.incr.mockResolvedValue(7)- redis.ttl.mockResolvedValue(42)+ redis.eval.mockResolvedValue([7, 'gen-1', 42000])const error = await service.spendColdPullBudget(organization, CATALOG_MISS).catch((e) => e)@@ -220,24 +228,96 @@ describe('ImageAdmissionService', () => {* with no guidance at all.*/it('restores the window and still answers when the key has no expiry', async () => {- redis.incr.mockResolvedValue(7)- redis.ttl.mockResolvedValue(-1)+ redis.eval.mockResolvedValue([7, 'gen-1', -1])const error = await service.spendColdPullBudget(organization, CATALOG_MISS).catch((e) => e)- expect(redis.expire).toHaveBeenCalledWith('image:coldpull:org-1', 60)expect(error.retryAfterSeconds).toBe(60)})/** Six starts fit in a window by default; the seventh is refused. */it('admits six cold pulls a window by default', async () => {- redis.incr.mockResolvedValue(6)- await expect(service.spendColdPullBudget(organization, CATALOG_MISS)).resolves.toBeUndefined()+ redis.eval.mockResolvedValue([6, 'gen-1', 60000])+ await expect(service.spendColdPullBudget(organization, CATALOG_MISS)).resolves.toEqual({+ generation: 'gen-1',+ spent: 1,+ })- redis.incr.mockResolvedValue(7)+ redis.eval.mockResolvedValue([7, 'gen-1', 60000])await expect(service.spendColdPullBudget(organization, CATALOG_MISS)).rejects.toThrow(/at most 6/)})+ describe('generation-bound refunds against Redis', () => {+ let directory: string+ let server: ChildProcess+ let client: Redis+ let live: ImageAdmissionService+ const counter = 'image:coldpull:org-1'+ const generation = counter + ':gen'++ beforeAll(async () => {+ directory = await mkdtemp(join(tmpdir(), 'boxlite-admission-'))+ const socket = join(directory, 'redis.sock')+ server = spawn('redis-server', ['--port', '0', '--unixsocket', socket, '--save', '', '--appendonly', 'no'])+ server.once('error', (error) => server.stdout!.destroy(error))+ for await (const chunk of server.stdout!) {+ if (chunk.toString().includes('Ready to accept connections')) break+ }+ client = new Redis({ path: socket, lazyConnect: true, maxRetriesPerRequest: 2 })+ await client.connect()+ })++ afterAll(async () => {+ await client?.quit().catch(() => client?.disconnect())+ if (server && server.exitCode === null) {+ const stopped = once(server, 'exit')+ server.kill()+ await stopped+ }+ if (directory) await rm(directory, { recursive: true, force: true })+ })++ beforeEach(async () => {+ await client.flushall()+ live = new ImageAdmissionService(+ client,+ images as unknown as Repository<Image>,+ credentials as unknown as RegistryCredentialService,+ )+ })++ it('refunds concurrent spends per unit without extending either expiry', async () => {+ const tickets = await Promise.all(+ Array.from({ length: 6 }, () => live.spendColdPullBudget(organization, CATALOG_MISS)),+ )+ expect(tickets.every((ticket) => ticket?.spent === 1)).toBe(true)+ await client.pexpire(counter, 10000)+ await client.pexpire(generation, 10000)+ await Promise.all(+ tickets.slice(1).map((ticket) => live.refundColdPullBudget(organization, CATALOG_MISS, ticket!)),+ )+ expect(await client.get(counter)).toBe('1')+ for (const redisKey of [counter, generation]) {+ expect(await client.pttl(redisKey)).toBeGreaterThan(0)+ expect(await client.pttl(redisKey)).toBeLessThanOrEqual(10000)+ }+ await live.refundColdPullBudget(organization, CATALOG_MISS, tickets[0]!)+ expect(await client.get(counter)).toBe('0')+ })++ it('does not resurrect an expired counter or refund its replacement', async () => {+ const stale = (await live.spendColdPullBudget(organization, CATALOG_MISS))!+ await client.pexpire(counter, 0)+ await live.refundColdPullBudget(organization, CATALOG_MISS, stale)+ expect(await client.exists(counter)).toBe(0)+ await client.del(generation)+ const fresh = (await live.spendColdPullBudget(organization, CATALOG_MISS))!+ expect(fresh.generation).not.toBe(stale.generation)+ await live.refundColdPullBudget(organization, CATALOG_MISS, stale)+ expect(await client.get(counter)).toBe('1')+ })+ })+describe('overridden by the environment', () => {afterEach(() => {delete process.env.BOXLITE_IMAGE_COLD_PULL_LIMIT@@ -254,9 +334,9 @@ describe('ImageAdmissionService', () => {const tuned = serviceWith('2', '30')await tuned.spendColdPullBudget(organization, CATALOG_MISS)- expect(redis.expire).toHaveBeenCalledWith('image:coldpull:org-1', 30)+ expect(redis.eval.mock.calls[0].slice(-2)).toEqual([30, 2])- redis.incr.mockResolvedValue(3)+ redis.eval.mockResolvedValue([3, 'gen-1', 30000])const error = await tuned.spendColdPullBudget(organization, CATALOG_MISS).catch((e) => e)expect(error.getResponse().message).toContain('at most 2 of them per 30s window')})diff --git a/apps/api/src/image/services/image-admission.service.ts b/apps/api/src/image/services/image-admission.service.tsindex 383c5b96c..7a3cfed3f 100644--- a/apps/api/src/image/services/image-admission.service.ts+++ b/apps/api/src/image/services/image-admission.service.ts@@ -30,6 +30,88 @@ const DEFAULT_COLD_PULL_LIMIT = 6const COLD_PULL_WINDOW_ENV = 'BOXLITE_IMAGE_COLD_PULL_WINDOW_SECONDS'const DEFAULT_COLD_PULL_WINDOW_SECONDS = 60+/**+ * The ticket a cold-pull spend hands back, and a refund must present.+ *+ * `generation` names the exact window the charge landed in — the value the+ * charge wrote to the window's generation key, which expires with the window.+ * A refund whose ticket names a window that is gone, or has been replaced by+ * a newer generation, is refused: it must never discount a window it did not+ * pay for. `spent` is one charged cold pull, independently of the window's+ * cumulative count, so a refund returns only this call's charge.+ */+export interface ColdPullTicket {+ generation: string+ spent: number+}++/**+ * Charge one cold pull and stamp the window's generation, atomically.+ *+ * The counter and its generation stamp live and expire together; the+ * generation source — a plain never-expiring counter — does not. Each window+ * rebuild takes the next number, so generations never repeat for one+ * organization and a refund can tell the window it paid for from any later+ * one, even one that starts with the same count. When the limit is crossed,+ * the last over-limit calls stay counted — the window refuses further work+ * either way, and its TTL, which the error reports, still reads true.+ *+ * Time window 1 window 2+ * spend A +1, ticket generation 1+ * expiry counter and stamp end+ * spend B +1, ticket generation 2+ * refund A generation mismatch; count stays 1+ *+ * KEYS[1] counter, KEYS[2] generation stamp, KEYS[3] generation sequence.+ * ARGV[1] window seconds, ARGV[2] limit.+ * Returns { new count, generation, counter pttl }.+ */+const COLD_PULL_SPEND_SCRIPT = `+local newWindow = redis.call('EXISTS', KEYS[1]) == 0+local count = redis.call('INCR', KEYS[1])+local ttl = redis.call('PTTL', KEYS[1])+if ttl < 0 then+ redis.call('EXPIRE', KEYS[1], ARGV[1])+ ttl = redis.call('PTTL', KEYS[1])+end+if newWindow or redis.call('EXISTS', KEYS[2]) == 0 then+ local generation = redis.call('INCR', KEYS[3])+ redis.call('SET', KEYS[2], generation)+end+redis.call('PEXPIRE', KEYS[2], ttl)+return {count, redis.call('GET', KEYS[2]), ttl}+`++/**+ * Give back exactly the units a spend charged, but only to the window the+ * spend paid for.+ *+ * The refund runs only when the generation key still holds the ticket's+ * generation — the same window, unexpired, unreplaced. It also floors the+ * counter at zero, so a manual trim of the counter cannot be driven negative+ * by a refund for charges that are already gone. If the generation has moved+ * on or expired, the refund is a no-op: the charge died with its window.+ *+ * KEYS[1] counter, KEYS[2] generation; ARGV[1] ticket generation,+ * ARGV[2] charged count. Returns the new counter value, or the old one when+ * the ticket does not match.+ */+const COLD_PULL_REFUND_SCRIPT = `+if redis.call('GET', KEYS[2]) ~= ARGV[1] then+ return redis.call('GET', KEYS[1]) or 0+end+local count = redis.call('GET', KEYS[1])+if not count then+ return 0+end+count = tonumber(count) - tonumber(ARGV[2])+if count < 0 then+ count = 0+end+redis.call('SET', KEYS[1], count, 'KEEPTTL')+return count+`+/*** A positive integer from the environment, or `fallback` when it is unset.* Anything else stops the API at boot: a limit an operator mistyped must not@@ -138,12 +220,66 @@ export class ImageAdmissionService {* taking its answer as the argument puts this after the resolver. Running* `assert` first, so a refused image never reaches the catalog query, is the* caller's to keep.+ *+ * Returns the ticket naming the window generation and the count this call+ * spent. The increment and the generation write are one atomic step: a+ * refund holding an older ticket must never be able to race a fresh window+ * into existence, or it would discount a window it never paid for.*/- async spendColdPullBudget(organization: Organization, resolved: ResolvedImage): Promise<void> {+ async spendColdPullBudget(organization: Organization, resolved: ResolvedImage): Promise<ColdPullTicket | undefined> {+ if (!resolved.isOrgOwned || resolved.imageId) {+ return undefined+ }+ const key = `image:coldpull:${organization.id}`+ const [count, generation, pttl] = (await this.redis.eval(+ COLD_PULL_SPEND_SCRIPT,+ 3,+ key,+ `${key}:gen`,+ `${key}:genseq`,+ this.coldPullWindowSeconds,+ this.coldPullLimit,+ )) as [number, string, number]++ if (count > this.coldPullLimit) {+ // A key that somehow lost its TTL would block the organization forever;+ // the script restores the expiry, and the answer reports a full window.+ const retryAfterSeconds = pttl >= 0 ? Math.ceil(pttl / 1000) : this.coldPullWindowSeconds+ throw new ImageColdPullRateLimitedError(this.coldPullLimit, this.coldPullWindowSeconds, retryAfterSeconds)+ }+ return { generation, spent: 1 }+ }++ /**+ * Hand one spent cold pull back, for a create whose only effect was that+ * spend: the box limit settles inside the insert, after the budget, and the+ * replay layer treats that rejection as retryable — without the refund,+ * automatic retries would drain the organization's window without a box to+ * show for it.+ *+ * The ticket names the window generation charged. A refund only counts down+ * the same generation: when the window has expired and a newer one replaced+ * it, the ticket no longer matches and the newer window keeps its count, so+ * a late refund cannot discount pulls it never paid for. An expired window+ * is never resurrected either: with no generation left there is nothing to+ * match against and the refund is a no-op.+ */+ async refundColdPullBudget(+ organization: Organization,+ resolved: ResolvedImage,+ ticket: ColdPullTicket,+ ): Promise<void> {if (!resolved.isOrgOwned || resolved.imageId) {return}- await this.assertPullBudget(organization)+ await this.redis.eval(+ COLD_PULL_REFUND_SCRIPT,+ 2,+ `image:coldpull:${organization.id}`,+ `image:coldpull:${organization.id}:gen`,+ ticket.generation,+ ticket.spent,+ )}/**@@ -170,26 +306,4 @@ export class ImageAdmissionService {throw new ImageCountLimitReachedError(organization.imageCountLimit)}}-- private async assertPullBudget(organization: Organization): Promise<void> {- const key = `image:coldpull:${organization.id}`- const started = await this.redis.incr(key)- if (started === 1) {- await this.redis.expire(key, this.coldPullWindowSeconds)- }- if (started > this.coldPullLimit) {- // A key that somehow lost its TTL would block the organization forever,- // so read the remaining time rather than assuming a full window, and- // restore the expiry when it is missing.- const ttl = await this.redis.ttl(key)- if (ttl < 0) {- await this.redis.expire(key, this.coldPullWindowSeconds)- }- throw new ImageColdPullRateLimitedError(- this.coldPullLimit,- this.coldPullWindowSeconds,- ttl > 0 ? ttl : this.coldPullWindowSeconds,- )- }- }}diff --git a/apps/api/src/main.spec.ts b/apps/api/src/main.spec.tsindex 40d4ed5d2..bcba3f526 100644--- a/apps/api/src/main.spec.ts+++ b/apps/api/src/main.spec.ts@@ -45,6 +45,12 @@ jest.mock('./box/controllers/secret-credential.controller', () => ({jest.mock('./mcp/mcp-body', () => ({ useApiBodyParsers: jest.fn() }))jest.mock('./mcp/mcp-tools', () => ({ McpTools: class {} }))jest.mock('./mcp/mcp-routes', () => ({ servedOperations: () => [] }))+jest.mock('./boxlite-rest/request-replay.interceptor', () => ({ RequestReplayInterceptor: class {} }))+jest.mock('./boxlite-rest/request-replay-policy', () => ({+ RequestReplayPolicy: class RequestReplayPolicy {},+ REPLAY_LIFETIME: 'PT24H',+}))+jest.mock('./common/replay-validation.pipe', () => ({ ReplayValidationPipe: class {} }))describe('API bootstrap listener', () => {const environment = process.env@@ -76,7 +82,9 @@ describe('API bootstrap listener', () => {matchAttachPath: jest.fn(() => false),}const app = {- get: jest.fn(() => service),+ get: jest.fn((key: unknown) =>+ (key as { name?: string } | undefined)?.name === 'RequestReplayPolicy' ? { configure: jest.fn() } : service,+ ),use: jest.fn(),useLogger: jest.fn(),flushLogs: jest.fn(),diff --git a/apps/api/src/main.ts b/apps/api/src/main.tsindex 64eebbd8d..4a1d16308 100644--- a/apps/api/src/main.ts+++ b/apps/api/src/main.ts@@ -12,7 +12,7 @@ import { NestFactory } from '@nestjs/core'import { NestExpressApplication } from '@nestjs/platform-express'import { AppModule } from './app.module'import { SwaggerModule } from '@nestjs/swagger'-import { INestApplication, Logger, ValidationPipe } from '@nestjs/common'+import { INestApplication, Logger } from '@nestjs/common'import { Context } from './common/context/context'import { PlatformReason } from './common/context/platform-reason.enum'import { AllExceptionsFilter } from './filters/all-exceptions.filter'@@ -43,6 +43,9 @@ import { useApiBodyParsers } from './mcp/mcp-body'import { McpTools } from './mcp/mcp-tools'import { servedOperations } from './mcp/mcp-routes'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'// https optionsconst httpsEnabled = process.env.CERT_PATH && process.env.CERT_KEY_PATH@@ -103,8 +106,9 @@ async function bootstrap() {app.useGlobalInterceptors(new LoggerErrorInterceptor())app.useGlobalInterceptors(new MetricsInterceptor(configService, app.get(AnalyticsService)))app.useGlobalInterceptors(app.get(AuditInterceptor))+ app.useGlobalInterceptors(app.get(RequestReplayInterceptor))app.useGlobalPipes(- new ValidationPipe({+ new ReplayValidationPipe({transform: true,}),)@@ -204,6 +208,7 @@ async function bootstrap() {dashboard: document,served: servedOperations(app.getHttpAdapter().getInstance(), (path) => !!wsProxy.matchAttachPath(path)),})+ app.get(RequestReplayPolicy).configure(app.getHttpAdapter().getInstance(), openapi('box.openapi.yaml'))// Started on its own, before listen(), so `/mcp` is ready with the first// request; Kafka below keeps its own start and cannot delay this one.await app.connectMicroservice({ strategy: mcpStrategy }).listen()diff --git a/apps/api/src/mcp/mcp-catalog.ts b/apps/api/src/mcp/mcp-catalog.tsindex 2d028f8c5..5e85a9995 100644--- a/apps/api/src/mcp/mcp-catalog.ts+++ b/apps/api/src/mcp/mcp-catalog.ts@@ -3,6 +3,8 @@* SPDX-License-Identifier: AGPL-3.0*/+import { replayPolicy } from '../boxlite-rest/request-replay-policy'+/** A JSON Schema object, as OpenAPI 3.x and MCP tool inputs carry it. */export type JsonSchema = Record<string, unknown>@@ -95,7 +97,7 @@ export class McpCatalog {}private addDocument(doc: OpenApiDocument, toRoute: (path: string) => string, admit: (id: string) => boolean): void {- const resolve = refResolver(doc)+ const resolve = refResolver(doc, { 'box.openapi.yaml': this.sources.box, 'admin.openapi.yaml': this.sources.admin })for (const [path, item] of Object.entries((doc.paths ?? {}) as Record<string, Record<string, unknown>>)) {const shared = asArray(item.parameters)for (const method of METHODS) {@@ -124,16 +126,27 @@ function toOperation(const properties: Record<string, JsonSchema> = {}const required: string[] = []const params: McpOperationParam[] = []+ const responses = (operation.responses ?? {}) as Record<string, unknown>+ const supportsReplay = replayPolicy(method, path, '101' in responses) === 'supported'for (const raw of [...sharedParams, ...asArray(operation.parameters)]) {const param = resolve(raw) as Record<string, unknown>const name = param.name as stringconst location = param.in as McpOperationParam['in']if (name === 'prefix' || !['path', 'query', 'header'].includes(location)) continueif (location === 'header' && RESERVED_HEADERS.test(name)) continue+ if (supportsReplay && location === 'header' && name.toLowerCase() === 'idempotency-key') continueparams.push({ name, in: location, required: param.required === true })properties[name] = { ...(param.schema as JsonSchema), description: param.description }if (param.required === true) required.push(name)}+ if (supportsReplay) {+ params.push({ name: 'Idempotency-Key', in: 'header', required: false })+ properties['Idempotency-Key'] = {+ type: 'string',+ format: 'uuid',+ description: 'Optional UUID for replaying this hosted write with the same business input for 24 hours.',+ }+ }const body = requestBody(resolve(operation.requestBody) as Record<string, unknown> | undefined)if (body?.kind === 'json') {@@ -143,7 +156,6 @@ function toOperation(}if (body?.required) required.push(body.kind === 'json' ? 'body' : 'body_base64')- const responses = (operation.responses ?? {}) as Record<string, unknown>return {operationId,method,@@ -172,23 +184,31 @@ function requestBody(body: Record<string, unknown> | undefined) {return binary ? { kind: 'binary' as const, contentType: binary, required, schema: {} } : undefined}-/** Inlines local `$ref`s; a reference back into its own chain becomes `{}` so cycles terminate. */-function refResolver(doc: OpenApiDocument): (value: unknown) => unknown {- const lookup = (ref: string) =>- ref- .replace(/^#\//, '')- .split('/')- .reduce<unknown>((node, key) => (node as Record<string, unknown> | undefined)?.[key], doc)- const inline = (value: unknown, chain: Set<string>): unknown => {- if (Array.isArray(value)) return value.map((item) => inline(item, chain))+/** Inline references from the loaded v1 documents; recursive schema references terminate at their cycle. */+function refResolver(doc: OpenApiDocument, documents: Record<string, OpenApiDocument>): (value: unknown) => unknown {+ const inline = (value: unknown, source: OpenApiDocument, chain: Set<string>): unknown => {+ if (Array.isArray(value)) return value.map((item) => inline(item, source, chain))if (!value || typeof value !== 'object') return value- const ref = (value as { $ref?: unknown }).$ref- if (typeof ref === 'string' && ref.startsWith('#/')) {- return chain.has(ref) ? {} : inline(lookup(ref), new Set(chain).add(ref))+ const { $ref, ...siblings } = value as Record<string, unknown>+ if (typeof $ref === 'string') {+ const [file, pointer] = $ref.split('#')+ const target = file ? documents[file.replace(/^\.\//, '')] : source+ if (target && pointer?.startsWith('/')) {+ const identity = `${Object.keys(documents).find((name) => documents[name] === target) ?? 'local'}#${pointer}`+ if (chain.has(identity)) return {}+ const resolved = pointer+ .slice(1)+ .split('/')+ .reduce<unknown>(+ (node, key) => (node as Record<string, unknown> | undefined)?.[key.replace(/~1/g, '/').replace(/~0/g, '~')],+ target,+ )+ return inline({ ...(resolved as object), ...siblings }, target, new Set(chain).add(identity))+ }}- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, inline(item, chain)]))+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, inline(item, source, chain)]))}- return (value) => inline(value, new Set())+ return (value) => inline(value, doc, new Set())}function asArray(value: unknown): unknown[] {diff --git a/apps/infra/mdeploy/stack/providers/aws/cache.ts b/apps/infra/mdeploy/stack/providers/aws/cache.tsindex 0cb0f182a..6b92b4a88 100644--- a/apps/infra/mdeploy/stack/providers/aws/cache.ts+++ b/apps/infra/mdeploy/stack/providers/aws/cache.ts@@ -25,6 +25,7 @@ export const awsCacheProvider =vpc: network.vpc,cluster: request.clustered,instance: INSTANCE[request.size],+ parameters: { 'maxmemory-policy': 'noeviction' },transform: {cluster: (args: any) => {/*diff --git a/apps/infra/mdeploy/stack/providers/gcp/cache.ts b/apps/infra/mdeploy/stack/providers/gcp/cache.tsindex 6727676a1..266709339 100644--- a/apps/infra/mdeploy/stack/providers/gcp/cache.ts+++ b/apps/infra/mdeploy/stack/providers/gcp/cache.ts@@ -44,6 +44,7 @@ export const gcpCacheProvider =project,region,memorySizeGb: MEMORY_GB[request.size],+ redisConfigs: { 'maxmemory-policy': 'noeviction' },// Standard keeps a replica in a second zone; basic is one node. A cache// that is lost is refilled, so this follows the request rather than// defaulting to the safer answer.diff --git a/apps/infra/stack/foundation.ts b/apps/infra/stack/foundation.tsindex aab659dc1..323783bfa 100644--- a/apps/infra/stack/foundation.ts+++ b/apps/infra/stack/foundation.ts@@ -48,7 +48,11 @@ export function createFoundation(region: string, isProd: boolean): FoundationRes},},})- const redis = new sst.aws.Redis('Cache', { vpc, cluster: false })+ const redis = new sst.aws.Redis('Cache', {+ vpc,+ cluster: false,+ parameters: { 'maxmemory-policy': 'noeviction' },+ })const storage = new sst.aws.Bucket('Storage', { versioning: true })const cluster = new sst.aws.Cluster('Cluster', {forceUpgrade: 'v2',diff --git a/docs/contributing/architecture/platform/api.md b/docs/contributing/architecture/platform/api.mdindex 59c4ea169..75e3556f0 100644--- a/docs/contributing/architecture/platform/api.md+++ b/docs/contributing/architecture/platform/api.md@@ -717,6 +717,54 @@ organization membership.</details>+### Hosted write request replay++`GET /api/v1/config` advertises `capabilities.idempotency_key_lifetime: "PT24H"`+and `capabilities.idempotency_operations`, generated from registered routes and+the shared replay policy. Check both on the target deployment before retrying.+The shared OpenAPI header does not promise support in `boxlite serve` or the+reference server. Unserved snapshot, clone, export and import operations are+absent from discovery.++Finite JSON and empty-response hosted writes use the global replay interceptor.+New writes receive protection without a per-operation opt-in. Supported writes+include Box lifecycle, execution control, volumes, checkpoints, image aliases,+registry credentials, domains, network updates, tunnel revocation and SSH.+Omitting `Idempotency-Key` preserves ordinary behavior and adds no replay-store+dependency. Clients and SDKs do not add a key or retry automatically.++For example, retry `POST /api/v1/boxes/box-1/exec` with the same UUID and JSON+command to receive the original execution ID. MCP forwards that header to the+same REST route; `wait` and `wait_timeout_seconds` control collection afterward+and are excluded from the delegated business request.++| Outcome | Same-key retry behavior |+| --- | --- |+| Original success recorded | Replays original status, bytes, Content-Type and Location, including empty 204 responses |+| Original execution active | `409 idempotency_in_progress`; no second dispatch |+| Business input changed | `409 idempotency_request_mismatch` |+| Outcome cannot be confirmed | `422 idempotency_outcome_unknown`; never automatically bypass with a new key |+| Proven rejection before effects | Allows another attempt with the same key and input |++Every attempt checks current authentication and permissions. Keys are scoped to+organization, user and operation; targets, business query and JSON values bind+the request. File transfers, tunnel preparation and WebSocket upgrades reject+a supplied key before side effects. Reads retain their ordinary behavior, and+organization invitations retain their separate transaction replay contract.+SSH configuration without a key can restart the listener on every call; retry+only with the same input and key when the deployment advertises the operation.++Retention starts at first use and lasts 24 hours without extension. Expiry,+record loss or manual removal ends the deduplication guarantee. Redis must not+evict valid records; this mechanism does not make business effects and Redis+completion one atomic transaction.++For deployment, drain or pause keyed writes, replace every API replica, then+reopen traffic. Preserve the Redis namespace and records. Never mix replicas+that silently ignore newly supported keys with replicas enforcing them.+Rollback must retain the public replay reader and fences, or stop affected+writes; returning to a version that ignores valid keys can duplicate effects.+<details><summary><b>Box lifecycle</b> · 7 routes</summary>diff --git a/openapi/admin.openapi.yaml b/openapi/admin.openapi.yamlindex 85da96945..a39db0ed0 100644--- a/openapi/admin.openapi.yaml+++ b/openapi/admin.openapi.yaml@@ -28,8 +28,10 @@ info:membership and owner rules without API-key scopes. Invitation acceptanceremains in the JWT-only Console Cloud API.- Authentication, pagination parameters, and error schemas are shared with- the Box API. This cloud-only API is not served by the local Box runtime.+ Authentication and pagination parameters are shared with the Box API.+ Errors keep a nested `error` object; the flat error format of the+ hosted Box API does not apply here. This cloud-only API is not served+ by the local Box runtime.Dedicated Admin SDK methods are not yet provided; callers may use HTTP.license:name: Apache 2.0@@ -81,9 +83,9 @@ paths:schema:$ref: "#/components/schemas/UserList""400":- $ref: "./box.openapi.yaml#/components/responses/BadRequestError"+ $ref: "#/components/responses/BadRequestError""401":- $ref: "./box.openapi.yaml#/components/responses/UnauthorizedError"+ $ref: "#/components/responses/UnauthorizedError""403":$ref: "#/components/responses/ForbiddenError""429":@@ -114,11 +116,11 @@ paths:"204":description: User removed and their organization keys revoked; no response body"401":- $ref: "./box.openapi.yaml#/components/responses/UnauthorizedError"+ $ref: "#/components/responses/UnauthorizedError""403":$ref: "#/components/responses/ForbiddenError""404":- $ref: "./box.openapi.yaml#/components/responses/NotFoundError"+ $ref: "#/components/responses/NotFoundError""429":$ref: "#/components/responses/RateLimitError"@@ -144,9 +146,9 @@ paths:schema:$ref: "#/components/schemas/InviteList""400":- $ref: "./box.openapi.yaml#/components/responses/BadRequestError"+ $ref: "#/components/responses/BadRequestError""401":- $ref: "./box.openapi.yaml#/components/responses/UnauthorizedError"+ $ref: "#/components/responses/UnauthorizedError""403":$ref: "#/components/responses/ForbiddenError""429":@@ -184,18 +186,18 @@ paths:schema:$ref: "#/components/schemas/Invite""400":- $ref: "./box.openapi.yaml#/components/responses/BadRequestError"+ $ref: "#/components/responses/BadRequestError""401":- $ref: "./box.openapi.yaml#/components/responses/UnauthorizedError"+ $ref: "#/components/responses/UnauthorizedError""403":$ref: "#/components/responses/ForbiddenError""404":- $ref: "./box.openapi.yaml#/components/responses/NotFoundError"+ $ref: "#/components/responses/NotFoundError""409":- $ref: "./box.openapi.yaml#/components/responses/ConflictError"+ $ref: "#/components/responses/ConflictError"description: Already a member, already invited, or the idempotency key is in progress."422":- $ref: "./box.openapi.yaml#/components/responses/UnprocessableEntityError"+ $ref: "#/components/responses/UnprocessableEntityError"description: The idempotency key was used with a different request payload."429":$ref: "#/components/responses/RateLimitError"@@ -224,13 +226,13 @@ paths:"204":description: Invitation cancelled; no response body"401":- $ref: "./box.openapi.yaml#/components/responses/UnauthorizedError"+ $ref: "#/components/responses/UnauthorizedError""403":$ref: "#/components/responses/ForbiddenError""404":- $ref: "./box.openapi.yaml#/components/responses/NotFoundError"+ $ref: "#/components/responses/NotFoundError""409":- $ref: "./box.openapi.yaml#/components/responses/ConflictError"+ $ref: "#/components/responses/ConflictError""429":$ref: "#/components/responses/RateLimitError"@@ -249,13 +251,32 @@ components:type: stringformat: uuidexample: c391e52c-fef2-4aae-80ec-a47b7520ce42+ # These stay local: the shared Box responses also allow the flat hosted error format.responses:+ BadRequestError:+ description: Invalid request parameters or body+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ErrorResponse"+ ConflictError:+ description: Resource state conflict+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ErrorResponse"ForbiddenError:description: Missing membership, owner role, or required API-key scopecontent:application/json:schema:$ref: "#/components/schemas/ErrorResponse"+ NotFoundError:+ description: Resource not found+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ErrorResponse"RateLimitError:description: Request rate limit exceededheaders:@@ -273,9 +294,25 @@ components:message: Too many requeststype: ResourceExhaustedErrorcode: resource_exhausted+ UnauthorizedError:+ description: Missing or invalid authentication credentials+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ErrorResponse"+ UnprocessableEntityError:+ description: Request understood but cannot be processed+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ErrorResponse"schemas:ErrorResponse:- $ref: "./box.openapi.yaml#/components/schemas/ErrorResponse"+ type: object+ required: [error]+ properties:+ error:+ $ref: "./box.openapi.yaml#/components/schemas/ErrorModel"CreateInviteRequest:type: objectadditionalProperties: falsediff --git a/openapi/box.openapi.yaml b/openapi/box.openapi.yamlindex 40ca18489..b176c67e9 100644--- a/openapi/box.openapi.yaml+++ b/openapi/box.openapi.yaml@@ -225,6 +225,8 @@ paths:summary: Create a managed persistent volumedescription: Creates a volume and waits until its backing object storage is ready.tags: [Volumes]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"requestBody:required: falsecontent:@@ -242,6 +244,10 @@ paths:$ref: "#/components/responses/BadRequestError""408":$ref: "#/components/responses/RequestTimeoutError"+ "409":+ $ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError""503":$ref: "#/components/responses/ServiceUnavailableError"@@ -281,6 +287,7 @@ paths:summary: Remove a managed persistent volumetags: [Volumes]parameters:+ - $ref: "#/components/parameters/idempotencyKey"- name: forcein: querydescription: Treat an already deleting or missing volume as successfully removed@@ -294,6 +301,12 @@ paths:$ref: "#/components/responses/BadRequestError""404":$ref: "#/components/responses/NotFoundError"+ "409":+ $ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"# -------------------------------------------------------------------------# Boxes@@ -440,10 +453,16 @@ paths:responses:"204":description: Box removed+ "400":+ $ref: "#/components/responses/BadRequestError""404":$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"# -------------------------------------------------------------------------# Box Lifecycle@@ -469,10 +488,16 @@ paths:application/json:schema:$ref: "#/components/schemas/Box"+ "400":+ $ref: "#/components/responses/BadRequestError""404":$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"/{prefix}/boxes/{box_id}/stop:parameters:@@ -499,10 +524,16 @@ paths:application/json:schema:$ref: "#/components/schemas/Box"+ "400":+ $ref: "#/components/responses/BadRequestError""404":$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"/{prefix}/boxes/{box_id}/ssh/enable:parameters:@@ -517,6 +548,8 @@ paths:Never starts or resumes the box or its main command, and does not countas activity. Requires write:boxes permission on hosted servers.tags: [Boxes]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"responses:"200":description: SSH enabled or already enabled@@ -530,6 +563,8 @@ paths:$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError""503":$ref: "#/components/responses/ServiceUnavailableError"@@ -542,7 +577,8 @@ paths:summary: Configure guest SSHdescription: |Replaces the guest's complete SSH configuration; every accepted call- fully restarts the listener, so it must not be retried automatically.+ fully restarts the listener. Retry only with the same key and input on+ a hosted deployment advertising configureSsh in idempotency_operations.May start a `configured` or resume a `stopped` box on the image'sdefault command; in those two states an explicit `cmd`/`entrypoint`requires a prior start (a running box with an explicit command is@@ -550,6 +586,8 @@ paths:invalid configuration is rejected without changing the listeneralready running.tags: [Boxes]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"requestBody:required: truecontent:@@ -569,6 +607,8 @@ paths:$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError""503":$ref: "#/components/responses/ServiceUnavailableError"get:@@ -602,6 +642,8 @@ paths:saved SSH intent. Never starts or resumes the VM or its main command,and does not count as activity.tags: [Boxes]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"responses:"200":description: SSH disabled or already disabled on a running box@@ -609,10 +651,14 @@ paths:application/json:schema:$ref: "#/components/schemas/SshStatus"+ "400":+ $ref: "#/components/responses/BadRequestError""404":$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError""503":$ref: "#/components/responses/ServiceUnavailableError"@@ -859,6 +905,10 @@ paths:$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"/{prefix}/boxes/{box_id}/executions:parameters:@@ -925,11 +975,21 @@ paths:client observes an `{"type":"exit","exit_code":...}` text framefollowed by a normal close.tags: [Execution]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"responses:"204":description: Execution killed and evicted.+ "400":+ $ref: "#/components/responses/BadRequestError""404":$ref: "#/components/responses/NotFoundError"+ "409":+ $ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"/{prefix}/boxes/{box_id}/attach:parameters:@@ -1093,10 +1153,16 @@ paths:responses:"204":description: Signal sent+ "400":+ $ref: "#/components/responses/BadRequestError""404":$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"/{prefix}/boxes/{box_id}/executions/{exec_id}/resize:parameters:@@ -1110,6 +1176,8 @@ paths:Resizes the pseudo-terminal for a TTY-enabled execution.Only applicable to executions started with `tty: true`.tags: [Execution]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"requestBody:required: truecontent:@@ -1119,10 +1187,16 @@ paths:responses:"204":description: TTY resized+ "400":+ $ref: "#/components/responses/BadRequestError""404":$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"# -------------------------------------------------------------------------# Files@@ -1314,6 +1388,7 @@ paths:while the port is revoked and serves again once it is reopened.tags: [Network]parameters:+ - $ref: "#/components/parameters/idempotencyKey"- name: portin: queryrequired: true@@ -1330,6 +1405,12 @@ paths:$ref: "#/components/responses/BadRequestError""404":$ref: "#/components/responses/NotFoundError"+ "409":+ $ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"/{prefix}/boxes/{box_id}/network/inbound:parameters:@@ -1349,6 +1430,8 @@ paths:Servers that support this advertise`capabilities.inbound_update_enabled` in `GET /config`.tags: [Network]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"requestBody:required: truecontent:@@ -1368,6 +1451,10 @@ paths:$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"/{prefix}/boxes/{box_id}/network/outbound:parameters:@@ -1390,6 +1477,8 @@ paths:rollback can leave live and stored policy different; retry the fullreplacement. GET box reports the last persisted policy.tags: [Network]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"requestBody:required: truecontent:@@ -1409,12 +1498,16 @@ paths:$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError""500":description: Application or persistence failed; retry the complete policycontent:application/json:schema:$ref: "#/components/schemas/ErrorResponse"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"/{prefix}/boxes/{box_id}/agents:parameters:@@ -1719,6 +1812,8 @@ paths:Error codes: `platform_domain_not_configured`, `subdomain_too_short`,`domain_count_limit_reached` (400), `subdomain_taken` (409).tags: [Domains]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"requestBody:required: truecontent:@@ -1745,6 +1840,10 @@ paths:$ref: "#/components/responses/BadRequestError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"/{prefix}/domains/{domain}/target:parameters:@@ -1779,6 +1878,8 @@ paths:Custom-domain errors: `subscription_required` (403),`subscription_not_ready` and `domain_not_ready` (409).tags: [Domains]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"requestBody:required: truecontent:@@ -1804,6 +1905,10 @@ paths:$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"delete:operationId: unbindDomainsummary: Stop routing a domain@@ -1817,6 +1922,8 @@ paths:The port's own URL stays public until revokeTunnel.Safe to repeat for an owned name; a name not owned by the caller is 404.tags: [Domains]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"responses:"204":description: The domain routes nowhere@@ -1824,6 +1931,12 @@ paths:$ref: "#/components/responses/BadRequestError""404":$ref: "#/components/responses/NotFoundError"+ "409":+ $ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"# -------------------------------------------------------------------------# Metrics@@ -1933,6 +2046,8 @@ paths:returns creating and becomes ready after upload succeeds. A 201response accepting `full` includes `kind: "full"` even while creating.tags: [Checkpoints]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"requestBody:required: truecontent:@@ -1952,6 +2067,8 @@ paths:$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError""503":$ref: "#/components/responses/ServiceUnavailableError"get:@@ -2003,6 +2120,7 @@ paths:retains deleting state and quota until a successful retry.tags: [Checkpoints]parameters:+ - $ref: "#/components/parameters/idempotencyKey"- name: forcein: querydescription: Ignore absence only; never bypass active use@@ -2018,6 +2136,8 @@ paths:$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError""503":$ref: "#/components/responses/ServiceUnavailableError"@@ -2049,6 +2169,8 @@ paths:A server refuses with `InvalidStateError` while a box can still bootfrom the image.tags: [Images]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"responses:"204":description: The image is no longer held@@ -2058,6 +2180,10 @@ paths:$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"/{prefix}/images/{image_name}/aliases:parameters:@@ -2073,6 +2199,8 @@ paths:existing boxes are unchanged, and nothing is pulled. A local runtimewithout a catalog answers UnsupportedError.tags: [Images]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"requestBody:required: truecontent:@@ -2092,6 +2220,10 @@ paths:$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"/{prefix}/images/{image_name}/aliases/{alias}:parameters:@@ -2106,6 +2238,8 @@ paths:upstream registry and existing boxes remain unchanged. An absent imageor alias answers NotFoundError. Local runtimes answer UnsupportedError.tags: [Images]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"responses:"204":description: The alias was deleted@@ -2113,6 +2247,12 @@ paths:$ref: "#/components/responses/BadRequestError""404":$ref: "#/components/responses/NotFoundError"+ "409":+ $ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"# -------------------------------------------------------------------------# Registries@@ -2145,6 +2285,8 @@ paths:for the same pair is refused with `AlreadyExistsError`. A server thatcannot pull private images answers `UnsupportedError`.tags: [Registries]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"requestBody:required: truecontent:@@ -2161,7 +2303,7 @@ paths:"400":$ref: "#/components/responses/BadRequestError""409":- description: A login is already held for this registry and prefix+ description: A login is already held for this registry and prefix, or a hosted key has different input (idempotency_request_mismatch) or is still in progress (idempotency_in_progress).content:application/json:schema:@@ -2171,12 +2313,16 @@ paths:message: "A credential for ghcr.io/acme/ already exists; remove it before adding another"type: AlreadyExistsErrorcode: already_exists+ "422":+ $ref: "#/components/responses/UnprocessableEntityError""501":description: This server does not pull private imagescontent:application/json:schema:$ref: "#/components/schemas/ErrorResponse"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"/{prefix}/images/registries/{registry_id}:parameters:@@ -2191,6 +2337,8 @@ paths:`InvalidStateError`, naming the boxes, while a box still pulls throughthe login.tags: [Registries]+ parameters:+ - $ref: "#/components/parameters/idempotencyKey"responses:"204":description: The login is gone, and its password destroyed@@ -2200,6 +2348,10 @@ paths:$ref: "#/components/responses/NotFoundError""409":$ref: "#/components/responses/ConflictError"+ "422":+ $ref: "#/components/responses/UnprocessableEntityError"+ "503":+ $ref: "#/components/responses/ServiceUnavailableError"# ===========================================================================# Components@@ -2390,11 +2542,17 @@ components:name: Idempotency-Keyin: headerdescription: |- Optional client-provided UUID for safe request retries.- If the server has already processed a request with this key,- it returns the original response without re-executing.- Same key with different payload returns 422.- Keys expire after the duration advertised in `GET /v1/config`.+ Optional client-provided UUID. Hosted deployments advertising this+ operation in capabilities.idempotency_operations replay the original+ successful status, body, Content-Type and Location for the same caller,+ key and business input. Retention is PT24H from first use, without extension.+ Concurrent attempts return 409 idempotency_in_progress; changed input+ returns 409 idempotency_request_mismatch; an uncertain outcome returns+ 422 idempotency_outcome_unknown and must not be automatically dispatched+ again using a new key. Missing, expired or lost records end the guarantee.+ Omission preserves the operation's ordinary behavior and sends no header.+ This header does not declare support in boxlite serve or the reference+ server; inspect GET /v1/config on the target deployment first.schema:type: stringformat: uuid@@ -2462,7 +2620,7 @@ components:value: {error: {message: "agent unavailable", type: UpstreamUnavailableError, code: upstream_unavailable, request_id: req_1}}BadRequestError:- description: Invalid request parameters or body+ description: Invalid request parameters or body, including malformed or duplicate Idempotency-Key headers and non-JSON keyed request bodies on hosted writes.content:application/json:schema:@@ -2501,7 +2659,7 @@ components:request_id: req_01HZK4TNRPQSXYZ8WM6NCVT9R5ConflictError:- description: Resource state conflict+ description: Resource state conflict. Hosted keyed writes return idempotency_request_mismatch for changed input or idempotency_in_progress while the original request is running.content:application/json:schema:@@ -2514,7 +2672,7 @@ components:request_id: req_01HZK4TNRPQSXYZ8WM6NCVT9R5UnprocessableEntityError:- description: Request understood but cannot be processed+ description: Request understood but cannot be processed. Hosted keyed writes return idempotency_outcome_unknown when the original outcome cannot be confirmed.content:application/json:schema:@@ -2548,7 +2706,7 @@ components:code: resource_exhaustedServiceUnavailableError:- description: A required backend service is not configured or available+ description: A required backend service is not configured or available. Hosted keyed writes return idempotency_storage_unavailable if reserving the key fails before dispatch.headers:Retry-After:description: Seconds to wait when Box creation admission is temporarily contended@@ -2892,8 +3050,14 @@ components:example: trueidempotency_key_lifetime:type: string- description: How long idempotency keys are retained (ISO 8601 duration)+ description: Retention from first use (ISO 8601 duration); hosted request replay advertises PT24Hexample: PT24H+ idempotency_operations:+ type: array+ description: Hosted operationIds generated from registered routes and the replay policy; absent means no advertised support+ items:+ type: string+ example: [createBox, startExecution, configureSsh]# =======================================================================# Authentication@@ -2974,7 +3138,13 @@ components:required: [error]properties:error:- $ref: "#/components/schemas/ErrorModel"+ oneOf:+ - $ref: "#/components/schemas/ErrorModel"+ - type: string+ message: {type: string}+ code:+ type: string+ description: Machine-readable reason returned by hosted APIs.ErrorModel:type: object