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.

fix(sharing): a link's viewers of a session that turns confidential are closed within a second (#1950)

0xken1571c269f3f81c
diff --git a/backend/integration/superTabObserver.test.ts b/backend/integration/superTabObserver.test.ts
index 7bc06a97a..196cc9859 100644
--- a/backend/integration/superTabObserver.test.ts
+++ b/backend/integration/superTabObserver.test.ts
@@ -18,6 +18,7 @@ vi.mock('../src/lib/bus.js', async original => {
return { ...await original<typeof import('../src/lib/bus.js')>(),
publishDown: async () => 1, subscribeUp: async () => () => {},
subscribeShareChanged: (id: string, callback: () => void) => listen(`share:${id}`, callback),
+ publishShareChanged: async (id: string) => { shared.channels.emit(`share:${id}`); return 1 },
subscribeSwarmAccessChanged: (tabId: string, callback: () => void) => listen(`swarm:${tabId}`, callback),
publishSwarmAccessChanged: async (tabId: string) => { shared.channels.emit(`swarm:${tabId}`); return 1 } }
})
@@ -25,6 +26,7 @@ vi.mock('../src/lib/hub.js', () => ({ trackSocketLiveness: () => () => {} }))
const { SuperTabStore } = await import('../src/superTabs/store.js')
const { attachObserver } = await import('../src/lib/observerWs.js')
const { publishSwarmAccessChanged } = await import('../src/lib/bus.js')
+const { tellSessionViewers } = await import('../src/routes/harnessLinks.js')
let database: LocalDatabase
let store: InstanceType<typeof SuperTabStore>
@@ -50,8 +52,10 @@ const until = async (condition: () => boolean, ms: number) => {
beforeAll(async () => {
database = await localDatabase()
shared.db = database.db
- // The routes' wiring (routes/superTabs.ts): a narrowing of who may watch is told after its commit.
- store = new SuperTabStore(database.db, Date.now, null, { accessChanged: tabId => { void publishSwarmAccessChanged(tabId) } })
+ // The routes' wiring (routes/superTabs.ts): a narrowing of who may watch, and a session turning confidential, are told after
+ // their commit.
+ store = new SuperTabStore(database.db, Date.now, null, { accessChanged: tabId => { void publishSwarmAccessChanged(tabId) },
+ sessionsConfidential: sessions => { void tellSessionViewers(sessions) } })
for (const user of [owner, peer, host]) await database.db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`,
email: user.email, autonomousEnv: user.autonomousEnv } })
await database.db.machine.create({ data: { machineId: 'test-host', userId: host.sub, apiKey: 'fixture-only', managerId: 'fixture',
@@ -79,7 +83,7 @@ describe('a terminal observer of a Swarm agent', () => {
const ws = new Socket()
await attachObserver(ws as never, peer, share)
expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: 'observer_connected' }))
- return { tab, ws, builder }
+ return { tab, ws, builder, harnessId }
}
it('closes within a second of its viewer being removed from the Swarm', async () => {
@@ -103,6 +107,22 @@ describe('a terminal observer of a Swarm agent', () => {
expect(ws.close).toHaveBeenCalledWith(4403, expect.any(String))
})
+ it('closes a link\'s viewer within a second of the watched session turning confidential, here by becoming its project’s Lead', async () => {
+ const { tab, builder, harnessId } = await watching(false)
+ const link = await database.db.harnessLink.create({ data: { id: randomUUID(), ownerId: host.sub, machineId: 'test-host', agentId: harnessId,
+ autonomousEnv: 'prod', name: 'Builder', engine: null, ownerPublicKey: 'fixture-key', visibility: 'public', revokedAt: null } })
+ const viewers = [new Socket(), new Socket()]
+ // A public link opens for anyone, signed in or not.
+ await attachObserver(viewers[0] as never, peer, link, 'prod')
+ await attachObserver(viewers[1] as never, null, link, 'prod')
+ for (const ws of viewers) expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: 'observer_connected' }))
+ await run(tab, { type: 'conversation.agent', conversationId: 'lead', agentId: builder, present: true, lead: true })
+ for (const ws of viewers) {
+ expect(await until(() => ws.close.mock.calls.length > 0, 1_000)).toBe(true)
+ expect(ws.close).toHaveBeenCalledWith(4403, expect.any(String))
+ }
+ })
+
it('stays open through a change that leaves its viewer allowed', async () => {
const { tab, ws } = await watching()
await run(tab, { type: 'conversation.create', title: 'Another task', brief: '', checks: [] })
diff --git a/backend/src/routes/harnessLinks.test.ts b/backend/src/routes/harnessLinks.test.ts
index 7bf77d70c..3b26f8aa7 100644
--- a/backend/src/routes/harnessLinks.test.ts
+++ b/backend/src/routes/harnessLinks.test.ts
@@ -2,14 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Fastify, { type FastifyInstance } from 'fastify'
import { randomUUID } from 'node:crypto'
const m = vi.hoisted(() => ({
- prisma: { harnessLink: { findFirst: vi.fn(), findUnique: vi.fn(), upsert: vi.fn(), updateMany: vi.fn() },
- harnessShare: { findFirst: vi.fn() }, machine: { findFirst: vi.fn() } },
- auth: vi.fn(), presence: vi.fn(), changed: vi.fn(),
+ prisma: { harnessLink: { findFirst: vi.fn(), findUnique: vi.fn(), findMany: vi.fn(), upsert: vi.fn(), updateMany: vi.fn() },
+ harnessShare: { findFirst: vi.fn(), findMany: vi.fn() }, machine: { findFirst: vi.fn() } },
+ auth: vi.fn(), presence: vi.fn(), changed: vi.fn(), confidential: vi.fn(),
}))
vi.mock('../lib/prisma.js', () => ({ prisma: m.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))
vi.mock('../lib/bus.js', () => ({ getAgentPresenceMany: m.presence, publishShareChanged: m.changed }))
+vi.mock('../superTabs/confidential.js', () => ({ confidentialSessions: m.confidential }))
vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof import('../lib/ssoAuth.js')>(), authenticateAccessToken: m.auth }))
-import { harnessLinkRoutes, recipientLink } from './harnessLinks.js'
+import { harnessLinkRoutes, recipientLink, tellSessionViewers } from './harnessLinks.js'
+import { stableId } from '../superTabs/model.js'
import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'
import { errorHandler } from '../middlewares/errorHandler.js'
@@ -30,6 +32,7 @@ describe('public/private browser links', () => {
m.prisma.harnessLink.updateMany.mockResolvedValue({ count: 1 })
m.prisma.machine.findFirst.mockResolvedValue(machine)
m.presence.mockResolvedValue(new Map([['m1', true]]))
+ m.confidential.mockResolvedValue(new Set())
app = Fastify(); app.setErrorHandler(errorHandler); registerAuthMiddleware(app, m.auth)
await app.register(harnessLinkRoutes); await app.ready()
})
@@ -69,6 +72,31 @@ describe('public/private browser links', () => {
m.prisma.harnessShare.findFirst.mockResolvedValue(null)
expect(await recipientLink(id, ken, 'prod')).toBeNull()
})
+ it('opens a link to a confidential session for its machine\'s owner alone, public or private, invited or not', async () => {
+ // A Lead, or an agent in a private chat, in some Swarm (superTabs/confidential.ts): its screen holds people's private chats.
+ m.confidential.mockImplementation(async (_db: unknown, ids: string[]) => new Set(ids))
+ expect((await get()).statusCode).toBe(401)
+ expect(m.confidential).toHaveBeenCalledWith(m.prisma, [stableId('m1', 'agent-1')])
+ m.auth.mockResolvedValue(ken)
+ m.prisma.harnessShare.findFirst.mockResolvedValue({ id: 'invitation' })
+ for (const visibility of ['public', 'private']) {
+ m.prisma.harnessLink.findFirst.mockResolvedValue({ ...link, visibility })
+ expect((await get(auth)).statusCode).toBe(403)
+ }
+ m.auth.mockResolvedValue(owner)
+ expect((await get(auth)).statusCode).toBe(200)
+ })
+ it('tells every share and link of a session that turned confidential to check again, and never fails for it', async () => {
+ m.prisma.harnessLink.findMany.mockResolvedValue([{ id: 'link-1' }])
+ m.prisma.harnessShare.findMany.mockResolvedValue([{ id: 'share-1' }, { id: 'share-2' }])
+ await tellSessionViewers([{ machineId: 'm1', harnessId: 'agent-1', machineOwnerId: 'owner' }])
+ const where = { machineId: 'm1', agentId: 'agent-1', ownerId: 'owner', revokedAt: null }
+ expect(m.prisma.harnessLink.findMany).toHaveBeenCalledWith({ where, select: { id: true } })
+ expect(m.prisma.harnessShare.findMany).toHaveBeenCalledWith({ where, select: { id: true } })
+ expect(m.changed.mock.calls).toEqual([['link-1'], ['share-1'], ['share-2']])
+ m.prisma.harnessLink.findMany.mockRejectedValue(new Error('db down'))
+ await expect(tellSessionViewers([{ machineId: 'm1', harnessId: 'agent-1', machineOwnerId: 'owner' }])).resolves.toBeUndefined()
+ })
it('fails closed across deletion, revocation, environments and billing', async () => {
m.prisma.harnessLink.findFirst.mockResolvedValue(null)
expect(await recipientLink(id, null, 'prod')).toBeNull()
diff --git a/backend/src/routes/harnessLinks.ts b/backend/src/routes/harnessLinks.ts
index 60b17324f..c714ae06f 100644
--- a/backend/src/routes/harnessLinks.ts
+++ b/backend/src/routes/harnessLinks.ts
@@ -7,6 +7,8 @@ import { parseAutonomousEnvironment, type AutonomousEnvironment } from '../lib/a
import { validateBody, validateParams } from '../middlewares/validation.js'
import { sendError, sendSuccess } from '../utils/response.js'
import type { AuthUser } from '../lib/ssoAuth.js'
+import { confidentialSessions } from '../superTabs/confidential.js'
+import { stableId } from '../superTabs/model.js'
const params = z.object({ id: z.string().uuid() })
const body = z.object({
@@ -19,6 +21,9 @@ const body = z.object({
export async function recipientLink(id: string, user: AuthUser | null, autonomousEnv: AutonomousEnvironment) {
const link = await prisma.harnessLink.findFirst({ where: { id, autonomousEnv, revokedAt: null } })
if (!link || user && user.autonomousEnv !== autonomousEnv) return null
+ // A confidential session's screen holds people's private chats (superTabs/confidential.ts): no link shows it to anyone but
+ // its machine's owner, public or private, invited or not, as no share does (SuperTabStore.mayOpenShare).
+ if (user?.sub !== link.ownerId && (await confidentialSessions(prisma, [stableId(link.machineId, link.agentId)])).size) return null
if (link.visibility !== 'public') {
if (!user) return null
if (user.sub !== link.ownerId && !await prisma.harnessShare.findFirst({ where: {
@@ -32,6 +37,20 @@ export async function recipientLink(id: string, user: AuthUser | null, autonomou
return machine && machineBillingAllowsDataPlane(machine) ? link : null
}
+/** Sessions that just turned confidential, after the commit (the store's `sessionsConfidential`): every share and link of
+ * them checks again at once (lib/observerWs.ts), so their viewers are closed within that event rather than the minute's
+ * re-check. A link or another Swarm's share follows no Swarm of its own to hear it by. Best effort: the re-check stays. */
+export async function tellSessionViewers(sessions: Array<{ machineId: string; harnessId: string; machineOwnerId: string }>): Promise<void> {
+ try {
+ for (const session of sessions) {
+ const where = { machineId: session.machineId, agentId: session.harnessId, ownerId: session.machineOwnerId, revokedAt: null }
+ const [links, shares] = await Promise.all([prisma.harnessLink.findMany({ where, select: { id: true } }),
+ prisma.harnessShare.findMany({ where, select: { id: true } })])
+ for (const { id } of [...links, ...shares]) await publishShareChanged(id)
+ }
+ } catch { /* best effort */ }
+}
+
export async function harnessLinkRoutes(app: FastifyInstance): Promise<void> {
// This one GET is optionally authenticated; mutations below retain the global SSO gate.
app.get<{ Params: z.infer<typeof params> }>('/api/shared-agents/:id',
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 89e3221c8..3d5333134 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -133,7 +133,8 @@ const updateRequired = (_req: unknown, reply: FastifyReply) => sendError(reply,
/** The store this server runs on. Loaded only here: importing the bus opens its Redis connections. */
async function productionStore(github: GitHubTokens | null): Promise<SuperTabStore> {
- const [bus, { announceSwarmDeliveries }] = await Promise.all([import('../lib/bus.js'), import('../lib/swarmDeliveryPushes.js')])
+ const [bus, { announceSwarmDeliveries }, { tellSessionViewers }] = await Promise.all([import('../lib/bus.js'), import('../lib/swarmDeliveryPushes.js'),
+ import('./harnessLinks.js')])
return new SuperTabStore(prisma, Date.now, attachmentsFromEnv(env),
// A task that ends revokes the token it was given; a revoke that fails is logged inside and never blocks the write.
{ workEnded: (tabId, ended) => { void github?.release(tabId, ended).catch(error => logger.warn('[github] release failed', { tabId, error: String(error) })) },
@@ -147,7 +148,8 @@ async function productionStore(github: GitHubTokens | null): Promise<SuperTabSto
terminalAnswered: requestId => { void bus.publishTerminalAnswered(requestId) },
watchTerminal: (requestId, onChange) => bus.subscribeTerminalAnswered(requestId, onChange),
// Its observer sockets may be on any instance.
- accessChanged: tabId => { void bus.publishSwarmAccessChanged(tabId) } })
+ accessChanged: tabId => { void bus.publishSwarmAccessChanged(tabId) },
+ sessionsConfidential: sessions => { void tellSessionViewers(sessions) } })
}
export async function superTabRoutes(app: FastifyInstance, options: { store?: SuperTabStore; github?: GitHubTokens | null; reads?: SwarmReads; hosts?: HostReads;
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index c37566395..719afed48 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -225,6 +225,9 @@ export interface SuperTabStoreHooks {
/** Who may watch an agent's terminal in this Swarm may have narrowed, after the commit: its observer sockets check again
* at once (lib/observerWs.ts). It must not throw. */
accessChanged?: (tabId: string) => void
+ /** These native sessions just turned confidential, after the commit: their shares and links, which follow no Swarm of
+ * theirs, check again at once (routes/harnessLinks.ts tellSessionViewers). It must not throw. */
+ sessionsConfidential?: (sessions: Array<{ machineId: string; harnessId: string; machineOwnerId: string }>) => void
/** The read cache this store reads through (cache.ts): the process's by default, none when null. */
readCache?: SwarmCache | null
/** When each caller's full delivery poll last succeeded, shared by every server (Redis in production, pollMemory.ts). Left
@@ -995,8 +998,12 @@ export class SuperTabStore {
await bindSession(tx, effects.state, target, context.now)
}
// A session that just became confidential writes the record its registrations write (confidential.ts).
- for (const target of effects.state.agents) {
- if (target.confidential && !original.agents.find(a => a.id === target.id)?.confidential) await recordConfidential(tx, effects.state, target, context.now)
+ const turned = effects.state.agents.filter(target => target.confidential && !original.agents.find(a => a.id === target.id)?.confidential)
+ for (const target of turned) await recordConfidential(tx, effects.state, target, context.now)
+ const tell = this.hooks.sessionsConfidential
+ if (tell && turned.length) {
+ const sessions = turned.map(({ machineId, harnessId, machineOwnerId }) => ({ machineId, harnessId, machineOwnerId }))
+ afterCommit(tx, () => tell(sessions))
}
if (command.type === 'project.sharing' && command.visibility === 'private') {
await makeProjectPrivate(tx, effects.state, command.projectId)
diff --git a/cli/src/sharing/collaboration.spec.ts b/cli/src/sharing/collaboration.spec.ts
index b61b3e028..304b66c62 100644
--- a/cli/src/sharing/collaboration.spec.ts
+++ b/cli/src/sharing/collaboration.spec.ts
@@ -195,6 +195,20 @@ describe('owner link and comment authority', () => {
expect((await connect()).cipher).toBeNull()
expect(grants.all().every(g => g.revoked)).toBe(true)
})
+ it('closes every viewer of a link within a second of its session turning confidential, invited or public', async () => {
+ // What the Swarm's roster marks (superTabs/observers.ts allows): a Lead, or an agent in a private chat, refuses every share.
+ let confidential = false
+ deps.allowsGrant = grant => !(confidential && grant.agentId === 'a')
+ await manage('link', { visibility: 'public' })
+ await manage('invite', { emails: ['[email protected]'], days: 7 })
+ const guest = await connect(), alice = await connect({ email: '[email protected]', authorId: 'alice' })
+ expect(guest.cipher).not.toBeNull()
+ expect(alice.cipher).not.toBeNull()
+ confidential = true
+ await vi.advanceTimersByTimeAsync(1000)
+ for (const viewer of [guest, alice]) expect(frames.find(f => f.id === viewer.id && f.type === 'observer_closed')).toMatchObject({ payload: { reason: 'Sharing ended or invitation expired', retry: false } })
+ expect((await connect()).cipher).toBeNull()
+ })
it('retries offline publication, fails closed on permanent errors, and scopes sync to this machine', async () => {
vi.mocked(deps.publish).mockRejectedValueOnce(new Error('offline'))
expect(await manage('link', { visibility: 'public' })).toMatchObject({ link: { pending: true } })
diff --git a/cli/src/sharing/owner.ts b/cli/src/sharing/owner.ts
index 0d7e6234a..3507066a2 100644
--- a/cli/src/sharing/owner.ts
+++ b/cli/src/sharing/owner.ts
@@ -98,8 +98,10 @@ export class HarnessShareOwner {
private authorized(observer: Observer): boolean {
if (observer.linkId) {
const link = this.deps.collaboration?.active(observer.linkId, this.deps.machineId())
+ // A session that turns confidential closes its links' viewers too, as it refuses them at open (`receive`).
return !!link && !!this.deps.resolveAgent(link.agentId) && (link.visibility === 'public'
|| observer.author?.owner === true || this.invited(link.agentId, observer.grant.recipientEmail))
+ && (this.deps.allowsGrant?.(observer.grant) ?? true)
}
return !!this.deps.grants.active(observer.grant.id, observer.grant.recipientEmail, this.deps.machineId())
&& (this.deps.allowsGrant?.(observer.grant) ?? true)