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.

Backend: sign-in reads its user once, machine list reads only what it shows, sockets stop polling device bindings (DB roadmap 2.7) (#2159)

0xken150e4da9b4e9c9
diff --git a/backend/src/lib/bus.ts b/backend/src/lib/bus.ts
index a99848a80..6d56b3274 100644
--- a/backend/src/lib/bus.ts
+++ b/backend/src/lib/bus.ts
@@ -761,7 +761,14 @@ export async function getDevicePresence(deviceId: string): Promise<boolean> {
}
}
-export interface DeviceStatusMsg { deviceId: string; online: boolean; lastSeenAt?: string }
+export interface DeviceStatusMsg {
+ deviceId: string
+ online: boolean
+ lastSeenAt?: string
+ /** The device was revoked (lib/deviceRevoke.ts): a web socket drops it from its copy of the account's devices. It
+ * still says `online: false`, so a server that predates the field reads it as the device going offline. */
+ removed?: true
+}
/** Per-USER transition channel (one sub per watching web socket); messages are PER-DEVICE. */
export function publishDeviceStatus(userId: string, msg: DeviceStatusMsg): Promise<number> {
diff --git a/backend/src/lib/deviceRevoke.test.ts b/backend/src/lib/deviceRevoke.test.ts
new file mode 100644
index 000000000..859e0277d
--- /dev/null
+++ b/backend/src/lib/deviceRevoke.test.ts
@@ -0,0 +1,31 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const m = vi.hoisted(() => ({ revoke: vi.fn(), pushDeviceRevoked: vi.fn(), publishDeviceControl: vi.fn(), publishDeviceStatus: vi.fn() }))
+vi.mock('../services/index.js', () => ({ deviceService: { revoke: m.revoke } }))
+vi.mock('./hub.js', () => ({ pushDeviceRevoked: m.pushDeviceRevoked }))
+vi.mock('./bus.js', () => ({ publishDeviceControl: m.publishDeviceControl, publishDeviceStatus: m.publishDeviceStatus }))
+vi.mock('../utils/logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }))
+
+import { revokeDeviceForUser } from './deviceRevoke.js'
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ m.publishDeviceControl.mockResolvedValue(1)
+ m.publishDeviceStatus.mockResolvedValue(1)
+})
+
+describe('revoking a device', () => {
+ // The owner's open web sockets keep their own copy of the account's devices (lib/webWs.ts): this is what drops it.
+ it('tells the owner\'s web sockets the device is gone', async () => {
+ m.revoke.mockResolvedValue({ deviceId: 'dial', machineIds: ['mac'] })
+ await expect(revokeDeviceForUser('dial', 'owner')).resolves.toBe(true)
+ expect(m.publishDeviceStatus).toHaveBeenCalledWith('owner', { deviceId: 'dial', online: false, removed: true })
+ })
+
+ it('tells nobody about a device that is not the caller\'s', async () => {
+ m.revoke.mockResolvedValue(null)
+ await expect(revokeDeviceForUser('dial', 'someone-else')).resolves.toBe(false)
+ expect(m.publishDeviceStatus).not.toHaveBeenCalled()
+ expect(m.publishDeviceControl).not.toHaveBeenCalled()
+ })
+})
diff --git a/backend/src/lib/deviceRevoke.ts b/backend/src/lib/deviceRevoke.ts
index eb9be4dc7..cb98fbd71 100644
--- a/backend/src/lib/deviceRevoke.ts
+++ b/backend/src/lib/deviceRevoke.ts
@@ -1,6 +1,6 @@
import { deviceService } from '../services/index.js'
import { pushDeviceRevoked } from './hub.js'
-import { publishDeviceControl } from './bus.js'
+import { publishDeviceControl, publishDeviceStatus } from './bus.js'
import { logger } from '../utils/logger.js'
/**
@@ -27,6 +27,8 @@ export async function revokeDeviceForUser(deviceId: string, userId: string): Pro
for (const machineId of revoked.machineIds) pushDeviceRevoked(machineId, revoked.deviceId)
// Duplicate delivery is harmless — the first frame reboots the device.
void publishDeviceControl(revoked.deviceId, { action: 'revoked' })
+ // The owner's open web sockets keep their own copy of the account's devices (lib/webWs.ts) and drop it on this.
+ void publishDeviceStatus(userId, { deviceId: revoked.deviceId, online: false, removed: true })
logger.info('device revoked', { deviceId: revoked.deviceId, machines: revoked.machineIds.length, by: userId })
return true
}
diff --git a/backend/src/lib/ssoAuth.test.ts b/backend/src/lib/ssoAuth.test.ts
index 7bc042eb9..12fc19985 100644
--- a/backend/src/lib/ssoAuth.test.ts
+++ b/backend/src/lib/ssoAuth.test.ts
@@ -182,7 +182,7 @@ describe('authenticated user resolution', () => {
externalId: 'stag-sub-1',
autonomousEnv: 'stag',
- }))
+ }), { existing })
expect(findByExternal).not.toHaveBeenCalled()
})
@@ -197,7 +197,7 @@ describe('authenticated user resolution', () => {
expect(upsertFromSso).toHaveBeenCalledWith(expect.objectContaining({
signUpAttribution: { source: 'app', rid: 'r-123' },
- }))
+ }), { existing: null })
})
it('claims a prod provisional row by User.externalId', async () => {
diff --git a/backend/src/lib/ssoAuth.ts b/backend/src/lib/ssoAuth.ts
index 5098e350c..4289e6500 100644
--- a/backend/src/lib/ssoAuth.ts
+++ b/backend/src/lib/ssoAuth.ts
@@ -309,7 +309,7 @@ export async function authenticateAccessToken(
autonomousEnv,
...metadata,
...(signUpAttribution ? { signUpAttribution } : {}),
- })
+ }, { existing })
// Learn the account's Google subject while an Autonomous token is in hand, so a computer of the same
// account signed in by QR can be answered later (lib/googleSubject.ts). Not awaited, never throws.
// Here and not in the REST hook, because a daemon that only holds a socket authenticates here too.
diff --git a/backend/src/lib/ssoAuth.userReads.test.ts b/backend/src/lib/ssoAuth.userReads.test.ts
new file mode 100644
index 000000000..a53e70805
--- /dev/null
+++ b/backend/src/lib/ssoAuth.userReads.test.ts
@@ -0,0 +1,96 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+// The real user service over a fake database: these tests count the user reads one signed-in request costs
+// (DB optimization roadmap, Phase 2 item 7).
+// Nothing is reused across requests: another server may have changed the account in between (demoted an admin,
+// deleted it, moved it to the other environment), and that must apply on the very next request.
+const findUnique = vi.hoisted(() => vi.fn())
+const update = vi.hoisted(() => vi.fn())
+const create = vi.hoisted(() => vi.fn())
+
+vi.mock('./prisma.js', () => ({
+ prisma: { user: { findUnique, update, create } },
+}))
+
+import { authenticateAccessToken, clearSsoProfileCache } from './ssoAuth.js'
+
+function profileFetch(id: string, email: string): void {
+ vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockImplementation(async () => new Response(
+ JSON.stringify({ status: 1, data: { id, email } }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } },
+ )))
+}
+
+const stored = (over: Record<string, unknown> = {}): Record<string, unknown> => ({
+ id: 'u1',
+ email: '[email protected]',
+ externalId: 'prod-sub-1',
+ stagExternalId: null,
+ name: null,
+ role: 'user',
+ autonomousEnv: 'prod',
+ googleSub: null,
+ // Checked just now, so no Google-subject fill runs and every read counted is the sign-in's own.
+ googleSubCheckedAt: new Date(),
+ ...over,
+})
+
+/** User reads by email: the sign-in's identity lookups. */
+const emailReads = (): number => findUnique.mock.calls.filter(([args]) => 'email' in (args as { where: object }).where).length
+
+describe('user reads per signed-in request', () => {
+ /** What the database holds for the account right now; a test changes it as another server would. */
+ let row: Record<string, unknown> | null
+
+ beforeEach(() => {
+ profileFetch('prod-sub-1', '[email protected]')
+ row = stored()
+ findUnique.mockImplementation(async ({ where }: { where: { id?: string; email?: string } }) =>
+ (row && (where.email === row.email || where.id === row.id) ? row : null))
+ update.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => ({ ...row, ...data }))
+ create.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => ({ id: 'u-new', ...data }))
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.clearAllMocks()
+ clearSsoProfileCache()
+ })
+
+ it('reads the user once for one request', async () => {
+ await expect(authenticateAccessToken('a.e30.c', 'prod')).resolves.toMatchObject({ sub: 'u1', role: 'user' })
+ expect(emailReads()).toBe(1)
+ })
+
+ it('reads the user once for a request that updates the account', async () => {
+ profileFetch('prod-sub-2', '[email protected]')
+ await expect(authenticateAccessToken('a.e30.c', 'prod')).resolves.toMatchObject({ sub: 'u1' })
+ expect(update).toHaveBeenCalledOnce()
+ expect(emailReads()).toBe(1)
+ })
+
+ it('reads the user again for the next request', async () => {
+ await authenticateAccessToken('a.e30.c', 'prod')
+ await authenticateAccessToken('a.e30.c', 'prod')
+ expect(emailReads()).toBe(2)
+ })
+
+ it('serves an admin demoted on another server as a user on the next request', async () => {
+ row = stored({ role: 'admin' })
+ await expect(authenticateAccessToken('a.e30.c', 'prod')).resolves.toMatchObject({ role: 'admin' })
+ row = stored({ role: 'user' })
+ await expect(authenticateAccessToken('a.e30.c', 'prod')).resolves.toMatchObject({ role: 'user' })
+ })
+
+ it('refuses the next request after another server moved the account to the other environment', async () => {
+ await authenticateAccessToken('a.e30.c', 'prod')
+ row = stored({ autonomousEnv: 'stag' })
+ await expect(authenticateAccessToken('a.e30.c', 'prod')).rejects.toMatchObject({ code: 'AUTONOMOUS_ENV_MISMATCH' })
+ })
+
+ it('never serves an account another server deleted', async () => {
+ await authenticateAccessToken('a.e30.c', 'prod')
+ row = null
+ await expect(authenticateAccessToken('a.e30.c', 'prod')).resolves.not.toMatchObject({ sub: 'u1' })
+ })
+})
diff --git a/backend/src/lib/webWs.ts b/backend/src/lib/webWs.ts
index 668937b58..704a128d3 100644
--- a/backend/src/lib/webWs.ts
+++ b/backend/src/lib/webWs.ts
@@ -25,7 +25,7 @@ import { extractKey } from '../utils/crypto.js'
import { machineIdFromKey } from '../utils/crypto.js'
import { prisma, machineAlive } from './prisma.js'
import { touchDeviceKey } from './deviceKeyLog.js'
-import { getAgentPresence, getAgentPresenceMany, subscribeStatus, getDevicePresence, subscribeDeviceStatus, subscribeDeviceMachineListChanged, subscribeDeviceE2eePair, subscribeMachineShareChanged } from './bus.js'
+import { getAgentPresence, getAgentPresenceMany, subscribeStatus, getDevicePresence, subscribeDeviceStatus, subscribeDeviceMachineListChanged, subscribeDeviceE2eePair, subscribeMachineShareChanged, type DeviceStatusMsg } from './bus.js'
import { sharedMachineAccess } from './machineAccess.js'
import { relayWebDocumentPushes } from './webAccountPushes.js'
import { DAEMONS } from '../config/env.js'
@@ -77,6 +77,10 @@ const WEB_FRAME_TYPES: ReadonlySet<string> = new Set([...TERMINAL_DOWN_TYPES, ..
// Device-status re-seed: covers the silent-offline case (worker crash → presence TTL 45s ages out
// with no transition published) — the watcher re-reads presence keys on this cadence.
const DEVICE_RESEED_MS = 30_000
+/** How old the socket's own copy of the account's device bindings may get before a re-seed reads them again. A pair or a
+ * revoke is pushed and re-reads at once; this only bounds how long a push lost on the way leaves the copy wrong. Every
+ * socket used to read them every DEVICE_RESEED_MS (DB optimization roadmap, Phase 2 item 7). */
+export const DEVICE_BINDINGS_REREAD_MS = 10 * 60_000
// Trailing debounce for list re-derivations poked by machines_watch (see scheduleWatchAgents).
const WATCH_DEBOUNCE_MS = 250
/** How long a relay refused for an offline machine waits before it selects that machine again: a daemon's relay
@@ -273,28 +277,66 @@ function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'we
// ── Live device-status feed (mirror of watchAgents; per-DEVICE statuses over one per-user sub) ──
// Transitions ride the user-scoped `devstatus:{userId}` channel (deviceWs publishes on connect/
- // disconnect), so a device paired AFTER the watch armed still reports without re-deriving the set.
- // The 30s re-seed poll covers the silent case: a worker holding a device socket crashes → nobody
- // publishes offline, the presence key just ages out (TTL 45s) — the poll notices within ~30s.
+ // disconnect, deviceRevoke on a revoke). The socket keeps its own copy of the account's device bindings:
+ // a revoke drops a device from it, and a report from a device it does not know (one paired after the copy
+ // was read) reads the bindings again. The 30s re-seed covers the silent case — a worker holding a device
+ // socket crashes, nobody publishes offline, the presence key just ages out (TTL 45s) — and reads only
+ // presence; the bindings themselves are read again only after DEVICE_BINDINGS_REREAD_MS.
const sendDeviceStatuses = (statuses: Array<{ deviceId: string; online: boolean; lastSeenAt?: string | null }>): void => {
if (ws.readyState !== WebSocket.OPEN || statuses.length === 0) return
send({ type: 'devices_status', payload: { statuses } })
}
let deviceStatusUnsub: (() => void) | null = null
let deviceSeedTimer: NodeJS.Timeout | null = null
+ // deviceId → its last seen time; null until the bindings were first read.
+ let knownDevices: Map<string, string | null> | null = null
+ let knownDevicesReadAt = 0
+ let deviceBindingsRead: Promise<void> | null = null
+ // Set by a change that lands while a read is in flight: that read may predate it, so another follows.
+ let deviceBindingsStale = false
+ const readDeviceBindings = (): Promise<void> => {
+ deviceBindingsStale = true
+ if (deviceBindingsRead) return deviceBindingsRead
+ deviceBindingsRead = (async () => {
+ try {
+ while (deviceBindingsStale && !closed) {
+ deviceBindingsStale = false
+ const rows = await prisma.deviceBinding.findMany({ where: { userId: user.sub }, select: { deviceId: true, lastSeenAt: true } })
+ if (deviceBindingsStale) continue
+ knownDevices = new Map(rows.map((d) => [d.deviceId, d.lastSeenAt?.toISOString() ?? null]))
+ knownDevicesReadAt = Date.now()
+ }
+ } finally {
+ deviceBindingsRead = null
+ }
+ })()
+ return deviceBindingsRead
+ }
const seedDeviceStatuses = async (): Promise<void> => {
- const rows = await prisma.deviceBinding.findMany({ where: { userId: user.sub }, select: { deviceId: true, lastSeenAt: true } })
- if (closed) return
+ if (!knownDevices || Date.now() - knownDevicesReadAt >= DEVICE_BINDINGS_REREAD_MS) await readDeviceBindings()
+ if (closed || !knownDevices) return
const statuses = await Promise.all(
- rows.map(async (d) => ({ deviceId: d.deviceId, online: await getDevicePresence(d.deviceId), lastSeenAt: d.lastSeenAt?.toISOString() ?? null })),
+ [...knownDevices].map(async ([deviceId, lastSeenAt]) => ({ deviceId, online: await getDevicePresence(deviceId), lastSeenAt })),
)
if (!closed) sendDeviceStatuses(statuses)
}
+ const onDeviceStatus = (msg: DeviceStatusMsg): void => {
+ if (msg.removed) {
+ knownDevices?.delete(msg.deviceId)
+ if (deviceBindingsRead) deviceBindingsStale = true
+ return
+ }
+ if (knownDevices?.has(msg.deviceId)) {
+ if (msg.lastSeenAt) knownDevices.set(msg.deviceId, msg.lastSeenAt)
+ } else if (knownDevices || deviceBindingsRead) {
+ // A device the copy does not hold, or a read under way that may predate it: read the bindings (again).
+ void readDeviceBindings().catch((err) => logger.warn('web-ws device bindings read failed', { userId: user.sub, error: String(err) }))
+ }
+ sendDeviceStatuses([{ deviceId: msg.deviceId, online: msg.online === true, ...(msg.lastSeenAt ? { lastSeenAt: msg.lastSeenAt } : {}) }])
+ }
const watchDevices = async (): Promise<void> => {
if (!deviceStatusUnsub) {
- deviceStatusUnsub = await subscribeDeviceStatus(user.sub, (msg) => {
- sendDeviceStatuses([{ deviceId: msg.deviceId, online: msg.online === true, ...(msg.lastSeenAt ? { lastSeenAt: msg.lastSeenAt } : {}) }])
- })
+ deviceStatusUnsub = await subscribeDeviceStatus(user.sub, onDeviceStatus)
if (closed) { deviceStatusUnsub(); deviceStatusUnsub = null; return }
}
if (!deviceSeedTimer) {
@@ -302,6 +344,8 @@ function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'we
void seedDeviceStatuses().catch(() => { /* ignore */ })
}, DEVICE_RESEED_MS)
}
+ // Asked to watch (the first time, or again after the client paired or revoked one): read the bindings now.
+ await readDeviceBindings()
await seedDeviceStatuses()
}
if (!feedsOnDemand) void watchDevices().catch((err) => logger.warn('web-ws watchDevices failed', { userId: user.sub, error: String(err) }))
diff --git a/backend/src/lib/webWsDevices.test.ts b/backend/src/lib/webWsDevices.test.ts
new file mode 100644
index 000000000..9c45cab6e
--- /dev/null
+++ b/backend/src/lib/webWsDevices.test.ts
@@ -0,0 +1,197 @@
+import { EventEmitter } from 'node:events'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+// A web socket's device feed (DB optimization roadmap, Phase 2 item 7). Each open socket re-read the account's device
+// bindings from the database every 30 s to notice a device whose worker died without saying it went offline. The
+// bindings change only on a pair or a revoke, so the socket now keeps them, re-reads them when a change is pushed,
+// and its 30 s check reads live presence alone.
+const m = vi.hoisted(() => ({
+ auth: vi.fn(), upgrade: vi.fn(), deviceFindMany: vi.fn(), subscribeDeviceStatus: vi.fn(), devicePresence: vi.fn(),
+}))
+vi.mock('../utils/logger.js', () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() } }))
+vi.mock('./ssoAuth.js', async original => ({ ...await original<typeof import('./ssoAuth.js')>(), authenticateAccessToken: m.auth }))
+vi.mock('./wsServer.js', async original => ({ ...await original<typeof import('./wsServer.js')>(), createWss: () => ({ handleUpgrade: m.upgrade }) }))
+vi.mock('./prisma.js', () => ({
+ prisma: { machine: { findUnique: vi.fn(), findMany: vi.fn(async () => []) }, deviceBinding: { findMany: m.deviceFindMany } },
+ machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] },
+}))
+vi.mock('./bus.js', () => ({
+ getAgentPresence: vi.fn(), getAgentPresenceMany: vi.fn(async () => new Map()), subscribeStatus: vi.fn(async () => () => {}),
+ getDevicePresence: m.devicePresence, subscribeDeviceStatus: m.subscribeDeviceStatus,
+ subscribeDeviceMachineListChanged: vi.fn(async () => () => {}), subscribeDeviceE2eePair: vi.fn(async () => () => {}),
+ subscribeMachineShareChanged: vi.fn(async () => () => {}),
+}))
+vi.mock('./providerLink.js', () => ({ machineOnline: vi.fn() }))
+vi.mock('./machineLifecycle.js', () => ({ ensureMachineReady: vi.fn(async () => {}), getMachineLifecycleStatus: vi.fn() }))
+vi.mock('./webAccountPushes.js', () => ({ relayWebDocumentPushes: vi.fn(async () => () => {}) }))
+vi.mock('./hub.js', () => ({ attachHubClient: vi.fn(), trackSocketLiveness: () => () => {} }))
+
+import { DEVICE_BINDINGS_REREAD_MS, handleWebUpgrade } from './webWs.js'
+
+const owner = { sub: 'owner', email: '[email protected]', role: 'user', autonomousEnv: 'prod' }
+const flush = async () => { for (let i = 0; i < 400; i++) await Promise.resolve() }
+
+class Socket extends EventEmitter {
+ readyState = 1; bufferedAmount = 0
+ send = vi.fn()
+ close = vi.fn(() => { this.readyState = 3; this.emit('close', 1000, Buffer.alloc(0)) })
+ terminate = vi.fn(() => this.close())
+ frame(body: unknown) { this.emit('message', Buffer.from(JSON.stringify(body)), false) }
+ sent() { return this.send.mock.calls.map(c => JSON.parse(c[0] as string)) }
+}
+const raw = () => ({ write: vi.fn(), destroy: vi.fn(), destroyed: false, on: vi.fn(), once: vi.fn() })
+
+type StatusMsg = { deviceId: string; online: boolean; lastSeenAt?: string; removed?: true }
+let push: (msg: StatusMsg) => void = () => { throw new Error('the socket did not subscribe') }
+let online = new Set<string>()
+
+async function opens(): Promise<Socket> {
+ const ws = new Socket()
+ m.upgrade.mockImplementation((_r, _s, _h, done) => done(ws))
+ handleWebUpgrade({ url: '/api/web-ws?autonomousEnv=prod&client=web', headers: { 'sec-websocket-protocol': 'access-token' } } as never, raw() as never, Buffer.alloc(0))
+ await vi.advanceTimersByTimeAsync(0)
+ await flush()
+ return ws
+}
+
+/** The device statuses of the last full picture the socket sent (the 30 s check sends every device it knows). */
+const lastPicture = (ws: Socket) => ws.sent().filter((f) => f.type === 'devices_status').at(-1)?.payload.statuses
+const tick = async () => { await vi.advanceTimersByTimeAsync(30_000); await flush() }
+const bindings = (...rows: Array<{ deviceId: string; lastSeenAt?: Date | null }>) =>
+ rows.map((r) => ({ deviceId: r.deviceId, lastSeenAt: r.lastSeenAt ?? null }))
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ vi.useFakeTimers()
+ online = new Set()
+ m.auth.mockResolvedValue(owner)
+ m.deviceFindMany.mockResolvedValue(bindings({ deviceId: 'dial' }))
+ m.devicePresence.mockImplementation(async (id: string) => online.has(id))
+ m.subscribeDeviceStatus.mockImplementation(async (_user: string, cb: (msg: StatusMsg) => void) => { push = cb; return () => {} })
+})
+afterEach(() => { vi.useRealTimers() })
+
+describe('a web socket\'s device feed', () => {
+ it('checks live presence every 30 s without reading the device bindings again', async () => {
+ const ws = await opens()
+ expect(m.deviceFindMany).toHaveBeenCalledOnce()
+ expect(lastPicture(ws)).toEqual([{ deviceId: 'dial', online: false, lastSeenAt: null }])
+
+ online.add('dial')
+ await tick()
+ expect(lastPicture(ws)).toEqual([{ deviceId: 'dial', online: true, lastSeenAt: null }])
+ // A worker died holding the device's socket: nobody says offline, the presence key just ages out.
+ online.delete('dial')
+ await tick()
+ await tick()
+ expect(lastPicture(ws)).toEqual([{ deviceId: 'dial', online: false, lastSeenAt: null }])
+ expect(m.deviceFindMany).toHaveBeenCalledOnce()
+ })
+
+ it('drops a revoked device at once, and the next check does not list it', async () => {
+ m.deviceFindMany.mockResolvedValue(bindings({ deviceId: 'dial' }, { deviceId: 'lamp' }))
+ const ws = await opens()
+ push({ deviceId: 'lamp', online: false, removed: true })
+ await flush()
+ await tick()
+ expect(lastPicture(ws)).toEqual([{ deviceId: 'dial', online: false, lastSeenAt: null }])
+ expect(m.deviceFindMany).toHaveBeenCalledOnce()
+ })
+
+ it('reads the bindings again when a device it does not know reports, and lists it from then on', async () => {
+ const ws = await opens()
+ m.deviceFindMany.mockResolvedValue(bindings({ deviceId: 'dial' }, { deviceId: 'new', lastSeenAt: new Date('2026-10-29T03:00:00Z') }))
+ online.add('new')
+ push({ deviceId: 'new', online: true })
+ await flush()
+ expect(ws.sent()).toContainEqual({ type: 'devices_status', payload: { statuses: [{ deviceId: 'new', online: true }] } })
+ expect(m.deviceFindMany).toHaveBeenCalledTimes(2)
+
+ await tick()
+ expect(lastPicture(ws)).toEqual([
+ { deviceId: 'dial', online: false, lastSeenAt: null },
+ { deviceId: 'new', online: true, lastSeenAt: '2026-10-29T03:00:00.000Z' },
+ ])
+ })
+
+ // Each report may come from a device paired after the read under way began, so one more read follows it: never one per report.
+ it('reads at most twice for a burst of reports from devices it does not know', async () => {
+ await opens()
+ let answer: (rows: unknown) => void = () => {}
+ m.deviceFindMany.mockImplementationOnce(() => new Promise((resolve) => { answer = resolve }))
+ for (const id of ['a', 'b', 'c', 'd']) push({ deviceId: id, online: true })
+ answer(bindings({ deviceId: 'dial' }, { deviceId: 'a' }, { deviceId: 'b' }, { deviceId: 'c' }, { deviceId: 'd' }))
+ await flush()
+ expect(m.deviceFindMany).toHaveBeenCalledTimes(3)
+ })
+
+ it('does not list a device the account does not hold, even after one reported on its channel', async () => {
+ const ws = await opens()
+ push({ deviceId: 'not-mine', online: true })
+ await flush()
+ await tick()
+ expect(lastPicture(ws)).toEqual([{ deviceId: 'dial', online: false, lastSeenAt: null }])
+ })
+
+ it('reads again when a device was revoked while a read was in flight', async () => {
+ const ws = await opens()
+ let answer: (rows: unknown) => void = () => {}
+ m.deviceFindMany.mockImplementationOnce(() => new Promise((resolve) => { answer = resolve }))
+ push({ deviceId: 'lamp', online: true })
+ await flush()
+ // The revoke lands after the read began: that read may still hold the device.
+ m.deviceFindMany.mockResolvedValue(bindings({ deviceId: 'dial' }))
+ push({ deviceId: 'lamp', online: false, removed: true })
+ answer(bindings({ deviceId: 'dial' }, { deviceId: 'lamp' }))
+ await flush()
+ await tick()
+ expect(lastPicture(ws)).toEqual([{ deviceId: 'dial', online: false, lastSeenAt: null }])
+ })
+
+ it('lists a device that reported while the first read was under way', async () => {
+ let answer: (rows: unknown) => void = () => {}
+ m.deviceFindMany.mockImplementationOnce(() => new Promise((resolve) => { answer = resolve }))
+ const ws = await opens()
+ // Paired after that read began: the read may not hold it.
+ m.deviceFindMany.mockResolvedValue(bindings({ deviceId: 'dial' }, { deviceId: 'new' }))
+ push({ deviceId: 'new', online: true })
+ answer(bindings({ deviceId: 'dial' }))
+ await flush()
+ await tick()
+ expect(lastPicture(ws)).toEqual([
+ { deviceId: 'dial', online: false, lastSeenAt: null },
+ { deviceId: 'new', online: false, lastSeenAt: null },
+ ])
+ })
+
+ it('keeps the last seen time a device reported going offline', async () => {
+ const ws = await opens()
+ push({ deviceId: 'dial', online: false, lastSeenAt: '2026-10-29T04:00:00.000Z' })
+ await flush()
+ await tick()
+ expect(lastPicture(ws)).toEqual([{ deviceId: 'dial', online: false, lastSeenAt: '2026-10-29T04:00:00.000Z' }])
+ })
+
+ it('still reads the bindings now and then, in case a change was lost on the way', async () => {
+ await opens()
+ await vi.advanceTimersByTimeAsync(DEVICE_BINDINGS_REREAD_MS)
+ await flush()
+ expect(m.deviceFindMany).toHaveBeenCalledTimes(2)
+ })
+
+ it('tries a failed read again at the next check, and sends nothing made up meanwhile', async () => {
+ m.deviceFindMany.mockRejectedValueOnce(new Error('db down'))
+ const ws = await opens()
+ expect(lastPicture(ws)).toBeUndefined()
+ await tick()
+ expect(m.deviceFindMany).toHaveBeenCalledTimes(2)
+ expect(lastPicture(ws)).toEqual([{ deviceId: 'dial', online: false, lastSeenAt: null }])
+ })
+
+ it('reads the bindings again when the client asks to watch devices', async () => {
+ const ws = await opens()
+ ws.frame({ type: 'devices_watch' })
+ await flush()
+ expect(m.deviceFindMany).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/backend/src/routes/mobile.ts b/backend/src/routes/mobile.ts
index 8f8116ec7..d36576289 100644
--- a/backend/src/routes/mobile.ts
+++ b/backend/src/routes/mobile.ts
@@ -12,9 +12,10 @@ import { resolveSsoAuth } from '../middlewares/authMiddleware.js'
//
// WHY A SEPARATE GROUP rather than widening /api/devices + /api/machines:
//
-// 1. `/api/machines` returns OwnerMachine, which carries `apiKey` — the DATA-PLANE credential,
-// where possession *is* authentication for that machine. The web is a first-party client that
-// needs it. An app-store binary must never receive it. Here the mapper builds an allow-listed
+// 1. `/api/machines` returns OwnerMachine. It no longer carries `apiKey` — the DATA-PLANE credential,
+// where possession *is* authentication for that machine — and the list does not even read it
+// (MachineService OWNER_VIEW_SELECT). An app-store binary must never receive one, whatever
+// OwnerMachine gains later. Here the mapper builds an allow-listed
// object field by field and NEVER spreads OwnerMachine, so a future field on that interface
// cannot silently leak. That is the whole reason this file exists; do not "simplify" it into a
// spread plus a delete.
diff --git a/backend/src/services/DeviceService.test.ts b/backend/src/services/DeviceService.test.ts
index e20d72e7c..f7bd6d218 100644
--- a/backend/src/services/DeviceService.test.ts
+++ b/backend/src/services/DeviceService.test.ts
@@ -8,15 +8,17 @@ const getDevicePresence = vi.hoisted(() => vi.fn())
const count = vi.hoisted(() => vi.fn())
const create = vi.hoisted(() => vi.fn())
const consumeNewIdQuota = vi.hoisted(() => vi.fn())
+const findUnique = vi.hoisted(() => vi.fn())
+const publishDeviceStatus = vi.hoisted(() => vi.fn())
vi.mock('../lib/prisma.js', () => ({
prisma: {
- deviceBinding: { findMany, findFirst, count, create, update, updateMany },
+ deviceBinding: { findMany, findFirst, findUnique, count, create, update, updateMany },
machine: { findMany: vi.fn() },
},
machineAlive: {},
}))
-vi.mock('../lib/bus.js', () => ({ getDevicePresence, consumeNewIdQuota }))
+vi.mock('../lib/bus.js', () => ({ getDevicePresence, consumeNewIdQuota, publishDeviceStatus }))
import { Prisma } from '@prisma/client'
import { deviceService } from './DeviceService.js'
@@ -42,6 +44,8 @@ const device = (over: Record<string, unknown> = {}): Record<string, unknown> =>
beforeEach(() => {
vi.clearAllMocks()
+ findUnique.mockResolvedValue(null)
+ publishDeviceStatus.mockResolvedValue(1)
updateMany.mockResolvedValue({ count: 1 })
getDevicePresence.mockResolvedValue(false)
})
@@ -223,7 +227,32 @@ describe('resolveOrCreateForComputer', () => {
it('a lost create race converges on the winner\'s row', async () => {
create.mockRejectedValue(new Prisma.PrismaClientKnownRequestError('dup', { code: 'P2002', clientVersion: 'x' }))
+ findUnique.mockResolvedValueOnce(null).mockResolvedValue({ userId: 'u1' })
await resolve()
expect(update).toHaveBeenCalledTimes(2) // the missed touch, then the converging one
})
+
+ // Review of #2159: the previous owner's open web sockets keep their own copy of the account's devices (lib/webWs.ts).
+ it('a computer another account held moves to this one, and its previous owner is told it is gone', async () => {
+ findUnique.mockResolvedValue({ userId: 'u0' })
+ const row = await resolve()
+ expect(row).toMatchObject({ userId: 'u1' })
+ expect(update).toHaveBeenLastCalledWith(expect.objectContaining({ data: expect.objectContaining({ userId: 'u1' }) }))
+ expect(publishDeviceStatus).toHaveBeenCalledWith('u0', { deviceId: row.deviceId, online: false, removed: true })
+ expect(create).not.toHaveBeenCalled()
+ })
+
+ it('a reconnect of the owner\'s own computer tells nobody', async () => {
+ update.mockReset()
+ update.mockResolvedValue(device())
+ await resolve()
+ expect(publishDeviceStatus).not.toHaveBeenCalled()
+ })
+
+ it('the reconnect write matches only the owner\'s own row', async () => {
+ update.mockReset()
+ update.mockResolvedValue(device())
+ await resolve()
+ expect(update.mock.calls[0]![0].where).toMatchObject({ userId: 'u1' })
+ })
})
diff --git a/backend/src/services/DeviceService.ts b/backend/src/services/DeviceService.ts
index b419082ff..5eb0c392f 100644
--- a/backend/src/services/DeviceService.ts
+++ b/backend/src/services/DeviceService.ts
@@ -3,7 +3,7 @@ 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, consumeNewIdQuota } from '../lib/bus.js'
+import { getDevicePresence, consumeNewIdQuota, publishDeviceStatus } from '../lib/bus.js'
import { env } from '../config/env.js'
import { AppError } from '../errors/index.js'
@@ -95,10 +95,21 @@ export const deviceService = {
// `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.
+ // The owner's own row: one write, as before. Matching the owner too lets a row another account holds miss, so
+ // the take-over below can tell that account.
const touch = (): Promise<DeviceBinding> => prisma.deviceBinding.update({
- where: { deviceId },
- data: { userId, computerId, lastSeenAt: new Date() },
+ where: { deviceId, userId },
+ data: { computerId, lastSeenAt: new Date() },
})
+ // The row exists under another account: it moves to this one, and the previous owner's open web sockets, which
+ // keep their own copy of the account's devices (lib/webWs.ts), drop it at once. Null when there is no row.
+ const takeOver = async (): Promise<DeviceBinding | null> => {
+ const held = await prisma.deviceBinding.findUnique({ where: { deviceId }, select: { userId: true } })
+ if (!held) return null
+ const row = await prisma.deviceBinding.update({ where: { deviceId }, data: { userId, computerId, lastSeenAt: new Date() } })
+ if (held.userId !== userId) void publishDeviceStatus(held.userId, { deviceId, online: false, removed: true })
+ return row
+ }
// 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
@@ -110,6 +121,8 @@ export const deviceService = {
} catch (err) {
if (!(err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2025')) throw err
}
+ const taken = await takeOver()
+ if (taken) return taken
// 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) {
@@ -125,7 +138,10 @@ export const deviceService = {
} 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()
+ if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
+ const winner = await takeOver()
+ if (winner) return winner
+ }
throw err
}
},
diff --git a/backend/src/services/MachineService.list.test.ts b/backend/src/services/MachineService.list.test.ts
index 32d896f5f..741ed6505 100644
--- a/backend/src/services/MachineService.list.test.ts
+++ b/backend/src/services/MachineService.list.test.ts
@@ -42,8 +42,10 @@ 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 warn = vi.hoisted(() => vi.fn())
+vi.mock('../utils/logger.js', () => ({ logger: { warn, info: vi.fn(), error: vi.fn(), debug: vi.fn() } }))
-const { machineService } = await import('./MachineService.js')
+const { machineService, MACHINE_LIST_MAX } = await import('./MachineService.js')
type Row = Record<string, unknown>
type Where = Record<string, unknown>
@@ -78,9 +80,20 @@ const ROWS: Row[] = [
{ ...base, machineId: 'someone-else', userId: 'u2' },
]
+/** What Prisma hands back for one findMany: the matching rows, newest first when asked, at most `take`, with only
+ * the selected fields when there is a `select`. */
+function answer(rows: Row[], args: { where: Where; select?: Record<string, boolean>; take?: number; orderBy?: { createdAt?: 'desc' } }): Row[] {
+ let out = rows.filter((r) => matches(r, args.where))
+ if (args.orderBy?.createdAt === 'desc') out = [...out].sort((a, b) => (b.createdAt as Date).getTime() - (a.createdAt as Date).getTime())
+ if (args.take !== undefined) out = out.slice(0, args.take)
+ if (!args.select) return out
+ const picked = Object.keys(args.select).filter((k) => args.select![k])
+ return out.map((r) => Object.fromEntries(picked.filter((k) => k in r).map((k) => [k, r[k]])))
+}
+
beforeEach(() => {
vi.clearAllMocks()
- findMany.mockImplementation(async ({ where }: { where: Where }) => ROWS.filter((r) => matches(r, where)))
+ findMany.mockImplementation(async (args: Parameters<typeof answer>[1]) => answer(ROWS, args))
groupBy.mockResolvedValue([])
planFindMany.mockResolvedValue([])
runCommandRaw.mockResolvedValue({ cursor: { firstBatch: [] } })
@@ -155,3 +168,64 @@ describe('listForUser — the Mac a team machine lives on', () => {
expect(hosts).toEqual({ laptop: null, 'laptop-team': 'laptop', mini: null, 'taken-over': null })
})
})
+
+// DB optimization roadmap, Phase 2 item 7: the list read whole machine documents, api keys included, with no limit.
+describe('listForUser — what it reads', () => {
+ const API_KEY = 'a'.repeat(64)
+ // Every field a machine document holds today that the list could carry, plus the secrets it must not.
+ const full: Row = {
+ ...base,
+ id: 'obj-1', machineId: 'm-full', userId: 'u1', apiKey: API_KEY, managerId: 'mgr-1', computerId: 'cmp-1',
+ workspaceId: 'ws-1', planId: 'plan-1', autonomousEnv: 'prod', authMode: 'remote', billingStatus: 'active',
+ name: 'Studio', hostname: 'studio.local', sessionKind: 'team', hostMachineId: 'm-host', credentialCiphertext: 'secret',
+ externalSubscriptionId: 'sub-1', createdAt: new Date('2026-03-01'),
+ }
+
+ it('gives every caller the same fields as before, and never an api key', async () => {
+ findMany.mockImplementation(async (args: Parameters<typeof answer>[1]) => answer([full], args))
+ planFindMany.mockResolvedValue([{ id: 'plan-1', name: 'Remote' }])
+ groupBy.mockResolvedValue([{ machineId: 'm-full', _count: { _all: 3 } }])
+ readAgentPresence.mockResolvedValue(true)
+
+ const [machine] = await machineService.listForUser('u1')
+
+ expect(machine).toEqual({
+ machineId: 'm-full', computerId: 'cmp-1', workspaceId: 'ws-1', planId: 'plan-1', autonomousEnv: 'prod',
+ authMode: 'remote', planName: 'Remote', billingStatus: 'active', createdAt: new Date('2026-03-01'),
+ status: 'running', agentCount: 3, engine: 'claude', name: 'Studio', hostname: 'studio.local',
+ sessionKind: 'team', hostMachineId: 'm-host',
+ })
+ expect(JSON.stringify(machine)).not.toContain(API_KEY)
+ })
+
+ it('does not read the api key or other secrets from the database', async () => {
+ let read: Row[] = []
+ findMany.mockImplementation(async (args: Parameters<typeof answer>[1]) => (read = answer([full], args)))
+
+ await machineService.listForUser('u1')
+
+ expect(read).toHaveLength(1)
+ expect(read[0]).not.toHaveProperty('apiKey')
+ expect(read[0]).not.toHaveProperty('credentialCiphertext')
+ expect(read[0]).not.toHaveProperty('externalSubscriptionId')
+ })
+
+ it('reads at most MACHINE_LIST_MAX machines, the newest, and says so in the log', async () => {
+ const many = Array.from({ length: MACHINE_LIST_MAX + 5 }, (_, i) => ({
+ ...base, machineId: `m-${i}`, userId: 'u1', createdAt: new Date(Date.UTC(2026, 0, 1, 0, i)),
+ }))
+ findMany.mockImplementation(async (args: Parameters<typeof answer>[1]) => answer(many, args))
+
+ const listed = (await machineService.listForUser('u1')).map((m) => m.machineId)
+
+ expect(listed).toHaveLength(MACHINE_LIST_MAX)
+ expect(listed[0]).toBe(`m-${MACHINE_LIST_MAX + 4}`)
+ expect(listed).not.toContain('m-0')
+ expect(warn).toHaveBeenCalledWith('machine list cut at its limit', expect.objectContaining({ userId: 'u1', limit: MACHINE_LIST_MAX }))
+ })
+
+ it('logs nothing for an account under the limit', async () => {
+ await machineService.listForUser('u1')
+ expect(warn).not.toHaveBeenCalled()
+ })
+})
diff --git a/backend/src/services/MachineService.ts b/backend/src/services/MachineService.ts
index 8783d89bb..eda270fcf 100644
--- a/backend/src/services/MachineService.ts
+++ b/backend/src/services/MachineService.ts
@@ -1,4 +1,4 @@
-import type { Machine } from '@prisma/client'
+import type { Machine, Prisma } from '@prisma/client'
import { prisma, machineAlive } from '../lib/prisma.js'
import { selectManagerId } from '../lib/managers.js'
import { provisionViaManager } from '../lib/provision.js'
@@ -82,7 +82,18 @@ function assertRequesterEnvironment(binding: Machine, requester: MachineRequeste
}
}
-function toOwner(b: Machine, status = 'unknown', agentCount = 0, plan?: PlanInfo, engine = 'claude'): OwnerMachine {
+/** The fields an owner view is built from: the list reads only these, never the api key or billing references. */
+const OWNER_VIEW_SELECT = {
+ machineId: true, computerId: true, workspaceId: true, planId: true, autonomousEnv: true, authMode: true,
+ billingStatus: true, createdAt: true, name: true, hostname: true, sessionKind: true, hostMachineId: true,
+} as const satisfies Prisma.MachineSelect
+type OwnerViewRow = Pick<Machine, keyof typeof OWNER_VIEW_SELECT>
+
+/** Machines one list returns at most, newest first. A computer account is capped at 20 (HARNESS_DEVICE_AUTH_MACHINE_LIMIT);
+ * past this an account is far outside any real one, and the log says the list was cut. */
+export const MACHINE_LIST_MAX = 200
+
+function toOwner(b: OwnerViewRow, status = 'unknown', agentCount = 0, plan?: PlanInfo, engine = 'claude'): OwnerMachine {
return {
machineId: b.machineId,
computerId: b.computerId ?? null,
@@ -160,7 +171,7 @@ function firstUsableComputerMachine(rows: Machine[]): Machine | undefined {
/** Resolve each agent's plan display name via its binding's planId. authMode comes from the BINDING
* (denormalized at create, backfilled at boot) — never from the plan, so a later plan-doc edit can't
* flip a live agent's mode. Missing/legacy → self. */
-async function plansByMachine(bindings: Machine[]): Promise<Map<string, PlanInfo>> {
+async function plansByMachine(bindings: Array<Pick<Machine, 'machineId' | 'planId' | 'authMode'>>): Promise<Map<string, PlanInfo>> {
const out = new Map<string, PlanInfo>()
const planIds = [...new Set(bindings.map((b) => b.planId).filter((id): id is string => !!id))]
const plans = planIds.length ? await prisma.subscriptionPlan.findMany({ where: { id: { in: planIds } } }) : []
@@ -215,7 +226,7 @@ function hasManagedCampaignBilling(binding: Machine): boolean {
/** Best-effort node status + engine per machineId, read directly from the shared Mongo `machine_nodes`
* collection (the agent-manager owns writes; the backend just reads). `machine_nodes.engine` is an
* optional per-machine override; when absent, fall back to the owning manager's MACHINE_ENGINE mirror. */
-async function nodeInfoByAgent(bindings: Machine[]): Promise<Map<string, { status: string; engine: string }>> {
+async function nodeInfoByAgent(bindings: Array<Pick<Machine, 'machineId'>>): Promise<Map<string, { status: string; engine: string }>> {
const out = new Map<string, { status: string; engine: string }>()
const ids = bindings.map((b) => b.machineId)
if (!ids.length) return out
@@ -251,7 +262,7 @@ async function nodeInfoByAgent(bindings: Machine[]): Promise<Map<string, { statu
* A presence read that FAILED is `unknown`, never `offline`: a daemon takes `offline` as evidence and
* labels that computer's models "seems offline" (grid-reads-without-waking issue 03). */
async function applyRemoteStatus(
- bindings: Machine[],
+ bindings: Array<Pick<Machine, 'machineId'>>,
plans: Map<string, PlanInfo>,
info: Map<string, { status: string; engine: string }>,
): Promise<void> {
@@ -545,13 +556,16 @@ export const machineService = {
return resolved
},
- /** List a user's agents (with best-effort live status). Includes the api key (owner only). */
+ /** List a user's agents (with best-effort live status). Never the api key: it is not even read. */
async listForUser(userId: string, autonomousEnv?: AutonomousEnvironment): Promise<OwnerMachine[]> {
const rows = await prisma.machine.findMany({
where: { userId, ...(autonomousEnv ? { autonomousEnv } : {}), ...machineAlive },
orderBy: { createdAt: 'desc' },
+ select: OWNER_VIEW_SELECT,
+ take: MACHINE_LIST_MAX,
})
if (rows.length === 0) return []
+ if (rows.length === MACHINE_LIST_MAX) logger.warn('machine list cut at its limit', { userId, limit: MACHINE_LIST_MAX })
const ids = rows.map((b) => b.machineId)
const [info, counts, plans] = await Promise.all([nodeInfoByAgent(rows), countByMachine(ids), plansByMachine(rows)])
await applyRemoteStatus(rows, plans, info)
diff --git a/backend/src/services/UserService.ts b/backend/src/services/UserService.ts
index a149c8389..47af90b14 100644
--- a/backend/src/services/UserService.ts
+++ b/backend/src/services/UserService.ts
@@ -75,8 +75,12 @@ export const userService = {
* Mirror an authenticated SSO profile. Email is the account identity; the selected environment
* decides which SSO subject field is refreshed. Production additionally claims a device-created
* provisional row whose externalId already equals the authenticated subject.
+ *
+ * `looked`: what the caller's own lookup just found for this profile — the row by email, else (production) the
+ * provisional row by subject, else null — so a sign-in reads its user once (DB optimization roadmap, Phase 2
+ * item 7). Read in this same request, never kept: another server may change the account at any moment.
*/
- async upsertFromSso(input: SsoUserInput): Promise<User> {
+ async upsertFromSso(input: SsoUserInput, looked?: { existing: User | null }): Promise<User> {
const externalId = input.externalId.trim()
const em = normalizeUserEmail(input.email)
if (!externalId || !em) throw new Error('SSO profile is missing its subject or email')
@@ -84,9 +88,9 @@ export const userService = {
? { signUpAttribution: { ...input.signUpAttribution, recordedAt: new Date() } }
: {}
const wantAdmin = input.roles?.includes('admin') || ADMIN_EMAILS.has(em)
- let existing = await prisma.user.findUnique({ where: { email: em } })
+ let existing = looked ? looked.existing : await prisma.user.findUnique({ where: { email: em } })
- if (!existing && input.autonomousEnv === 'prod') {
+ if (!looked && !existing && input.autonomousEnv === 'prod') {
const byExternal = await prisma.user.findUnique({ where: { externalId } })
if (byExternal && isProvisionalUserEmail(byExternal.email)) existing = byExternal
}