Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat: add per-account rate limits and Redis quotas for new machine and device creation

0xken1522bd05fdc8db
diff --git a/backend/src/config/env.ts b/backend/src/config/env.ts
index 750b0aecb..8eb2fdd67 100644
--- a/backend/src/config/env.ts
+++ b/backend/src/config/env.ts
@@ -131,6 +131,16 @@ const envSchema = z.object({
// (`harness auth device`). That path is free and its computer id is self-declared, so this caps the
// rows one account can mint; 0 disables the check. Hygiene, not a security control.
HARNESS_DEVICE_AUTH_MACHINE_LIMIT: z.coerce.number().int().min(0).default(20),
+ // Same idea for device rows (`/api/device-ws` resolves-or-creates one per self-declared computer id).
+ // A revoked device is hard-deleted, so the ceiling alone is not enough — see the rates below.
+ HARNESS_DEVICE_LIMIT: z.coerce.number().int().min(0).default(20),
+ // How fast one account may mint NEW machine / device ids (Redis fixed windows, shared by every
+ // replica). A reconnect of an existing id never counts. Ceilings above stop a pile-up; these stop a
+ // create → delete → create loop, which the ceilings cannot see. 0 disables that window.
+ HARNESS_NEW_MACHINE_PER_HOUR: z.coerce.number().int().min(0).default(5),
+ HARNESS_NEW_MACHINE_PER_DAY: z.coerce.number().int().min(0).default(20),
+ HARNESS_NEW_DEVICE_PER_HOUR: z.coerce.number().int().min(0).default(5),
+ HARNESS_NEW_DEVICE_PER_DAY: z.coerce.number().int().min(0).default(20),
AUTONOMOUS_BFF_URL: z.string().url().default('https://apiv2.autonomous.ai'),
STAGING_AUTONOMOUS_BFF_URL: z.string().url().default('https://apiv2.staging.autonomousdev.xyz'),
// Server-to-server subscription snapshots used by the singleton billing worker. These use
diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.ts
index 68d1017ee..860706800 100644
--- a/backend/src/lib/adapterWs.ts
+++ b/backend/src/lib/adapterWs.ts
@@ -15,7 +15,7 @@
import type { IncomingMessage } from 'http'
import type { Duplex } from 'stream'
import { WebSocket, type RawData } from 'ws'
-import { createWss, WS_LIMITS } from './wsServer.js'
+import { createWss, upgradeStatusText, WS_LIMITS } from './wsServer.js'
import { prisma } from './prisma.js'
import {
publishUp, claimMachineOwner, releaseMachineOwner, publishDeviceE2eePair,
@@ -187,11 +187,10 @@ export function handleAdapterUpgrade(req: IncomingMessage, socket: Duplex, head:
wss.handleUpgrade(req, socket, head, (ws) => void attachAdapter(ws, machineId, machine.userId, machine.name, label, computerId, clientVersion, countryCode))
})().catch((err) => {
if (err instanceof AppError) {
- // 403 is the revoked-machine answer from `resolveOrCreateForComputer`; the CLI keys off the
- // numeric status, but sending it under the wrong reason phrase would mislead anyone reading a
- // packet capture or a proxy log.
- const text = err.statusCode === 403 ? 'Forbidden' : err.statusCode === 409 ? 'Conflict' : 'Service Unavailable'
- try { socket.write(`HTTP/1.1 ${err.statusCode} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`) } catch { /* ignore */ }
+ // 403 is the revoked-machine answer from `resolveOrCreateForComputer`, 429 its new-id rate limit
+ // (the CLI retries it with backoff and keeps its token); the CLI keys off the numeric status, but
+ // sending it under the wrong reason phrase would mislead anyone reading a capture or a proxy log.
+ try { socket.write(`HTTP/1.1 ${err.statusCode} ${upgradeStatusText(err.statusCode)}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`) } catch { /* ignore */ }
socket.destroy()
return
}
diff --git a/backend/src/lib/bus.test.ts b/backend/src/lib/bus.test.ts
index 6dca8d7a0..f000f321e 100644
--- a/backend/src/lib/bus.test.ts
+++ b/backend/src/lib/bus.test.ts
@@ -35,6 +35,8 @@ vi.mock('ioredis', () => {
unsubscribe = vi.fn(async () => 1)
quit = vi.fn(async () => 'OK')
on = vi.fn()
+ eval = vi.fn(async () => 0)
+ get = vi.fn(async (_key: string): Promise<string | null> => null)
pipelines: FakePipeline[] = []
pipeline() { const p = new FakePipeline(); this.pipelines.push(p); return p }
opts: unknown
@@ -42,13 +44,18 @@ vi.mock('ioredis', () => {
}
return { Redis: FakeRedis }
})
-vi.mock('../config/env.js', () => ({ env: { REDIS_URL: 'redis://test' } }))
+vi.mock('../config/env.js', () => ({ env: {
+ REDIS_URL: 'redis://test',
+ HARNESS_NEW_MACHINE_PER_HOUR: 5, HARNESS_NEW_MACHINE_PER_DAY: 20,
+ HARNESS_NEW_DEVICE_PER_HOUR: 5, HARNESS_NEW_DEVICE_PER_DAY: 20,
+} }))
vi.mock('../utils/logger.js', () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn() } }))
const bus = await import('./bus.js')
type MockFn = ReturnType<typeof vi.fn>
const pub = state.instances[0] as unknown as {
publish: MockFn; subscribe: MockFn; opts: unknown
+ eval: MockFn; get: MockFn
pipelines: Array<{ calls: Array<{ cmd: string; args: unknown[] }> }>
}
@@ -124,3 +131,59 @@ describe('setAgentClientCountsBatch HEXPIRE fallback', () => {
expect(expireCalls).toHaveLength(0)
})
})
+
+describe('clearDevicePresence', () => {
+ beforeEach(() => { pub.eval.mockClear(); pub.get.mockClear(); pub.eval.mockResolvedValue(0) })
+
+ it('reports `cleared` when the key is gone afterwards, and only deletes on a token match', async () => {
+ pub.get.mockResolvedValue(null)
+ expect(await bus.clearDevicePresence('dev-1', 'tok-1')).toBe('cleared')
+ const [script, keyCount, key, token] = pub.eval.mock.calls[0]
+ expect(script).toContain("redis.call('del', KEYS[1])")
+ expect(script).toContain('== ARGV[1]')
+ expect(keyCount).toBe(1)
+ expect(key).toContain('dev-1')
+ expect(token).toBe('tok-1')
+ })
+
+ it('reports `superseded` when a newer connection still holds the key', async () => {
+ pub.get.mockResolvedValue('tok-2')
+ expect(await bus.clearDevicePresence('dev-1', 'tok-1')).toBe('superseded')
+ })
+
+ it('reports `unknown` — never `superseded` — when Redis is unreachable', async () => {
+ pub.eval.mockRejectedValue(new Error('ECONNREFUSED'))
+ expect(await bus.clearDevicePresence('dev-1', 'tok-1')).toBe('unknown')
+ pub.eval.mockResolvedValue(0)
+ pub.get.mockRejectedValue(new Error('ECONNREFUSED'))
+ expect(await bus.clearDevicePresence('dev-1', 'tok-1')).toBe('unknown')
+ })
+})
+
+describe('consumeNewIdQuota', () => {
+ beforeEach(() => { pub.eval.mockReset() })
+
+ it('counts an hour and a day window per kind and user, in one atomic call', async () => {
+ pub.eval.mockResolvedValue([1, 1])
+ expect(await bus.consumeNewIdQuota('device', 'u1')).toBe(true)
+ const [script, keyCount, ...rest] = pub.eval.mock.calls[0]
+ expect(script).toContain("redis.call('incr', key)")
+ expect(keyCount).toBe(2)
+ expect(rest.slice(0, 2)).toEqual(['newid:device:u1:h', 'newid:device:u1:d'])
+ expect(rest.slice(2)).toEqual([3_600_000, 86_400_000])
+ })
+
+ it('allows up to the limit and refuses past it, in either window', async () => {
+ pub.eval.mockResolvedValue([5, 5])
+ expect(await bus.consumeNewIdQuota('machine', 'u1')).toBe(true)
+ pub.eval.mockResolvedValue([6, 6])
+ expect(await bus.consumeNewIdQuota('machine', 'u1')).toBe(false)
+ pub.eval.mockResolvedValue([1, 21])
+ expect(await bus.consumeNewIdQuota('machine', 'u1')).toBe(false)
+ })
+
+ it('fails open when Redis is unreachable', async () => {
+ pub.eval.mockRejectedValue(new Error('ECONNREFUSED'))
+ expect(await bus.consumeNewIdQuota('device', 'u1')).toBe(true)
+ })
+})
diff --git a/backend/src/lib/bus.ts b/backend/src/lib/bus.ts
index 137921dc3..2032d5006 100644
--- a/backend/src/lib/bus.ts
+++ b/backend/src/lib/bus.ts
@@ -512,6 +512,52 @@ export async function clearMachineAppState(machineId: string): Promise<void> {
}
}
+// ── new-id quota (how fast one account may mint machine / device rows) ────────────────────────────────
+// Both are resolved-or-created from a SELF-DECLARED computer id, so a valid token plus a loop of fresh
+// ids would otherwise mint rows without bound. Fixed windows, one hour and one day, counted in Redis
+// because every replica must share them. Called only on the CREATE path — a reconnect never spends one.
+const NEW_ID_WINDOWS = [
+ { suffix: 'h', ms: 60 * 60_000 },
+ { suffix: 'd', ms: 24 * 60 * 60_000 },
+] as const
+
+// INCR every window, arming its expiry on first use; return the counts in KEYS order. One round trip,
+// and atomic, so two replicas cannot both read "under the limit" off the same count.
+const NEW_ID_QUOTA_SCRIPT = `
+local out = {}
+for i, key in ipairs(KEYS) do
+ local n = redis.call('incr', key)
+ if n == 1 then redis.call('pexpire', key, ARGV[i]) end
+ out[i] = n
+end
+return out`
+
+export type NewIdKind = 'machine' | 'device'
+
+function newIdLimits(kind: NewIdKind): [number, number] {
+ return kind === 'machine'
+ ? [env.HARNESS_NEW_MACHINE_PER_HOUR, env.HARNESS_NEW_MACHINE_PER_DAY]
+ : [env.HARNESS_NEW_DEVICE_PER_HOUR, env.HARNESS_NEW_DEVICE_PER_DAY]
+}
+
+/**
+ * Spend one new-id for `userId`; false when any window is over its limit (0 = window disabled).
+ * Fails OPEN on a Redis error: the per-account row ceilings still hold, and refusing every first login
+ * during a Redis blip would be worse than a few extra rows.
+ */
+export async function consumeNewIdQuota(kind: NewIdKind, userId: string): Promise<boolean> {
+ const limits = newIdLimits(kind)
+ if (limits.every((l) => l <= 0)) return true
+ try {
+ const keys = NEW_ID_WINDOWS.map((w) => `newid:${kind}:${userId}:${w.suffix}`)
+ const counts = await pub.eval(NEW_ID_QUOTA_SCRIPT, keys.length, ...keys, ...NEW_ID_WINDOWS.map((w) => w.ms)) as number[]
+ return counts.every((n, i) => limits[i]! <= 0 || n <= limits[i]!)
+ } catch (err) {
+ logger.error('[bus] consumeNewIdQuota failed — allowing', err, { kind, userId })
+ return true
+ }
+}
+
// ── device presence (is a paired device's socket currently connected?) ─────────────────────────────
// One key PER DEVICE (`device:{deviceId}:conn`) — a user with many devices has one independent key,
// refresh loop and supersede scope per device. The VALUE is the connection's own token so that when
@@ -531,18 +577,28 @@ export async function setDevicePresence(deviceId: string, connToken: string, ttl
}
}
-/** Conditional delete: only removes the key if it still holds THIS connection's token.
- * Returns true when the key is gone afterwards (deleted by us or already absent). */
-export async function clearDevicePresence(deviceId: string, connToken: string): Promise<boolean> {
+/**
+ * What a conditional clear observed. The caller needs all three apart, because they justify
+ * different things (see deviceWs.ts closeBoth):
+ * - `cleared` the key is gone — this socket really was the device's last one.
+ * - `superseded` the key is held by a NEWER connection: the device is ONLINE on another socket and
+ * this one no longer speaks for it. Reached whenever a device reconnects before its
+ * previous socket is reaped, which is ordinary, not exceptional.
+ * - `unknown` Redis could not be reached, so neither of the above is established.
+ */
+export type DevicePresenceClear = 'cleared' | 'superseded' | 'unknown'
+
+/** Conditional delete: only removes the key if it still holds THIS connection's token. */
+export async function clearDevicePresence(deviceId: string, connToken: string): Promise<DevicePresenceClear> {
try {
await pub.eval(
"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",
1, devicePresenceKey(deviceId), connToken,
)
- return !(await pub.get(devicePresenceKey(deviceId)))
+ return (await pub.get(devicePresenceKey(deviceId))) ? 'superseded' : 'cleared'
} catch (err) {
logger.error('[bus] clearDevicePresence failed', err, { deviceId })
- return false
+ return 'unknown'
}
}
diff --git a/backend/src/lib/deviceWs.ts b/backend/src/lib/deviceWs.ts
index 4eba13278..08adc4ce4 100644
--- a/backend/src/lib/deviceWs.ts
+++ b/backend/src/lib/deviceWs.ts
@@ -1,7 +1,7 @@
import type { IncomingMessage } from 'http'
import type { Duplex } from 'stream'
import { WebSocket, type RawData } from 'ws'
-import { createWss, WS_LIMITS } from './wsServer.js'
+import { createWss, upgradeStatusText, WS_LIMITS } from './wsServer.js'
import { randomUUID } from 'crypto'
import { attachHubClient, trackSocketLiveness, DEVICE_IDLE_DEADLINE_MS, type HubClient } from './hub.js'
import {
@@ -362,7 +362,7 @@ export function handleDeviceUpgrade(req: IncomingMessage, socket: Duplex, head:
countryCode: countryCodeFromHeaders(req.headers),
}))
})().catch((err) => {
- if (err instanceof AppError) { denyWith(err.statusCode, 'Service Unavailable'); return }
+ if (err instanceof AppError) { denyWith(err.statusCode, upgradeStatusText(err.statusCode)); return }
logger.warn('device-ws upgrade failed', { error: errMsg(err) })
denyWith(503, 'Service Unavailable')
})
@@ -880,21 +880,24 @@ function relay(device: WebSocket, opts: RelayOpts): void {
if (machineListUnsub) { machineListUnsub(); machineListUnsub = null }
if (presenceDeviceId) {
const id = presenceDeviceId
- // Conditional clear: only publish offline if the key is really gone (a superseding reconnect
- // keeps its own key → we stay silent). lastSeenAt = the moment the device actually went away.
+ // A SUPERSEDED socket says nothing at all. The device reconnected before this one was reaped
+ // (up to ~100s later, on the hub heartbeat), so it is online on the newer socket: announcing it
+ // offline would be a lie, and stamping either `lastSeenAt` would date the row to the moment
+ // this corpse was collected rather than to anything the device did. adapterWs.ts applies the
+ // same rule to a superseded adapter. `seenAt` is taken here, at the close, not after the Redis
+ // round trip, so what lands is when the device went away — the thing a session is measured by.
const seenAt = new Date()
- fireAndForget(clearDevicePresence(id, connToken).then((gone) => {
- if (!gone) return
- // Only a socket that REALLY owned this device writes the goodbye. `gone` is false when a
- // superseding reconnect already holds the presence key: the device is online on the newer
- // socket, and letting this dying one stamp `lastSeenAt` would date the row to the moment the
- // OLD connection was reaped (up to ~100s after the handover) — the same reason the offline
- // publish above is conditional, and the same rule adapterWs.ts applies to a superseded
- // adapter. `seenAt` rather than "now": the moment of the close, not of the Redis round trip.
+ fireAndForget(clearDevicePresence(id, connToken).then((outcome) => {
+ if (outcome === 'superseded') return
+ // 'unknown' (Redis unreachable) still writes these two: we watched this socket until now, so
+ // the timestamp is honest, and a goodbye lost to an outage cannot be recovered later.
touchDevicePresence(id, 'close', seenAt)
- return publishDeviceStatus(userId, { deviceId: id, online: false, lastSeenAt: seenAt.toISOString() })
+ void prisma.deviceBinding.update({ where: { deviceId: id }, data: { lastSeenAt: seenAt } })
+ .catch(() => { /* best effort */ })
+ // The offline PUSH is different: it is only justified by a clear we actually observed. On
+ // 'unknown' the device may well be online, and watchDevices re-reads liveness on its own.
+ if (outcome === 'cleared') return publishDeviceStatus(userId, { deviceId: id, online: false, lastSeenAt: seenAt.toISOString() })
}), 'device offline publish', { userId, deviceId: id })
- void prisma.deviceBinding.update({ where: { deviceId: id }, data: { lastSeenAt: seenAt } }).catch(() => { /* best effort */ })
}
for (const [, unsub] of statusSubs) unsub()
statusSubs.clear()
diff --git a/backend/src/lib/wsServer.ts b/backend/src/lib/wsServer.ts
index fec8939bc..9d4dca800 100644
--- a/backend/src/lib/wsServer.ts
+++ b/backend/src/lib/wsServer.ts
@@ -81,3 +81,13 @@ export async function drainAllSockets(graceMs = 4_000): Promise<void> {
}
}
}
+
+const UPGRADE_STATUS_TEXT: Record<number, string> = {
+ 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 409: 'Conflict',
+ 429: 'Too Many Requests', 503: 'Service Unavailable',
+}
+
+/** Reason phrase for a refused upgrade. Clients key off the number; this is for whoever reads a capture. */
+export function upgradeStatusText(status: number): string {
+ return UPGRADE_STATUS_TEXT[status] ?? 'Service Unavailable'
+}
diff --git a/backend/src/services/DeviceService.test.ts b/backend/src/services/DeviceService.test.ts
index 468198a76..e20d72e7c 100644
--- a/backend/src/services/DeviceService.test.ts
+++ b/backend/src/services/DeviceService.test.ts
@@ -5,16 +5,20 @@ const findFirst = vi.hoisted(() => vi.fn())
const update = vi.hoisted(() => vi.fn())
const updateMany = vi.hoisted(() => vi.fn())
const getDevicePresence = vi.hoisted(() => vi.fn())
+const count = vi.hoisted(() => vi.fn())
+const create = vi.hoisted(() => vi.fn())
+const consumeNewIdQuota = vi.hoisted(() => vi.fn())
vi.mock('../lib/prisma.js', () => ({
prisma: {
- deviceBinding: { findMany, findFirst, update, updateMany },
+ deviceBinding: { findMany, findFirst, count, create, update, updateMany },
machine: { findMany: vi.fn() },
},
machineAlive: {},
}))
-vi.mock('../lib/bus.js', () => ({ getDevicePresence }))
+vi.mock('../lib/bus.js', () => ({ getDevicePresence, consumeNewIdQuota }))
+import { Prisma } from '@prisma/client'
import { deviceService } from './DeviceService.js'
const device = (over: Record<string, unknown> = {}): Record<string, unknown> => ({
@@ -165,3 +169,61 @@ describe('detailForUser', () => {
expect(await deviceService.detailForUser('dev-1', 'u2')).toBeNull()
})
})
+
+describe('resolveOrCreateForComputer', () => {
+ const resolve = () => deviceService.resolveOrCreateForComputer('u1', 'prod', 'a'.repeat(32), 'laptop')
+
+ const notFound = () => new Prisma.PrismaClientKnownRequestError('missing', { code: 'P2025', clientVersion: 'x' })
+
+ beforeEach(() => {
+ count.mockResolvedValue(0)
+ consumeNewIdQuota.mockResolvedValue(true)
+ create.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => device(data))
+ // Default: no row yet — the touch misses. A test that wants a known device overrides once.
+ update.mockRejectedValueOnce(notFound())
+ update.mockImplementation(async ({ where }: { where: { deviceId: string } }) => device({ deviceId: where.deviceId }))
+ })
+
+ it('a known device reconnects in one write, without touching the ceiling or the new-id quota', async () => {
+ update.mockReset()
+ update.mockResolvedValue(device())
+ await resolve()
+ expect(update).toHaveBeenCalledOnce()
+ expect(count).not.toHaveBeenCalled()
+ expect(consumeNewIdQuota).not.toHaveBeenCalled()
+ expect(create).not.toHaveBeenCalled()
+ })
+
+ it('rethrows a touch failure that is not "no such row"', async () => {
+ update.mockReset()
+ update.mockRejectedValue(new Error('mongo down'))
+ await expect(resolve()).rejects.toThrow('mongo down')
+ expect(create).not.toHaveBeenCalled()
+ })
+
+ it('a new device spends one new-id and is created with a derived id', async () => {
+ const row = await resolve()
+ expect(consumeNewIdQuota).toHaveBeenCalledWith('device', 'u1')
+ expect(create).toHaveBeenCalledOnce()
+ expect(row.deviceId).toMatch(/^cmp-[0-9a-f]{24}$/)
+ })
+
+ it('refuses a new device past the per-account ceiling with 409, before spending quota', async () => {
+ count.mockResolvedValue(20)
+ await expect(resolve()).rejects.toMatchObject({ statusCode: 409, code: 'TOO_MANY_DEVICES' })
+ expect(consumeNewIdQuota).not.toHaveBeenCalled()
+ expect(create).not.toHaveBeenCalled()
+ })
+
+ it('refuses a new device over the new-id rate with 429', async () => {
+ consumeNewIdQuota.mockResolvedValue(false)
+ await expect(resolve()).rejects.toMatchObject({ statusCode: 429, code: 'NEW_DEVICE_RATE_LIMITED' })
+ expect(create).not.toHaveBeenCalled()
+ })
+
+ it('a lost create race converges on the winner\'s row', async () => {
+ create.mockRejectedValue(new Prisma.PrismaClientKnownRequestError('dup', { code: 'P2002', clientVersion: 'x' }))
+ await resolve()
+ expect(update).toHaveBeenCalledTimes(2) // the missed touch, then the converging one
+ })
+})
diff --git a/backend/src/services/DeviceService.ts b/backend/src/services/DeviceService.ts
index 5954dc469..b419082ff 100644
--- a/backend/src/services/DeviceService.ts
+++ b/backend/src/services/DeviceService.ts
@@ -1,9 +1,11 @@
-import type { DeviceBinding } from '@prisma/client'
+import { Prisma, type DeviceBinding } from '@prisma/client'
import { prisma, machineAlive } from '../lib/prisma.js'
import { sha256hex } from '../utils/crypto.js'
import { logger } from '../utils/logger.js'
import { machineBillingAllowsDataPlane } from '../lib/billingState.js'
-import { getDevicePresence } from '../lib/bus.js'
+import { getDevicePresence, consumeNewIdQuota } from '../lib/bus.js'
+import { env } from '../config/env.js'
+import { AppError } from '../errors/index.js'
export interface DeviceView {
deviceId: string
@@ -77,8 +79,8 @@ export const deviceService = {
* `@unique` while `computerId` is self-declared by the client — using the computer id verbatim would let
* one account squat another's row. Hashing the userId in namespaces it per account, and the environment
* keeps the "same person, separate rows per Autonomous plane" rule true regardless of how User rows are
- * scoped. Determinism is what makes this a single idempotent upsert with no key to mint and therefore no
- * create-lock: two daemons racing on the same computer converge on the same row.
+ * scoped. Determinism is what makes this idempotent with no key to mint and therefore no create-lock: two
+ * daemons racing on the same computer converge on the same row.
*
* Identity is the SSO subject resolved upstream (`user.sub`), never email.
*/
@@ -90,14 +92,42 @@ export const deviceService = {
): Promise<DeviceBinding> {
const deviceId = `cmp-${sha256hex(`${userId}:${autonomousEnv}:${computerId}`).slice(0, 24)}`
const name = label.trim().slice(0, 120) || 'computer'
- return prisma.deviceBinding.upsert({
+ // `userId` is re-applied so a computer that changed hands follows its owner. `name` is deliberately
+ // NOT overwritten: it is the user-editable display name, and a reconnect must not undo a rename —
+ // the same rule Machine.name follows.
+ const touch = (): Promise<DeviceBinding> => prisma.deviceBinding.update({
where: { deviceId },
- create: { userId, deviceId, computerId, name, lastSeenAt: new Date() },
- // `userId` is re-applied so a computer that changed hands follows its owner. `name` is deliberately
- // NOT overwritten: it is the user-editable display name, and a reconnect must not undo a rename —
- // the same rule Machine.name follows.
- update: { userId, computerId, lastSeenAt: new Date() },
+ data: { userId, computerId, lastSeenAt: new Date() },
})
+ // Touch first, create only when there was nothing to touch — rather than one upsert, because only a
+ // NEW row may be charged against the account's ceiling and new-id rate, and the reconnect of a known
+ // device must stay a single free write. The computer id is self-declared, so without those a valid
+ // token plus a loop of fresh ids mints rows without bound — and a revoke is a hard delete, which is
+ // why the ceiling alone cannot stop a create/revoke loop. P2025 also covers a revoke landing between
+ // the device's last connect and this one: it simply pairs again, as the upsert used to.
+ try {
+ return await touch()
+ } catch (err) {
+ if (!(err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2025')) throw err
+ }
+ // No lock around count → create: parallel fresh ids can overshoot the ceiling, but only by what the
+ // (atomic) new-id rate below lets through in one window.
+ if (env.HARNESS_DEVICE_LIMIT > 0 && await prisma.deviceBinding.count({ where: { userId } }) >= env.HARNESS_DEVICE_LIMIT) {
+ logger.warn('device limit reached', { userId, computerId })
+ throw new AppError('Too many devices on this account', 409, 'TOO_MANY_DEVICES')
+ }
+ if (!(await consumeNewIdQuota('device', userId))) {
+ logger.warn('new id rate limited', { kind: 'device', userId, computerId })
+ throw new AppError('Too many new devices on this account, try again later', 429, 'NEW_DEVICE_RATE_LIMITED')
+ }
+ try {
+ return await prisma.deviceBinding.create({ data: { userId, deviceId, computerId, name, lastSeenAt: new Date() } })
+ } catch (err) {
+ // Two dials of the same computer raced past the lookup; the id is derived, so the loser's row IS
+ // the winner's — converge on it exactly as the upsert used to.
+ if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') return touch()
+ throw err
+ }
},
/** The user's machines for the device machine-picker. Ordered oldest-first for a stable list.
diff --git a/backend/src/services/MachineService.computer.test.ts b/backend/src/services/MachineService.computer.test.ts
new file mode 100644
index 000000000..a849d3970
--- /dev/null
+++ b/backend/src/services/MachineService.computer.test.ts
@@ -0,0 +1,80 @@
+/**
+ * `resolveOrCreateForComputer` — the free path that mints a Remote machine for a self-declared computer id.
+ *
+ * What is pinned here is the abuse bound: a reconnect is free, only a CREATE spends the account's new-id
+ * quota, and the create lock is per ACCOUNT so N parallel fresh ids cannot all pass the same ceiling count.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const findMany = vi.hoisted(() => vi.fn())
+const count = vi.hoisted(() => vi.fn())
+const create = vi.hoisted(() => vi.fn())
+const planFindFirst = vi.hoisted(() => vi.fn())
+const redisSet = vi.hoisted(() => vi.fn())
+const consumeNewIdQuota = vi.hoisted(() => vi.fn())
+
+vi.mock('../lib/prisma.js', () => ({
+ machineAlive: {},
+ prisma: {
+ machine: { findMany, count, create, findUnique: vi.fn() },
+ subscriptionPlan: { findFirst: planFindFirst },
+ },
+}))
+vi.mock('../lib/bus.js', () => ({
+ getAgentPresence: vi.fn(),
+ clearAgentPresence: vi.fn(),
+ publishDown: vi.fn(),
+ publishDeviceMachineListChanged: vi.fn(async () => {}),
+ consumeNewIdQuota,
+ pub: { set: redisSet, eval: vi.fn(async () => 1) },
+}))
+vi.mock('../config/env.js', () => ({ env: { HARNESS_DEVICE_AUTH_MACHINE_LIMIT: 20 } }))
+vi.mock('../lib/managers.js', () => ({ selectManagerId: vi.fn() }))
+vi.mock('../lib/provision.js', () => ({ provisionViaManager: vi.fn() }))
+vi.mock('../lib/machineLifecycle.js', () => ({ ensureMachineReady: vi.fn(), publishMachineLifecycle: vi.fn() }))
+vi.mock('../lib/machineCredential.js', () => ({ encryptMachineCredential: vi.fn() }))
+vi.mock('./MachineBillingService.js', () => ({ machineBillingService: {} }))
+
+const { machineService } = await import('./MachineService.js')
+
+const COMPUTER = 'a'.repeat(32)
+const resolve = () => machineService.resolveOrCreateForComputer('u1', 'prod', COMPUTER, 'laptop')
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ findMany.mockResolvedValue([])
+ count.mockResolvedValue(0)
+ planFindFirst.mockResolvedValue(null)
+ redisSet.mockResolvedValue('OK')
+ consumeNewIdQuota.mockResolvedValue(true)
+ create.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => ({ ...data }))
+})
+
+describe('resolveOrCreateForComputer', () => {
+ it('reuses the computer\'s machine without a lock or a quota spend', async () => {
+ findMany.mockResolvedValue([{ machineId: 'm1', billingStatus: 'not_required' }])
+ const out = await resolve()
+ expect(out).toMatchObject({ created: false, machine: { machineId: 'm1' } })
+ expect(redisSet).not.toHaveBeenCalled()
+ expect(consumeNewIdQuota).not.toHaveBeenCalled()
+ })
+
+ it('creates under a lock keyed by the ACCOUNT, spending one machine new-id', async () => {
+ const out = await resolve()
+ expect(out.created).toBe(true)
+ expect(redisSet.mock.calls[0]?.[0]).toBe('machine:create:u1')
+ expect(consumeNewIdQuota).toHaveBeenCalledWith('machine', 'u1')
+ })
+
+ it('refuses a create over the new-id rate with 429 and writes nothing', async () => {
+ consumeNewIdQuota.mockResolvedValue(false)
+ await expect(resolve()).rejects.toMatchObject({ statusCode: 429, code: 'NEW_MACHINE_RATE_LIMITED' })
+ expect(create).not.toHaveBeenCalled()
+ })
+
+ it('hits the live-row ceiling first, without spending quota', async () => {
+ count.mockResolvedValue(20)
+ await expect(resolve()).rejects.toMatchObject({ statusCode: 409, code: 'TOO_MANY_MACHINES' })
+ expect(consumeNewIdQuota).not.toHaveBeenCalled()
+ })
+})
diff --git a/backend/src/services/MachineService.ts b/backend/src/services/MachineService.ts
index 1427221f1..553824b04 100644
--- a/backend/src/services/MachineService.ts
+++ b/backend/src/services/MachineService.ts
@@ -2,7 +2,7 @@ import type { Machine } from '@prisma/client'
import { prisma, machineAlive } from '../lib/prisma.js'
import { selectManagerId } from '../lib/managers.js'
import { provisionViaManager } from '../lib/provision.js'
-import { getAgentPresence, clearAgentPresence, publishDown, publishDeviceMachineListChanged, pub } from '../lib/bus.js'
+import { getAgentPresence, clearAgentPresence, publishDown, publishDeviceMachineListChanged, pub, consumeNewIdQuota } from '../lib/bus.js'
import { randomUUID } from 'node:crypto'
import { generateApiKey, machineIdFromKey } from '../utils/crypto.js'
import { assertMachineId, isMachineId } from '../utils/slug.js'
@@ -98,8 +98,11 @@ const COMPUTER_CREATE_LOCK_WAIT_MS = 10_000
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))
-function computerCreateLockKey(userId: string, computerId: string): string {
- return `machine:create:${userId}:${computerId}`
+// Per ACCOUNT, not per (account, computer): the ceiling check below is a count-then-create, and a lock
+// scoped to one computer id let N parallel upgrades with N fresh ids all pass the same count. This is the
+// rare first-login path, so serializing one person's creates costs nothing a real user can notice.
+function computerCreateLockKey(userId: string): string {
+ return `machine:create:${userId}`
}
/**
@@ -108,7 +111,7 @@ function computerCreateLockKey(userId: string, computerId: string): string {
* under a short Redis lock prevents concurrent adapter upgrades from minting duplicate rows.
*/
async function withComputerCreateLock<T>(userId: string, computerId: string, action: () => Promise<T>): Promise<T> {
- const key = computerCreateLockKey(userId, computerId)
+ const key = computerCreateLockKey(userId)
const owner = randomUUID()
const deadline = Date.now() + COMPUTER_CREATE_LOCK_WAIT_MS
let acquired = false
@@ -455,6 +458,12 @@ export const machineService = {
throw new AppError('Too many connected computers on this account', 409, 'TOO_MANY_MACHINES')
}
}
+ // The ceiling above counts LIVE rows, and deletion is soft — so create → delete → create never
+ // reaches it. The rate is what bounds that loop. 429 keeps the CLI retrying with its token intact.
+ if (!(await consumeNewIdQuota('machine', userId))) {
+ logger.warn('new id rate limited', { kind: 'machine', userId, computerId })
+ throw new AppError('Too many new computers on this account, try again later', 429, 'NEW_MACHINE_RATE_LIMITED')
+ }
const apiKey = generateApiKey()
const machineId = machineIdFromKey(apiKey)