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: share a machine with other accounts, by address or company domain

bitcoinbuilder7f37744ad0fe
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index b387378d3..c65142ee7 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -777,6 +777,43 @@ model HarnessShare {
@@map("harness_shares")
}
+/// A whole machine its owner shares with other accounts (docs/plans/2026-10-15-share-machine-plan.md):
+/// with these addresses, and with everyone at `domain` when the owner turned that on. Off by default, so
+/// a machine with no row is shared with no one. The backend's copy decides who is LISTED the machine and
+/// who may select it on the relay; the machine's own daemon keeps the policy it published and trusts
+/// only the keys of accounts that policy names (cli services/sharedMachines.ts), as Share's owner does.
+model MachineShare {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ machineId String @unique
+ ownerId String
+ autonomousEnv String
+ /// Normalized (trimmed, lower case), never the owner's own.
+ emails String[]
+ /// The owner's email domain while "Everyone at @domain" is on; null when off. Written by the backend
+ /// from the owner's verified address, never taken from the client, and never a public domain.
+ domain String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([emails, autonomousEnv])
+ @@index([domain, autonomousEnv])
+ @@index([ownerId])
+ @@map("machine_shares")
+}
+
+/// Someone at a machine's domain added it to their machines (a domain share takes one click to add; an
+/// address the owner named needs none). Only the accounts that added it are trusted by the machine.
+model MachineShareAdd {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ machineId String
+ userId String
+ createdAt DateTime @default(now())
+
+ @@unique([machineId, userId])
+ @@index([userId])
+ @@map("machine_share_adds")
+}
+
/// The account's DESK: its tabs, in order, and the agents each holds — one document per user, the
/// same on every computer the person signs in on (owner, 2026-09-21: "tab là global"). Holds only
/// what the person would call "my tabs": ids, names, order, `(machineId, agentId)` pairs. Nothing
diff --git a/backend/src/lib/bus.ts b/backend/src/lib/bus.ts
index a78df309e..19cdb0f4c 100644
--- a/backend/src/lib/bus.ts
+++ b/backend/src/lib/bus.ts
@@ -218,6 +218,15 @@ export function publishShareChanged(id: string): Promise<number> {
return safePublish(`harness-share:${id}`, '{}')
}
+/** A machine's sharing changed (routes/machineShares.ts): a session another account holds to it on any
+ * instance asks again whether it may stay (lib/webWs.ts). No content on this channel. */
+export function subscribeMachineShareChanged(machineId: string, cb: () => void): Promise<() => void> {
+ return addSub(`machine-share:${machineId}`, cb)
+}
+export function publishMachineShareChanged(machineId: string): Promise<number> {
+ return safePublish(`machine-share:${machineId}`, '{}')
+}
+
export function publishUp(machineId: string, msg: UpBusMsg): Promise<number> {
const type = (msg.frame as { type?: unknown } | undefined)?.type
if (typeof type === 'string' && STATUS_TYPES.has(type)) void safePublish(statusChannel(machineId), JSON.stringify(msg.frame))
diff --git a/backend/src/lib/deviceKeyLog.ts b/backend/src/lib/deviceKeyLog.ts
index 814aca256..3f55f9d7f 100644
--- a/backend/src/lib/deviceKeyLog.ts
+++ b/backend/src/lib/deviceKeyLog.ts
@@ -5,7 +5,7 @@ import { logger } from '../utils/logger.js'
import { revokeHarnessSessionById } from './harnessSession.js'
import {
applyDevLogEntries, DevLogError, emptyDevLogState, parseDevLogEntry,
- type DevLogEntry, type DevLogHead, type DevLogState,
+ type DevLogEntry, type DevLogHead, type DevLogMember, type DevLogState,
} from './deviceLogCore.js'
import { checkDevAck } from './deviceAckCore.js'
@@ -102,6 +102,22 @@ async function currentState(userId: string): Promise<{ state: DevLogState; sessi
return { state, sessions }
}
+/**
+ * The machine keys the account's log leaves active, by machine: what a machine shared with this account
+ * trusts it under (lib/machineAccess.ts), and the key another account's daemon pins to reach a machine
+ * shared with it. The newest key wins when one machine has two.
+ */
+export async function activeMachineKeys(userId: string): Promise<DevLogMember[]> {
+ const { state } = await currentState(userId)
+ const byMachine = new Map<string, DevLogMember>()
+ for (const member of Object.values(state.active)) {
+ if (member.kind !== 'machine' || !member.machineId) continue
+ const held = byMachine.get(member.machineId)
+ if (!held || held.seq < member.seq) byMachine.set(member.machineId, member)
+ }
+ return [...byMachine.values()]
+}
+
/**
* Keep the snapshot at [state]. It only moves forward, so a slower append cannot put an older one back
* — except over [replacing], a snapshot found not to fit the log, which is overwritten only if it is
diff --git a/backend/src/lib/machineAccess.test.ts b/backend/src/lib/machineAccess.test.ts
new file mode 100644
index 000000000..dcedd7f9d
--- /dev/null
+++ b/backend/src/lib/machineAccess.test.ts
@@ -0,0 +1,150 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+const mocks = vi.hoisted(() => ({
+ prisma: {
+ machineShare: { findUnique: vi.fn(), findMany: vi.fn() },
+ machineShareAdd: { findUnique: vi.fn(), findMany: vi.fn() },
+ machine: { findMany: vi.fn() },
+ user: { findMany: vi.fn() },
+ },
+ presence: vi.fn(), keys: vi.fn(),
+}))
+vi.mock('./prisma.js', () => ({ prisma: mocks.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))
+vi.mock('./bus.js', () => ({ getAgentPresenceMany: mocks.presence }))
+vi.mock('./deviceKeyLog.js', () => ({ activeMachineKeys: mocks.keys }))
+import { machinesSharedWith, shareMembers, sharedMachineAccess, sharedVia } from './machineAccess.js'
+import { emailDomain, isPublicEmailDomain } from './publicEmailDomains.js'
+
+const pub = (n: number) => Buffer.alloc(32, n).toString('base64')
+const kim = { sub: 'kim', email: ' [email protected] ', role: 'user', autonomousEnv: 'prod' as const }
+const share = (patch: Record<string, unknown> = {}) => ({ id: 's1', machineId: 'm1', ownerId: 'owner', autonomousEnv: 'prod',
+ emails: [] as string[], domain: null as string | null, createdAt: new Date(), updatedAt: new Date(), ...patch })
+const machine = (patch: Record<string, unknown> = {}) => ({ machineId: 'm1', userId: 'owner', autonomousEnv: 'prod', name: 'Studio',
+ hostname: 'studio.local', billingStatus: 'not_required', ...patch })
+
+describe('public email domains', () => {
+ it('reads a domain, and knows the ones anyone can have an address at', () => {
+ expect(emailDomain(' [email protected] ')).toBe('acme.io')
+ expect(emailDomain('kim@localhost')).toBeNull()
+ expect(emailDomain('no-at-all')).toBeNull()
+ for (const domain of ['gmail.com', 'GMAIL.COM', 'privaterelay.appleid.com', 'pending.harness.invalid', 'x.invalid', null]) {
+ expect(isPublicEmailDomain(domain)).toBe(true)
+ }
+ expect(isPublicEmailDomain('acme.io')).toBe(false)
+ })
+})
+
+describe('who a share reaches', () => {
+ it('names an address, or everyone at the domain, never a public one', () => {
+ expect(sharedVia(share({ emails: ['[email protected]'] }), kim.email)).toBe('email')
+ expect(sharedVia(share({ domain: 'acme.io' }), kim.email)).toBe('domain')
+ expect(sharedVia(share({ domain: 'acme.io' }), '[email protected]')).toBeNull()
+ // A row that somehow holds a public domain shares with no one through it.
+ expect(sharedVia(share({ domain: 'gmail.com' }), '[email protected]')).toBeNull()
+ expect(sharedVia(share(), kim.email)).toBeNull()
+ })
+})
+
+describe('sharedMachineAccess', () => {
+ beforeEach(() => { vi.resetAllMocks() })
+
+ it('lets a named address in, and a colleague only once they added it', async () => {
+ mocks.prisma.machineShare.findUnique.mockResolvedValue(share({ emails: ['[email protected]'] }))
+ expect(await sharedMachineAccess(kim, machine())).toBe('email')
+ mocks.prisma.machineShare.findUnique.mockResolvedValue(share({ domain: 'acme.io' }))
+ mocks.prisma.machineShareAdd.findUnique.mockResolvedValueOnce(null)
+ expect(await sharedMachineAccess(kim, machine())).toBeNull()
+ mocks.prisma.machineShareAdd.findUnique.mockResolvedValueOnce({ machineId: 'm1', userId: 'kim' })
+ expect(await sharedMachineAccess(kim, machine())).toBe('domain')
+ expect(mocks.prisma.machineShareAdd.findUnique).toHaveBeenCalledWith({ where: { machineId_userId: { machineId: 'm1', userId: 'kim' } } })
+ })
+
+ it('refuses the owner (no share needed), no share, another owner’s row and another environment', async () => {
+ expect(await sharedMachineAccess(kim, machine({ userId: 'kim' }))).toBeNull()
+ expect(mocks.prisma.machineShare.findUnique).not.toHaveBeenCalled()
+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(null)
+ expect(await sharedMachineAccess(kim, machine())).toBeNull()
+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(share({ emails: ['[email protected]'], ownerId: 'someone-else' }))
+ expect(await sharedMachineAccess(kim, machine())).toBeNull()
+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(share({ emails: ['[email protected]'], autonomousEnv: 'stag' }))
+ expect(await sharedMachineAccess(kim, machine())).toBeNull()
+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(share({ emails: ['[email protected]'] }))
+ expect(await sharedMachineAccess(kim, machine({ autonomousEnv: 'stag' }))).toBeNull()
+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(share({ emails: ['[email protected]'] }))
+ expect(await sharedMachineAccess(kim, machine())).toBeNull()
+ })
+})
+
+describe('machinesSharedWith', () => {
+ beforeEach(() => {
+ vi.resetAllMocks()
+ mocks.presence.mockResolvedValue(new Map([['m1', 'mgr']]))
+ mocks.prisma.machineShareAdd.findMany.mockResolvedValue([])
+ mocks.prisma.user.findMany.mockResolvedValue([{ id: 'owner', name: 'Dee', email: '[email protected]' }])
+ mocks.keys.mockResolvedValue([{ machineId: 'm1', pub: pub(1), label: 'studio', kind: 'machine', addedAt: 1, seq: 1 }])
+ })
+
+ it('lists named and domain shares, with the owner, the machine key and whether it was added', async () => {
+ mocks.prisma.machineShare.findMany.mockResolvedValue([share({ emails: ['[email protected]'] }), share({ machineId: 'm2', domain: 'acme.io' })])
+ mocks.prisma.machine.findMany.mockResolvedValue([machine(), machine({ machineId: 'm2', name: null, hostname: null })])
+ const rows = await machinesSharedWith(kim)
+ expect(mocks.prisma.machineShare.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: {
+ autonomousEnv: 'prod', ownerId: { not: 'kim' }, OR: [{ emails: { has: '[email protected]' } }, { domain: 'acme.io' }],
+ } }))
+ expect(rows).toEqual([
+ { machineId: 'm1', name: 'Studio', hostname: 'studio.local', authMode: 'remote', status: 'running', pub: pub(1),
+ share: { ownerName: 'Dee', ownerEmail: '[email protected]', via: 'email', added: true } },
+ { machineId: 'm2', name: null, hostname: null, authMode: 'remote', status: 'offline', pub: null,
+ share: { ownerName: 'Dee', ownerEmail: '[email protected]', via: 'domain', added: false } },
+ ])
+ })
+
+ it('asks no domain at a public one, and drops deleted, suspended and re-owned machines', async () => {
+ const gmail = { ...kim, email: '[email protected]' }
+ mocks.prisma.machineShare.findMany.mockResolvedValue([share({ emails: ['[email protected]'] }), share({ machineId: 'm2', emails: ['[email protected]'] }),
+ share({ machineId: 'm3', emails: ['[email protected]'] })])
+ mocks.prisma.machine.findMany.mockResolvedValue([machine({ billingStatus: 'suspended' }), machine({ machineId: 'm2', userId: 'thief' })])
+ expect(await machinesSharedWith(gmail)).toEqual([])
+ expect(mocks.prisma.machineShare.findMany.mock.calls[0][0].where.OR).toEqual([{ emails: { has: '[email protected]' } }])
+ })
+
+ it('answers nothing without touching machines when nothing reaches the person', async () => {
+ mocks.prisma.machineShare.findMany.mockResolvedValue([share({ emails: ['[email protected]'] })])
+ expect(await machinesSharedWith(kim)).toEqual([])
+ expect(mocks.prisma.machine.findMany).not.toHaveBeenCalled()
+ })
+
+ it('names an owner with no name by email, and one gone as a Harness user; an added domain share reads added', async () => {
+ mocks.prisma.machineShare.findMany.mockResolvedValue([share({ domain: 'acme.io' })])
+ mocks.prisma.machine.findMany.mockResolvedValue([machine()])
+ mocks.prisma.machineShareAdd.findMany.mockResolvedValue([{ machineId: 'm1', userId: 'kim' }])
+ mocks.prisma.user.findMany.mockResolvedValueOnce([{ id: 'owner', name: null, email: '[email protected]' }])
+ expect((await machinesSharedWith(kim))[0].share).toEqual({ ownerName: '[email protected]', ownerEmail: '[email protected]', via: 'domain', added: true })
+ mocks.prisma.user.findMany.mockResolvedValueOnce([])
+ expect((await machinesSharedWith(kim))[0].share).toMatchObject({ ownerName: 'Harness user', ownerEmail: '' })
+ })
+})
+
+describe('shareMembers', () => {
+ beforeEach(() => {
+ vi.resetAllMocks()
+ mocks.keys.mockImplementation(async (id: string) => [{ machineId: `${id}-mac`, pub: pub(id.length), label: `${id}'s Mac`, kind: 'machine', addedAt: 1, seq: 1 }])
+ })
+
+ it('names the addresses and the colleagues who added it, with their machines’ keys', async () => {
+ mocks.prisma.machineShareAdd.findMany.mockResolvedValue([{ machineId: 'm1', userId: 'kim' }])
+ mocks.prisma.user.findMany.mockResolvedValue([
+ { id: 'ann', email: '[email protected]', name: 'Ann' },
+ { id: 'kim', email: '[email protected]', name: null },
+ { id: 'lee', email: '[email protected]', name: 'Lee' }, // at the domain, never added
+ { id: 'old', email: '[email protected]', name: 'Old' }, // added once, no longer reached
+ ])
+ const members = await shareMembers(share({ emails: ['[email protected]'], domain: 'acme.io' }))
+ expect(mocks.prisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: {
+ autonomousEnv: 'prod', id: { not: 'owner' }, OR: [{ email: { in: ['[email protected]'] } }, { id: { in: ['kim'] } }],
+ } }))
+ expect(members).toEqual([
+ { email: '[email protected]', name: 'Ann', via: 'email', machines: [{ machineId: 'ann-mac', name: "ann's Mac", pub: pub(3) }] },
+ { email: '[email protected]', name: null, via: 'domain', machines: [{ machineId: 'kim-mac', name: "kim's Mac", pub: pub(3) }] },
+ ])
+ })
+})
diff --git a/backend/src/lib/machineAccess.ts b/backend/src/lib/machineAccess.ts
new file mode 100644
index 000000000..a57caf653
--- /dev/null
+++ b/backend/src/lib/machineAccess.ts
@@ -0,0 +1,133 @@
+/**
+ * Who may use a machine another account owns (docs/plans/2026-10-15-share-machine-plan.md). Its owner
+ * shares it with addresses, and with everyone at the owner's own domain; someone at the domain adds it with
+ * one click (`MachineShareAdd`), someone the owner named needs none. A shared machine is used with the
+ * owner's own rights: `machine_select` (lib/webWs.ts) asks `sharedMachineAccess` where it once compared
+ * owners, and `machinesSharedWith` is the "Shared with you" half of the Machines list.
+ *
+ * Only the listing and the relay are decided here. The machine's daemon keeps the policy it published and
+ * trusts the keys of the accounts it names and no others (cli services/sharedMachines.ts), so this
+ * backend's word alone never opens a machine to anyone.
+ */
+import type { Machine, MachineShare } from '@prisma/client'
+import { prisma, machineAlive } from './prisma.js'
+import { getAgentPresenceMany } from './bus.js'
+import { machineBillingAllowsDataPlane } from './billingState.js'
+import { activeMachineKeys } from './deviceKeyLog.js'
+import { emailDomain, isPublicEmailDomain } from './publicEmailDomains.js'
+import { storedAutonomousEnvironment } from './autonomousEnvironment.js'
+import type { AuthUser } from './ssoAuth.js'
+
+export type ShareVia = 'email' | 'domain'
+
+/** The most machines one account is shown as shared with it, and the most a machine lists as using it. */
+export const SHARED_LIST_MAX = 200
+
+const normalized = (email: string): string => email.trim().toLowerCase()
+
+/** How `share` reaches `email`: named, at the owner's domain, or not at all. */
+export function sharedVia(share: Pick<MachineShare, 'emails' | 'domain'>, email: string): ShareVia | null {
+ const address = normalized(email)
+ if (share.emails.includes(address)) return 'email'
+ const domain = emailDomain(address)
+ if (share.domain && domain === share.domain && !isPublicEmailDomain(domain)) return 'domain'
+ return null
+}
+
+/** Whether `user` may use `machine`, which another account owns: how it was shared with them, or null. A
+ * domain share counts once they added it. */
+export async function sharedMachineAccess(user: AuthUser, machine: Pick<Machine, 'machineId' | 'userId' | 'autonomousEnv'>): Promise<ShareVia | null> {
+ if (machine.userId === user.sub) return null
+ const share = await prisma.machineShare.findUnique({ where: { machineId: machine.machineId } })
+ if (!share || share.ownerId !== machine.userId || share.autonomousEnv !== user.autonomousEnv
+ || storedAutonomousEnvironment(machine.autonomousEnv) !== user.autonomousEnv) return null
+ const via = sharedVia(share, user.email)
+ if (via !== 'domain') return via
+ const added = await prisma.machineShareAdd.findUnique({ where: { machineId_userId: { machineId: machine.machineId, userId: user.sub } } })
+ return added ? via : null
+}
+
+/** A machine shared with the person asking, as their Machines list shows it. `pub` is the machine's own
+ * E2EE identity as its account's device key log names it: what their daemon pins to reach it. */
+export interface SharedMachineRow {
+ machineId: string
+ name: string | null
+ hostname: string | null
+ authMode: 'remote'
+ status: 'running' | 'offline'
+ pub: string | null
+ share: { ownerName: string; ownerEmail: string; via: ShareVia; added: boolean }
+}
+
+/** The machines other accounts share with `user`: named ones, and those at their domain, added or not. */
+export async function machinesSharedWith(user: AuthUser): Promise<SharedMachineRow[]> {
+ const email = normalized(user.email)
+ const domain = emailDomain(email)
+ const shares = await prisma.machineShare.findMany({
+ where: {
+ autonomousEnv: user.autonomousEnv, ownerId: { not: user.sub },
+ OR: [{ emails: { has: email } }, ...(isPublicEmailDomain(domain) ? [] : [{ domain }])],
+ },
+ orderBy: { createdAt: 'asc' }, take: SHARED_LIST_MAX,
+ })
+ const reaching = shares.flatMap(share => {
+ const via = sharedVia(share, email)
+ return via ? [{ share, via }] : []
+ })
+ if (!reaching.length) return []
+ const machines = (await prisma.machine.findMany({ where: {
+ machineId: { in: reaching.map(r => r.share.machineId) }, autonomousEnv: user.autonomousEnv, ...machineAlive,
+ } })).filter(machineBillingAllowsDataPlane)
+ const usable = reaching.flatMap(r => {
+ const machine = machines.find(m => m.machineId === r.share.machineId && m.userId === r.share.ownerId)
+ return machine ? [{ ...r, machine }] : []
+ })
+ if (!usable.length) return []
+ const ids = usable.map(u => u.machine.machineId)
+ const ownerIds = [...new Set(usable.map(u => u.machine.userId))]
+ const [adds, owners, presence, keys] = await Promise.all([
+ prisma.machineShareAdd.findMany({ where: { userId: user.sub, machineId: { in: ids } } }),
+ prisma.user.findMany({ where: { id: { in: ownerIds } }, select: { id: true, name: true, email: true } }),
+ getAgentPresenceMany(ids),
+ Promise.all(ownerIds.map(async id => [id, await activeMachineKeys(id)] as const)),
+ ])
+ const keyOf = (ownerId: string, machineId: string): string | null =>
+ keys.find(([id]) => id === ownerId)?.[1].find(k => k.machineId === machineId)?.pub ?? null
+ return usable.map(({ machine, via }) => {
+ const owner = owners.find(o => o.id === machine.userId)
+ return {
+ machineId: machine.machineId, name: machine.name ?? null, hostname: machine.hostname ?? null, authMode: 'remote',
+ status: presence.get(machine.machineId) ? 'running' : 'offline',
+ pub: keyOf(machine.userId, machine.machineId),
+ share: { ownerName: owner?.name || owner?.email || 'Harness user', ownerEmail: owner?.email ?? '', via,
+ added: via === 'email' || adds.some(a => a.machineId === machine.machineId) },
+ }
+ })
+}
+
+/** Someone who may use a machine, and their machines' keys: what the machine's daemon trusts. */
+export interface ShareMember {
+ email: string
+ name: string | null
+ via: ShareVia
+ machines: Array<{ machineId: string; name: string; pub: string }>
+}
+
+/** The accounts `share` lets use its machine right now: those named, and those at the domain who added it. */
+export async function shareMembers(share: MachineShare): Promise<ShareMember[]> {
+ const adds = await prisma.machineShareAdd.findMany({ where: { machineId: share.machineId }, take: SHARED_LIST_MAX })
+ const users = await prisma.user.findMany({
+ where: { autonomousEnv: share.autonomousEnv, id: { not: share.ownerId },
+ OR: [{ email: { in: share.emails } }, { id: { in: adds.map(a => a.userId) } }] },
+ select: { id: true, email: true, name: true }, take: SHARED_LIST_MAX,
+ })
+ const members = users.flatMap(user => {
+ const via = sharedVia(share, user.email)
+ if (!via || (via === 'domain' && !adds.some(a => a.userId === user.id))) return []
+ return [{ user, via }]
+ })
+ return Promise.all(members.map(async ({ user, via }) => ({
+ email: normalized(user.email), name: user.name ?? null, via,
+ machines: (await activeMachineKeys(user.id)).map(k => ({ machineId: k.machineId, name: k.label, pub: k.pub })),
+ })))
+}
diff --git a/backend/src/lib/publicEmailDomains.ts b/backend/src/lib/publicEmailDomains.ts
new file mode 100644
index 000000000..9b351805f
--- /dev/null
+++ b/backend/src/lib/publicEmailDomains.ts
@@ -0,0 +1,36 @@
+/**
+ * Email domains anyone can get an address at. Sharing a machine with "everyone at @domain"
+ * (lib/machineAccess.ts) is offered only for a domain that names an organization: at one of these it would
+ * share the machine with strangers. Apple's private relay is here too: "Hide My Email" gives every Apple
+ * account an address under it, and `pending.harness.invalid` is the placeholder a device row signs in
+ * with before its account is known (services/UserService.ts).
+ *
+ * Kept short and plain on purpose: the providers people actually sign in with. A domain missing here is
+ * offered to its owner, who still has to turn it on.
+ */
+const PUBLIC_EMAIL_DOMAINS = new Set([
+ 'gmail.com', 'googlemail.com',
+ 'outlook.com', 'hotmail.com', 'live.com', 'msn.com', 'passport.com',
+ 'hotmail.co.uk', 'hotmail.fr', 'hotmail.de', 'hotmail.it', 'hotmail.es', 'outlook.fr', 'outlook.de', 'live.co.uk',
+ 'yahoo.com', 'ymail.com', 'rocketmail.com', 'yahoo.co.uk', 'yahoo.fr', 'yahoo.de', 'yahoo.co.jp', 'yahoo.com.vn',
+ 'icloud.com', 'me.com', 'mac.com', 'privaterelay.appleid.com',
+ 'aol.com', 'aim.com',
+ 'proton.me', 'protonmail.com', 'protonmail.ch', 'pm.me',
+ 'gmx.com', 'gmx.net', 'gmx.de', 'web.de', 'mail.com',
+ 'zoho.com', 'zohomail.com', 'yandex.com', 'yandex.ru', 'mail.ru', 'inbox.ru', 'list.ru', 'bk.ru',
+ 'tutanota.com', 'tuta.io', 'fastmail.com', 'hey.com', 'duck.com',
+ 'qq.com', '163.com', '126.com', 'yeah.net', 'sina.com', 'naver.com', 'daum.net', 'hanmail.net',
+ 'pending.harness.invalid',
+])
+
+/** The domain of `email`, lower case; null when it has none. */
+export function emailDomain(email: string): string | null {
+ const at = email.trim().toLowerCase().lastIndexOf('@')
+ const domain = at < 0 ? '' : email.trim().toLowerCase().slice(at + 1)
+ return domain.includes('.') ? domain : null
+}
+
+/** Whether `domain` is one anyone can have an address at (or no organization's at all). */
+export function isPublicEmailDomain(domain: string | null): boolean {
+ return !domain || PUBLIC_EMAIL_DOMAINS.has(domain.toLowerCase()) || domain.toLowerCase().endsWith('.invalid')
+}
diff --git a/backend/src/lib/webWs.ts b/backend/src/lib/webWs.ts
index 6d7ba3e33..6d1774fff 100644
--- a/backend/src/lib/webWs.ts
+++ b/backend/src/lib/webWs.ts
@@ -5,7 +5,7 @@
*
* - PER-USER (current): the subprotocol is the user's SSO access token → ONE socket per user.
* The socket starts UNATTACHED; the client scopes it with `machine_select {machineId}` (ownership-checked
- * against `agentBinding.userId`), which detaches the previous hub client and attaches a fresh one
+ * against `agentBinding.userId`, or shared with this account: lib/machineAccess.ts), which detaches the previous hub client and attaches a fresh one
* (new connId — keeps the (agent, connId) invariant that E2EE and reply-targeting rely on). While
* attached, frames flow exactly like the legacy mode (sendDown / up:{machineId} fan-out). The socket
* also live-watches ALL the user's agents and pushes `machines_status` frames (node_status transitions
@@ -24,7 +24,8 @@ 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 } from './bus.js'
+import { getAgentPresence, getAgentPresenceMany, subscribeStatus, getDevicePresence, subscribeDeviceStatus, subscribeDeviceMachineListChanged, subscribeDeviceE2eePair, subscribeMachineShareChanged } from './bus.js'
+import { sharedMachineAccess } from './machineAccess.js'
import { relayWebDocumentPushes } from './webAccountPushes.js'
import { DAEMONS } from '../config/env.js'
import { attachHubClient, trackSocketLiveness, type HubClient } from './hub.js'
@@ -321,7 +322,12 @@ function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'we
const gen = ++selectGen
const binding = await prisma.machine.findUnique({ where: { machineId: machineId } })
if (closed || gen !== selectGen) return // superseded by a newer select
- if (!binding || binding.deletedAt || binding.userId !== user.sub) {
+ // Another account's machine is selected only while it is shared with this one (lib/machineAccess.ts),
+ // with the same rights as the owner's own; its daemon decides again whether to trust this account.
+ const shared = binding && !binding.deletedAt && binding.userId !== user.sub
+ ? await sharedMachineAccess(user, binding).catch(() => null) : null
+ if (closed || gen !== selectGen) return
+ if (!binding || binding.deletedAt || (binding.userId !== user.sub && !shared)) {
logger.warn('machine_select rejected', { userId: user.sub, machineId })
send({ type: 'machine_select_error', payload: { machineId: machineId, error: 'NOT_YOUR_MACHINE' } })
return
@@ -356,10 +362,39 @@ function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'we
client = attachHubClient(ws, machineId, 'web')
currentAgentId = machineId
currentBinding = binding
- logger.info('web user selected agent', { userId: user.sub, machineId, connId: client.connId })
+ watchShare(shared ? machineId : null)
+ logger.info('web user selected agent', { userId: user.sub, machineId, connId: client.connId, ...(shared ? { shared } : {}) })
ack(machineId)
}
+ // A machine shared with this account stays selected while its sharing still lets it: the owner taking
+ // the address off, turning the domain off or stopping, or this account removing it from its list, ends
+ // the session at once on whichever instance holds it (bus `machine-share:<id>`).
+ let shareUnsub: (() => void) | null = null
+ let shareGen = 0
+ const watchShare = (machineId: string | null): void => {
+ const gen = ++shareGen
+ shareUnsub?.()
+ shareUnsub = null
+ if (!machineId) return
+ const recheck = async (): Promise<void> => {
+ const binding = await prisma.machine.findUnique({ where: { machineId } })
+ const still = binding && !binding.deletedAt ? await sharedMachineAccess(user, binding) : null
+ if (still || closed || gen !== shareGen || currentAgentId !== machineId) return
+ logger.info('shared machine session ended: sharing changed', { userId: user.sub, machineId })
+ selectGen++
+ client?.detach()
+ client = null
+ currentAgentId = null
+ currentBinding = null
+ send({ type: 'machine_select_error', payload: { machineId, error: 'NOT_YOUR_MACHINE' } })
+ ws.close(4403, 'Sharing ended')
+ }
+ void subscribeMachineShareChanged(machineId, () => { void recheck().catch(() => { /* the next change asks again */ }) })
+ .then((unsub) => { if (gen === shareGen && !closed) shareUnsub = unsub; else unsub() })
+ .catch((err) => logger.warn('web-ws machine share watch failed', { userId: user.sub, machineId, error: String(err) }))
+ }
+
// Presence, remembered briefly. Every non-terminal frame used to cost one Redis GET on the hot path;
// the key itself has a 30s TTL, so a 2s memory of "it was there" is well inside its own staleness.
// Only a POSITIVE answer is cached — an absent key must keep triggering the wake path.
@@ -440,6 +475,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'we
}
if (type === 'machine_deselect') {
selectGen++ // cancel any in-flight bindAgent
+ watchShare(null)
client?.detach()
client = null
currentAgentId = null
@@ -532,6 +568,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'we
client?.detach()
client = null
currentBinding = null
+ watchShare(null)
for (const [, unsub] of statusSubs) unsub()
statusSubs.clear()
if (watchAgentsTimer) { clearTimeout(watchAgentsTimer); watchAgentsTimer = null }
diff --git a/backend/src/routes/machineShares.test.ts b/backend/src/routes/machineShares.test.ts
new file mode 100644
index 000000000..a0cb8e352
--- /dev/null
+++ b/backend/src/routes/machineShares.test.ts
@@ -0,0 +1,191 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import Fastify, { type FastifyInstance } from 'fastify'
+const mocks = vi.hoisted(() => ({
+ prisma: {
+ machine: { findFirst: vi.fn() },
+ machineShare: { findUnique: vi.fn(), upsert: vi.fn(), deleteMany: vi.fn() },
+ machineShareAdd: { findMany: vi.fn(), upsert: vi.fn(), deleteMany: vi.fn() },
+ user: { findMany: vi.fn() },
+ },
+ listChanged: vi.fn(), shareChanged: vi.fn(), sharedWith: vi.fn(), members: vi.fn(), auth: vi.fn(),
+}))
+vi.mock('../lib/prisma.js', () => ({ prisma: mocks.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))
+vi.mock('../lib/bus.js', () => ({ publishDeviceMachineListChanged: mocks.listChanged, publishMachineShareChanged: mocks.shareChanged }))
+vi.mock('../lib/machineAccess.js', async original => ({ ...await original<typeof import('../lib/machineAccess.js')>(),
+ machinesSharedWith: mocks.sharedWith, shareMembers: mocks.members }))
+vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof import('../lib/ssoAuth.js')>(), authenticateAccessToken: mocks.auth }))
+import { machineShareRoutes, SHARE_EMAILS_MAX } from './machineShares.js'
+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'
+import { errorHandler } from '../middlewares/errorHandler.js'
+
+const M1 = 'ab'.repeat(16)
+const dee = { sub: 'dee', email: '[email protected]', role: 'user', autonomousEnv: 'prod' as const }
+const kim = { sub: 'kim', email: '[email protected]', role: 'user', autonomousEnv: 'prod' as const }
+const machine = { machineId: M1, userId: 'dee', autonomousEnv: 'prod', billingStatus: 'not_required' }
+const row = (patch: Record<string, unknown> = {}) => ({ id: 's1', machineId: M1, ownerId: 'dee', autonomousEnv: 'prod',
+ emails: ['[email protected]'], domain: 'acme.io', createdAt: new Date(), updatedAt: new Date(), ...patch })
+const members = [{ email: '[email protected]', name: 'Ann', via: 'email', machines: [] }]
+
+describe('sharing a machine', () => {
+ let app: FastifyInstance
+ const auth = { authorization: 'Bearer fixture' }
+ beforeEach(async () => {
+ vi.resetAllMocks()
+ mocks.auth.mockResolvedValue(dee)
+ mocks.prisma.machine.findFirst.mockResolvedValue(machine)
+ mocks.prisma.machineShare.findUnique.mockResolvedValue(null)
+ mocks.prisma.machineShare.upsert.mockImplementation(async ({ create }: { create: Record<string, unknown> }) => row(create))
+ mocks.prisma.machineShareAdd.findMany.mockResolvedValue([])
+ mocks.prisma.machineShareAdd.deleteMany.mockResolvedValue({ count: 0 })
+ mocks.prisma.user.findMany.mockResolvedValue([])
+ mocks.shareChanged.mockResolvedValue(1)
+ mocks.listChanged.mockResolvedValue(1)
+ mocks.members.mockResolvedValue(members)
+ app = Fastify(); app.setErrorHandler(errorHandler); registerAuthMiddleware(app, mocks.auth)
+ await app.register(machineShareRoutes); await app.ready()
+ })
+ afterEach(async () => { await app.close() })
+ const put = (payload: unknown, machineId = M1) =>
+ app.inject({ method: 'PUT', url: `/api/machines/${machineId}/share`, headers: auth, payload: payload as any })
+
+ it('requires a sign-in on every endpoint', async () => {
+ for (const [method, url] of [['GET', `/api/machines/${M1}/share`], ['PUT', `/api/machines/${M1}/share`], ['GET', '/api/machine-shares'],
+ ['POST', `/api/machine-shares/${M1}/add`], ['DELETE', `/api/machine-shares/${M1}/add`]] as const) {
+ expect((await app.inject({ method, url })).statusCode).toBe(401)
+ }
+ })
+
+ it('reads the owner’s policy: off by default, with the domain it may offer', async () => {
+ let res = await app.inject({ method: 'GET', url: `/api/machines/${M1}/share`, headers: auth })
+ expect(res.json().data).toEqual({ emails: [], sameDomain: false, domain: 'acme.io', members: [] })
+ expect(mocks.prisma.machine.findFirst).toHaveBeenCalledWith({ where: expect.objectContaining({ machineId: M1, userId: 'dee', autonomousEnv: 'prod' }) })
+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(row())
+ res = await app.inject({ method: 'GET', url: `/api/machines/${M1}/share`, headers: auth })
+ expect(res.json().data).toEqual({ emails: ['[email protected]'], sameDomain: true, domain: 'acme.io', members })
+ // A row another owner wrote is not this one's policy.
+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(row({ ownerId: 'someone' }))
+ res = await app.inject({ method: 'GET', url: `/api/machines/${M1}/share`, headers: auth })
+ expect(res.json().data.emails).toEqual([])
+ })
+
+ it('offers no domain at a public one', async () => {
+ mocks.auth.mockResolvedValue({ ...dee, email: '[email protected]' })
+ const res = await app.inject({ method: 'GET', url: `/api/machines/${M1}/share`, headers: auth })
+ expect(res.json().data.domain).toBeNull()
+ })
+
+ it('answers 404 for a machine the caller does not own, read or written', async () => {
+ mocks.prisma.machine.findFirst.mockResolvedValue(null)
+ expect((await app.inject({ method: 'GET', url: `/api/machines/${M1}/share`, headers: auth })).statusCode).toBe(404)
+ expect((await put({ emails: [], sameDomain: false })).statusCode).toBe(404)
+ expect(mocks.prisma.machineShare.upsert).not.toHaveBeenCalled()
+ })
+
+ it('writes normalized addresses (never the owner’s own) and the owner’s domain, and tells everyone affected', async () => {
+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(row({ emails: ['[email protected]'], domain: null }))
+ mocks.prisma.user.findMany.mockResolvedValue([{ id: 'ann' }, { id: 'kim' }, { id: 'dee' }])
+ mocks.prisma.machineShareAdd.findMany.mockImplementation(async (args: { select?: unknown }) => args.select ? [{ userId: 'lee' }] : [])
+ const res = await put({ emails: [' [email protected] ', '[email protected]', '[email protected]', '[email protected]'], sameDomain: true })
+ expect(res.statusCode).toBe(200)
+ expect(mocks.prisma.machineShare.upsert).toHaveBeenCalledWith({ where: { machineId: M1 },
+ create: { machineId: M1, ownerId: 'dee', autonomousEnv: 'prod', emails: ['[email protected]'], domain: 'acme.io' },
+ update: { ownerId: 'dee', autonomousEnv: 'prod', emails: ['[email protected]'], domain: 'acme.io' } })
+ expect(res.json().data).toEqual({ emails: ['[email protected]'], sameDomain: true, domain: 'acme.io', members })
+ expect(mocks.shareChanged).toHaveBeenCalledWith(M1)
+ expect(mocks.prisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { OR: [
+ { email: { in: ['[email protected]', '[email protected]'] } }, { email: { endsWith: '@acme.io' } }] } }))
+ expect(mocks.listChanged.mock.calls.map(c => c[0]).sort()).toEqual(['ann', 'kim', 'lee'])
+ })
+
+ it('refuses everyone at a public domain', async () => {
+ mocks.auth.mockResolvedValue({ ...dee, email: '[email protected]' })
+ const res = await put({ emails: [], sameDomain: true })
+ expect(res.statusCode).toBe(400)
+ expect(res.json().error.code).toBe('PUBLIC_DOMAIN')
+ expect(mocks.prisma.machineShare.upsert).not.toHaveBeenCalled()
+ })
+
+ it('stops sharing when no one is left: the policy and every add go', async () => {
+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(row())
+ const res = await put({ emails: [], sameDomain: false })
+ expect(res.json().data).toEqual({ emails: [], sameDomain: false, domain: 'acme.io', members: [] })
+ expect(mocks.prisma.machineShare.deleteMany).toHaveBeenCalledWith({ where: { machineId: M1 } })
+ expect(mocks.prisma.machineShareAdd.deleteMany).toHaveBeenCalledWith({ where: { machineId: M1 } })
+ expect(mocks.prisma.machineShare.upsert).not.toHaveBeenCalled()
+ expect(mocks.shareChanged).toHaveBeenCalledWith(M1)
+ })
+
+ it('tells no one when nothing was ever shared, and a failure to tell does not fail the write', async () => {
+ await put({ emails: [], sameDomain: false })
+ expect(mocks.prisma.user.findMany).not.toHaveBeenCalled()
+ mocks.prisma.user.findMany.mockRejectedValueOnce(new Error('db down'))
+ mocks.shareChanged.mockRejectedValueOnce(new Error('redis down'))
+ expect((await put({ emails: ['[email protected]'], sameDomain: false })).statusCode).toBe(200)
+ })
+
+ it('validates the policy', async () => {
+ for (const body of [{ emails: ['nope'], sameDomain: false }, { emails: [], sameDomain: 'yes' }, { emails: [] },
+ { emails: [], sameDomain: false, canControl: true }, { emails: Array.from({ length: SHARE_EMAILS_MAX + 1 }, (_, i) => `p${i}@acme.io`), sameDomain: false }]) {
+ expect((await put(body)).statusCode).toBe(400)
+ }
+ expect((await put({ emails: [], sameDomain: false }, '../m1')).statusCode).toBeGreaterThanOrEqual(400)
+ })
+
+ it('lists the machines shared with the caller', async () => {
+ mocks.sharedWith.mockResolvedValue([{ machineId: 'm9' }])
+ const res = await app.inject({ method: 'GET', url: '/api/machine-shares', headers: auth })
+ expect(res.json().data).toEqual({ machines: [{ machineId: 'm9' }] })
+ expect(mocks.sharedWith).toHaveBeenCalledWith(dee)
+ })
+
+ describe('adding a machine shared with your domain', () => {
+ const add = (method: 'POST' | 'DELETE' = 'POST') => app.inject({ method, url: `/api/machine-shares/${M1}/add`, headers: auth })
+ beforeEach(() => { mocks.auth.mockResolvedValue(kim) })
+
+ it('adds a domain share and tells the owner’s daemon and the caller', async () => {
+ mocks.prisma.machineShare.findUnique.mockResolvedValue(row({ emails: [] }))
+ expect((await add()).json().data).toEqual({ added: true })
+ expect(mocks.prisma.machineShareAdd.upsert).toHaveBeenCalledWith({ where: { machineId_userId: { machineId: M1, userId: 'kim' } },
+ create: { machineId: M1, userId: 'kim' }, update: {} })
+ expect(mocks.listChanged.mock.calls.map(c => c[0])).toEqual(['dee', 'kim'])
+ })
+
+ it('needs no add for a named address', async () => {
+ mocks.prisma.machineShare.findUnique.mockResolvedValue(row({ emails: ['[email protected]'], domain: null }))
+ expect((await add()).statusCode).toBe(200)
+ expect(mocks.prisma.machineShareAdd.upsert).not.toHaveBeenCalled()
+ })
+
+ it('refuses a machine not shared with the caller, their own, another environment’s, or one gone', async () => {
+ for (const share of [null, row({ emails: [], domain: 'other.io' }), row({ ownerId: 'kim' }), row({ autonomousEnv: 'stag' })]) {
+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(share)
+ const res = await add()
+ expect(res.statusCode).toBe(404)
+ expect(res.json().error.code).toBe('NOT_SHARED')
+ }
+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(row())
+ mocks.prisma.machine.findFirst.mockResolvedValueOnce(null)
+ expect((await add()).statusCode).toBe(404)
+ expect(mocks.prisma.machineShareAdd.upsert).not.toHaveBeenCalled()
+ })
+
+ it('takes it back out, ending a live session and telling both', async () => {
+ mocks.prisma.machineShareAdd.deleteMany.mockResolvedValueOnce({ count: 1 })
+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(row())
+ expect((await add('DELETE')).json().data).toEqual({ removed: true })
+ expect(mocks.prisma.machineShareAdd.deleteMany).toHaveBeenCalledWith({ where: { machineId: M1, userId: 'kim' } })
+ expect(mocks.shareChanged).toHaveBeenCalledWith(M1)
+ expect(mocks.listChanged.mock.calls.map(c => c[0])).toEqual(['dee', 'kim'])
+ })
+
+ it('says so when there was nothing to remove; a share gone since tells only the caller', async () => {
+ expect((await add('DELETE')).json().data).toEqual({ removed: false })
+ expect(mocks.listChanged).not.toHaveBeenCalled()
+ mocks.prisma.machineShareAdd.deleteMany.mockResolvedValueOnce({ count: 1 })
+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(null)
+ mocks.shareChanged.mockRejectedValueOnce(new Error('redis down'))
+ expect((await add('DELETE')).statusCode).toBe(200)
+ expect(mocks.listChanged.mock.calls.map(c => c[0])).toEqual(['kim'])
+ })
+ })
+})
diff --git a/backend/src/routes/machineShares.ts b/backend/src/routes/machineShares.ts
new file mode 100644
index 000000000..9cc7afa49
--- /dev/null
+++ b/backend/src/routes/machineShares.ts
@@ -0,0 +1,150 @@
+/**
+ * Sharing a whole machine with other accounts (docs/plans/2026-10-15-share-machine-plan.md).
+ *
+ * - `GET|PUT /api/machines/:machineId/share`: the owner's policy, the addresses and whether everyone at
+ * the owner's domain is in, and who uses the machine now with their machines' keys. Written by the
+ * machine's own daemon from the policy it keeps (cli services/sharedMachines.ts), which reads the members
+ * back to know whose keys to trust.
+ * - `GET /api/machine-shares`: the machines shared with the person asking (also in `GET /api/machines`).
+ * - `POST|DELETE /api/machine-shares/:machineId/add`: add a machine shared with your domain, or take it
+ * back out of your list. An address the owner named needs no adding.
+ */
+import type { FastifyInstance } from 'fastify'
+import type { MachineShare } from '@prisma/client'
+import { z } from 'zod'
+import { prisma, machineAlive } from '../lib/prisma.js'
+import { publishDeviceMachineListChanged, publishMachineShareChanged } from '../lib/bus.js'
+import { machinesSharedWith, shareMembers, sharedVia } from '../lib/machineAccess.js'
+import { emailDomain, isPublicEmailDomain } from '../lib/publicEmailDomains.js'
+import { validateBody, validateParams } from '../middlewares/validation.js'
+import { isMachineId } from '../utils/slug.js'
+import { sendError, sendSuccess } from '../utils/response.js'
+import { logger } from '../utils/logger.js'
+import type { AuthUser } from '../lib/ssoAuth.js'
+
+/** The most addresses one machine is shared with. */
+export const SHARE_EMAILS_MAX = 100
+/** The most accounts told at once that a machine's sharing changed. */
+const TELL_MAX = 2000
+
+const params = z.object({ machineId: z.string().refine(isMachineId, 'Invalid machineId') })
+const policyBody = z.object({
+ emails: z.array(z.string().trim().toLowerCase().email().max(254)).max(SHARE_EMAILS_MAX),
+ sameDomain: z.boolean(),
+}).strict()
+
+const normalized = (email: string): string => email.trim().toLowerCase()
+
+function ownedMachine(machineId: string, user: AuthUser) {
+ return prisma.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })
+}
+
+/** The policy as the owner's apps show it: `domain` is the owner's own, or null at a public domain, where
+ * "everyone at" is never offered. */
+async function policyView(share: MachineShare | null, user: AuthUser) {
+ const domain = emailDomain(user.email)
+ return {
+ emails: share?.emails ?? [], sameDomain: !!share?.domain,
+ domain: isPublicEmailDomain(domain) ? null : domain,
+ members: share ? await shareMembers(share) : [],
+ }
+}
+
+/**
+ * Everyone a change of the policy may add the machine to or take it from, their apps and daemons told to
+ * read their Machines again: the addresses before and after, everyone at the domain before and after, and
+ * whoever had added it. Best effort, like Share's `tellRecipient`: the policy is written already.
+ */
+async function tellAffected(machineId: string, ownerId: string, before: MachineShare | null, after: MachineShare | null): Promise<void> {
+ try {
+ const emails = [...new Set([...before?.emails ?? [], ...after?.emails ?? []])]
+ const domains = [...new Set([before?.domain, after?.domain].filter((d): d is string => !!d))]
+ const where = [...emails.length ? [{ email: { in: emails } }] : [], ...domains.map(d => ({ email: { endsWith: `@${d}` } }))]
+ const [users, adds] = await Promise.all([
+ where.length ? prisma.user.findMany({ where: { OR: where }, select: { id: true }, take: TELL_MAX }) : [],
+ prisma.machineShareAdd.findMany({ where: { machineId }, select: { userId: true }, take: TELL_MAX }),
+ ])
+ const ids = new Set([...users.map(u => u.id), ...adds.map(a => a.userId)])
+ ids.delete(ownerId)
+ await Promise.all([...ids].map(id => publishDeviceMachineListChanged(id, { reason: 'updated' })))
+ } catch (err) {
+ logger.warn('machine share: could not tell everyone it changed', { machineId, error: String(err) })
+ }
+}
+
+export async function machineShareRoutes(app: FastifyInstance): Promise<void> {
+ app.get<{ Params: z.infer<typeof params> }>('/api/machines/:machineId/share',
+ { preHandler: [validateParams(params)] }, async (req, reply) => {
+ const user = req.user!
+ if (!await ownedMachine(req.params.machineId, user)) return sendError(reply, 'Machine not found.', 'NOT_FOUND', 404)
+ const share = await prisma.machineShare.findUnique({ where: { machineId: req.params.machineId } })
+ sendSuccess(reply, await policyView(share && share.ownerId === user.sub ? share : null, user))
+ })
+
+ app.put<{ Params: z.infer<typeof params>; Body: z.infer<typeof policyBody> }>('/api/machines/:machineId/share',
+ { preHandler: [validateParams(params), validateBody(policyBody)] }, async (req, reply) => {
+ const user = req.user!
+ const { machineId } = req.params
+ if (!await ownedMachine(machineId, user)) return sendError(reply, 'Machine not found.', 'NOT_FOUND', 404)
+ const own = normalized(user.email)
+ // Any address may be named, at a public domain too: it names one person. Never the owner's own, and
+ // never a placeholder no one signs in with.
+ const emails = [...new Set(req.body.emails)].filter(email => email !== own && !email.endsWith('.invalid'))
+ let domain: string | null = null
+ if (req.body.sameDomain) {
+ domain = emailDomain(own)
+ if (isPublicEmailDomain(domain)) {
+ return sendError(reply, `Everyone at @${domain ?? 'your domain'} is not offered: it is a public email domain.`, 'PUBLIC_DOMAIN', 400)
+ }
+ }
+ const before = await prisma.machineShare.findUnique({ where: { machineId } })
+ let after: MachineShare | null = null
+ if (!emails.length && !domain) {
+ // Shared with no one: the row goes, and with it every colleague's add.
+ await prisma.machineShare.deleteMany({ where: { machineId } })
+ await prisma.machineShareAdd.deleteMany({ where: { machineId } })
+ } else {
+ const data = { ownerId: user.sub, autonomousEnv: user.autonomousEnv, emails, domain }
+ after = await prisma.machineShare.upsert({ where: { machineId }, create: { machineId, ...data }, update: data })
+ }
+ await publishMachineShareChanged(machineId).catch(() => 0)
+ await tellAffected(machineId, user.sub, before, after)
+ sendSuccess(reply, await policyView(after, user))
+ })
+
+ app.get('/api/machine-shares', async (req, reply) => {
+ sendSuccess(reply, { machines: await machinesSharedWith(req.user!) })
+ })
+
+ app.post<{ Params: z.infer<typeof params> }>('/api/machine-shares/:machineId/add',
+ { preHandler: [validateParams(params)] }, async (req, reply) => {
+ const user = req.user!
+ const { machineId } = req.params
+ const share = await prisma.machineShare.findUnique({ where: { machineId } })
+ const machine = share && share.ownerId !== user.sub && share.autonomousEnv === user.autonomousEnv
+ ? await prisma.machine.findFirst({ where: { machineId, userId: share.ownerId, autonomousEnv: user.autonomousEnv, ...machineAlive } })
+ : null
+ const via = share && machine ? sharedVia(share, user.email) : null
+ if (!share || !via) return sendError(reply, 'This machine is not shared with you.', 'NOT_SHARED', 404)
+ if (via === 'domain') {
+ await prisma.machineShareAdd.upsert({ where: { machineId_userId: { machineId, userId: user.sub } },
+ create: { machineId, userId: user.sub }, update: {} })
+ }
+ // The owner's daemon reads who uses the machine again and trusts this account's machines.
+ await Promise.all([share.ownerId, user.sub].map(id => publishDeviceMachineListChanged(id, { reason: 'updated' }))).catch(() => [])
+ sendSuccess(reply, { added: true })
+ })
+
+ app.delete<{ Params: z.infer<typeof params> }>('/api/machine-shares/:machineId/add',
+ { preHandler: [validateParams(params)] }, async (req, reply) => {
+ const user = req.user!
+ const { machineId } = req.params
+ const removed = await prisma.machineShareAdd.deleteMany({ where: { machineId, userId: user.sub } })
+ if (removed.count) {
+ const share = await prisma.machineShare.findUnique({ where: { machineId } })
+ await publishMachineShareChanged(machineId).catch(() => 0)
+ await Promise.all([...share ? [share.ownerId] : [], user.sub].map(id => publishDeviceMachineListChanged(id, { reason: 'updated' }))).catch(() => [])
+ }
+ sendSuccess(reply, { removed: removed.count > 0 })
+ })
+}
diff --git a/backend/src/routes/machines.ts b/backend/src/routes/machines.ts
index ae06f285c..532281fa8 100644
--- a/backend/src/routes/machines.ts
+++ b/backend/src/routes/machines.ts
@@ -15,6 +15,7 @@ import { storedAutonomousEnvironment } from '../lib/autonomousEnvironment.js'
import { env } from '../config/env.js'
import { probeProvider, ProviderProbeError } from '../lib/providerProbe.js'
import { normalizeComputerId } from '../lib/deviceAuth.js'
+import { machinesSharedWith } from '../lib/machineAccess.js'
const createBody = z.object({
// Defaults to the caller; admins may provision for another user.
@@ -295,10 +296,19 @@ export async function machineRoutes(app: FastifyInstance): Promise<void> {
},
)
- // List the caller's agent(s).
+ // List the caller's agent(s), and beside them the machines other accounts share with the caller
+ // (lib/machineAccess.ts). Those stay out of `machines`, which every client and daemon reads as the
+ // account's own; a client that knows them reads `sharedMachines`. Left out when they could not be
+ // read, so a client keeps the ones it had rather than dropping them for a moment.
app.get('/api/machines', async (req, reply) => {
- const bindings = await machineService.listForUser(req.user!.sub, req.user!.autonomousEnv)
- return sendSuccess(reply, { machines: bindings })
+ const [bindings, shared] = await Promise.all([
+ machineService.listForUser(req.user!.sub, req.user!.autonomousEnv),
+ machinesSharedWith(req.user!).catch((err: unknown) => {
+ logger.warn('shared machines could not be listed', { userId: req.user!.sub, error: String(err) })
+ return undefined
+ }),
+ ])
+ return sendSuccess(reply, { machines: bindings, ...(shared ? { sharedMachines: shared } : {}) })
})
// Canonical Remote-machine lookup for an authenticated Harness CLI. The computer id is stable
diff --git a/backend/src/server.ts b/backend/src/server.ts
index d25305632..37dfb7ae5 100644
--- a/backend/src/server.ts
+++ b/backend/src/server.ts
@@ -10,6 +10,7 @@ import { registerAuthMiddleware } from './middlewares/authMiddleware.js'
import { cursorRoutes } from './routes/cursor.js'
import { voiceRoutes } from './routes/voice.js'
import { harnessShareRoutes } from './routes/harnessShares.js'
+import { machineShareRoutes } from './routes/machineShares.js'
import { harnessLinkRoutes } from './routes/harnessLinks.js'
import { communityRoutes } from './routes/community.js'
import { communityTranslateRoutes } from './routes/communityTranslate.js'
@@ -178,6 +179,7 @@ async function start(): Promise<void> {
await app.register(deviceAuthRoutes) // device-authorization grant: how the desktop app gets a machine key
await app.register(storeRoutes) // the Harness Store's ratings and reviews; the catalogue is the CLI's registry
await app.register(harnessShareRoutes)
+ await app.register(machineShareRoutes)
await app.register(harnessLinkRoutes)
await app.register(communityRoutes)
await app.register(communityEditRoutes) // an author edits their publication in place
diff --git a/cli/AGENTS.md b/cli/AGENTS.md
index a5f1432b7..bf2a8a281 100644
--- a/cli/AGENTS.md
+++ b/cli/AGENTS.md
@@ -28,7 +28,7 @@ they show as `harnessd`, `harnessd-core` and `harnessd-<process>` (`src/harnessd
| engine-claude, engine-codex | history, last-turn readers, live transcript parsers, runtime profiles/catalogs, screen interpretation, submission verification readings, model control, question navigation, and (Codex) the shared app-server connection | on demand: an attach or read for that engine |
| search | session search | always |
| viewers | the harness viewers, their remote streams and rendered surfaces, and the Store | on demand: a harness here (an agent with a DSH at start, or attached since), a Store or viewers request (the list, an install, a harness's create or restore, a client's viewer stream or rendered frame), or at start when the release's own harnesses are to be put in place or an earlier process left viewer servers running |
-| edge | the shell service, workspaces, usage, the monitor, the project readers, the change-agent handoff, the recaps, the agent cleanup, Agent Messages (which runs no timer while it is off or the computer is signed out) | always |
+| edge | the shell service, workspaces, usage, the monitor, the project readers, the change-agent handoff, the recaps, the agent cleanup, Agent Messages (which runs no timer while it is off or the computer is signed out), shared machines (sharing this machine with other accounts, and pinning the machines shared with this one) | always |
| gateway | the relay and its E2EE (`src/gateway/`) | on demand: as the core starts when signed in or anything is paired here, or when something needs it (a pairing, a window's E2EE request, a key command, the Wi-Fi device) |
| models | grid, local models, the Model Manager | on demand: once grid is in use here (a managed grid, saved grid pictures, local models), or on a models request |
| updater | checks, downloads and stages a new build (`src/services/updaterProcess.ts`) | by the master, for the installed copy only |
diff --git a/cli/e2e/harness/fakeBackend.ts b/cli/e2e/harness/fakeBackend.ts
index fde14c216..ec699fce5 100644
--- a/cli/e2e/harness/fakeBackend.ts
+++ b/cli/e2e/harness/fakeBackend.ts
@@ -29,6 +29,12 @@
* - `PUT`/`DELETE /api/harness-links/:id` and `/api/harness-shares/:id`: Share publishing a link or an
* invitation, answered 200; what a node sends to one of Share's observers (`observer:` connections) is
* kept in `targeted`, so a test can open what Share sealed for it.
+ * - Machines of more than one account (`FakeMachine.account`, `email`), and a whole machine shared across
+ * them as the real backend does it (backend routes/machineShares.ts, lib/machineAccess.ts):
+ * `GET`/`PUT /api/machines/:id/share`, `GET /api/machine-shares`, `POST`/`DELETE /api/machine-shares/:id/add`,
+ * `sharedMachines` beside each account's own in `GET /api/machines`, and `machine_select` on the web socket
+ * allowed for a machine shared with the account. A change is `machines_changed` to the nodes it concerns,
+ * and a web socket on a machine no longer shared with its account is closed (4403).
*
* - The account's device key log, once a test turns it on (`enableDeviceLog`), as the real backend keeps
* it (backend lib/deviceKeyLog.ts): `GET /api/device-keys?since=`, a machine's `devlog_append` over its
@@ -61,8 +67,20 @@ export interface FakeMachine {
name: string
/** The access token this machine's daemon signs in with. */
token: string
+ /** The account it is on, FAKE_ACCOUNT unless a test says, and that account's address. */
+ account?: string
+ email?: string
+ /** Its E2EE identity, as its account's device key log would name it: what sharing hands the other side. */
+ pub?: string
}
+/** A whole machine its owner shares (backend `MachineShare`): addresses, and the owner's domain when on. */
+interface FakeShare { emails: string[]; domain: string | null }
+
+const accountOf = (machine: FakeMachine): string => machine.account ?? FAKE_ACCOUNT
+const emailOf = (machine: FakeMachine): string => machine.email ?? `${accountOf(machine)}@example.com`
+const domainOf = (email: string): string => email.slice(email.lastIndexOf('@') + 1)
+
type Frame = { type?: string; machineId?: string; agentId?: string; payload?: Record<string, unknown>; [key: string]: unknown }
/** One web socket (a phone, a browser): bound to at most one machine at a time, under one connection id. */
@@ -70,6 +88,8 @@ interface WebClient {
ws: WebSocket
connId: string
machineId: string | null
+ /** Who opened it: a machine's daemon (its account's), or a phone of FAKE_ACCOUNT. */
+ by: FakeMachine
}
/** One device socket: a commander on every machine of the account, one connection id per machine. */
@@ -118,6 +138,9 @@ export class FakeBackend {
deviceLog: { entries: DevLogEntry[]; state: DevLogState; acks: unknown[] } | null = null
/** Off: a backend from before acknowledgements — their routes answer 404. */
deviceAcks = true
+ /** Machines shared across accounts, by machine id, and who added one shared with their domain. */
+ readonly shares = new Map<string, FakeShare>()
+ readonly shareAdds = new Set<string>()
private constructor(private readonly server: Server, readonly port: number) {}
@@ -156,9 +179,10 @@ export class FakeBackend {
return
}
if (req.method === 'GET' && req.url?.split('?')[0] === '/api/machines') {
- res.end(json({ success: true, data: { machines: backend.rows() } }))
+ res.end(json({ success: true, data: { machines: backend.rows(accountOf(machine)), sharedMachines: backend.sharedRows(machine) } }))
return
}
+ if (backend.sharesRoute(req, res, machine)) return
if (req.method === 'GET' && req.url?.split('?')[0] === '/api/agent-messages' && backend.agentMessages) {
res.end(json({ success: true, data: backend.agentMessages }))
return
@@ -375,13 +399,112 @@ export class FakeBackend {
await new Promise<void>((done) => this.server.close(() => done()))
}
- private rows(): Array<Record<string, unknown>> {
- return [...this.machines.values()].map((m) => ({
+ private rows(account = FAKE_ACCOUNT): Array<Record<string, unknown>> {
+ return [...this.machines.values()].filter((m) => accountOf(m) === account).map((m) => ({
machineId: m.machineId, computerId: m.computerId, name: m.name, hostname: m.name,
status: this.online.get(m.machineId) ? 'running' : 'offline', authMode: 'remote',
}))
}
+ // ── machines shared across accounts ─────────────────────────────────────────────────────────
+
+ /** How `machineId`'s share reaches `who`: named, at the owner's domain, or not at all. */
+ private sharedVia(machineId: string, who: FakeMachine): 'email' | 'domain' | null {
+ const share = this.shares.get(machineId)
+ const owner = this.machines.get(machineId)
+ if (!share || !owner || accountOf(owner) === accountOf(who)) return null
+ const email = emailOf(who)
+ if (share.emails.includes(email)) return 'email'
+ return share.domain && domainOf(email) === share.domain ? 'domain' : null
+ }
+
+ /** Whether `who` may select `machineId`: its account's own, or shared with it (a domain share once added). */
+ mayUse(machineId: string, who: FakeMachine): boolean {
+ const target = this.machines.get(machineId)
+ if (!target) return false
+ if (accountOf(target) === accountOf(who)) return true
+ const via = this.sharedVia(machineId, who)
+ return via === 'email' || (via === 'domain' && this.shareAdds.has(`${machineId}:${accountOf(who)}`))
+ }
+
+ private sharedRows(who: FakeMachine): Array<Record<string, unknown>> {
+ return [...this.machines.values()].flatMap((m) => {
+ const via = this.sharedVia(m.machineId, who)
+ if (!via) return []
+ return [{ machineId: m.machineId, name: m.name, hostname: m.name, authMode: 'remote', pub: m.pub ?? null,
+ status: this.online.get(m.machineId) ? 'running' : 'offline',
+ share: { ownerName: accountOf(m), ownerEmail: emailOf(m), via, added: this.mayUse(m.machineId, who) } }]
+ })
+ }
+
+ /** The accounts that may use `machineId` now, with their machines' keys: what its daemon trusts. */
+ private shareMembers(machineId: string): Array<Record<string, unknown>> {
+ const accounts = new Map<string, FakeMachine[]>()
+ for (const m of this.machines.values()) {
+ if (!this.mayUse(machineId, m) || accountOf(m) === accountOf(this.machines.get(machineId)!)) continue
+ accounts.set(accountOf(m), [...accounts.get(accountOf(m)) ?? [], m])
+ }
+ return [...accounts.values()].map((ms) => ({
+ email: emailOf(ms[0]), name: accountOf(ms[0]), via: this.sharedVia(machineId, ms[0]),
+ machines: ms.filter((m) => m.pub).map((m) => ({ machineId: m.machineId, name: m.name, pub: m.pub })),
+ }))
+ }
+
+ /** `machines_changed` to every node of every account, and a web socket that may no longer use its machine closed. */
+ private sharesChanged(): void {
+ for (const machineId of this.nodes.keys()) this.sendNode(machineId, '', { type: 'machines_changed', payload: { reason: 'updated' } })
+ for (const client of this.webClients) if (client.machineId && !this.mayUse(client.machineId, client.by)) client.ws.close(4403, 'Sharing ended')
+ }
+
+ /** The share routes; false when the request is not one of them. */
+ private sharesRoute(req: IncomingMessage, res: import('node:http').ServerResponse, who: FakeMachine): boolean {
+ const path = req.url?.split('?')[0] ?? ''
+ const policy = /^\/api\/machines\/([^/]+)\/share$/.exec(path)
+ const add = /^\/api\/machine-shares\/([^/]+)\/add$/.exec(path)
+ if (req.method === 'GET' && path === '/api/machine-shares') {
+ res.end(json({ success: true, data: { machines: this.sharedRows(who) } }))
+ return true
+ }
+ if (policy && (req.method === 'GET' || req.method === 'PUT')) {
+ const machineId = policy[1]
+ const owned = this.machines.get(machineId)
+ if (!owned || accountOf(owned) !== accountOf(who)) { res.statusCode = 404; res.end(json({ success: false, error: { code: 'NOT_FOUND' } })); return true }
+ const view = (): Record<string, unknown> => {
+ const share = this.shares.get(machineId)
+ return { emails: share?.emails ?? [], sameDomain: !!share?.domain, domain: domainOf(emailOf(who)), members: share ? this.shareMembers(machineId) : [] }
+ }
+ if (req.method === 'GET') { res.end(json({ success: true, data: view() })); return true }
+ let raw = ''
+ req.on('data', (chunk) => { raw += chunk })
+ req.on('end', () => {
+ const body = JSON.parse(raw || '{}') as { emails?: string[]; sameDomain?: boolean }
+ const emails = (body.emails ?? []).map((e) => e.trim().toLowerCase()).filter((e) => e !== emailOf(who))
+ if (!emails.length && !body.sameDomain) {
+ this.shares.delete(machineId)
+ for (const key of [...this.shareAdds]) if (key.startsWith(`${machineId}:`)) this.shareAdds.delete(key)
+ } else this.shares.set(machineId, { emails, domain: body.sameDomain ? domainOf(emailOf(who)) : null })
+ res.end(json({ success: true, data: view() }))
+ this.sharesChanged()
+ })
+ return true
+ }
+ if (add && (req.method === 'POST' || req.method === 'DELETE')) {
+ const machineId = add[1]
+ const key = `${machineId}:${accountOf(who)}`
+ if (req.method === 'POST') {
+ if (!this.sharedVia(machineId, who)) { res.statusCode = 404; res.end(json({ success: false, error: { code: 'NOT_SHARED', message: 'This machine is not shared with you.' } })); return true }
+ this.shareAdds.add(key)
+ res.end(json({ success: true, data: { added: true } }))
+ } else {
+ const removed = this.shareAdds.delete(key)
+ res.end(json({ success: true, data: { removed } }))
+ }
+ this.sharesChanged()
+ return true
+ }
+ return false
+ }
+
private statuses(): Array<{ machineId: string; online: boolean }> {
return [...this.machines.keys()].map((machineId) => ({ machineId, online: this.online.get(machineId) === true }))
}
@@ -407,7 +530,7 @@ export class FakeBackend {
if (this.down) { refuse(503, 'Service Unavailable'); return }
if (!machine) { refuse(401, 'Unauthorized'); return }
if (url.pathname === '/api/web-ws') {
- this.wss.handleUpgrade(req, socket, head, (ws) => this.attachWeb(ws))
+ this.wss.handleUpgrade(req, socket, head, (ws) => this.attachWeb(ws, machine))
return
}
if (!machine.machineId) { refuse(403, 'Forbidden'); return }
@@ -505,10 +628,10 @@ export class FakeBackend {
// ── web clients (phones, browsers) ───────────────────────────────────────────────────────────
- private attachWeb(ws: WebSocket): void {
- const client: WebClient = { ws, connId: randomUUID(), machineId: null }
+ private attachWeb(ws: WebSocket, by: FakeMachine): void {
+ const client: WebClient = { ws, connId: randomUUID(), machineId: null, by }
this.webClients.add(client)
- ws.send(json({ type: 'connected', payload: { userId: 'e2e-user' } }))
+ ws.send(json({ type: 'connected', payload: { userId: accountOf(by) } }))
ws.on('message', (raw, binary) => {
if (binary) this.fromWebBinary(client, raw)
else this.fromWeb(client, raw)
@@ -528,7 +651,7 @@ export class FakeBackend {
if (type.startsWith('__')) return
if (type === 'machine_select') {
const machineId = String(frame.payload?.machineId ?? '')
- if (!this.machines.has(machineId)) {
+ if (!this.mayUse(machineId, client.by)) {
client.ws.send(json({ type: 'machine_select_error', payload: { machineId, error: 'NOT_YOUR_MACHINE' } }))
return
}
diff --git a/cli/e2e/sharedMachines.e2e.ts b/cli/e2e/sharedMachines.e2e.ts
new file mode 100644
index 000000000..64716ea8e
--- /dev/null
+++ b/cli/e2e/sharedMachines.e2e.ts
@@ -0,0 +1,120 @@
+/**
+ * A machine shared across accounts (docs/plans/2026-10-15-share-machine-plan.md), end to end: two real
+ * daemons on two accounts at one domain, signed in to the fake backend (harness/fakeBackend.ts).
+ *
+ * Dee shares her machine with everyone at acme.io; Kim, at acme.io on another account, adds it. Kim's
+ * daemon then pins Dee's machine and Dee's daemon trusts Kim's (services/sharedMachines.ts, through the
+ * gateway: gateway/sharedTrust.ts), so a window on Kim's computer reaches Dee's machine through the relay,
+ * end to end encrypted, with the owner's rights. Neither joins the other's trust group. Dee stopping
+ * sharing ends the session and takes the trust back on both sides.
+ */
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import WebSocket from 'ws'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { b64e, newIdentity } from '../src/lib/e2ee/core.js'
+import { LocalClient } from './harness/client.js'
+import { until, type IsolatedDaemon } from './harness/daemon.js'
+import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'
+import { signedInDaemon, writeE2ee } from './harness/fleet.js'
+
+/** What a window's `machine_select` of `machineId` through `daemon` comes to: connected, or the code it was closed with. */
+async function select(daemon: IsolatedDaemon, machineId: string): Promise<'connected' | number> {
+ const ws = new WebSocket(`ws+unix://${daemon.socketPath}:/api/local-ws`)
+ return new Promise((resolve) => {
+ ws.on('open', () => ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } })))
+ ws.on('message', (raw) => {
+ if ((JSON.parse(raw.toString()) as { type?: string }).type !== 'connected') return
+ resolve('connected')
+ ws.close()
+ })
+ ws.on('close', (code) => resolve(code))
+ ws.on('error', () => resolve(-1))
+ })
+}
+
+function e2eFile(daemon: IsolatedDaemon, name: string): unknown[] {
+ try { return JSON.parse(readFileSync(join(daemon.dataDir, 'e2e', name), 'utf-8')) as unknown[] } catch { return [] }
+}
+const roster = (daemon: IsolatedDaemon): string => {
+ try { return readFileSync(join(daemon.dataDir, 'e2e', 'group.json'), 'utf-8') } catch { return '' }
+}
+
+describe('a machine shared across accounts', () => {
+ let backend: FakeBackend | null = null
+ const daemons: IsolatedDaemon[] = []
+ const clients: LocalClient[] = []
+ afterEach(async () => {
+ for (const client of clients.splice(0)) client.close()
+ await Promise.allSettled(daemons.splice(0).map((daemon) => daemon.close()))
+ await backend?.close()
+ backend = null
+ })
+
+ it('is reached from a colleague’s computer once shared and added, with the owner’s rights, and no longer once sharing stops', async () => {
+ backend = await FakeBackend.start()
+ const specs = [
+ { machineId: 'd1'.repeat(16), computerId: 'e2e-computer-0000-0000-0000000000d1', name: 'dee-studio', token: 'e2e-token-dee', account: 'dee', email: '[email protected]', identity: newIdentity() },
+ { machineId: 'c2'.repeat(16), computerId: 'e2e-computer-0000-0000-0000000000c2', name: 'kim-mac', token: 'e2e-token-kim', account: 'kim', email: '[email protected]', identity: newIdentity() },
+ ]
+ for (const spec of specs) {
+ const machine: FakeMachine = { ...spec, pub: b64e(spec.identity.pub) }
+ backend.addMachine(machine)
+ const daemon = await signedInDaemon(backend, machine)
+ daemons.push(daemon)
+ await writeE2ee(daemon, { 'identity.json': { priv: b64e(spec.identity.priv), pub: b64e(spec.identity.pub) } })
+ }
+ const [dee, kim] = daemons
+ const [deeSpec, kimSpec] = specs
+ onTestFailed(() => {
+ console.log(`---- Dee's daemon\n${dee.log().split('\n').slice(-80).join('\n')}`)
+ console.log(`---- Kim's daemon\n${kim.log().split('\n').slice(-80).join('\n')}`)
+ })
+ await Promise.all(daemons.map((daemon) => daemon.start()))
+ await until('both machines on the relay', () => backend!.nodeUp(deeSpec.machineId) && backend!.nodeUp(kimSpec.machineId), 30_000)
+
+ // Not shared: Kim's computer has no way to Dee's machine.
+ expect(await select(kim, deeSpec.machineId)).toBe(4404)
+
+ // Dee shares it with everyone at acme.io, from her own window.
+ const onDee = await LocalClient.connect(dee, { machineId: deeSpec.machineId })
+ clients.push(onDee)
+ expect(await onDee.request('shared_machines', { action: 'set', emails: [], sameDomain: true }, 30_000))
+ .toMatchObject({ emails: [], sameDomain: true, domain: 'acme.io', members: [] })
+ // Listed to Kim, not yet added: still no way there.
+ const onKim = await LocalClient.connect(kim, { machineId: kimSpec.machineId })
+ clients.push(onKim)
+ expect(await select(kim, deeSpec.machineId)).toBe(4404)
+
+ // Kim adds it. Her daemon pins Dee's machine; Dee's, told by the backend, trusts Kim's.
+ expect(await onKim.request('shared_machines', { action: 'add', machineId: deeSpec.machineId }, 30_000)).toMatchObject({ ok: true })
+ await until('Dee’s machine pinned on Kim’s', () => e2eFile(kim, 'machinePeers.json')
+ .some((p) => (p as { machineId: string; shared?: boolean }).machineId === deeSpec.machineId && (p as { shared?: boolean }).shared === true) || null, 30_000)
+ await until('Kim’s machine trusted on Dee’s', () => e2eFile(dee, 'paired.json')
+ .some((p) => (p as { identityPub: string; shared?: boolean }).identityPub === b64e(kimSpec.identity.pub) && (p as { shared?: boolean }).shared === true) || null, 30_000)
+
+ // A window on Kim's computer works on Dee's machine, with the owner's rights: the sharing itself reads.
+ const viaKim = await LocalClient.connect(kim, { machineId: deeSpec.machineId })
+ clients.push(viaKim)
+ expect((await viaKim.request<{ agents?: unknown[] }>('agents_list', {}, 30_000)).agents).toEqual(expect.any(Array))
+ expect(await viaKim.request('shared_machines', { action: 'get' }, 30_000)).toMatchObject({
+ sameDomain: true, members: [{ email: '[email protected]', via: 'domain', machines: 1 }] })
+ // Sealed end to end: the relay saw the outer type and never what was in it.
+ const relayed = [...backend.webSent.values()].flat().filter((frame) => frame.type === 'agents_list' || frame.type === 'shared_machines')
+ expect(relayed.length).toBeGreaterThanOrEqual(2)
+ expect(relayed.every((frame) => !!(frame.payload as { __e2e?: unknown } | undefined)?.__e2e)).toBe(true)
+
+ // Neither account's trust group took in the other's machine.
+ expect(roster(dee)).not.toContain(b64e(kimSpec.identity.pub))
+ expect(roster(kim)).not.toContain(b64e(deeSpec.identity.pub))
+
+ // Dee stops sharing: Kim's session ends, and the trust goes on both sides.
+ expect(await onDee.request('shared_machines', { action: 'set', emails: [], sameDomain: false }, 30_000)).toMatchObject({ sameDomain: false })
+ await until('Kim’s window on Dee’s machine closed', () => viaKim.closed || null, 30_000)
+ await until('Kim’s machine untrusted on Dee’s', () => !e2eFile(dee, 'paired.json')
+ .some((p) => (p as { identityPub: string }).identityPub === b64e(kimSpec.identity.pub)) || null, 30_000)
+ await until('Dee’s machine unpinned on Kim’s', () => !e2eFile(kim, 'machinePeers.json')
+ .some((p) => (p as { machineId: string }).machineId === deeSpec.machineId) || null, 30_000)
+ expect(await select(kim, deeSpec.machineId)).not.toBe('connected')
+ }, 240_000)
+})
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 444098559..67c48490b 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -3,6 +3,7 @@ import type { ProductUsageMetric } from '../lib/productUsageContract.js'
import type { PreparedHandoff, HandoffPermit, HandoffOutcome } from '../lib/handoffAuthority.js'
import type { AgentTokenUsage, AgentUsageTarget } from '../lib/agentUsageWire.js'
import type { CloudHarness } from '../lib/cloudAgents.js'
+import type { SharedTrustPeer } from '../lib/sharedMachinesPort.js'
import type { GridAssignmentProcess, GridAssignmentAnswer } from '../lib/gridAssignmentWire.js'
/**
* The boundary the services stand on (docs/design/2026-10-03-harnessd.md, "The core boundary"):
@@ -523,6 +524,9 @@ export const WINDOW_NAMES_REQUESTS = ['window_name'] as const
export const HANDOFF_REQUESTS = ['agent_handoff_prepare'] as const
/** Connected services for every local agent, and their MCP bridge, in the edge host (services/connectors.ts). */
export const CONNECTORS_REQUESTS = ['connectors'] as const
+/** Sharing this machine with other accounts, and adding machines shared with this one, in the edge host
+ * (services/sharedMachines.ts). */
+export const SHARED_MACHINES_REQUESTS = ['shared_machines'] as const
/** A Harness OS computer managed from the owner's phone: whether it runs Harness OS, its update, and its Wi-Fi,
* in the edge host (services/osDevice.ts). */
export const OS_DEVICE_REQUESTS = ['os_device'] as const
@@ -1390,8 +1394,13 @@ export interface GatewayOps {
observerKey: ObserverKey
/** The account's connected services sealed for its machines (`core.account.connectorVault`). */
connectorVault: ConnectorVault
+ /** Machines shared across accounts, made to hold exactly what the shared-machines service says
+ * (gateway/sharedTrust.ts): the ones shared with this account pinned, the machines of the accounts this
+ * one is shared with trusted; a part left out stays as it is. Answers how many of each it holds. */
+ sharedTrust(desired: { pins?: SharedTrustPeer[]; keys?: SharedTrustPeer[] }): Promise<{ pins: number; keys: number }>
}
+
/** A window on this computer working on another of the owner's machines, through the relay: what the
* local socket asks of the gateway for it (lib/remoteRelay.ts `RemoteRelayPool`, or its link). */
export interface WindowRelaySession {
diff --git a/cli/src/core/gatewayLink.spec.ts b/cli/src/core/gatewayLink.spec.ts
index 70b13d001..0bca113a2 100644
--- a/cli/src/core/gatewayLink.spec.ts
+++ b/cli/src/core/gatewayLink.spec.ts
@@ -380,6 +380,19 @@ describe('the gateway in its own process, as the core sees it', () => {
expect(await link.ops.connectorVault.open({})).toBeNull()
})
+ it('asks the gateway to hold what sharing trusts, and says it could not while the gateway is not running', async () => {
+ let answer: Record<string, unknown> = { pins: 1, keys: 2 }
+ const { link, call } = setup({ call: async () => answer })
+ expect(await link.ops.sharedTrust({ pins: [], keys: [] })).toEqual({ pins: 1, keys: 2 })
+ expect(call).toHaveBeenLastCalledWith(GATEWAY_CALLS.sharedTrust, { pins: [], keys: [] }, LANE_WAIT_MS)
+ answer = { error: 'stores unwritable' }
+ await expect(link.ops.sharedTrust({})).rejects.toThrow('stores unwritable')
+ for (const error of ['SERVICE_UNAVAILABLE', undefined]) {
+ answer = error ? { error } : {}
+ await expect(link.ops.sharedTrust({})).rejects.toThrow(/not running/)
+ }
+ })
+
it('carries the fleet\'s lane to the gateway\'s sessions, every step a call in order, and never a frame back unsealed', async () => {
let answer: Record<string, unknown> = {}
const { link, call } = setup({ call: async () => answer })
diff --git a/cli/src/core/gatewayLink.ts b/cli/src/core/gatewayLink.ts
index 9d0ca011b..09ed0fccf 100644
--- a/cli/src/core/gatewayLink.ts
+++ b/cli/src/core/gatewayLink.ts
@@ -334,6 +334,12 @@ export function createGatewayLink(deps: GatewayLinkDeps) {
return typeof answer.plaintext === 'string' ? { plaintext: answer.plaintext, complete: answer.complete === true } : null
},
},
+ // Machines shared across accounts, pinned and trusted by the gateway (gateway/sharedTrust.ts).
+ sharedTrust: async (desired) => {
+ const answer = await deps.call(GATEWAY_CALLS.sharedTrust, { ...desired }, LANE_WAIT_MS)
+ if (typeof answer.pins === 'number' && typeof answer.keys === 'number') return { pins: answer.pins, keys: answer.keys }
+ throw new Error(typeof answer.error === 'string' && !answer.error.startsWith('SERVICE_') ? answer.error : 'the gateway is not running')
+ },
}
/** A window's session through the gateway: to another of the owner's machines, or to a harness shared
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index fab09776b..8e76bee02 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -167,7 +167,7 @@ import { createEngineHooks, installEngineHooks, installOpencodePluginBeforeSpawn
import { createCursorDiscovery } from './engines/cursorDiscovery.js'
import { createCursorTaskHooks, loadPendingCursorTasks } from './engines/cursorTasks.js'
import { databaseHistory, hermesDb } from './transcripts/databaseHistory.js'
-import { CLOUD_FALLBACKS, CLOUD_REQUESTS, type CloudCore, CONNECTORS_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, OS_DEVICE_REQUESTS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, MESSAGES_FALLBACKS, MESSAGES_REQUESTS, TURN_DELIVERERS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type WindowFocus } from './api.js'
+import { CLOUD_FALLBACKS, CLOUD_REQUESTS, type CloudCore, CONNECTORS_REQUESTS, SHARED_MACHINES_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, OS_DEVICE_REQUESTS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, MESSAGES_FALLBACKS, MESSAGES_REQUESTS, TURN_DELIVERERS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type WindowFocus } from './api.js'
import { createServiceHost, testFaults } from './serviceHost.js'
import { startStalls } from './stall.js'
import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'
@@ -187,6 +187,8 @@ import { createSharingLink } from './sharingLink.js'
import { createAgentSettingsSync, createExperimentHooks, wakeExperiments } from './experiments.js'
import { answerExperimentQuery, createForExperiment } from './experimentQueries.js'
import { answerConnectorsQuery } from './connectorsQueries.js'
+import { answerSharedMachinesQuery } from './sharedMachinesQueries.js'
+import { inlineSharedMachinesPort } from '../lib/sharedMachinesPort.js'
import { createOrchestratorLink } from './orchestratorLink.js'
import { daemonCommand } from '../lib/daemonCommand.js'
import { KNOWN_SERVICES, masterRunsEngineRuntime, masterRunsLiveEngines, servicesTheMasterRuns } from '../harnessd/services.js'
@@ -1292,7 +1294,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The requests each service that can run in its own process answers, as core/api.ts declares them.
const requestsOf: Record<string, readonly string[]> = {
- search: SEARCH_REQUESTS, store: STORE_REQUESTS, usage: USAGE_REQUESTS, monitor: MONITOR_REQUESTS, projects: PROJECTS_REQUESTS, models: MODELS_REQUESTS, handoff: HANDOFF_REQUESTS, connectors: CONNECTORS_REQUESTS,
+ search: SEARCH_REQUESTS, store: STORE_REQUESTS, usage: USAGE_REQUESTS, monitor: MONITOR_REQUESTS, projects: PROJECTS_REQUESTS, models: MODELS_REQUESTS, handoff: HANDOFF_REQUESTS, connectors: CONNECTORS_REQUESTS, sharedMachines: SHARED_MACHINES_REQUESTS,
devices: DEVICES_REQUESTS, windowNames: WINDOW_NAMES_REQUESTS, shell: SHELL_REQUESTS, messages: MESSAGES_REQUESTS, osDevice: OS_DEVICE_REQUESTS,
...Object.fromEntries(Object.entries(EXPERIMENTS).map(([name, experiment]) => [name, experiment.requests])),
}
@@ -1324,6 +1326,17 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if ((notice.type === 'connectors_changed' || notice.type === 'device_keys_changed') && outOfProcess.has('connectors')) {
serviceLinks.notify('connectors', { type: 'service_event', payload: { kind: 'notice', notice } })
}
+ // Shared machines read who uses this machine, and which machines are shared with this account, again
+ // (services/sharedMachines.ts): someone added it, or the sharing of one changed.
+ if (notice.type === 'machines_changed' && outOfProcess.has('sharedMachines')) {
+ serviceLinks.notify('sharedMachines', { type: 'service_event', payload: { kind: 'notice', notice } })
+ }
+ }
+ // What shared machines in their own process reach through the core: this machine's sharing on the
+ // backend, signed in here, and the gateway's trust stores (core/sharedMachinesQueries.ts).
+ const sharedMachinesAccount = {
+ backend: coreApi.account.backend, machineId: () => coreApi.daemon.machineId(),
+ trust: (desired: Parameters<typeof gatewayOps.sharedTrust>[0]) => gatewayOps.sharedTrust(desired),
}
// What the Store in its own process tells the core: an install's progress, and that what is installed changed (core/storeLink.ts).
const storeLink = createStoreLink(coreApi, invalidateInstalledDsh, (type, payload) => serviceLinks.call('store', type, payload))
@@ -1370,6 +1383,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Agent Messages is answered what it uses and nothing more, never what an experiment may ask (core/messagesLink.ts).
?? (service === 'messages' ? await messagesLink.answer(query, payload) : null)
?? await answerConnectorsQuery(coreApi, service, query, payload)
+ ?? await answerSharedMachinesQuery(sharedMachinesAccount, service, query, payload)
?? await answerExperimentQuery(coreApi, experiments, service, query, payload)
?? await terminalWatch.answer(service, query, payload)
?? (service === 'orchestrator' ? orchestratorLink.answer(query, payload) : null)
@@ -1504,6 +1518,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (!outOfProcess.has('handoff')) serviceHost.serve('handoff', inline!.startHandoff, coreApi, HANDOFF_REQUESTS)
// Connected services' MCP bridge and the Connectors screen (services/connectors.ts): here, or in the edge host.
if (!outOfProcess.has('connectors')) serviceHost.serve('connectors', inline!.startConnectors, coreApi, CONNECTORS_REQUESTS)
+ // Sharing this machine with other accounts, and the machines shared with this one (services/sharedMachines.ts).
+ if (!outOfProcess.has('sharedMachines')) serviceHost.serve('sharedMachines', (core) => inline!.startSharedMachines(core,
+ { port: inlineSharedMachinesPort(sharedMachinesAccount, core.account.signedIn()) }), coreApi, SHARED_MACHINES_REQUESTS)
// A Harness OS computer managed from the owner's phone: its update and its Wi-Fi (services/osDevice.ts): here, or in the edge host.
if (!outOfProcess.has('osDevice')) serviceHost.serve('osDevice', inline!.startOsDevice, coreApi, OS_DEVICE_REQUESTS)
// The recaps: in this process, or in the edge host (services/recapsProcess.ts), told each turn's lifecycle.
diff --git a/cli/src/core/sharedMachinesQueries.spec.ts b/cli/src/core/sharedMachinesQueries.spec.ts
new file mode 100644
index 000000000..d1a11ade0
--- /dev/null
+++ b/cli/src/core/sharedMachinesQueries.spec.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it, vi } from 'vitest'
+import { answerSharedMachinesQuery } from './sharedMachinesQueries.js'
+
+describe('what the shared-machines service may ask of the core', () => {
+ const account = {
+ backend: vi.fn(async (method: string, path: string) => ({ status: 200, body: { method, path } })),
+ machineId: () => 'ab'.repeat(16),
+ trust: vi.fn(async () => ({ pins: 0, keys: 0 })),
+ }
+
+ it('answers shared_machines for the shared-machines service alone', async () => {
+ expect(await answerSharedMachinesQuery(account, 'sharedMachines', 'shared_machines', { op: 'shared' }))
+ .toEqual({ status: 200, body: { method: 'GET', path: '/api/machine-shares' } })
+ expect(await answerSharedMachinesQuery(account, 'connectors', 'shared_machines', { op: 'shared' })).toBeNull()
+ expect(await answerSharedMachinesQuery(account, 'sharedMachines', 'backend', { op: 'shared' })).toBeNull()
+ })
+})
diff --git a/cli/src/core/sharedMachinesQueries.ts b/cli/src/core/sharedMachinesQueries.ts
new file mode 100644
index 000000000..e14c12b34
--- /dev/null
+++ b/cli/src/core/sharedMachinesQueries.ts
@@ -0,0 +1,17 @@
+/**
+ * What the shared-machines service in its own process may ask of the core (`service_query`,
+ * core/serviceLinks.ts): `shared_machines`, with an `op` of `policy` and `publish` (this machine's sharing,
+ * as the backend holds it), `shared` (the machines shared with this account), `add` and `remove` (a domain
+ * share), all signed in by the core, and `trust`, the gateway's trust stores (gateway/sharedTrust.ts).
+ * Only the shared-machines service is answered; it reaches no other path of the backend this way
+ * (lib/sharedMachinesPort.ts).
+ */
+import { answerSharedMachinesOp, type SharedMachinesAccount } from '../lib/sharedMachinesPort.js'
+
+type Payload = Record<string, unknown>
+
+/** The answer to the shared-machines service's query, or null when it is not one. */
+export async function answerSharedMachinesQuery(account: SharedMachinesAccount, service: string, query: string, payload: Payload): Promise<Payload | null> {
+ if (query !== 'shared_machines' || service !== 'sharedMachines') return null
+ return answerSharedMachinesOp(account, payload)
+}
diff --git a/cli/src/gateway/gatewayProcess.spec.ts b/cli/src/gateway/gatewayProcess.spec.ts
index 715a93dcf..b5dc24733 100644
--- a/cli/src/gateway/gatewayProcess.spec.ts
+++ b/cli/src/gateway/gatewayProcess.spec.ts
@@ -48,6 +48,10 @@ function stubGateway() {
seal: vi.fn(async (plaintext: string) => { if (!plaintext) throw new Error('nothing to seal'); return { sealed: plaintext } }),
open: vi.fn(async (envelope: unknown) => ((envelope as { sealed?: string })?.sealed ? { plaintext: (envelope as { sealed: string }).sealed, complete: true } : null)),
},
+ sharedTrust: vi.fn(async (desired: { pins?: unknown[]; keys?: unknown[] }) => {
+ if (desired.pins?.length === 0 && desired.keys?.length === 0) throw new Error('stores unwritable')
+ return { pins: desired.pins?.length ?? -1, keys: desired.keys?.length ?? -1 }
+ }),
} satisfies GatewayOps
const sessions: Array<{ send: ReturnType<typeof vi.fn>; sendBinary: ReturnType<typeof vi.fn>; detach: ReturnType<typeof vi.fn> }> = []
const windowRelay = {
@@ -319,6 +323,21 @@ describe('the gateway\'s process, spoken to by the core', () => {
expect(await w.options().requests[GATEWAY_CALLS.connectorVault]({ op: 'nothing' }, { local: true, owner: true })).toEqual({ error: 'UNKNOWN_OP' })
})
+ it('makes the trust stores hold what sharing asks, only the parts it sent, valid peers only', async () => {
+ const w = wire()
+ const trust = w.link.ops.sharedTrust
+ await expect(trust({ pins: [] })).rejects.toThrow(/not started|not running/)
+ w.connect()
+ const peer = { machineId: 'a'.repeat(32), pub: Buffer.alloc(32, 1).toString('base64'), label: 'Studio' }
+ expect(await trust({ pins: [peer, { machineId: '../x', pub: 'bad', label: '' }] })).toEqual({ pins: 1, keys: -1 })
+ expect(w.gateways[0].ops.sharedTrust).toHaveBeenLastCalledWith({ pins: [peer] })
+ expect(await trust({ keys: [peer] })).toEqual({ pins: -1, keys: 1 })
+ expect(w.gateways[0].ops.sharedTrust).toHaveBeenLastCalledWith({ keys: [peer] })
+ await expect(trust({ pins: [], keys: [] })).rejects.toThrow('stores unwritable')
+ w.gateways[0].ops.sharedTrust.mockRejectedValueOnce('odd')
+ await expect(trust({})).rejects.toThrow('odd')
+ })
+
it('opens a window\'s session on another machine, carries it both ways, and fails it as the pool did', async () => {
const w = wire()
w.connect()
diff --git a/cli/src/gateway/gatewayProcess.ts b/cli/src/gateway/gatewayProcess.ts
index ba0171478..25099483b 100644
--- a/cli/src/gateway/gatewayProcess.ts
+++ b/cli/src/gateway/gatewayProcess.ts
@@ -20,6 +20,7 @@ import { decodeTerminalLocal, encodeTerminalLocal } from '../lib/terminalBinary.
import { accountLink } from '../services/accountLink.js'
import { runServiceProcess, type CoreConnection, type ServiceProcess } from '../services/process.js'
import { startGateway, type StartedGateway } from './start.js'
+import { sharedPeers } from './sharedTrust.js'
type Payload = Record<string, unknown>
@@ -255,6 +256,14 @@ export function runGatewayService(options: GatewayServiceOptions): ServiceProces
return { error: error instanceof Error ? error.message : String(error) }
}
},
+ // Machines shared across accounts (gateway/sharedTrust.ts): the stores made to hold what was asked.
+ [GATEWAY_CALLS.sharedTrust]: async (p: Payload): Promise<Payload> => {
+ try {
+ return { ...await ops().sharedTrust({ ...(p.pins !== undefined ? { pins: sharedPeers(p.pins) } : {}), ...(p.keys !== undefined ? { keys: sharedPeers(p.keys) } : {}) }) }
+ } catch (error) {
+ return { error: error instanceof Error ? error.message : String(error) }
+ }
+ },
// The account's connected services (lib/e2ee/connectorVault.ts): an envelope sealed, or one opened.
[GATEWAY_CALLS.connectorVault]: async (p: Payload): Promise<Payload> => {
const vault = ops().connectorVault
diff --git a/cli/src/gateway/sharedTrust.spec.ts b/cli/src/gateway/sharedTrust.spec.ts
new file mode 100644
index 000000000..422ed0c12
--- /dev/null
+++ b/cli/src/gateway/sharedTrust.spec.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it, vi } from 'vitest'
+import { applySharedTrust, isSharedKey, sharedPeers, SHARED_TRUST_MAX, type SharedTrustDeps } from './sharedTrust.js'
+import type { PairedClient } from '../lib/e2ee/store.js'
+import type { LinkedPeer } from '../lib/e2ee/manager.js'
+
+const key = (n: number) => Buffer.alloc(32, n).toString('base64')
+const id = (c: string) => c.repeat(32)
+type Pin = { machineId: string; pub: string; label: string; linkedAt: number; shared?: true }
+
+function stores(pins: Pin[] = [], paired: PairedClient[] = []) {
+ const held = new Map(pins.map((p) => [p.machineId, p]))
+ const trusted = new Map(paired.map((p) => [p.identityPub, p]))
+ const deps: SharedTrustDeps = {
+ peers: {
+ get: (machineId) => held.get(machineId) ?? null,
+ pin: vi.fn((machineId: string, pub: string, label: string, at = 0, shared = false) => {
+ held.set(machineId, { machineId, pub, label, linkedAt: at, ...(shared ? { shared: true as const } : {}) })
+ }),
+ unlink: vi.fn((machineId: string) => held.delete(machineId)),
+ list: () => [...held.values()].map((p) => ({ ...p, fingerprint: 'fp' })),
+ },
+ paired: () => [...trusted.values()],
+ trust: vi.fn((peer: LinkedPeer) => {
+ trusted.set(peer.pub, { identityPub: peer.pub, label: peer.label, pairedAt: 1, role: 'web', machineId: peer.machineId, kind: peer.kind,
+ ...(peer.shared ? { shared: true as const } : {}) })
+ }),
+ untrust: vi.fn((pub: string) => { trusted.delete(pub) }),
+ dropSessions: vi.fn(),
+ selfPub: () => key(99),
+ }
+ return { deps, held, trusted }
+}
+
+describe('sharedPeers', () => {
+ it('keeps valid peers once each, trims labels, and caps the list', () => {
+ const good = { machineId: id('a'), pub: key(1), label: 'x'.repeat(200) }
+ expect(sharedPeers([good, { ...good }, { ...good, machineId: id('b') }, { machineId: '../m', pub: key(2) }, { machineId: id('c'), pub: 'short' },
+ null, 'text', { machineId: id('d'), pub: key(4) }])).toEqual([{ ...good, label: 'x'.repeat(120) }, { machineId: id('d'), pub: key(4), label: '' }])
+ expect(sharedPeers('nope')).toEqual([])
+ const many = Array.from({ length: SHARED_TRUST_MAX + 5 }, (_, i) => ({ machineId: `m${i}`, pub: Buffer.alloc(32, i % 250).toString('base64').slice(0, 40) + `${String(i).padStart(3, '0')}=`, label: '' }))
+ expect(sharedPeers(many).length).toBeLessThanOrEqual(SHARED_TRUST_MAX)
+ })
+})
+
+describe('applySharedTrust', () => {
+ it('pins the machines shared with this account, marked shared, and takes back only its own', () => {
+ const { deps, held } = stores([
+ { machineId: id('o'), pub: key(10), label: 'own', linkedAt: 1 }, // the account's own machine
+ { machineId: id('g'), pub: key(11), label: 'gone', linkedAt: 1, shared: true }, // no longer shared
+ { machineId: id('k'), pub: key(12), label: 'kept', linkedAt: 1, shared: true }, // still shared, same key
+ { machineId: id('r'), pub: key(13), label: 'rekeyed', linkedAt: 1, shared: true }, // still shared, new key
+ ])
+ const result = applySharedTrust(deps, { pins: [
+ { machineId: id('k'), pub: key(12), label: 'kept' },
+ { machineId: id('r'), pub: key(14), label: 'rekeyed' },
+ { machineId: id('n'), pub: key(15), label: 'new' },
+ { machineId: id('o'), pub: key(16), label: 'not over the account’s own' },
+ { machineId: id('s'), pub: key(99), label: 'this machine itself' },
+ ] })
+ expect(result).toEqual({ pins: 3, keys: 0 })
+ expect(held.get(id('o'))).toMatchObject({ pub: key(10) })
+ expect(held.has(id('g'))).toBe(false)
+ expect(held.get(id('r'))).toMatchObject({ pub: key(14), shared: true })
+ expect(held.get(id('n'))).toMatchObject({ pub: key(15), shared: true })
+ expect(held.has(id('s'))).toBe(false)
+ expect(deps.dropSessions).toHaveBeenCalledWith(id('g'))
+ expect(deps.dropSessions).toHaveBeenCalledWith(id('r'))
+ expect(deps.dropSessions).not.toHaveBeenCalledWith(id('k'))
+ expect(deps.peers.pin).not.toHaveBeenCalledWith(id('k'), expect.anything(), expect.anything(), expect.anything(), expect.anything())
+ })
+
+ it('trusts the machines of accounts this one is shared with, never over the account’s own trust, and untrusts the rest it gave', () => {
+ const { deps, trusted } = stores([], [
+ { identityPub: key(20), label: 'own phone', pairedAt: 1, role: 'web' },
+ { identityPub: key(21), label: 'old colleague', pairedAt: 1, role: 'web', kind: 'machine', machineId: id('x'), shared: true },
+ ])
+ const result = applySharedTrust(deps, { keys: [
+ { machineId: id('k'), pub: key(22), label: 'Kim’s Mac' },
+ { machineId: id('o'), pub: key(20), label: 'already ours' },
+ { machineId: id('s'), pub: key(99), label: 'this machine' },
+ ] })
+ expect(result).toEqual({ pins: 0, keys: 1 })
+ expect(deps.untrust).toHaveBeenCalledWith(key(21))
+ expect(deps.untrust).not.toHaveBeenCalledWith(key(20))
+ expect(trusted.get(key(22))).toMatchObject({ shared: true, kind: 'machine', machineId: id('k'), role: 'web' })
+ expect(trusted.get(key(20))?.shared).toBeUndefined()
+ expect(trusted.has(key(99))).toBe(false)
+ })
+
+ it('leaves a part it was not sent as it is, and says how many sharing holds', () => {
+ const { deps } = stores([{ machineId: id('k'), pub: key(12), label: 'kept', linkedAt: 1, shared: true }],
+ [{ identityPub: key(21), label: 'colleague', pairedAt: 1, role: 'web', shared: true }])
+ expect(applySharedTrust(deps, {})).toEqual({ pins: 1, keys: 1 })
+ expect(deps.peers.unlink).not.toHaveBeenCalled()
+ expect(deps.untrust).not.toHaveBeenCalled()
+ })
+
+ it('knows a key trusted only through sharing', () => {
+ const paired: PairedClient[] = [{ identityPub: key(1), label: '', pairedAt: 1, role: 'web', shared: true }, { identityPub: key(2), label: '', pairedAt: 1, role: 'web' }]
+ expect(isSharedKey(paired, key(1))).toBe(true)
+ expect(isSharedKey(paired, key(2))).toBe(false)
+ expect(isSharedKey(paired, key(3))).toBe(false)
+ })
+})
diff --git a/cli/src/gateway/sharedTrust.ts b/cli/src/gateway/sharedTrust.ts
new file mode 100644
index 000000000..dd1127cda
--- /dev/null
+++ b/cli/src/gateway/sharedTrust.ts
@@ -0,0 +1,101 @@
+/**
+ * Machines shared across accounts (docs/plans/2026-10-15-share-machine-plan.md), as the gateway's trust
+ * stores hold them. The shared-machines service (services/sharedMachines.ts) works out what should be
+ * trusted and says it whole each time; this makes the stores say exactly that:
+ *
+ * - `pins`: the machines shared WITH this account, each under the key its owner's device key log names.
+ * Pinned in machinePeers.json so a window here reaches one through the relay as it does the account's
+ * own (lib/remoteRelay.ts).
+ * - `keys`: the machines of the accounts THIS machine is shared with. Trusted in paired.json as the
+ * account's own machines are (role `web`): the owner shares the machine with full rights.
+ *
+ * Each is marked `shared`, which keeps it out of the trust group (lib/e2ee/groupSyncer.ts) and lets this
+ * take back what it gave and nothing else. Something the account itself already trusts or pins is never
+ * touched: sharing adds to the account's own trust, it never changes it. Taking a key back is the same
+ * untrust as an unpair: its sessions close and the group key turns over.
+ */
+import type { MachinePeerStore } from '../lib/e2ee/machinePeers.js'
+import type { LinkedPeer } from '../lib/e2ee/manager.js'
+import type { PairedClient } from '../lib/e2ee/store.js'
+
+/** One machine and its key, as the service names it. */
+export interface SharedPeer { machineId: string; pub: string; label: string }
+
+/** What the service wants trusted; the most of each it may ask for. A part left out is left as it is:
+ * the service says only what it could read this time. */
+export interface SharedTrustDesired { pins?: SharedPeer[]; keys?: SharedPeer[] }
+export const SHARED_TRUST_MAX = 1000
+
+export interface SharedTrustDeps {
+ peers: Pick<MachinePeerStore, 'get' | 'pin' | 'unlink' | 'list'>
+ paired: () => PairedClient[]
+ trust: (peer: LinkedPeer) => void
+ untrust: (pub: string) => void
+ /** Close the relay sessions to a machine whose pin went or changed. */
+ dropSessions: (machineId: string) => void
+ /** This machine's own key, never trusted as another's. */
+ selfPub: () => string
+}
+
+const PUB_RE = /^[A-Za-z0-9+/]{43}=$/
+const MACHINE_RE = /^[A-Za-z0-9_-]{1,128}$/
+
+/** The valid peers of a list the service sent, at most SHARED_TRUST_MAX, each machine and key once. */
+export function sharedPeers(raw: unknown): SharedPeer[] {
+ if (!Array.isArray(raw)) return []
+ const seen = new Set<string>()
+ const out: SharedPeer[] = []
+ for (const item of raw.slice(0, SHARED_TRUST_MAX)) {
+ const p = item as Partial<SharedPeer> | null
+ if (!p || typeof p.pub !== 'string' || !PUB_RE.test(p.pub) || typeof p.machineId !== 'string' || !MACHINE_RE.test(p.machineId)) continue
+ if (seen.has(p.machineId) || seen.has(p.pub)) continue
+ seen.add(p.machineId); seen.add(p.pub)
+ out.push({ machineId: p.machineId, pub: p.pub, label: typeof p.label === 'string' ? p.label.slice(0, 120) : '' })
+ }
+ return out
+}
+
+/** Make the stores hold exactly `desired` among what sharing put there; how many of each it holds now. */
+export function applySharedTrust(deps: SharedTrustDeps, desired: SharedTrustDesired): { pins: number; keys: number } {
+ const self = deps.selfPub()
+ return {
+ pins: desired.pins ? applyPins(deps, desired.pins.filter((p) => p.pub !== self)) : deps.peers.list().filter((p) => p.shared).length,
+ keys: desired.keys ? applyKeys(deps, desired.keys.filter((k) => k.pub !== self)) : deps.paired().filter((p) => p.shared).length,
+ }
+}
+
+function applyPins(deps: SharedTrustDeps, desired: SharedPeer[]): number {
+ const pins = new Map(desired.map((p) => [p.machineId, p]))
+ for (const held of deps.peers.list()) {
+ if (!held.shared || pins.get(held.machineId)?.pub === held.pub) continue
+ deps.peers.unlink(held.machineId)
+ deps.dropSessions(held.machineId)
+ }
+ let pinned = 0
+ for (const want of pins.values()) {
+ const held = deps.peers.get(want.machineId)
+ if (held && !held.shared) continue // the account's own machine: its pin is the trust group's
+ if (!held || held.pub !== want.pub) deps.peers.pin(want.machineId, want.pub, want.label, Date.now(), true)
+ pinned++
+ }
+ return pinned
+}
+
+function applyKeys(deps: SharedTrustDeps, desired: SharedPeer[]): number {
+ const keys = new Map(desired.map((k) => [k.pub, k]))
+ const paired = deps.paired()
+ for (const held of paired) if (held.shared && !keys.has(held.identityPub)) deps.untrust(held.identityPub)
+ let trusted = 0
+ for (const want of keys.values()) {
+ const held = paired.find((p) => p.identityPub === want.pub)
+ if (held && !held.shared) continue // trusted as the account's own already
+ deps.trust({ pub: want.pub, machineId: want.machineId, kind: 'machine', label: want.label, shared: true })
+ trusted++
+ }
+ return trusted
+}
+
+/** Whether `pub` is trusted here only because of sharing. */
+export function isSharedKey(paired: PairedClient[], pub: string): boolean {
+ return paired.some((p) => p.identityPub === pub && p.shared === true)
+}
diff --git a/cli/src/gateway/start.ts b/cli/src/gateway/start.ts
index 92d51b8e5..d4c762ae9 100644
--- a/cli/src/gateway/start.ts
+++ b/cli/src/gateway/start.ts
@@ -33,6 +33,7 @@ import { DeviceLogStore } from '../lib/e2ee/deviceLogStore.js'
import { DeviceLogSyncer, type DeviceKeysSeen, type DeviceLogFetched, type DeviceLogTrustOutcome } from '../lib/e2ee/deviceLogSyncer.js'
import { GroupSyncer, relayRequester, SELF_STAMP } from '../lib/e2ee/groupSyncer.js'
import { MachinePeerStore } from '../lib/e2ee/machinePeers.js'
+import { applySharedTrust, isSharedKey } from './sharedTrust.js'
import { E2eeStore } from '../lib/e2ee/store.js'
import { TrustGroupStore, type GroupMember } from '../lib/e2ee/trustGroup.js'
import { RemoteRelayPool } from '../lib/remoteRelay.js'
@@ -175,6 +176,9 @@ export function startGateway(host: GatewayHost): StartedGateway {
// A machine the account's device key log names under this very key will trust us as soon as it
// reads the log: keep its pin through a few denials, and nudge it (and us) to read.
expectsTrust: (machineId, pub) => {
+ // A machine shared with this account trusts it once its own daemon has read who it is shared
+ // with (gateway/sharedTrust.ts): its pin stays until sharing takes it back.
+ if (relayPeers.get(machineId)?.shared && relayPeers.get(machineId)?.pub === pub) return true
const m = devLogSyncer?.list().members.find((x) => x.pub === pub)
const expected = !!m && m.kind === 'machine' && m.machineId === machineId && !devLogSyncer?.suspendedKeys().includes(pub)
if (expected) void devLogSyncer?.refresh()
@@ -216,6 +220,7 @@ export function startGateway(host: GatewayHost): StartedGateway {
suspended: () => new Set(devLogSyncer?.suspendedKeys() ?? []),
// Only a list the backend answered says who is offline; otherwise try every member.
reachable: () => reachable,
+ shared: (pub) => isSharedKey(gateway.pairedPeers(), pub),
ready: () => devLogSyncer?.current() ?? false,
log: (line) => console.log(line),
})
@@ -510,6 +515,14 @@ export function startGateway(host: GatewayHost): StartedGateway {
reachable: (machineIds) => { reachable = machineIds ? new Set(machineIds) : null },
lane,
observerKey: ownerKey,
+ sharedTrust: async (desired) => applySharedTrust({
+ peers: relayPeers,
+ paired: () => gateway.pairedPeers(),
+ trust: (peer) => gateway.trustPeer(peer),
+ untrust: (pub) => { gateway.untrustPeer(pub) },
+ dropSessions: (machineId) => { relayPool.invalidate(machineId); relayPool.invalidateIsolated(machineId) },
+ selfPub: () => b64e(relayIdentityStore.getIdentity().pub),
+ }, desired),
connectorVault: {
// Sealed for every machine the verified log holds, this one included, but never a key a fork
// suspended or one nobody has yet said is theirs (pending): a device added by whoever got hold of
diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.ts
index 955e33a1e..97b3f45cc 100644
--- a/cli/src/harnessd/services.spec.ts
+++ b/cli/src/harnessd/services.spec.ts
@@ -494,7 +494,7 @@ describe('ServiceSupervisor', () => {
const hosted = Object.values(SERVICE_HOSTS).flatMap((host) => host.services)
expect(KNOWN_SERVICES).toEqual(hosted)
expect(new Set(hosted).size).toBe(hosted.length)
- expect(SERVICE_HOSTS.edge.services).toEqual(['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames', 'shell', 'connectors', 'agentCleanup', 'messages', 'osDevice'])
+ expect(SERVICE_HOSTS.edge.services).toEqual(['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames', 'shell', 'connectors', 'sharedMachines', 'agentCleanup', 'messages', 'osDevice'])
// Agent Messages has no process of its own: one cost every computer it was on 62 MiB at idle (2026-10-12).
expect(Object.keys(SERVICE_HOSTS)).not.toContain('messages')
})
@@ -549,7 +549,7 @@ describe('which services the core leaves to its master', () => {
expect(serviceProcessesEnv(serviceSpecs({ HARNESSD_SERVICES: 'store' }, SERVICE_HOSTS), 42)).toMatchObject({ [SERVICE_PROCESSES_ENV]: 'store' })
// By service, not by process: a core from before the edge host routes the services it knows of it.
const hosted = serviceSpecs({ HARNESSD_SERVICES: 'edge' }, SERVICE_HOSTS)
- expect(serviceProcessesEnv(hosted, 42)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell,connectors,agentCleanup,messages,osDevice', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell,connectors,agentCleanup,messages,osDevice', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1', [ENGINE_QUESTION_CONTROL_ENV]: '42:1', [ENGINE_SUBMISSION_ENV]: '42:1', [ENGINE_NATIVE_CONTROL_ENV]: '42:1' })
+ expect(serviceProcessesEnv(hosted, 42)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell,connectors,sharedMachines,agentCleanup,messages,osDevice', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell,connectors,sharedMachines,agentCleanup,messages,osDevice', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1', [ENGINE_QUESTION_CONTROL_ENV]: '42:1', [ENGINE_SUBMISSION_ENV]: '42:1', [ENGINE_NATIVE_CONTROL_ENV]: '42:1' })
expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(hosted, 42) }, known)]).toEqual(['workspaces', 'messages'])
expect(serviceProcessesEnv([], 42)).toEqual({ [SERVICE_PROCESSES_ENV]: '', HARNESSD_SERVICES: 'none', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1', [ENGINE_QUESTION_CONTROL_ENV]: '42:1', [ENGINE_SUBMISSION_ENV]: '42:1', [ENGINE_NATIVE_CONTROL_ENV]: '42:1' })
expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(specs, 42) }, known)]).toEqual(['search', 'workspaces'])
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index e76048648..6a8c2433f 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -392,7 +392,7 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {
// the bundle rather than messaging: here it costs the edge host about 1 MiB on, and 0.4 MiB off
// (e2e/footprint.e2e.ts, 2026-10-12). The Harness OS computer's management (services/osDevice.ts) holds one
// timestamp and runs its commands bounded, or detached when they must outlive this process.
- edge: { services: ['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames', 'shell', 'connectors', 'agentCleanup', 'messages', 'osDevice'], heapLimitMiB: 384, rssLimitMiB: 768 },
+ edge: { services: ['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames', 'shell', 'connectors', 'sharedMachines', 'agentCleanup', 'messages', 'osDevice'], heapLimitMiB: 384, rssLimitMiB: 768 },
// The orchestrator (services/orchestratorProcess.ts), an experiment: started only once it is on, for a
// saved project or a request (core/api.ts `EXPERIMENTS`). Its projects' files and the frames of their
// Directors; the agents it runs are the core's.
diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.ts
index c59159919..935ade76f 100644
--- a/cli/src/lib/e2ee/applicationFrames.ts
+++ b/cli/src/lib/e2ee/applicationFrames.ts
@@ -32,6 +32,8 @@ const MACHINE_REQUESTS = new Set([...SHELL_REQUESTS, 'agent_purge', 'agent_workt
'cloud_transcript', 'cloud_send', 'cloud_agents',
// A Harness OS computer managed from the phone (services/osDevice.ts): a Wi-Fi join carries the network's password.
'os_device',
+ // Sharing a machine across accounts (services/sharedMachines.ts): the addresses it is shared with.
+ 'shared_machines',
// A sign-in a phone caught for a page a harness's program opened (core/terminals/browser.ts): it holds the code.
'browser_callback', ...ROUTE_COMMAND_TYPES])
const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))
diff --git a/cli/src/lib/e2ee/groupSyncer.spec.ts b/cli/src/lib/e2ee/groupSyncer.spec.ts
index d46812dbd..5fe93beeb 100644
--- a/cli/src/lib/e2ee/groupSyncer.spec.ts
+++ b/cli/src/lib/e2ee/groupSyncer.spec.ts
@@ -19,11 +19,13 @@ beforeAll(async () => {
afterEach(() => { vi.useRealTimers() })
-interface Pin { machineId: string; pub: string; label: string; linkedAt: number }
+interface Pin { machineId: string; pub: string; label: string; linkedAt: number; shared?: true }
class MemPeers {
pins = new Map<string, Pin>()
get(id: string): Pin | null { return this.pins.get(id) ?? null }
- pin(machineId: string, pub: string, label: string, at = 1): void { this.pins.set(machineId, { machineId, pub, label, linkedAt: at }) }
+ pin(machineId: string, pub: string, label: string, at = 1, shared = false): void {
+ this.pins.set(machineId, { machineId, pub, label, linkedAt: at, ...(shared ? { shared: true as const } : {}) })
+ }
unlink(id: string): boolean { return this.pins.delete(id) }
list(): Array<Pin & { fingerprint: string }> { return [...this.pins.values()].map((p) => ({ ...p, fingerprint: 'fp' })) }
}
@@ -33,7 +35,7 @@ interface Node {
pub: string
machineId: string | null
peers: MemPeers
- trusted: Map<string, { kind?: string; machineId?: string }>
+ trusted: Map<string, { kind?: string; machineId?: string; shared?: boolean }>
syncer: InstanceType<typeof S.GroupSyncer>
online: boolean
/** What `ready` answers: the device key log is this sign-in's. */
@@ -72,7 +74,8 @@ function fleet(): { add: (name: string, machine?: boolean) => Node; link: (joine
self: () => ({ pub: node.pub, kind: machine ? 'machine' : 'viewer', label: name, at: S.SELF_STAMP, ...(node.machineId ? { machineId: node.machineId } : {}) }),
trust: (p) => { node.trusted.set(p.pub, { kind: p.kind, machineId: p.machineId }) },
untrust: (p) => { node.trusted.delete(p) },
- paired: () => [...node.trusted].map(([identityPub, t]) => ({ identityPub, label: 'x', pairedAt: 1, role: 'web' as const, ...(t.kind ? { kind: t.kind as 'machine' } : {}), ...(t.machineId ? { machineId: t.machineId } : {}) })),
+ paired: () => [...node.trusted].map(([identityPub, t]) => ({ identityPub, label: 'x', pairedAt: 1, role: 'web' as const, ...(t.kind ? { kind: t.kind as 'machine' } : {}), ...(t.machineId ? { machineId: t.machineId } : {}), ...(t.shared ? { shared: true as const } : {}) })),
+ shared: (pub) => node.trusted.get(pub)?.shared === true,
request: async (machineId, frame: Frame) => {
const target = nodes.find((n) => n.machineId === machineId)
if (!target?.online) return null
@@ -104,6 +107,41 @@ function fleet(): { add: (name: string, machine?: boolean) => Node; link: (joine
}
describe('GroupSyncer', () => {
+ it('never makes a machine shared across accounts part of the group, either way', async () => {
+ vi.useFakeTimers()
+ const f = fleet()
+ // Dee's two machines, linked; Kim's machine and phone, another account.
+ const [dee, dee2, kim] = [f.add('d'), f.add('e'), f.add('k')]
+ const kimPhone = f.add('p', false)
+ f.link(dee, dee2)
+ f.link(kimPhone, kim)
+ await dee.syncer.syncAll()
+ await kim.syncer.syncAll()
+ // Dee shares her machine with Kim (gateway/sharedTrust.ts): Kim pins it, it trusts Kim's machine.
+ kim.peers.pin(dee.machineId!, dee.pub, 'Dee’s machine', 1, true)
+ dee.trusted.set(kim.pub, { kind: 'machine', machineId: kim.machineId!, shared: true })
+
+ // Kim's rounds never dial it, and an exchange with it is refused before anything is sent.
+ expect(await kim.syncer.syncWith(dee.machineId!)).toBe(false)
+ await kim.syncer.syncAll()
+ // A group_sync from Kim's machine is refused by Dee's.
+ expect(dee.syncer.handle(kim.pub, { self: { pub: kim.pub, kind: 'machine', label: 'k', machineId: kim.machineId, at: S.SELF_STAMP },
+ members: [{ pub: kimPhone.pub, kind: 'viewer', label: 'p', at: 5 }], removed: [] })).toEqual({ error: 'SHARED' })
+ await dee.syncer.syncAll()
+
+ expect(dee.trusted.has(kimPhone.pub)).toBe(false)
+ expect(dee2.trusted.has(kim.pub)).toBe(false)
+ expect(kim.trusted.has(dee.pub)).toBe(false)
+ expect(kim.trusted.has(dee2.pub)).toBe(false)
+ expect(dee.syncer.roster().members.map((m) => m.pub)).not.toContain(kim.pub)
+ expect(kim.syncer.roster().members.map((m) => m.pub)).not.toContain(dee.pub)
+ // Nor is either seeded from the other as the daemon starts again.
+ kim.syncer.start(); dee.syncer.start()
+ expect(kim.syncer.roster().members.map((m) => m.pub)).not.toContain(dee.pub)
+ expect(dee.syncer.roster().members.map((m) => m.pub)).not.toContain(kim.pub)
+ for (const n of f.nodes) n.syncer.stop()
+ })
+
it('A links B, A links C ⇒ B and C reach each other both ways, no password', async () => {
vi.useFakeTimers()
const f = fleet()
diff --git a/cli/src/lib/e2ee/groupSyncer.ts b/cli/src/lib/e2ee/groupSyncer.ts
index 42bff8809..a23c01870 100644
--- a/cli/src/lib/e2ee/groupSyncer.ts
+++ b/cli/src/lib/e2ee/groupSyncer.ts
@@ -8,6 +8,11 @@
* dialer sends its roster and itself, the dialed machine merges, answers with its own, and the dialer
* merges that. Whatever changed is then pushed on to the other members, so a link made anywhere
* reaches everyone who is online, and the rest catch up on their next contact.
+ *
+ * A machine shared across accounts (gateway/sharedTrust.ts, marked `shared` in both stores) is never part
+ * of this: rosters are not exchanged with it, it is not seeded from its pin or its trust, and a
+ * `group_sync` from it is refused. Otherwise sharing one machine would make the colleague's other
+ * machines trusted here, and this account's trusted by theirs.
*/
import type { Frame, LocalClientSink } from '../../backendSocket.js'
import type { RelaySession } from '../remoteRelay.js'
@@ -58,6 +63,9 @@ export interface GroupSyncerDeps {
suspended?: () => ReadonlySet<string>
/** Machines worth dialing now; null = unknown, try every member. */
reachable?: () => Set<string> | null
+ /** Whether `pub` is a machine of another account trusted only because it is shared with this one (or this
+ * one with it): it never takes part in the group. */
+ shared?: (pub: string) => boolean
/** Whether the roster here is the account's this machine is signed in to (deviceLogSyncer `current`).
* While not, nothing is swapped: a daemon started after a switch of accounts read the new account's
* log only after its first rounds, and handed the roster of the account it left to the new one's
@@ -199,6 +207,7 @@ export class GroupSyncer {
/** Responder side of `group_sync`, for a sealed request from the session identity `peerPub`. */
handle(peerPub: string, payload: Record<string, unknown>): Record<string, unknown> {
+ if (this.deps.shared?.(peerPub)) return { error: 'SHARED' }
if (this.deps.ready?.() === false) {
const none: Roster = { members: [], removed: [] }
return { ...none, digest: rosterDigest(none) }
@@ -240,7 +249,7 @@ export class GroupSyncer {
const targets = new Set<string>()
const suspended = this.deps.suspended?.() ?? new Set<string>()
for (const m of this.deps.store.read().members) if (m.kind === 'machine' && m.machineId && !suspended.has(m.pub)) targets.add(m.machineId)
- for (const p of this.deps.peers.list()) if (!suspended.has(p.pub)) targets.add(p.machineId)
+ for (const p of this.deps.peers.list()) if (!suspended.has(p.pub) && !p.shared) targets.add(p.machineId)
if (self) targets.delete(self)
// All at once: one machine that never answers (offline, or too old to know the frame) must not
// hold up the rest for its whole timeout.
@@ -261,7 +270,7 @@ export class GroupSyncer {
private async exchange(machineId: string): Promise<boolean> {
const pin = this.deps.peers.get(machineId)
- if (!pin || this.deps.ready?.() === false) return false
+ if (!pin || pin.shared || this.deps.ready?.() === false) return false
const generation = this.generation
const local = this.deps.store.read()
const devlog = this.devlog?.gossip()
@@ -313,11 +322,12 @@ export class GroupSyncer {
private seedFromExistingLinks(): void {
const seed: GroupMember[] = []
for (const p of this.deps.peers.list()) {
+ if (p.shared) continue
const m = parseMember({ pub: p.pub, machineId: p.machineId, kind: 'machine', label: p.label, at: p.linkedAt || SELF_STAMP }, this.now())
if (m) seed.push(m)
}
for (const p of this.deps.paired()) {
- if (!p.kind) continue
+ if (!p.kind || p.shared) continue
const m = parseMember({ pub: p.identityPub, machineId: p.machineId, kind: p.kind, label: p.label, at: p.pairedAt || SELF_STAMP }, this.now())
if (m) seed.push(m)
}
diff --git a/cli/src/lib/e2ee/machinePeers.ts b/cli/src/lib/e2ee/machinePeers.ts
index 5b3b8e6f6..612354f7a 100644
--- a/cli/src/lib/e2ee/machinePeers.ts
+++ b/cli/src/lib/e2ee/machinePeers.ts
@@ -25,6 +25,9 @@ export interface MachinePeer {
pub: string // base64 Ed25519 pubkey of the peer machine's own identity
label: string
linkedAt: number
+ /** Another account's machine shared with this one (gateway/sharedTrust.ts): dialed like the account's
+ * own, but never a member of the trust group, which never exchanges rosters with it. */
+ shared?: true
}
function readAll(): Map<string, MachinePeer> {
@@ -48,9 +51,9 @@ export class MachinePeerStore {
return readAll().get(machineId) ?? null
}
- pin(machineId: string, pub: string, label: string, at = Date.now()): void {
+ pin(machineId: string, pub: string, label: string, at = Date.now(), shared = false): void {
const peers = readAll()
- peers.set(machineId, { machineId, pub, label, linkedAt: at })
+ peers.set(machineId, { machineId, pub, label, linkedAt: at, ...(shared ? { shared: true as const } : {}) })
writeAll(peers)
}
diff --git a/cli/src/lib/e2ee/manager.ts b/cli/src/lib/e2ee/manager.ts
index 762f4d23c..4a048eae2 100644
--- a/cli/src/lib/e2ee/manager.ts
+++ b/cli/src/lib/e2ee/manager.ts
@@ -138,6 +138,7 @@ export interface LinkedPeer {
machineId?: string // set when kind is 'machine'
kind?: PeerKind // absent for an older joiner that did not say
label: string
+ shared?: boolean // another account's machine this one is shared with (gateway/sharedTrust.ts)
}
const MACHINE_ID_RE = /^[a-f0-9]{32}$/
@@ -194,8 +195,9 @@ export class E2eeManager {
* for members learned from a trust-group sync. */
trustPeer(peer: LinkedPeer, at = this.now()): void {
const existing = this.store.pairedPeer(peer.pub)
- if (existing && existing.label === peer.label && existing.machineId === peer.machineId && existing.kind === peer.kind) return
- this.store.addPaired(peer.pub, peer.label, existing?.pairedAt ?? at, existing?.role ?? 'web', { machineId: peer.machineId, kind: peer.kind })
+ if (existing && existing.label === peer.label && existing.machineId === peer.machineId && existing.kind === peer.kind
+ && !!existing.shared === !!peer.shared) return
+ this.store.addPaired(peer.pub, peer.label, existing?.pairedAt ?? at, existing?.role ?? 'web', { machineId: peer.machineId, kind: peer.kind, shared: peer.shared })
}
/** Stop trusting `pub` (a no-op when it is not paired): the same path as `harness unpair`. */
untrustPeer(pub: string): boolean {
diff --git a/cli/src/lib/e2ee/store.ts b/cli/src/lib/e2ee/store.ts
index 99fca5e2b..66c81138e 100644
--- a/cli/src/lib/e2ee/store.ts
+++ b/cli/src/lib/e2ee/store.ts
@@ -58,6 +58,9 @@ export interface PairedClient {
* joining machine's id when `kind` is 'machine', absent for a viewer app. Absent on older records. */
machineId?: string
kind?: PeerKind
+ /** A machine of another account this machine is shared with (gateway/sharedTrust.ts): trusted like the
+ * account's own, but never a member of the trust group, and taken back when the sharing ends. */
+ shared?: true
}
/** What a password-linked peer is: another harness machine (which also serves, so it can be dialed back)
@@ -156,11 +159,12 @@ export class E2eeStore {
return this.paired.get(identityPubB64) ?? null
}
- addPaired(identityPubB64: string, label: string, at: number, role: PairRole = 'web', peer?: { machineId?: string; kind?: PeerKind }): void {
+ addPaired(identityPubB64: string, label: string, at: number, role: PairRole = 'web', peer?: { machineId?: string; kind?: PeerKind; shared?: boolean }): void {
this.paired.set(identityPubB64, {
identityPub: identityPubB64, label, pairedAt: at, role,
...(peer?.machineId ? { machineId: peer.machineId } : {}),
...(peer?.kind ? { kind: peer.kind } : {}),
+ ...(peer?.shared ? { shared: true as const } : {}),
})
writeSecure(PAIRED_FILE, [...this.paired.values()])
}
diff --git a/cli/src/lib/gatewayWire.ts b/cli/src/lib/gatewayWire.ts
index d1a0a100b..a0bb86280 100644
--- a/cli/src/lib/gatewayWire.ts
+++ b/cli/src/lib/gatewayWire.ts
@@ -66,4 +66,5 @@ export const GATEWAY_CALLS = {
lane: 'gateway_lane',
observerKey: 'gateway_observer_key',
connectorVault: 'gateway_connector_vault',
+ sharedTrust: 'gateway_shared_trust',
} as const
diff --git a/cli/src/lib/sharedMachinesPort.spec.ts b/cli/src/lib/sharedMachinesPort.spec.ts
new file mode 100644
index 000000000..30599935e
--- /dev/null
+++ b/cli/src/lib/sharedMachinesPort.spec.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it, vi } from 'vitest'
+import { answerSharedMachinesOp, failed, inlineSharedMachinesPort, sharedMachinesPortOf, type SharedMachinesAccount } from './sharedMachinesPort.js'
+
+const M = 'ab'.repeat(16)
+const pub = Buffer.alloc(32, 1).toString('base64')
+
+function account(machineId = M): SharedMachinesAccount & { backend: ReturnType<typeof vi.fn>; trust: ReturnType<typeof vi.fn> } {
+ return {
+ backend: vi.fn(async (method: string, path: string, body?: unknown) => ({ status: 200, body: { method, path, ...(body ? { sent: body } : {}) } })),
+ machineId: () => machineId,
+ trust: vi.fn(async () => ({ pins: 1, keys: 2 })),
+ }
+}
+
+describe('answerSharedMachinesOp', () => {
+ it('reaches only its own paths of the backend, signed in, for this machine', async () => {
+ const a = account()
+ expect(await answerSharedMachinesOp(a, { op: 'policy' })).toEqual({ status: 200, body: { method: 'GET', path: `/api/machines/${M}/share` } })
+ expect(await answerSharedMachinesOp(a, { op: 'publish', emails: ['[email protected]'], sameDomain: 'yes' }))
+ .toEqual({ status: 200, body: { method: 'PUT', path: `/api/machines/${M}/share`, sent: { emails: ['[email protected]'], sameDomain: false } } })
+ expect(await answerSharedMachinesOp(a, { op: 'shared' })).toEqual({ status: 200, body: { method: 'GET', path: '/api/machine-shares' } })
+ expect(await answerSharedMachinesOp(a, { op: 'add', machineId: M })).toMatchObject({ body: { method: 'POST', path: `/api/machine-shares/${M}/add` } })
+ expect(await answerSharedMachinesOp(a, { op: 'remove', machineId: M })).toMatchObject({ body: { method: 'DELETE', path: `/api/machine-shares/${M}/add` } })
+ expect(await answerSharedMachinesOp(a, { op: 'add', machineId: '../../api/admin' })).toEqual({ status: 400, body: { error: 'BAD_MACHINE' } })
+ expect(await answerSharedMachinesOp(a, { op: 'nothing' })).toEqual({ error: 'UNKNOWN_OP' })
+ })
+
+ it('reads no policy signed out', async () => {
+ const a = account('')
+ expect(await answerSharedMachinesOp(a, { op: 'policy' })).toEqual({ status: 401, body: { error: 'NOT_SIGNED_IN' } })
+ expect(await answerSharedMachinesOp(a, { op: 'publish' })).toEqual({ status: 401, body: { error: 'NOT_SIGNED_IN' } })
+ expect(a.backend).not.toHaveBeenCalled()
+ })
+
+ it('hands the gateway only the parts it was sent, and answers a failure as an error', async () => {
+ const a = account()
+ expect(await answerSharedMachinesOp(a, { op: 'trust', pins: [], keys: 'no' })).toEqual({ pins: 1, keys: 2 })
+ expect(a.trust).toHaveBeenLastCalledWith({ pins: [] })
+ expect(await answerSharedMachinesOp(a, { op: 'trust', keys: [] })).toEqual({ pins: 1, keys: 2 })
+ expect(a.trust).toHaveBeenLastCalledWith({ keys: [] })
+ a.trust.mockRejectedValueOnce(new Error('the gateway is not running'))
+ expect(await answerSharedMachinesOp(a, { op: 'trust' })).toEqual({ error: 'the gateway is not running' })
+ a.backend.mockRejectedValueOnce('odd')
+ expect(await answerSharedMachinesOp(a, { op: 'shared' })).toEqual({ error: 'odd' })
+ })
+})
+
+describe('sharedMachinesPortOf', () => {
+ const ok = (data: unknown) => ({ status: 200, body: { success: true, data } })
+
+ it('reads the policy, its members and their machines', async () => {
+ const call = vi.fn(async () => ok({ emails: ['[email protected]', 3], sameDomain: true, domain: 'b.io', members: [
+ { email: '[email protected]', name: 'A', via: 'email', machines: [{ machineId: M, pub, name: 'Mac' }, { machineId: M }, null, { machineId: 'm2', pub, label: 'Labelled' }] },
+ { email: '[email protected]', via: 'domain', machines: 'none' },
+ { name: 'no email' }, null,
+ ] }))
+ const port = sharedMachinesPortOf(call)
+ expect(await port.policy()).toEqual({ emails: ['[email protected]'], sameDomain: true, domain: 'b.io', members: [
+ { email: '[email protected]', name: 'A', via: 'email', machines: [{ machineId: M, pub, label: 'Mac' }, { machineId: 'm2', pub, label: 'Labelled' }] },
+ { email: '[email protected]', name: null, via: 'domain', machines: [] },
+ ] })
+ expect(call).toHaveBeenCalledWith('policy')
+ call.mockResolvedValueOnce(ok({ emails: 'none', domain: '' }))
+ expect(await port.publish(['[email protected]'], true)).toEqual({ emails: [], sameDomain: false, domain: null, members: [] })
+ expect(call).toHaveBeenLastCalledWith('publish', { emails: ['[email protected]'], sameDomain: true })
+ })
+
+ it('reads the machines shared with this account', async () => {
+ const call = vi.fn(async () => ok({ machines: [
+ { machineId: M, name: 'Studio', hostname: 'studio.local', pub, share: { ownerName: 'Dee', ownerEmail: '[email protected]', via: 'domain', added: true } },
+ { machineId: 'm2', name: 3, share: null },
+ { name: 'no id' }, null,
+ ] }))
+ expect(await sharedMachinesPortOf(call).shared()).toEqual([
+ { machineId: M, name: 'Studio', hostname: 'studio.local', pub, share: { ownerName: 'Dee', ownerEmail: '[email protected]', via: 'domain', added: true } },
+ { machineId: 'm2', name: null, hostname: null, pub: null, share: { ownerName: '', ownerEmail: '', via: 'email', added: false } },
+ ])
+ call.mockResolvedValueOnce(ok({}))
+ expect(await sharedMachinesPortOf(call).shared()).toEqual([])
+ })
+
+ it('adds, removes and asks for trust', async () => {
+ const call = vi.fn(async (op: string) => op === 'trust' ? { pins: 1, keys: 0 } : ok({ added: true }))
+ const port = sharedMachinesPortOf(call)
+ expect(await port.add(M)).toBe(true)
+ expect(call).toHaveBeenLastCalledWith('add', { machineId: M })
+ expect(await port.remove(M)).toBe(true)
+ expect(call).toHaveBeenLastCalledWith('remove', { machineId: M })
+ expect(await port.trust({ pins: [] })).toEqual({ pins: 1, keys: 0 })
+ expect(call).toHaveBeenLastCalledWith('trust', { pins: [] })
+ })
+
+ it('says why, in words an app can show, whenever there is no answer', async () => {
+ const call = vi.fn()
+ const port = sharedMachinesPortOf(call)
+ call.mockResolvedValueOnce({ status: 400, body: { success: false, error: { code: 'PUBLIC_DOMAIN', message: 'It is a public email domain.' } } })
+ expect(await port.publish([], true)).toEqual({ failed: { status: 400, code: 'PUBLIC_DOMAIN', message: 'It is a public email domain.' } })
+ call.mockResolvedValueOnce({ status: 401, body: { error: 'NOT_SIGNED_IN' } })
+ expect(await port.policy()).toEqual({ failed: { status: 401, code: 'NOT_SIGNED_IN', message: expect.stringContaining('could not be reached') } })
+ call.mockResolvedValueOnce({ error: 'not connected to the core' })
+ expect(await port.add(M)).toEqual({ failed: { status: 502, code: 'not connected to the core', message: expect.any(String) } })
+ call.mockResolvedValueOnce({ status: 404, body: { success: false, error: { code: 'NOT_SHARED' } } })
+ expect(await port.remove(M)).toMatchObject({ failed: { code: 'NOT_SHARED' } })
+ call.mockResolvedValueOnce({ status: 200, body: { success: true } })
+ expect(await port.shared()).toMatchObject({ failed: { code: 'UNAVAILABLE' } })
+ call.mockResolvedValueOnce({})
+ expect(await port.trust({})).toMatchObject({ failed: { code: 'UNAVAILABLE' } })
+ expect(failed(null)).toBe(false)
+ expect(failed(true)).toBe(false)
+ })
+})
+
+describe('inlineSharedMachinesPort', () => {
+ it('answers in line in the core’s own process, signed in, and is no port signed out', async () => {
+ const a = account()
+ expect(inlineSharedMachinesPort(a, false)).toBeNull()
+ a.backend.mockResolvedValueOnce({ status: 200, body: { success: true, data: { machines: [] } } })
+ expect(await inlineSharedMachinesPort(a, true)!.shared()).toEqual([])
+ expect(a.backend).toHaveBeenCalledWith('GET', '/api/machine-shares')
+ })
+})
diff --git a/cli/src/lib/sharedMachinesPort.ts b/cli/src/lib/sharedMachinesPort.ts
new file mode 100644
index 000000000..a0b886d6e
--- /dev/null
+++ b/cli/src/lib/sharedMachinesPort.ts
@@ -0,0 +1,158 @@
+/**
+ * What the shared-machines service (services/sharedMachines.ts) reaches through the core: this machine's
+ * sharing as the backend holds it, the machines shared with this account, adding one, and the gateway's
+ * trust stores (gateway/sharedTrust.ts). The core answers `shared_machines` (core/sharedMachinesQueries.ts)
+ * with `answerSharedMachinesOp`, signed in with its own session, and the service, in its process or in the
+ * core's, reads the answers through `sharedMachinesPortOf`. It reaches no other path of the backend.
+ */
+type Payload = Record<string, unknown>
+type Answer = { status: number; body: Record<string, unknown> }
+
+export interface SharedMachinesAccount {
+ backend(method: string, path: string, body?: unknown): Promise<Answer>
+ /** This machine's id on the account; empty while signed out. */
+ machineId(): string
+ trust(desired: { pins?: SharedTrustPeer[]; keys?: SharedTrustPeer[] }): Promise<{ pins: number; keys: number }>
+}
+
+export interface SharedTrustPeer { machineId: string; pub: string; label: string }
+
+const MACHINE_RE = /^[a-f0-9]{32}$/
+
+export async function answerSharedMachinesOp(account: SharedMachinesAccount, payload: Payload): Promise<Payload> {
+ try {
+ const self = account.machineId()
+ const target = typeof payload.machineId === 'string' && MACHINE_RE.test(payload.machineId) ? payload.machineId : null
+ switch (payload.op) {
+ case 'policy':
+ if (!self) return { status: 401, body: { error: 'NOT_SIGNED_IN' } }
+ return { ...await account.backend('GET', `/api/machines/${self}/share`) }
+ case 'publish':
+ if (!self) return { status: 401, body: { error: 'NOT_SIGNED_IN' } }
+ return { ...await account.backend('PUT', `/api/machines/${self}/share`, { emails: payload.emails, sameDomain: payload.sameDomain === true }) }
+ case 'shared': return { ...await account.backend('GET', '/api/machine-shares') }
+ case 'add':
+ case 'remove':
+ if (!target) return { status: 400, body: { error: 'BAD_MACHINE' } }
+ return { ...await account.backend(payload.op === 'add' ? 'POST' : 'DELETE', `/api/machine-shares/${target}/add`) }
+ case 'trust': return { ...await account.trust({
+ ...(Array.isArray(payload.pins) ? { pins: payload.pins as SharedTrustPeer[] } : {}),
+ ...(Array.isArray(payload.keys) ? { keys: payload.keys as SharedTrustPeer[] } : {}),
+ }) }
+ default: return { error: 'UNKNOWN_OP' }
+ }
+ } catch (error) {
+ return { error: error instanceof Error ? error.message : String(error) }
+ }
+}
+
+/** Someone a machine is shared with, as the backend lists them for its owner. */
+export interface ShareMember {
+ email: string
+ name: string | null
+ via: 'email' | 'domain'
+ machines: SharedTrustPeer[]
+}
+
+/** This machine's sharing as the backend holds it. `domain` is the owner's own, null at a public one. */
+export interface SharePolicy {
+ emails: string[]
+ sameDomain: boolean
+ domain: string | null
+ members: ShareMember[]
+}
+
+/** A machine another account shares with this one. */
+export interface SharedMachine {
+ machineId: string
+ name: string | null
+ hostname: string | null
+ pub: string | null
+ share: { ownerName: string; ownerEmail: string; via: 'email' | 'domain'; added: boolean }
+}
+
+/** What went wrong, in words an app can show; `code` is the backend's. */
+export interface PortFailure { failed: { status: number; code: string; message: string } }
+
+export interface SharedMachinesPort {
+ policy(): Promise<SharePolicy | PortFailure>
+ publish(emails: string[], sameDomain: boolean): Promise<SharePolicy | PortFailure>
+ shared(): Promise<SharedMachine[] | PortFailure>
+ add(machineId: string): Promise<true | PortFailure>
+ remove(machineId: string): Promise<true | PortFailure>
+ trust(desired: { pins?: SharedTrustPeer[]; keys?: SharedTrustPeer[] }): Promise<{ pins: number; keys: number } | PortFailure>
+}
+
+export const failed = (value: unknown): value is PortFailure => !!value && typeof value === 'object' && 'failed' in value
+
+const text = (value: unknown): string => typeof value === 'string' ? value : ''
+const list = (value: unknown): unknown[] => Array.isArray(value) ? value : []
+
+function failure(answer: Payload): PortFailure {
+ const body = (answer.body ?? {}) as Payload
+ const error = (body.error ?? answer.error) as Payload | string | undefined
+ const code = typeof error === 'string' ? error : text(error?.code) || 'UNAVAILABLE'
+ const message = typeof error === 'object' && text(error?.message) ? text(error.message) : 'The Harness backend could not be reached. Try again in a moment.'
+ return { failed: { status: typeof answer.status === 'number' ? answer.status : 502, code, message } }
+}
+
+/** The backend's `data`, or why there is none. */
+function data(answer: Payload): Payload | PortFailure {
+ const body = answer.body as Payload | undefined
+ return answer.status === 200 && body?.success === true && body.data && typeof body.data === 'object' ? body.data as Payload : failure(answer)
+}
+
+function peer(raw: unknown): SharedTrustPeer | null {
+ const p = (raw ?? {}) as Payload
+ return typeof p.machineId === 'string' && typeof p.pub === 'string' ? { machineId: p.machineId, pub: p.pub, label: text(p.name) || text(p.label) } : null
+}
+
+function policyOf(d: Payload): SharePolicy {
+ return {
+ emails: list(d.emails).filter((e): e is string => typeof e === 'string'),
+ sameDomain: d.sameDomain === true,
+ domain: typeof d.domain === 'string' && d.domain ? d.domain : null,
+ members: list(d.members).map((raw) => {
+ const m = (raw ?? {}) as Payload
+ return { email: text(m.email), name: typeof m.name === 'string' ? m.name : null, via: m.via === 'domain' ? 'domain' as const : 'email' as const,
+ machines: list(m.machines).map(peer).filter((p): p is SharedTrustPeer => p !== null) }
+ }).filter((m) => m.email),
+ }
+}
+
+function sharedOf(raw: unknown): SharedMachine | null {
+ const r = (raw ?? {}) as Payload
+ const share = (r.share ?? {}) as Payload
+ if (typeof r.machineId !== 'string') return null
+ return {
+ machineId: r.machineId, name: typeof r.name === 'string' ? r.name : null, hostname: typeof r.hostname === 'string' ? r.hostname : null,
+ pub: typeof r.pub === 'string' ? r.pub : null,
+ share: { ownerName: text(share.ownerName), ownerEmail: text(share.ownerEmail), via: share.via === 'domain' ? 'domain' : 'email', added: share.added === true },
+ }
+}
+
+/** The port over the core's `shared_machines` query, asked in line or over the service's link. */
+export function sharedMachinesPortOf(call: (op: string, payload?: Payload) => Promise<Payload>): SharedMachinesPort {
+ const policy = (answer: Payload): SharePolicy | PortFailure => { const d = data(answer); return failed(d) ? d : policyOf(d) }
+ const done = (answer: Payload): true | PortFailure => { const d = data(answer); return failed(d) ? d : true }
+ return {
+ policy: async () => policy(await call('policy')),
+ publish: async (emails, sameDomain) => policy(await call('publish', { emails, sameDomain })),
+ shared: async () => {
+ const d = data(await call('shared'))
+ return failed(d) ? d : list(d.machines).map(sharedOf).filter((m): m is SharedMachine => m !== null)
+ },
+ add: async (machineId) => done(await call('add', { machineId })),
+ remove: async (machineId) => done(await call('remove', { machineId })),
+ trust: async (desired) => {
+ const answer = await call('trust', { ...desired })
+ return typeof answer.pins === 'number' && typeof answer.keys === 'number' ? { pins: answer.pins, keys: answer.keys } : failure(answer)
+ },
+ }
+}
+
+/** The port in the core's own process, answered in line by the core's sign-in and the gateway it runs;
+ * null signed out, when there is nothing to share or read. */
+export function inlineSharedMachinesPort(account: SharedMachinesAccount, signedIn: boolean): SharedMachinesPort | null {
+ return signedIn ? sharedMachinesPortOf((op, payload = {}) => answerSharedMachinesOp(account, { ...payload, op })) : null
+}
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index 64c7e3799..27b292d88 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -41,6 +41,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M
['shell', async () => (await import('./services/shellProcess.js')).runShellService],
['handoff', async () => (await import('./services/handoffProcess.js')).runHandoffService],
['connectors', async () => (await import('./services/connectorsProcess.js')).runConnectorsService],
+ ['sharedMachines', async () => (await import('./services/sharedMachinesProcess.js')).runSharedMachinesService],
['osDevice', async () => (await import('./services/osDeviceProcess.js')).runOsDeviceService],
['recaps', async () => (await import('./services/recapsProcess.js')).runRecapsService],
['agentCleanup', async () => (await import('./services/agentCleanupProcess.js')).runAgentCleanupService],
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index 947f4bfbc..148172a76 100644
--- a/cli/src/services/AGENTS.md
+++ b/cli/src/services/AGENTS.md
@@ -54,7 +54,7 @@ that process. A process per risk, not per feature (`SERVICE_HOSTS` in `src/harne
| `engine-claude`, `engine-codex` | history, live parsers, runtime profiles, screens, submission readings, model control, question navigation and Codex's app-server connection (`src/engines/worker/`) | engine behavior outside core; snapshots and revocable model- and question-control grants | on demand |
| `search` | search | native `node:sqlite`, the index's memory | always |
| `viewers` | viewers, store | the viewer servers, the remote viewer streams and rendered surfaces, minutes-long installs | on demand |
-| `edge` | workspaces, usage, monitor, projects, handoff, recaps, windowNames, shell, connectors, agentCleanup, messages, osDevice | light pure-JS services: isolated from the core, not from each other | always |
+| `edge` | workspaces, usage, monitor, projects, handoff, recaps, windowNames, shell, connectors, sharedMachines, agentCleanup, messages, osDevice | light pure-JS services: isolated from the core, not from each other | always |
| `gateway` | gateway | network, crypto and pure-JS WebRTC: the attack surface | on demand |
| `models` | models | grid's installs, downloads and commands | on demand |
| `devices` | devices, wifi | the dials' serial ports, the fleet's lane, the voice router's worker, the Wi-Fi device | on demand |
diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.ts
index f65b3e900..c0c402aa9 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -25,6 +25,7 @@ import { startRouter } from './router.js'
import { startCloud } from './cloud.js'
import { startSearch } from './search.js'
import { startShell } from './shell.js'
+import { startSharedMachines } from './sharedMachines.js'
import { startSharing } from './sharing.js'
import { startStoreInCore } from './store.js'
import { startUsageInCore } from './usage.js'
@@ -35,6 +36,6 @@ import { startWorkspaces } from './workspaces.js'
describe('the services the core runs in its own process only when they do not run in theirs', () => {
it('are their own starts, unchanged: the same services either way', () => {
- expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startAgentCleanup, startCloud, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startOsDevice, startProjects, startRecaps, startRouter, startSearch, startSharing, startShell, startStoreInCore, startMessagesInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })
+ expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startAgentCleanup, startCloud, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startOsDevice, startProjects, startRecaps, startRouter, startSearch, startSharedMachines, startSharing, startShell, startStoreInCore, startMessagesInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })
})
})
diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.ts
index 3b546d84a..8756d465c 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -25,6 +25,7 @@ export { startAgentCleanup } from './agentCleanup.js'
export { startMemory } from './memory.js'
export { startCloud } from './cloud.js'
export { startConnectors } from './connectors.js'
+export { startSharedMachines } from './sharedMachines.js'
export { startDevices } from './devices.js'
export { startHandoff } from './handoff.js'
export { startMessagesInCore } from './messages.js'
diff --git a/cli/src/services/sharedMachines.spec.ts b/cli/src/services/sharedMachines.spec.ts
new file mode 100644
index 000000000..28ef57862
--- /dev/null
+++ b/cli/src/services/sharedMachines.spec.ts
@@ -0,0 +1,265 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fakeCore } from '../testing/fakeCore.js'
+import type { Asker, BackendNotice } from '../core/api.js'
+import type { PortFailure, SharedMachine, SharedMachinesPort, SharePolicy } from '../lib/sharedMachinesPort.js'
+import { normalizeEmails, readPolicy, SHARE_EMAILS_MAX, SHARED_MACHINES_REQUESTS, startSharedMachines, trustedKeys } from './sharedMachines.js'
+
+const owner: Asker = { local: true, owner: true }
+const key = (n: number) => Buffer.alloc(32, n).toString('base64')
+const M = 'ab'.repeat(16)
+const down: PortFailure = { failed: { status: 502, code: 'BACKEND_UNREACHABLE', message: 'Could not reach the Harness backend.' } }
+
+function policy(patch: Partial<SharePolicy> = {}): SharePolicy {
+ return { emails: [], sameDomain: false, domain: 'acme.io', members: [], ...patch }
+}
+const kim = { email: '[email protected]', name: 'Kim', via: 'domain' as const, machines: [{ machineId: 'k'.repeat(32), pub: key(1), label: 'Kim’s Mac' }] }
+const ann = { email: '[email protected]', name: null, via: 'email' as const, machines: [{ machineId: 'a'.repeat(32), pub: key(2), label: '' }] }
+const studio: SharedMachine = { machineId: M, name: 'Studio', hostname: 'studio.local', pub: key(3),
+ share: { ownerName: 'Dee', ownerEmail: '[email protected]', via: 'domain', added: true } }
+
+function fakePort(over: Partial<SharedMachinesPort> = {}): { [K in keyof SharedMachinesPort]: ReturnType<typeof vi.fn> } {
+ return {
+ policy: vi.fn(async () => policy()),
+ publish: vi.fn(async (emails: string[], sameDomain: boolean) => policy({ emails, sameDomain })),
+ shared: vi.fn(async () => []),
+ add: vi.fn(async () => true as const),
+ remove: vi.fn(async () => true as const),
+ trust: vi.fn(async () => ({ pins: 0, keys: 0 })),
+ ...over,
+ } as never
+}
+
+describe('shared machines', () => {
+ let dir: string
+ let file: string
+ let timers: Array<{ fn: () => void; ms: number; cancelled: boolean }>
+ const setTimer = (fn: () => void, ms: number) => {
+ const t = { fn, ms, cancelled: false }
+ timers.push(t)
+ return { cancel: () => { t.cancelled = true } }
+ }
+ const live = () => timers.filter((t) => !t.cancelled)
+ const fire = async () => { const t = live().at(-1)!; t.cancelled = true; t.fn(); await vi.waitFor(() => expect(live().length).toBe(1)) }
+ const log = vi.fn()
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'shared-machines-'))
+ file = join(dir, 'shared-machines.json')
+ timers = []
+ log.mockReset()
+ })
+ afterEach(() => rmSync(dir, { recursive: true, force: true }))
+
+ const start = (port: ReturnType<typeof fakePort> | null, notices?: Array<(n: BackendNotice) => void>) => {
+ const core = fakeCore({ dataDir: dir, account: { onNotice: vi.fn((listener) => { notices?.push(listener); return () => {} }) } })
+ return startSharedMachines(core, { port: port as SharedMachinesPort | null, file, setTimer, log }).shared_machines!
+ }
+
+ it('declares its one request', () => {
+ expect(SHARED_MACHINES_REQUESTS).toEqual(['shared_machines'])
+ })
+
+ it('is the owner’s alone', async () => {
+ const handle = start(fakePort())
+ expect(await handle({ action: 'get' }, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })
+ expect(await handle({ action: 'teleport' }, owner)).toEqual({ error: 'UNKNOWN_ACTION' })
+ })
+
+ describe('this machine’s sharing', () => {
+ it('is off by default, and offers the owner’s domain', async () => {
+ expect(await start(fakePort())({ action: 'get' }, owner)).toEqual({ emails: [], sameDomain: false, domain: 'acme.io', members: [] })
+ })
+
+ it('shares with addresses and the domain: published, kept here, and the machines it names trusted', async () => {
+ const port = fakePort({ policy: vi.fn(async () => policy({ emails: ['[email protected]'], sameDomain: true, members: [ann, kim,
+ { email: '[email protected]', name: null, via: 'email', machines: [] }] })) })
+ const view = await start(port)({ action: 'set', emails: [' [email protected] ', '[email protected]'], sameDomain: true }, owner)
+ expect(port.publish).toHaveBeenCalledWith(['[email protected]'], true)
+ expect(JSON.parse(readFileSync(file, 'utf-8'))).toEqual({ emails: ['[email protected]'], sameDomain: true })
+ expect(port.trust).toHaveBeenCalledWith({ pins: [], keys: [
+ { machineId: 'a'.repeat(32), pub: key(2), label: 'Machine · [email protected]' },
+ { machineId: 'k'.repeat(32), pub: key(1), label: 'Kim’s Mac · [email protected]' },
+ ] })
+ // Who uses it: those this machine's own policy names, never one the backend alone lists.
+ expect(view).toEqual({ emails: ['[email protected]'], sameDomain: true, domain: 'acme.io', members: [
+ { email: '[email protected]', name: null, via: 'email', machines: 1 },
+ { email: '[email protected]', name: 'Kim', via: 'domain', machines: 1 },
+ ] })
+ })
+
+ it('refuses what is not a list of addresses, and says why the backend did', async () => {
+ const port = fakePort({ publish: vi.fn(async () => ({ failed: { status: 400, code: 'PUBLIC_DOMAIN', message: 'It is a public email domain.' } })) })
+ const handle = start(port)
+ // An address the backend would refuse is named, never sent: a whole save once failed on `name@!gmail.com`.
+ expect(await handle({ action: 'set', emails: ['[email protected]', 'bitcoinbuilder.ai@!gmail.com'], sameDomain: false }, owner))
+ .toEqual({ error: 'BAD_REQUEST', message: 'Not an email address: bitcoinbuilder.ai@!gmail.com' })
+ for (const payload of [{ emails: '[email protected]', sameDomain: false }, { emails: ['nope'], sameDomain: false }, { emails: [7], sameDomain: false }, { emails: [], sameDomain: 'yes' },
+ { emails: Array.from({ length: SHARE_EMAILS_MAX + 1 }, (_, i) => `p${i}@acme.io`), sameDomain: false }]) {
+ expect(await handle({ action: 'set', ...payload }, owner)).toMatchObject({ error: 'BAD_REQUEST' })
+ }
+ expect(await handle({ action: 'set', emails: [], sameDomain: true }, owner)).toEqual({ error: 'PUBLIC_DOMAIN', message: 'It is a public email domain.' })
+ expect(readPolicy(file)).toEqual({ emails: [], sameDomain: false })
+ })
+
+ it('reads as kept here when the backend cannot say, and signed out', async () => {
+ writeFileSync(file, JSON.stringify({ emails: ['[email protected]'], sameDomain: true }))
+ expect(await start(fakePort({ policy: vi.fn(async () => down) }))({ action: 'get' }, owner)).toEqual({
+ emails: ['[email protected]'], sameDomain: true, domain: null, members: [], error: 'BACKEND_UNREACHABLE', message: down.failed.message })
+ const before = timers.length
+ const signedOut = start(null)
+ expect(await signedOut({ action: 'get' }, owner)).toMatchObject({ emails: ['[email protected]'], error: 'NOT_SIGNED_IN' })
+ expect(await signedOut({ action: 'set', emails: [], sameDomain: false }, owner)).toMatchObject({ error: 'NOT_SIGNED_IN' })
+ expect(await signedOut({ action: 'add', machineId: M }, owner)).toMatchObject({ error: 'NOT_SIGNED_IN' })
+ // Signed out, nothing is read: no timer.
+ expect(timers.length).toBe(before)
+ })
+
+ it('offers no domain sharing at a public one, even one kept from before', async () => {
+ writeFileSync(file, JSON.stringify({ emails: [], sameDomain: true }))
+ const port = fakePort({ policy: vi.fn(async () => policy({ domain: null })) })
+ expect(await start(port)({ action: 'get' }, owner)).toMatchObject({ sameDomain: false, domain: null })
+ })
+ })
+
+ describe('machines shared with this account', () => {
+ it('adds one shared with the domain, and pins the machines it may use', async () => {
+ const port = fakePort({ shared: vi.fn(async () => [studio, { ...studio, machineId: 'n'.repeat(32), name: null, hostname: null, share: { ...studio.share, ownerEmail: '', added: false } },
+ { ...studio, machineId: 'x'.repeat(32), pub: null }, { ...studio, machineId: 'h'.repeat(32), name: null, share: { ...studio.share, via: 'email' as const, ownerEmail: '' } },
+ { ...studio, machineId: 'z'.repeat(32), name: null, hostname: null }]) })
+ expect(await start(port)({ action: 'add', machineId: M }, owner)).toEqual({ ok: true })
+ expect(port.add).toHaveBeenCalledWith(M)
+ expect(port.trust).toHaveBeenCalledWith({ pins: [
+ { machineId: M, pub: key(3), label: 'Studio · [email protected]' },
+ { machineId: 'h'.repeat(32), pub: key(3), label: 'studio.local · Dee' },
+ { machineId: 'z'.repeat(32), pub: key(3), label: 'Machine · [email protected]' },
+ ], keys: [] })
+ })
+
+ it('takes one back out, and says why it could not', async () => {
+ const port = fakePort({ remove: vi.fn(async () => ({ failed: { status: 404, code: 'NOT_SHARED', message: 'This machine is not shared with you.' } })) })
+ const handle = start(port)
+ expect(await handle({ action: 'remove', machineId: M }, owner)).toEqual({ error: 'NOT_SHARED', message: 'This machine is not shared with you.' })
+ expect(await handle({ action: 'remove' }, owner)).toEqual({ error: 'BAD_REQUEST' })
+ port.remove.mockResolvedValueOnce(true)
+ expect(await handle({ action: 'remove', machineId: M }, owner)).toEqual({ ok: true })
+ })
+ })
+
+ describe('reading again', () => {
+ it('starts soon, again when the machines change, and every few minutes, more often while anything is shared', async () => {
+ const notices: Array<(n: BackendNotice) => void> = []
+ const port = fakePort()
+ start(port, notices)
+ expect(live().map((t) => t.ms)).toEqual([5_000])
+ await fire()
+ expect(port.trust).toHaveBeenCalledWith({ pins: [], keys: [] })
+ expect(live().map((t) => t.ms)).toEqual([15 * 60_000])
+ notices[0]({ type: 'desk_changed', revision: 1 } as BackendNotice)
+ expect(live().map((t) => t.ms)).toEqual([15 * 60_000])
+ notices[0]({ type: 'machines_changed', reason: 'updated' })
+ expect(live().map((t) => t.ms)).toEqual([1_000])
+ port.shared.mockResolvedValue([studio])
+ await fire()
+ expect(live().map((t) => t.ms)).toEqual([2 * 60_000])
+ })
+
+ it('tells the backend again what this machine holds, and stops sharing at a domain that went public', async () => {
+ writeFileSync(file, JSON.stringify({ emails: ['[email protected]'], sameDomain: true }))
+ const port = fakePort({ policy: vi.fn(async () => policy({ domain: null })) })
+ start(port)
+ await fire()
+ expect(port.publish).toHaveBeenCalledWith(['[email protected]'], false)
+ expect(readPolicy(file)).toEqual({ emails: ['[email protected]'], sameDomain: false })
+ // Held the same way on both sides: nothing to tell.
+ port.publish.mockClear()
+ port.policy.mockResolvedValue(policy({ emails: ['[email protected]'], members: [ann] }))
+ await fire()
+ expect(port.publish).not.toHaveBeenCalled()
+ expect(port.trust).toHaveBeenLastCalledWith({ pins: [], keys: [{ ...ann.machines[0], label: 'Machine · [email protected]' }] })
+ })
+
+ it('changes only what it could read, and nothing when it read nothing', async () => {
+ const port = fakePort({ shared: vi.fn(async () => down), policy: vi.fn(async () => down) })
+ start(port)
+ await fire()
+ expect(port.trust).not.toHaveBeenCalled()
+ port.policy.mockResolvedValue(policy())
+ await fire()
+ expect(port.trust).toHaveBeenLastCalledWith({ keys: [] })
+ port.shared.mockResolvedValue([])
+ port.policy.mockResolvedValue(down)
+ await fire()
+ expect(port.trust).toHaveBeenLastCalledWith({ pins: [] })
+ // A publish that failed is not written as the policy here.
+ writeFileSync(file, JSON.stringify({ emails: [], sameDomain: true }))
+ port.policy.mockResolvedValue(policy({ domain: null }))
+ port.publish.mockResolvedValue(down)
+ await fire()
+ expect(readPolicy(file).sameDomain).toBe(true)
+ expect(port.trust).toHaveBeenLastCalledWith({ pins: [] })
+ })
+
+ it('logs a read or a trust update that failed, and goes on', async () => {
+ const port = fakePort({ trust: vi.fn(async () => down) })
+ start(port)
+ await fire()
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('could not update the trust stores'))
+ port.shared.mockRejectedValueOnce(new Error('boom'))
+ await fire()
+ expect(log).toHaveBeenCalledWith('read failed: boom')
+ port.shared.mockRejectedValueOnce('odd')
+ await fire()
+ expect(log).toHaveBeenCalledWith('read failed: odd')
+ })
+
+ it('runs one read at a time, and one asked for meanwhile right after', async () => {
+ let release: () => void = () => {}
+ const port = fakePort({ shared: vi.fn(() => new Promise<SharedMachine[]>((resolve) => { release = () => resolve([]) })) })
+ const handle = start(port)
+ const adding = handle({ action: 'add', machineId: M }, owner)
+ const removing = handle({ action: 'remove', machineId: M }, owner)
+ await vi.waitFor(() => expect(port.shared).toHaveBeenCalledTimes(1))
+ release()
+ await vi.waitFor(() => expect(port.shared).toHaveBeenCalledTimes(2))
+ release()
+ expect(await adding).toEqual({ ok: true })
+ expect(await removing).toEqual({ ok: true })
+ expect(port.shared).toHaveBeenCalledTimes(2)
+ })
+ })
+
+ it('reads a policy file that is missing, broken or holds what is not an address as off', () => {
+ expect(readPolicy(join(dir, 'missing.json'))).toEqual({ emails: [], sameDomain: false })
+ writeFileSync(file, '{')
+ expect(readPolicy(file)).toEqual({ emails: [], sameDomain: false })
+ writeFileSync(file, JSON.stringify({ emails: ['nope'], sameDomain: 'yes' }))
+ expect(readPolicy(file)).toEqual({ emails: [], sameDomain: false })
+ expect(normalizeEmails([7])).toBeNull()
+ expect(normalizeEmails([`${'x'.repeat(250)}@a.io`])).toBeNull()
+ })
+
+ it('trusts only the members its own policy names', () => {
+ expect(trustedKeys({ emails: [], sameDomain: true }, policy({ domain: null, members: [kim] }))).toEqual([])
+ expect(trustedKeys({ emails: [], sameDomain: false }, policy({ members: [kim, ann] }))).toEqual([])
+ expect(trustedKeys({ emails: [], sameDomain: true }, policy({ members: [{ ...kim, email: '[email protected]' }] }))).toEqual([])
+ })
+
+ it('keeps its own timer, file and log by default', async () => {
+ vi.useFakeTimers()
+ const said = vi.spyOn(console, 'log').mockImplementation(() => {})
+ try {
+ const notices: Array<(n: BackendNotice) => void> = []
+ const core = fakeCore({ dataDir: dir, account: { onNotice: vi.fn((listener) => { notices.push(listener); return () => {} }) } })
+ const port = fakePort({ trust: vi.fn(async () => down) })
+ startSharedMachines(core, { port: port as never })
+ notices[0]({ type: 'machines_changed', reason: 'updated' })
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(port.shared).toHaveBeenCalledTimes(1)
+ expect(said).toHaveBeenCalledWith(expect.stringContaining('[shared-machines] could not update the trust stores'))
+ startSharedMachines(core)
+ } finally { said.mockRestore(); vi.useRealTimers() }
+ })
+})
diff --git a/cli/src/services/sharedMachines.ts b/cli/src/services/sharedMachines.ts
new file mode 100644
index 000000000..793fda65d
--- /dev/null
+++ b/cli/src/services/sharedMachines.ts
@@ -0,0 +1,206 @@
+/**
+ * Sharing a whole machine with other accounts (docs/plans/2026-10-15-share-machine-plan.md), in the edge
+ * host. Off by default.
+ *
+ * `shared_machines` takes `{action}`:
+ * - `get`: this machine's sharing, `{emails, sameDomain, domain, members}`. `domain` is the owner's, null
+ * at a public one (gmail.com, …), where "everyone at" is never offered; `members` are who use it now.
+ * - `set` {emails, sameDomain}: share this machine with these addresses and, or, everyone at the domain.
+ * Empty and false is "not shared".
+ * - `add` {machineId}: add a machine shared with this account's domain to its machines; `remove` takes it
+ * back out.
+ * Owner only, like every request that changes this machine.
+ *
+ * The policy is kept here, on the machine (`shared-machines.json`), and published to the backend, which
+ * lists the machine to the people it names and lets their relay sessions through. Whom to trust is still
+ * this machine's to decide: it reads who uses it from the backend, keeps those its own policy names, and
+ * has the gateway trust their machines' keys (gateway/sharedTrust.ts), as Share's owner keeps its grants.
+ * The other half is for the machines shared with this account: their keys are pinned, so a window here
+ * reaches them as it reaches the account's own.
+ *
+ * Read again as it starts, when the backend says the machines changed (someone added this machine, the
+ * sharing of one shared with this account changed), after each change made here, and every few minutes
+ * while anything is shared either way.
+ */
+import { join } from 'node:path'
+import { readFileSync, renameSync, writeFileSync } from 'node:fs'
+import type { CoreApi, ServiceRequests } from '../core/api.js'
+import { failed, type PortFailure, type ShareMember, type SharedMachinesPort, type SharePolicy,
+ type SharedTrustPeer } from '../lib/sharedMachinesPort.js'
+
+/** The request shared machines answers for the apps, declared in core/api.ts for the core to route. */
+export { SHARED_MACHINES_REQUESTS } from '../core/api.js'
+
+/** The most addresses one machine is shared with (the backend's `SHARE_EMAILS_MAX`). */
+export const SHARE_EMAILS_MAX = 100
+/** How often the sharing is read again while anything is shared either way, and while nothing is. */
+const BUSY_MS = 2 * 60_000
+const IDLE_MS = 15 * 60_000
+/** A first read waits for the core and the gateway to settle; a notice is read soon after. */
+const START_MS = 5_000
+const NOTICE_MS = 1_000
+
+/** The backend's own rule for an address (zod's `email()`): one it refuses is refused here first, by name,
+ * rather than failing the whole list there (an address typed `name@!gmail.com`, 2026-10-15). */
+const EMAIL_RE = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/
+
+/** This machine's sharing as its owner set it. */
+export interface LocalPolicy { emails: string[]; sameDomain: boolean }
+
+export interface SharedMachinesDeps {
+ /** The core's `shared_machines` answers, or null signed out: nothing is shared or read. */
+ port: SharedMachinesPort | null
+ file: string
+ setTimer: (fn: () => void, ms: number) => { cancel(): void }
+ log: (line: string) => void
+}
+
+const OFF: LocalPolicy = { emails: [], sameDomain: false }
+
+export function readPolicy(file: string): LocalPolicy {
+ try {
+ const raw = JSON.parse(readFileSync(file, 'utf-8')) as Partial<LocalPolicy>
+ return { emails: normalizeEmails(raw.emails) ?? [], sameDomain: raw.sameDomain === true }
+ } catch { return OFF }
+}
+
+function writePolicy(file: string, policy: LocalPolicy): void {
+ const temp = `${file}.${process.pid}.tmp`
+ writeFileSync(temp, JSON.stringify(policy, null, 2), { mode: 0o600 })
+ renameSync(temp, file)
+}
+
+/** Addresses trimmed, lower case, each once; null when one is not an address or there are too many. */
+export function normalizeEmails(raw: unknown): string[] | null {
+ if (!Array.isArray(raw)) return null
+ const emails = [...new Set(raw.map((e) => typeof e === 'string' ? e.trim().toLowerCase() : ''))]
+ if (emails.length > SHARE_EMAILS_MAX || emails.some((e) => e.length > 254 || !EMAIL_RE.test(e))) return null
+ return emails
+}
+
+const shares = (policy: LocalPolicy): boolean => policy.emails.length > 0 || policy.sameDomain
+const samePolicy = (a: LocalPolicy, b: LocalPolicy): boolean =>
+ a.sameDomain === b.sameDomain && a.emails.length === b.emails.length && a.emails.every((e) => b.emails.includes(e))
+
+/** Whether this machine's own policy names someone the backend says uses it. */
+const names = (local: LocalPolicy, domain: string | null, member: ShareMember): boolean => member.via === 'email'
+ ? local.emails.includes(member.email)
+ : local.sameDomain && !!domain && member.email.endsWith(`@${domain}`)
+
+/** The machines of those the backend says use this one, those this machine's own policy names. */
+export function trustedKeys(local: LocalPolicy, remote: SharePolicy): SharedTrustPeer[] {
+ return remote.members
+ .filter((m) => names(local, remote.domain, m))
+ .flatMap((m) => m.machines.map((machine) => ({ ...machine, label: `${machine.label || 'Machine'} · ${m.email}` })))
+}
+
+const answerFailure = (f: PortFailure): Record<string, unknown> => ({ error: f.failed.code, message: f.failed.message })
+
+export function startSharedMachines(core: CoreApi, overrides: Partial<SharedMachinesDeps> = {}): ServiceRequests {
+ const deps: SharedMachinesDeps = {
+ port: overrides.port !== undefined ? overrides.port : null,
+ file: overrides.file ?? join(core.dataDir, 'shared-machines.json'),
+ setTimer: overrides.setTimer ?? ((fn, ms) => { const t = setTimeout(fn, ms).unref(); return { cancel: () => clearTimeout(t) } }),
+ log: overrides.log ?? ((line) => console.log(`[shared-machines] ${line}`)),
+ }
+ const port = deps.port
+ let timer: { cancel(): void } | null = null
+ let reading: Promise<void> | null = null
+ let again = false
+ /** Whether anything was shared with this account at the last read. */
+ let sharedWithUs = false
+
+ /** Publish this machine's policy and trust whom it names; pin the machines shared with this account. */
+ const refresh = async (port: SharedMachinesPort): Promise<void> => {
+ const local = readPolicy(deps.file)
+ const desired: { pins?: SharedTrustPeer[]; keys?: SharedTrustPeer[] } = {}
+ const shared = await port.shared()
+ if (!failed(shared)) {
+ sharedWithUs = shared.length > 0
+ desired.pins = shared.filter((m) => m.share.added && m.pub).map((m) => ({
+ machineId: m.machineId, pub: m.pub!, label: `${m.name || m.hostname || 'Machine'} · ${m.share.ownerEmail || m.share.ownerName}`,
+ }))
+ }
+ let remote = await port.policy()
+ // The backend is told again what this machine holds, whenever it says otherwise (a write that failed,
+ // a backend that lost it, the owner's domain now public).
+ if (!failed(remote) && !samePolicy(local, remote)) {
+ const sameDomain = local.sameDomain && !!remote.domain
+ remote = await port.publish(local.emails, sameDomain)
+ if (!failed(remote) && sameDomain !== local.sameDomain) writePolicy(deps.file, { ...local, sameDomain })
+ }
+ if (!failed(remote)) desired.keys = shares(local) ? trustedKeys(local, remote) : []
+ if (!desired.pins && !desired.keys) return
+ const held = await port.trust(desired)
+ if (failed(held)) deps.log(`could not update the trust stores: ${held.failed.message}`)
+ }
+
+ /** One read at a time; one asked for while another runs follows it. Then the next round. */
+ const read = (port: SharedMachinesPort): Promise<void> => {
+ if (reading) { again = true; return reading }
+ reading = (async () => {
+ do {
+ again = false
+ await refresh(port).catch((error: unknown) => deps.log(`read failed: ${error instanceof Error ? error.message : String(error)}`))
+ } while (again)
+ })().finally(() => {
+ reading = null
+ schedule(port, shares(readPolicy(deps.file)) || sharedWithUs ? BUSY_MS : IDLE_MS)
+ })
+ return reading
+ }
+
+ const schedule = (port: SharedMachinesPort, ms: number): void => {
+ timer?.cancel()
+ timer = deps.setTimer(() => { timer = null; void read(port) }, ms)
+ }
+
+ if (port) {
+ schedule(port, START_MS)
+ core.account.onNotice((notice) => { if (notice.type === 'machines_changed') schedule(port, NOTICE_MS) })
+ }
+
+ const view = async (): Promise<Record<string, unknown>> => {
+ const local = readPolicy(deps.file)
+ const remote = port ? await port.policy() : null
+ if (!remote || failed(remote)) {
+ return { ...local, domain: null, members: [], ...(remote ? answerFailure(remote) : { error: 'NOT_SIGNED_IN' }) }
+ }
+ return { ...local, sameDomain: local.sameDomain && !!remote.domain, domain: remote.domain,
+ members: remote.members.filter((m) => names(local, remote.domain, m))
+ .map((m) => ({ email: m.email, name: m.name, via: m.via, machines: m.machines.length })) }
+ }
+
+ return {
+ shared_machines: async (payload, asker) => {
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
+ switch (payload.action) {
+ case 'get': return view()
+ case 'set': {
+ const emails = normalizeEmails(payload.emails)
+ if (!emails || typeof payload.sameDomain !== 'boolean') {
+ const bad = Array.isArray(payload.emails) && payload.emails.length <= SHARE_EMAILS_MAX
+ ? payload.emails.find((e) => typeof e !== 'string' || !EMAIL_RE.test(e.trim().toLowerCase())) : undefined
+ return { error: 'BAD_REQUEST', message: typeof bad === 'string' ? `Not an email address: ${bad}` : `Enter up to ${SHARE_EMAILS_MAX} email addresses.` }
+ }
+ if (!port) return { error: 'NOT_SIGNED_IN', message: 'Sign in to share this machine.' }
+ const published = await port.publish(emails, payload.sameDomain)
+ if (failed(published)) return answerFailure(published)
+ writePolicy(deps.file, { emails: published.emails, sameDomain: published.sameDomain })
+ await read(port)
+ return view()
+ }
+ case 'add':
+ case 'remove': {
+ if (typeof payload.machineId !== 'string') return { error: 'BAD_REQUEST' }
+ if (!port) return { error: 'NOT_SIGNED_IN', message: 'Sign in to add a shared machine.' }
+ const done = payload.action === 'add' ? await port.add(payload.machineId) : await port.remove(payload.machineId)
+ if (failed(done)) return answerFailure(done)
+ await read(port)
+ return { ok: true }
+ }
+ default: return { error: 'UNKNOWN_ACTION' }
+ }
+ },
+ }
+}
diff --git a/cli/src/services/sharedMachinesProcess.spec.ts b/cli/src/services/sharedMachinesProcess.spec.ts
new file mode 100644
index 000000000..081ea660a
--- /dev/null
+++ b/cli/src/services/sharedMachinesProcess.spec.ts
@@ -0,0 +1,64 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { runServiceProcess, type ServiceProcessOptions } from './process.js'
+import { runSharedMachinesService } from './sharedMachinesProcess.js'
+import type { SharedMachinesDeps } from './sharedMachines.js'
+import type { CoreApi } from '../core/api.js'
+
+// The real default reaches a real socket: never in a test.
+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))
+
+describe('shared machines in their own process', () => {
+ afterEach(() => vi.clearAllMocks())
+
+ it('answers shared_machines with the same handler as in the core\'s process', async () => {
+ let options: ServiceProcessOptions | null = null
+ runSharedMachinesService({
+ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',
+ run: (given) => { options = given; return { stop: vi.fn() } },
+ start: () => ({ shared_machines: async () => ({ emails: [] }) }),
+ })
+ expect(options).toMatchObject({ name: 'sharedMachines', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
+ expect(await options!.requests.shared_machines!({ action: 'get' }, { local: true, owner: true })).toEqual({ emails: [] })
+ })
+
+ it('asks the core for the sharing and the trust stores, and hears the notices that change them', async () => {
+ let options: ServiceProcessOptions | null = null
+ let given: { api: CoreApi, overrides: Partial<SharedMachinesDeps> } | null = null
+ runSharedMachinesService({
+ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',
+ run: (o) => { options = o; return { stop: vi.fn() } },
+ start: (api, overrides = {}) => { given = { api, overrides }; return { shared_machines: async () => ({}) } },
+ })
+ const port = given!.overrides.port!
+ // No core yet: it reads as unreachable.
+ expect(await port.shared()).toMatchObject({ failed: { code: expect.stringContaining('not connected') } })
+ const query = vi.fn(async (_query: string, payload: Record<string, unknown>) =>
+ payload.op === 'shared' ? { status: 200, body: { success: true, data: { machines: [] } } } : {})
+ options!.onConnected!({ query } as never)
+ expect(await port.shared()).toEqual([])
+ expect(query).toHaveBeenCalledWith('shared_machines', { op: 'shared' })
+
+ const heard = vi.fn()
+ const stop = given!.api.account.onNotice(heard)
+ await options!.onEvent!({ kind: 'notice', notice: { type: 'machines_changed', reason: 'updated' } })
+ await options!.onEvent!({ kind: 'notice' })
+ await options!.onEvent!({ kind: 'something_else', notice: { type: 'desk_changed', revision: 1 } })
+ expect(heard).toHaveBeenCalledTimes(1)
+ expect(heard).toHaveBeenCalledWith({ type: 'machines_changed', reason: 'updated' })
+ stop()
+ await options!.onEvent!({ kind: 'notice', notice: { type: 'machines_changed', reason: 'updated' } })
+ expect(heard).toHaveBeenCalledTimes(1)
+
+ options!.onDisconnected!()
+ expect(await port.shared()).toMatchObject({ failed: expect.any(Object) })
+ })
+
+ it('runs as a real service by default', () => {
+ const stopTimers = vi.useFakeTimers()
+ runSharedMachinesService({ dataDir: '/nonexistent', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
+ expect(runServiceProcess).toHaveBeenCalledWith(expect.objectContaining({ name: 'sharedMachines' }))
+ const requests = vi.mocked(runServiceProcess).mock.calls[0][0].requests
+ expect(Object.keys(requests)).toEqual(['shared_machines'])
+ stopTimers.useRealTimers()
+ })
+})
diff --git a/cli/src/services/sharedMachinesProcess.ts b/cli/src/services/sharedMachinesProcess.ts
new file mode 100644
index 000000000..452cf261a
--- /dev/null
+++ b/cli/src/services/sharedMachinesProcess.ts
@@ -0,0 +1,48 @@
+/**
+ * Shared machines in their own process (`harness __service sharedMachines`, in the edge host): the same
+ * `shared_machines` handler as in the core's process (services/sharedMachines.ts). It asks the core one
+ * thing, `shared_machines` (core/sharedMachinesQueries.ts): this machine's sharing and the machines shared
+ * with this account, read and written through the core's sign-in, and the gateway's trust stores, which
+ * only the gateway holds. The core tells it `machines_changed` (`service_event` kind `notice`).
+ */
+import type { BackendNotice } from '../core/api.js'
+import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
+import { processCoreApi } from './processCoreApi.js'
+import { startSharedMachines } from './sharedMachines.js'
+import { sharedMachinesPortOf } from '../lib/sharedMachinesPort.js'
+
+export interface SharedMachinesServiceOptions {
+ dataDir: string
+ socketPath: string
+ machineId: string
+ token: string
+ /** Swapped in tests for one that does not touch the real socket or process. */
+ run?: typeof runServiceProcess
+ /** Swapped in tests for one that keeps no timer. */
+ start?: typeof startSharedMachines
+}
+
+export function runSharedMachinesService(options: SharedMachinesServiceOptions): ServiceProcess {
+ let core: CoreConnection | null = null
+ const ask = (query: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> =>
+ core ? core.query(query, payload) : Promise.reject(new Error('not connected to the core'))
+ const listeners = new Set<(notice: BackendNotice) => void>()
+ const api = processCoreApi(options.dataDir, 'sharedMachines', {
+ onNotice: (listener) => { listeners.add(listener); return () => { listeners.delete(listener) } },
+ })
+ // A refusal or no core reads as the backend unreachable: the next round tries again.
+ const port = sharedMachinesPortOf((op, payload = {}) => ask('shared_machines', { ...payload, op }).catch((error: unknown) => ({ error: String(error) })))
+ return (options.run ?? runServiceProcess)({
+ name: 'sharedMachines',
+ socketPath: options.socketPath,
+ machineId: options.machineId,
+ token: options.token,
+ requests: (options.start ?? startSharedMachines)(api, { port }),
+ onEvent: (payload) => {
+ if (payload.kind !== 'notice' || !payload.notice || typeof payload.notice !== 'object') return
+ for (const listener of listeners) listener(payload.notice as BackendNotice)
+ },
+ onConnected: (connection) => { core = connection },
+ onDisconnected: () => { core = null },
+ })
+}
diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dart
index 2def58121..f31100660 100644
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@ -17,9 +17,17 @@ import 'bearer_auth_interceptor.dart';
/// Rows and freshness from one response, even when requests overlap.
class MachineInventory extends UnmodifiableListView<Machine> {
- MachineInventory(super.source, {required this.isStale});
+ MachineInventory(
+ super.source, {
+ required this.isStale,
+ this.toAdd = const [],
+ });
final bool isStale;
+
+ /// Machines shared with this account's domain and not added yet: listed under Add machine, where one
+ /// click adds it (backend routes/machineShares.ts).
+ final List<Machine> toAdd;
}
/// Control-plane REST client.
@@ -587,6 +595,12 @@ class ApiClient {
final owned = list
.map((e) => Machine.fromJson(e as Map<String, dynamic>))
.toList();
+ // Whole machines other accounts share with this one: those named for it and those it added are its
+ // machines too; those shared with its domain and not added wait under Add machine.
+ final sharedWhole = [
+ for (final row in data['sharedMachines'] as List? ?? const [])
+ Machine.fromJson(Map<String, dynamic>.from(row as Map)),
+ ].where((m) => !owned.any((own) => own.machineId == m.machineId)).toList();
var sharedMachines = _sharedMachines;
try {
final shared = await _dio.get('/api/harness-shares');
@@ -609,12 +623,20 @@ class ApiClient {
_sharedMachines = sharedMachines;
lastMachinesStale = stale;
}
- return MachineInventory([
+ final usable = [
...owned,
- ...sharedMachines.where(
- (shared) => !owned.any((own) => own.machineId == shared.machineId),
- ),
- ], isStale: stale);
+ ...sharedWhole.where((m) => m.machineShare?.added == true),
+ ];
+ return MachineInventory(
+ [
+ ...usable,
+ ...sharedMachines.where(
+ (shared) => !usable.any((own) => own.machineId == shared.machineId),
+ ),
+ ],
+ isStale: stale,
+ toAdd: sharedWhole.where((m) => m.machineShare?.added != true).toList(),
+ );
}
Future<String?> renameMachine({
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index cf1f1b079..232798885 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -102,6 +102,36 @@ class SharedHarness {
bool sameMachineId(String a, String b) =>
a.replaceAll('-', '').toLowerCase() == b.replaceAll('-', '').toLowerCase();
+/// A whole machine another account shares with this one (backend lib/machineAccess.ts): its owner
+/// named this account's address ([via] `email`), or shared it with everyone at their domain and this
+/// account added it ([via] `domain`, [added]). Used with the owner's own rights, unlike [Machine.isShared],
+/// one harness shared to watch.
+class MachineShare {
+ final String ownerName;
+ final String ownerEmail;
+ final String via;
+ final bool added;
+
+ const MachineShare({
+ required this.ownerName,
+ required this.ownerEmail,
+ required this.via,
+ required this.added,
+ });
+
+ bool get viaDomain => via == 'domain';
+
+ factory MachineShare.fromJson(Map<String, dynamic> j) => MachineShare(
+ ownerName: j['ownerName'] as String? ?? '',
+ ownerEmail: j['ownerEmail'] as String? ?? '',
+ via: j['via'] == 'domain' ? 'domain' : 'email',
+ added: j['added'] == true,
+ );
+
+ /// Who shared it, as a person reads it: their name, or their address.
+ String get owner => ownerName.isNotEmpty ? ownerName : ownerEmail;
+}
+
class Machine {
final String machineId;
@@ -117,6 +147,9 @@ class Machine {
final List<SharedHarness> sharedHarnesses;
final String? status;
+ /// Set when another account shares this whole machine with this one; null for the account's own.
+ final MachineShare? machineShare;
+
const Machine({
required this.machineId,
this.apiKey = '',
@@ -129,8 +162,13 @@ class Machine {
this.ownerName,
this.sharedHarnesses = const [],
this.status,
+ this.machineShare,
});
+ /// Another account's machine, shared whole with this one: used as the account's own, managed (renamed,
+ /// removed, shared on) by its owner alone.
+ bool get isSharedMachine => machineShare != null;
+
String get displayName => (name != null && name!.isNotEmpty)
? name!
: 'machine-${machineId.length > 8 ? machineId.substring(0, 8) : machineId}';
@@ -172,6 +210,9 @@ class Machine {
SharedHarness.fromJson(Map<String, dynamic>.from(row as Map)),
],
status: j['status'] as String?,
+ machineShare: j['share'] is Map
+ ? MachineShare.fromJson(Map<String, dynamic>.from(j['share'] as Map))
+ : null,
);
Machine copyWith({String? name}) => Machine(
@@ -186,6 +227,7 @@ class Machine {
ownerName: ownerName,
sharedHarnesses: sharedHarnesses,
status: status,
+ machineShare: machineShare,
);
}
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
index b33c04cc9..64800f03c 100644
--- a/desktop/lib/e2ee/envelope.dart
+++ b/desktop/lib/e2ee/envelope.dart
@@ -36,6 +36,8 @@ const Set<String> encryptedDownTypes = {
'viewer_surface',
'api_connections',
'connectors',
+ // Sharing a machine across accounts (CLI services/sharedMachines.ts): the addresses it is shared with.
+ 'shared_machines',
'orchestrator',
'route_task',
'route_send',
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 656f1347e..960b94986 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -6113,7 +6113,18 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
if (choice.destination.isCreate) {
if (_search!.isMachineMode) {
- _previewControls.invoke('picker.focus_actions');
+ // A click lands on the row it clicked, as a machine row's does: focusing the actions alone
+ // left the machine selected before it in charge, so clicking Add machine after a machine
+ // did nothing (2026-10-15).
+ final index = _search!.rows.indexWhere(
+ (row) => row.id == choice.destination.id,
+ );
+ if (index >= 0) _search!.move(index - _search!.cursor);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && _search?.selected?.id == choice.destination.id) {
+ _previewControls.invoke('picker.focus_actions');
+ }
+ });
return;
}
if (_search!.isModelMode) {
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 2fccf8dd7..9d7e9bc36 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1348,6 +1348,10 @@ class AppNotifier extends ChangeNotifier {
}
List<Machine> machines = [];
+
+ /// Machines other accounts share with this one's domain, not added yet: Add machine lists them, and
+ /// [addSharedMachine] adds one.
+ List<Machine> machinesToAdd = const [];
final Map<String, MachineState> machineStates = {};
final Set<String> expandedMachines = {};
String? selectedMachineId;
@@ -7008,6 +7012,69 @@ class AppNotifier extends ChangeNotifier {
/// machines", which an empty list alone cannot say.
bool machinesLoading = false;
+ /// This machine's sharing with other accounts (CLI services/sharedMachines.ts), asked of [machineId]
+ /// itself: the policy lives on the machine. `{emails, sameDomain, domain, members}`, or `{error,
+ /// message}`.
+ Future<Map<String, dynamic>> machineSharing(String machineId) =>
+ _sharedMachines(machineId, {'action': 'get'});
+
+ /// Share [machineId] with these addresses and, when [sameDomain], everyone at its owner's domain.
+ Future<Map<String, dynamic>> setMachineSharing(
+ String machineId,
+ List<String> emails, {
+ required bool sameDomain,
+ }) => _sharedMachines(machineId, {
+ 'action': 'set',
+ 'emails': emails,
+ 'sameDomain': sameDomain,
+ });
+
+ /// Add a machine shared with this account's domain to its machines, or take one back out
+ /// ([remove]). Asked of this computer's daemon, which pins the machine's key; null when done, else
+ /// what went wrong.
+ Future<String?> addSharedMachine(
+ String machineId, {
+ bool remove = false,
+ }) async {
+ final here = machineStates.values
+ .where(
+ (state) => state.isLocalMachine && !state.machine.isSharedMachine,
+ )
+ .firstOrNull;
+ if (here == null) return 'This computer’s Harness is not running.';
+ try {
+ final answer = await _sharedMachines(here.machine.machineId, {
+ 'action': remove ? 'remove' : 'add',
+ 'machineId': machineId,
+ });
+ if (answer['error'] != null) {
+ return answer['message'] as String? ??
+ 'Could not ${remove ? 'remove' : 'add'} it: ${answer['error']}.';
+ }
+ } catch (error) {
+ return 'Could not ${remove ? 'remove' : 'add'} it: $error';
+ }
+ await refreshMachines();
+ return null;
+ }
+
+ /// A refusal is an answer (`{error, message}`), shown in the machine's own words: only a request that
+ /// never got one is "could not reach".
+ Future<Map<String, dynamic>> _sharedMachines(
+ String machineId,
+ Map<String, dynamic> payload,
+ ) async {
+ try {
+ return await _conn(machineId).request(
+ 'shared_machines',
+ payload: payload,
+ timeout: const Duration(seconds: 30),
+ );
+ } on WsRequestFailure catch (failure) {
+ return {...failure.payload, 'error': failure.code};
+ }
+ }
+
Future<Map<String, dynamic>> manageHarnessShares(
String machineId,
String agentId,
@@ -7331,6 +7398,7 @@ class AppNotifier extends ChangeNotifier {
if (!_machineInventoryCurrent(revision, request)) return;
_machineInventoryLoaded = true;
machinesAreStale = stale;
+ if (list is MachineInventory) machinesToAdd = list.toAdd;
final localEndpoint = probed;
if (localEndpoint != null) {
_noteBackendOnline(localEndpoint.backendOnline, refetch: false);
@@ -7619,7 +7687,8 @@ class AppNotifier extends ChangeNotifier {
) async {
final revision = _authRevision;
bool current() =>
- _authWorkCurrent(revision) && identical(machineStates[machineId], state);
+ _authWorkCurrent(revision) &&
+ identical(machineStates[machineId], state);
final finishConnection = productConnections.manual(machineId);
final done = Completer<bool>();
var dialed = false;
@@ -9304,10 +9373,8 @@ class AppNotifier extends ChangeNotifier {
///
/// Never throws — a machine whose daemon is too old to know the RPC, one with no grid, and one
/// that timed out are all "nothing to offer", which is what the picker shows.
- Future<GridModels> gridModels(
- String machineId, {
- bool userAction = false,
- }) => _askGridModels(machineId, {
+ Future<GridModels> gridModels(String machineId, {bool userAction = false}) =>
+ _askGridModels(machineId, {
'rowState': true,
if (userAction) 'userAction': true,
});
@@ -12875,6 +12942,9 @@ class AppNotifier extends ChangeNotifier {
if (machine.machine.isShared) {
return Future.value('Shared machines are view-only.');
}
+ if (machine.machine.isSharedMachine) {
+ return Future.value('Only its owner can rename or remove this machine.');
+ }
if (name == null && machine.isLocalMachine) {
return Future.value('This computer cannot be deleted here.');
}
diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dart
index e7eaaf02f..d796b09c3 100644
--- a/desktop/lib/state/swarm_navigation.dart
+++ b/desktop/lib/state/swarm_navigation.dart
@@ -601,6 +601,8 @@ class SwarmSearchCatalog {
title: machine.machine.displayName,
detail: [
'Machine',
+ if (machine.machine.machineShare case final share?)
+ 'Shared by ${share.owner}',
_countLabel(members.length, 'harness'),
if (machine.needsLink)
'Link required'
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 457b3a5f9..6ccec089e 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -1084,7 +1084,7 @@ class SwarmSearchController extends ChangeNotifier {
/// What the create row's preview says, in full: the steps, for Add machine.
String get createDescription => isMachineMode
- ? 'On the other computer:\n\n1. Install the app or CLI.\n2. Sign in to the same account.\n\nIt appears here and connects on its own.'
+ ? 'On the other computer:\n\n1. Install the app or CLI.\n2. Sign in to the same account.\n\nIt appears here and connects on its own.\n\nA machine someone shares with you appears here too.'
: isModelMode
? 'Add an API key\n\n'
'OpenRouter or a Custom API: Use its models to run a harness.\n'
diff --git a/desktop/lib/widgets/machine_sharing_form.dart b/desktop/lib/widgets/machine_sharing_form.dart
new file mode 100644
index 000000000..76e2fd2e7
--- /dev/null
+++ b/desktop/lib/widgets/machine_sharing_form.dart
@@ -0,0 +1,622 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
+import '../state/app_state.dart';
+import '../terminal/terminal_text.dart';
+import '../terminal/terminal_theme.dart';
+import '../terminal/terminal_theme_store.dart';
+import 'box_chrome.dart' show ReadlineKeys;
+import 'desktop_chrome.dart';
+import 'terminal_text_action.dart';
+
+/// The most addresses one machine is shared with (CLI services/sharedMachines.ts `SHARE_EMAILS_MAX`).
+const int machineShareEmailsMax = 100;
+
+/// The backend's own rule for an address (zod's `email()`): one it would refuse is refused as it is
+/// typed, by name, never as a failed save of the whole list.
+final _emailPattern = RegExp(
+ r"^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$",
+);
+
+/// Sharing one of the account's machines with other accounts
+/// (docs/plans/2026-10-15-share-machine-plan.md), in the Machines picker's preview like Rename: the
+/// addresses it is shared with, and everyone at the owner's domain. The policy lives on the machine
+/// itself, so it is read from and written to that machine (`shared_machines`).
+class MachineSharingForm extends StatefulWidget {
+ const MachineSharingForm({
+ super.key,
+ required this.app,
+ required this.machineId,
+ required this.onClose,
+ required this.onFocusChanged,
+ this.onSwitchPane,
+ });
+ final AppNotifier app;
+ final String machineId;
+ final ValueChanged<String?> onClose;
+ final ValueChanged<bool> onFocusChanged;
+ final VoidCallback? onSwitchPane;
+
+ @override
+ State<MachineSharingForm> createState() => MachineSharingFormState();
+}
+
+class MachineSharingFormState extends State<MachineSharingForm> {
+ final _scope = FocusNode(debugLabel: 'Machine sharing');
+ final _input = FocusNode(debugLabel: 'Share email');
+ final _buttons = <String, FocusNode>{};
+ final _value = TextEditingController();
+ bool _loading = true, _busy = false, _error = false;
+ String? _message;
+ List<String> _emails = [];
+ List<String> _savedEmails = [];
+ bool _sameDomain = false, _savedSameDomain = false;
+ String? _domain;
+ List<Map<String, dynamic>> _members = const [];
+
+ AppNotifier get app => widget.app;
+ String get _name =>
+ app.stateOf(widget.machineId)?.machine.displayName ?? 'this machine';
+ bool get _changed =>
+ _sameDomain != _savedSameDomain ||
+ _emails.length != _savedEmails.length ||
+ _emails.any((email) => !_savedEmails.contains(email));
+ bool get _composing =>
+ _value.value.composing.isValid && !_value.value.composing.isCollapsed;
+
+ @override
+ void initState() {
+ super.initState();
+ unawaited(_load());
+ }
+
+ @override
+ void dispose() {
+ _scope.dispose();
+ _input.dispose();
+ for (final node in _buttons.values) {
+ node.dispose();
+ }
+ _value.dispose();
+ super.dispose();
+ }
+
+ Future<void> _load() async {
+ Map<String, dynamic> answer;
+ try {
+ answer = await app.machineSharing(widget.machineId);
+ } catch (error) {
+ answer = {
+ 'error': 'UNAVAILABLE',
+ 'message': 'Could not reach $_name: $error',
+ };
+ }
+ if (!mounted) return;
+ setState(() {
+ _loading = false;
+ _show(answer);
+ });
+ focus();
+ }
+
+ /// What the machine answered: its sharing as saved, or why it could not say.
+ void _show(Map<String, dynamic> answer) {
+ _savedEmails = [
+ for (final email in answer['emails'] as List? ?? const [])
+ if (email is String) email,
+ ];
+ _savedSameDomain = answer['sameDomain'] == true;
+ _emails = [..._savedEmails];
+ _sameDomain = _savedSameDomain;
+ _domain = answer['domain'] as String?;
+ _members = [
+ for (final member in answer['members'] as List? ?? const [])
+ if (member is Map) Map<String, dynamic>.from(member),
+ ];
+ final error = answer['error'];
+ _error = error != null;
+ _message = error == null
+ ? null
+ : error == 'UNSUPPORTED'
+ ? 'Update Harness on $_name to share it.'
+ : answer['message'] as String? ??
+ 'Could not read its sharing ($error).';
+ }
+
+ void focus() {
+ final target = _busy || _loading ? _scope : _input;
+ if (target.context != null) {
+ target.requestFocus();
+ } else {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) target.requestFocus();
+ });
+ }
+ }
+
+ /// Every address typed in the field joins the list; false when one is not an address.
+ bool _addTyped() {
+ final typed = _value.text
+ .split(RegExp(r'[\s,;]+'))
+ .map((email) => email.trim().toLowerCase())
+ .where((email) => email.isNotEmpty)
+ .toList();
+ if (typed.isEmpty) return true;
+ final bad = typed
+ .where((email) => !_emailPattern.hasMatch(email))
+ .firstOrNull;
+ if (bad != null) {
+ _say('Not an email address: $bad');
+ return false;
+ }
+ final next = {..._emails, ...typed}.toList();
+ if (next.length > machineShareEmailsMax) {
+ _say('Share with up to $machineShareEmailsMax addresses.');
+ return false;
+ }
+ setState(() {
+ _emails = next;
+ _value.clear();
+ _message = null;
+ });
+ return true;
+ }
+
+ void _say(String message, {bool error = true}) {
+ setState(() {
+ _message = message;
+ _error = error;
+ });
+ }
+
+ void _remove(String email) {
+ setState(() {
+ _emails = [..._emails]..remove(email);
+ _message = null;
+ });
+ focus();
+ }
+
+ Future<void> _save() async {
+ if (_busy || _loading || _composing) return;
+ if (!_addTyped()) {
+ _input.requestFocus();
+ return;
+ }
+ if (!_changed) {
+ widget.onClose(null);
+ return;
+ }
+ setState(() {
+ _busy = true;
+ _message = null;
+ });
+ Map<String, dynamic> answer;
+ try {
+ answer = await app.setMachineSharing(
+ widget.machineId,
+ _emails,
+ sameDomain: _sameDomain,
+ );
+ } catch (error) {
+ answer = {
+ 'error': 'UNAVAILABLE',
+ 'message': 'Could not reach $_name: $error',
+ };
+ }
+ if (!mounted) return;
+ if (answer['error'] != null) {
+ setState(() {
+ _busy = false;
+ _error = true;
+ _message =
+ answer['message'] as String? ??
+ 'Could not share it (${answer['error']}).';
+ });
+ focus();
+ return;
+ }
+ setState(() => _busy = false);
+ final emails = (answer['emails'] as List? ?? const []).length;
+ final domain = answer['sameDomain'] == true
+ ? answer['domain'] as String?
+ : null;
+ widget.onClose(
+ emails == 0 && domain == null
+ ? 'Not shared.'
+ : 'Shared with ${[if (emails > 0) emails == 1 ? '1 person' : '$emails people', if (domain != null) 'everyone at @$domain'].join(' and ')}.',
+ );
+ }
+
+ List<({String id, String label, VoidCallback? run})> get _actions => [
+ if (_domain != null && !_loading)
+ (
+ id: 'domain',
+ label: 'Everyone at @$_domain: ${_sameDomain ? 'On' : 'Off'}',
+ run: _busy ? null : () => setState(() => _sameDomain = !_sameDomain),
+ ),
+ for (final email in _emails)
+ (
+ id: 'remove:$email',
+ label: 'Remove $email',
+ run: _busy ? null : () => _remove(email),
+ ),
+ (
+ id: 'save',
+ label: _busy ? 'Saving…' : 'Save',
+ run: _busy || _loading ? null : () => unawaited(_save()),
+ ),
+ (id: 'cancel', label: 'Cancel', run: () => widget.onClose(null)),
+ ];
+
+ List<FocusNode> get _nodes => [
+ if (!_loading && !_busy) _input,
+ for (final action in _actions)
+ if (action.run != null && _buttons[action.id] != null)
+ _buttons[action.id]!,
+ ];
+
+ void _move(bool forward) {
+ if (_composing) return;
+ final nodes = _nodes;
+ if (nodes.isEmpty) return;
+ final current = nodes.indexWhere((node) => node.hasFocus);
+ final node =
+ nodes[current < 0 ? 0 : (current + (forward ? 1 : -1)) % nodes.length];
+ node.requestFocus();
+ if (node.context case final context?) Scrollable.ensureVisible(context);
+ }
+
+ void _tab(bool forward) {
+ if (_composing) return;
+ final nodes = _nodes;
+ final current = nodes.indexWhere((node) => node.hasFocus);
+ final next = current + (forward ? 1 : -1);
+ if (next >= 0 && next < nodes.length) {
+ nodes[next].requestFocus();
+ } else if (widget.onSwitchPane != null) {
+ widget.onSwitchPane!();
+ } else {
+ _move(forward);
+ }
+ }
+
+ void _accept() {
+ if (_composing) return;
+ final action = _actions
+ .where((a) => _buttons[a.id]?.hasFocus == true)
+ .firstOrNull;
+ if (action != null) {
+ action.run?.call();
+ } else if (_input.hasFocus && _value.text.trim().isNotEmpty) {
+ _addTyped();
+ } else {
+ unawaited(_save());
+ }
+ }
+
+ /// The picker's commands, while this editor holds the keys.
+ bool handle(String command) {
+ if (_composing) return true;
+ switch (command) {
+ case 'picker.cancel':
+ widget.onClose(null);
+ case 'picker.accept':
+ _scope.hasFocus ? _accept() : focus();
+ case 'picker.complete':
+ _tab(true);
+ case 'picker.complete_back':
+ _tab(false);
+ case 'picker.next' || 'picker.previous':
+ if (!_scope.hasFocus) return false;
+ _move(command == 'picker.next');
+ default:
+ return false;
+ }
+ return true;
+ }
+
+ Widget _keys(Widget child) {
+ if (KeymapTheme.of(context) != null) {
+ return KeymapRegion(
+ contextKind: KeymapContext.picker,
+ composing: () => _composing,
+ actions: {
+ 'picker.accept': _accept,
+ 'picker.cancel': () => widget.onClose(null),
+ 'picker.complete': () => _tab(true),
+ 'picker.complete_back': () => _tab(false),
+ 'picker.next': () => _move(true),
+ 'picker.previous': () => _move(false),
+ },
+ child: child,
+ );
+ }
+ return CallbackShortcuts(
+ bindings: {
+ const SingleActivator(LogicalKeyboardKey.enter, includeRepeats: false):
+ _accept,
+ const SingleActivator(
+ LogicalKeyboardKey.numpadEnter,
+ includeRepeats: false,
+ ): _accept,
+ const SingleActivator(LogicalKeyboardKey.escape): () =>
+ widget.onClose(null),
+ const SingleActivator(LogicalKeyboardKey.tab): () => _tab(true),
+ const SingleActivator(LogicalKeyboardKey.tab, shift: true): () =>
+ _tab(false),
+ const SingleActivator(LogicalKeyboardKey.arrowDown): () => _move(true),
+ const SingleActivator(LogicalKeyboardKey.arrowUp): () => _move(false),
+ },
+ child: child,
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ TerminalFontScope.watch(context);
+ grid.AppTheme.watch(context);
+ final desktop = DesktopChrome.of(context);
+ final cell = desktop ? const Size(9, 14) : terminalCellSizeOf(context);
+ final theme = terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ );
+ final gap = SizedBox(height: cell.height);
+ Widget line(String text, {bool muted = false}) => Text(
+ text,
+ style: desktop
+ ? DesktopChrome.text(
+ size: 13,
+ color: muted ? DesktopChrome.muted : null,
+ )
+ : terminalContentStyle(color: muted ? theme.muted : theme.foreground),
+ );
+ Widget button(({String id, String label, VoidCallback? run}) action) {
+ final node = _buttons.putIfAbsent(
+ action.id,
+ () => FocusNode(debugLabel: action.label),
+ );
+ final destructive = action.id.startsWith('remove:');
+ return desktop
+ ? DesktopPill(
+ key: ValueKey('machine-sharing:${action.id}'),
+ label: destructive ? 'Remove' : action.label,
+ compact: true,
+ focusNode: node,
+ foregroundColor: destructive
+ ? Theme.of(context).colorScheme.error
+ : null,
+ onPressed: action.run,
+ )
+ : TerminalTextAction(
+ key: ValueKey('machine-sharing:${action.id}'),
+ label: destructive ? 'Remove' : action.label,
+ padding: EdgeInsets.zero,
+ focusNode: node,
+ onPressed: action.run,
+ );
+ }
+
+ final actions = _actions;
+ final field = ReadlineKeys(
+ controller: _value,
+ enabled: !_busy,
+ onChanged: (_) {
+ if (_message != null) setState(() => _message = null);
+ },
+ child: TextField(
+ key: const ValueKey('machine-sharing-email'),
+ controller: _value,
+ focusNode: _input,
+ readOnly: _busy || _loading,
+ onTapOutside: (_) {},
+ enableSuggestions: false,
+ autocorrect: false,
+ keyboardType: TextInputType.emailAddress,
+ style: desktop
+ ? DesktopChrome.text(size: 13)
+ : terminalContentStyle(color: theme.foreground),
+ cursorColor: desktop ? DesktopChrome.accent : theme.foreground,
+ decoration: desktop
+ ? InputDecoration(
+ hintText: '[email protected]',
+ hintStyle: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
+ ),
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(
+ grid.AppDesktop.fieldRadius,
+ ),
+ borderSide: BorderSide(color: DesktopChrome.rim),
+ ),
+ enabledBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(
+ grid.AppDesktop.fieldRadius,
+ ),
+ borderSide: BorderSide(color: DesktopChrome.rim),
+ ),
+ focusedBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(
+ grid.AppDesktop.fieldRadius,
+ ),
+ borderSide: BorderSide(
+ color: DesktopChrome.focusRing,
+ width: grid.AppDesktop.focusWidth,
+ ),
+ ),
+ filled: true,
+ fillColor: DesktopChrome.field,
+ isDense: true,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 10,
+ ),
+ )
+ : InputDecoration(
+ hintText: '[email protected]',
+ hintStyle: terminalContentStyle(color: theme.muted),
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ filled: false,
+ isDense: true,
+ isCollapsed: true,
+ constraints: const BoxConstraints(),
+ contentPadding: EdgeInsets.zero,
+ ),
+ onEditingComplete: () {},
+ onChanged: (_) {
+ if (_message != null) setState(() => _message = null);
+ },
+ ),
+ );
+ final using = [
+ for (final member in _members)
+ if (member['email'] is String) member['email'] as String,
+ ];
+ final body = SingleChildScrollView(
+ padding: EdgeInsets.symmetric(
+ horizontal: cell.width * 2,
+ vertical: cell.height,
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ 'Share $_name',
+ style: desktop
+ ? DesktopChrome.heading()
+ : terminalContentStyle(color: theme.foreground),
+ ),
+ gap,
+ line(
+ 'People you share it with use it as their own: its harnesses, terminals and files.',
+ muted: true,
+ ),
+ gap,
+ if (_loading)
+ line('Reading its sharing…', muted: true)
+ else ...[
+ if (actions.where((a) => a.id == 'domain').firstOrNull
+ case final domain?) ...[
+ button(domain),
+ if (_sameDomain)
+ line('They add it from Add machine.', muted: true),
+ gap,
+ ],
+ if (desktop) ...[
+ Text(
+ 'Email',
+ style: DesktopChrome.text(size: 12, color: DesktopChrome.muted),
+ ),
+ const SizedBox(height: 6),
+ field,
+ ] else
+ Row(
+ children: [
+ SizedBox(
+ width: cell.width * 8,
+ child: Text(
+ 'email >',
+ style: terminalContentStyle(color: theme.muted),
+ ),
+ ),
+ Expanded(child: field),
+ ],
+ ),
+ line('Enter adds it. They see it in their Machines.', muted: true),
+ if (_emails.isNotEmpty) ...[
+ gap,
+ for (final email in _emails)
+ Padding(
+ padding: EdgeInsets.only(bottom: desktop ? 4 : 0),
+ child: Row(
+ children: [
+ Expanded(child: line(email)),
+ button(
+ actions.firstWhere((a) => a.id == 'remove:$email'),
+ ),
+ ],
+ ),
+ ),
+ ],
+ if (using.isNotEmpty) ...[
+ gap,
+ line('Using it now: ${using.join(', ')}', muted: true),
+ ],
+ ],
+ gap,
+ if (_message != null) ...[
+ Semantics(
+ liveRegion: true,
+ child: Text(
+ _message!,
+ style: desktop
+ ? DesktopChrome.text(
+ size: 12,
+ color: _error
+ ? Theme.of(context).colorScheme.error
+ : DesktopChrome.muted,
+ )
+ : terminalContentStyle(
+ color: _error ? theme.yellow : theme.muted,
+ ),
+ ),
+ ),
+ gap,
+ ],
+ Wrap(
+ spacing: desktop ? 8 : cell.width * 2,
+ runSpacing: desktop ? 8 : cell.height,
+ children: [
+ for (final action in actions)
+ if (action.id == 'save' || action.id == 'cancel')
+ button(action),
+ ],
+ ),
+ ],
+ ),
+ );
+ String? hint(String command) => effectiveCommandHint(
+ context,
+ command,
+ contextKind: KeymapContext.picker,
+ )?.replaceAll('⇥', 'Tab').replaceAll('↵', 'Enter');
+ return _keys(
+ Focus(
+ focusNode: _scope,
+ onFocusChange: widget.onFocusChanged,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(child: body),
+ Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: cell.width * 2,
+ vertical: cell.height,
+ ),
+ child: Text(
+ [
+ if (hint('picker.accept') case final enter?)
+ '$enter add or save',
+ if (hint('picker.complete') case final tab?) '$tab next',
+ if (hint('picker.cancel') case final escape?) '$escape back',
+ ].join(' · '),
+ style: desktop
+ ? DesktopChrome.metadata()
+ : terminalContentStyle(color: theme.muted),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/swarm_resource_preview.dart b/desktop/lib/widgets/swarm_resource_preview.dart
index 93d7e1cbe..74ccba814 100644
--- a/desktop/lib/widgets/swarm_resource_preview.dart
+++ b/desktop/lib/widgets/swarm_resource_preview.dart
@@ -28,6 +28,7 @@ import '../terminal/terminal_theme_store.dart';
import 'account_device_detail.dart'
show confirmDeviceAction, removeDeviceDetail;
import 'machine_picker_form.dart';
+import 'machine_sharing_form.dart';
import 'api_picker_form.dart';
import 'swarm_search_preview.dart';
import 'swarm_preview_scroll.dart';
@@ -126,6 +127,9 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
MachinePickerFormKind? _machineForm;
String? _formResource;
var _formKey = GlobalKey<MachinePickerFormState>();
+ // The machine's sharing (MachineSharingForm), open in place of a machine form.
+ bool _sharing = false;
+ var _sharingKey = GlobalKey<MachineSharingFormState>();
final _messages = <String, String>{};
bool _apiFormOpen = false, _apiRemoving = false;
String? _apiResource, _apiConnectionId;
@@ -181,21 +185,38 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
}
void _mine(AccountDevice device) => _devices?.mine(device);
- bool get _editingMachine => _machineForm != null && _formResource == row?.id;
+ bool get _editingMachine =>
+ (_machineForm != null || _sharing) && _formResource == row?.id;
void _editMachine(MachinePickerFormKind kind) {
setState(() {
_formKey = GlobalKey<MachinePickerFormState>();
_machineForm = kind;
+ _sharing = false;
_formResource = row?.id;
});
}
+ void _shareMachine() {
+ setState(() {
+ _sharingKey = GlobalKey<MachineSharingFormState>();
+ _machineForm = null;
+ _sharing = true;
+ _formResource = row?.id;
+ });
+ }
+
+ /// Add a machine shared with this account's domain, from Add machine; or take one back out.
+ void _addSharedMachine(Machine machine, {bool remove = false}) => unawaited(
+ _run(() => app.addSharedMachine(machine.machineId, remove: remove)),
+ );
+
void _closeMachineForm(String? message) {
if (!mounted) return;
setState(() {
if (message != null && row != null) _messages[row!.id] = message;
_machineForm = null;
+ _sharing = false;
_formResource = null;
});
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -292,9 +313,10 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
if (mounted) widget.onRefocus();
});
}
- if (_machineForm != null && _formResource != row?.id) {
+ if ((_machineForm != null || _sharing) && _formResource != row?.id) {
// A click/query change closes the old editor before any later reply.
_machineForm = null;
+ _sharing = false;
_formResource = null;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) widget.onRefocus();
@@ -402,7 +424,10 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
}
if (_editingMachine &&
widget.search.managing &&
- _formKey.currentState?.handle(command) == true) {
+ (_sharing
+ ? _sharingKey.currentState?.handle(command)
+ : _formKey.currentState?.handle(command)) ==
+ true) {
return true;
}
if (command == 'picker.resource_add_api' && widget.search.isModelMode) {
@@ -491,7 +516,9 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
if (_editingApi) {
_apiFormKey.currentState?.focus();
} else if (_editingMachine) {
- _formKey.currentState?.focus();
+ _sharing
+ ? _sharingKey.currentState?.focus()
+ : _formKey.currentState?.focus();
} else {
_focusActions();
}
@@ -862,6 +889,13 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
() => _editMachine(MachinePickerFormKind.cli),
command: 'picker.machine_cli',
),
+ // Machines shared with this account's domain: one click adds each.
+ for (final shared in app.machinesToAdd)
+ _ResourceAction(
+ 'Add ${shared.displayName}',
+ busy ? null : () => _addSharedMachine(shared),
+ command: 'picker.machine_add_shared:${shared.machineId}',
+ ),
];
}
if (search.isModelMode) {
@@ -1031,12 +1065,29 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
),
...secondary.where((a) => a.command == 'picker.resource_connect'),
...secondary.where((a) => a.command == 'picker.resource_settings'),
- if (!machine.machine.isShared)
+ if (!machine.machine.isShared && !machine.machine.isSharedMachine)
_ResourceAction(
'Rename',
busy ? null : () => _editMachine(MachinePickerFormKind.rename),
command: 'picker.resource_rename',
),
+ // Sharing it with other accounts is its owner's, signed in.
+ if (!machine.machine.isShared &&
+ !machine.machine.isSharedMachine &&
+ !app.isGuest)
+ _ResourceAction(
+ 'Share',
+ busy ? null : _shareMachine,
+ command: 'picker.resource_share',
+ ),
+ if (machine.machine.machineShare case final share? when share.viaDomain)
+ _ResourceAction(
+ 'Remove from my list',
+ busy
+ ? null
+ : () => _addSharedMachine(machine.machine, remove: true),
+ command: 'picker.resource_unshare',
+ ),
...secondary.where((a) => a.command == 'picker.resource_remove'),
...secondary.where((a) => a.command == 'picker.device_mine'),
if (app.machineListError != null)
@@ -1150,7 +1201,10 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
),
],
] else if (selected?.isMachine == true && machine != null) ...[
+ // A machine shared with this account is reached by its key, never a password: it links as
+ // soon as both daemons have read the sharing.
if (!machine.isLocalMachine &&
+ !machine.machine.isSharedMachine &&
machine.needsLink &&
machine.nodeOnline != false)
_ResourceAction(
@@ -1164,7 +1218,9 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
() => _editMachine(MachinePickerFormKind.password),
command: 'picker.resource_settings',
),
- if (!machine.isLocalMachine && !machine.machine.isShared)
+ if (!machine.isLocalMachine &&
+ !machine.machine.isShared &&
+ !machine.machine.isSharedMachine)
_ResourceAction(
'Remove',
() => _editMachine(MachinePickerFormKind.delete),
@@ -1640,8 +1696,14 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
status,
if (machine.isLocalMachine) 'This computer',
if (machine.machine.isShared) 'View only',
+ if (machine.machine.machineShare case final share?)
+ 'Shared by ${share.owner}',
].join(' · '),
'',
+ if (machine.machine.machineShare case final share?) ...[
+ 'You use it as your own. Only ${share.owner} can rename, remove or share it.',
+ '',
+ ],
if (resources?.cpuPercent case final cpu?) 'CPU ${cpu.round()}%',
if (resources?.memoryUsedBytes != null &&
resources?.memoryTotalBytes != null)
@@ -2016,6 +2078,15 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
onFocusChanged: widget.search.setManaging,
onSwitchPane: _switchPane,
)
+ : _editingMachine && _sharing
+ ? MachineSharingForm(
+ key: _sharingKey,
+ app: app,
+ machineId: row!.machineId!,
+ onClose: _closeMachineForm,
+ onFocusChanged: widget.search.setManaging,
+ onSwitchPane: _switchPane,
+ )
: _editingMachine
? MachinePickerForm(
key: _formKey,
@@ -2052,6 +2123,12 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
: row?.isCreate == true
? _details([
...widget.search.createDescription.split('\n'),
+ if (_machineSetup && app.machinesToAdd.isNotEmpty) ...[
+ '',
+ 'Shared with your team:',
+ for (final shared in app.machinesToAdd)
+ '${shared.displayName} · ${shared.machineShare?.owner ?? ''}',
+ ],
], controls: _machineSetup)
: widget.search.isStoreMode
? _details([
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index 11095b2a6..59bf68b5f 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -1228,8 +1228,14 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
padding: const EdgeInsets.symmetric(vertical: 2),
child: Material(
key: ValueKey('swarm-search-line:${row.id}'),
+ // Blue while the list has the keys; a quiet fill while the row's actions
+ // beside it have them, so it still says whose actions those are. Dropping
+ // it left only the pointer's hover tint, which read as a second colour of
+ // selection (owner, 2026-10-15).
color: highlighted
? DesktopChrome.activeSelection
+ : selected && search.managing
+ ? grid.AppSurface.selectedFill
: Colors.transparent,
borderRadius: BorderRadius.circular(10),
child: tile,
diff --git a/desktop/test/machine_inventory_api_test.dart b/desktop/test/machine_inventory_api_test.dart
index 05f5eb0f8..49ff0e64a 100644
--- a/desktop/test/machine_inventory_api_test.dart
+++ b/desktop/test/machine_inventory_api_test.dart
@@ -109,6 +109,60 @@ void main() {
expect(snapshot.isStale, isTrue);
});
+ test('a machine shared whole joins the list once added, and waits under Add machine before', () async {
+ final listed = api.machines();
+ await _until(() => requests.machines.length == 1);
+ Map<String, dynamic> shared(String id, String via, bool added) => {
+ 'machineId': id,
+ 'name': id,
+ 'authMode': 'remote',
+ 'status': 'running',
+ 'share': {
+ 'ownerName': 'Dee',
+ 'ownerEmail': '[email protected]',
+ 'via': via,
+ 'added': added,
+ },
+ };
+ requests.machines.single.response
+ ..statusCode = 200
+ ..headers.contentType = ContentType.json
+ ..write(
+ jsonEncode({
+ 'success': true,
+ 'data': {
+ 'machines': [
+ {'machineId': 'own', 'name': 'own', 'authMode': 'remote'},
+ ],
+ 'sharedMachines': [
+ shared('named', 'email', true),
+ shared('team-added', 'domain', true),
+ shared('team-waiting', 'domain', false),
+ // Listed as the account's own too: the account's own row wins.
+ shared('own', 'email', true),
+ ],
+ },
+ }),
+ );
+ await requests.machines.single.response.close();
+ await _until(() => requests.shares.length == 1);
+ await _reply(requests.shares.single, 'unused', fails: true);
+ final inventory = await listed as MachineInventory;
+ expect(inventory.map((m) => m.machineId), ['own', 'named', 'team-added']);
+ expect(inventory.first.isSharedMachine, isFalse);
+ final named = inventory[1];
+ expect(named.isSharedMachine, isTrue);
+ expect(named.isShared, isFalse);
+ expect(named.machineShare!.owner, 'Dee');
+ expect(named.machineShare!.viaDomain, isFalse);
+ expect(inventory[2].machineShare!.viaDomain, isTrue);
+ expect(inventory.toAdd.map((m) => m.machineId), ['team-waiting']);
+ expect(
+ named.copyWith(name: 'Renamed').machineShare?.ownerEmail,
+ );
+ });
+
test('account reset stops an old request before it fetches sharing for the new account', () async {
final old = api.machines();
final rejected = expectLater(old, throwsStateError);
diff --git a/docs/plans/2026-10-15-share-machine-plan.md b/docs/plans/2026-10-15-share-machine-plan.md
new file mode 100644
index 000000000..a1a6ba66d
--- /dev/null
+++ b/docs/plans/2026-10-15-share-machine-plan.md
@@ -0,0 +1,49 @@
+# Share a machine
+
+Status: implemented on `feat/share-machine` (2026-10-15).
+
+## Experience
+
+Today a computer can add only the machines signed in to the same account. Now a machine's owner can share
+it, and the person it is shared with uses it as their own.
+
+- **Off by default.** In the machine's details, **Share** opens the machine's sharing: email addresses, and
+ **Everyone at @company.com**. The second is offered only when the owner's address is not at a public
+ domain (gmail.com, outlook.com, icloud.com, Apple's private relay, …).
+- **Shared with your email:** the machine appears in your Machines under **Shared with you** and connects
+ on its own, like your own machines.
+- **Shared with your domain:** the machine is listed in **Add machine** under **Shared with your team** and
+ takes one click to add. Only colleagues who add it get it in their list, and only their machines are
+ trusted by it. **Remove from my list** takes it back out.
+- **Full owner rights.** A shared machine works exactly like one on your own account: its harnesses,
+ terminals, new harnesses, models. Renaming it, removing it from the account, billing, its remote password
+ and its sharing stay with its owner.
+- Stopping sharing, or taking an address off, ends access at once.
+
+Sign-in requires a verified email (confirmed with the SSO side), so an address or a domain names a person.
+
+## How it works
+
+- **Backend.** `MachineShare` holds a machine's policy (addresses, and the owner's domain when the domain is
+ on) and `MachineShareAdd` the accounts that added a domain share. `lib/machineAccess.ts` decides who may use
+ a machine; `machine_select` on `/api/web-ws` asks it instead of comparing owners, and drops a session when
+ the policy stops allowing it. `GET /api/machines` lists the machines shared with you beside your own
+ (`sharedMachines`), never with an API key. `routes/machineShares.ts` writes the policy, lists who may use
+ a machine with their machines' keys, and adds or removes a domain share.
+- **The shared machine's daemon decides.** The owner's policy is kept on the machine itself
+ (`services/sharedMachines.ts`, `shared-machines.json`), as Share keeps its grants: the backend's word alone
+ cannot grant access. The service reads who may use the machine, checks each address against its own
+ policy, and has the gateway trust those accounts' machine keys.
+- **The adding machine's daemon** pins the shared machine's key, so its windows connect through the relay
+ as they do to their own machines.
+- **Kept apart from the trust group.** Shared keys and pins are marked `shared` in `paired.json` and
+ `machinePeers.json`. The trust group never exchanges rosters with them, never seeds them, and refuses a
+ `group_sync` from them, so sharing one machine never makes a colleague's other machines trusted, or yours
+ trusted by theirs. Removing a key rotates the group key, as an unpair does.
+- **Daemon changes outside the service:** the gateway's `sharedTrust` call (`gateway/sharedTrust.ts`),
+ the service's process and query link, and the trust-group filter. Nothing in the core's request switch.
+
+## Out of scope
+
+The phone app (later), invitation emails, and sharing a machine with only some of its harnesses (Share
+already does that, view only).
diff --git a/tui/src/app.rs b/tui/src/app.rs
index c85a6168f..89d3415fe 100644
--- a/tui/src/app.rs
+++ b/tui/src/app.rs
@@ -1340,7 +1340,11 @@ impl App {
self.spawn(async move { http_json(port, "GET", "/api/machines", None).await }, move |app, reply| {
if app.account_epoch != epoch || request != app.machines_request { return }
let Ok(reply) = reply else { return };
- let Some(rows) = reply.get("machines").and_then(Value::as_array) else { return };
+ let Some(owned) = reply.get("machines").and_then(Value::as_array) else { return };
+ // Whole machines other accounts share with this one: those named for it and those it added
+ // are its machines too; one shared with its domain waits to be added. A list that could not
+ // say (no `sharedMachines`) keeps the ones it had.
+ let rows = &app.fleet.take_shared(owned, reply.get("sharedMachines").and_then(Value::as_array));
let local = app.fleet.local_id.clone();
// Only a fresh response is authoritative for removals. Outage caches may
// predate a connected computer, so their omissions must retain its views.
diff --git a/tui/src/devices.rs b/tui/src/devices.rs
index 6ef7d1b8c..5e3d32dbd 100644
--- a/tui/src/devices.rs
+++ b/tui/src/devices.rs
@@ -3,8 +3,9 @@
//!
//! - **Connect a machine…** — a machine on the account that is not linked yet, its remote password
//! (hidden), then `harness link connect <id> --stdin --json` with the stages it reports, live.
-//! - **Machines & devices…** — this computer's remote password, the account's machines (rename,
-//! remove), the links made from here (unlink), and the steps that add another machine.
+//! - **Machines & devices…** — this computer's remote password and sharing, the account's machines
+//! (rename, remove), the machines other accounts share with it (add, remove from the list), the
+//! links made from here (unlink), and the steps that add another machine.
//! - **Add phone…** — the QR code the app shows (the very same link), in half blocks.
//!
//! Everything that writes asks y/n first, in a dialog over the panel (`dialog::Dialog`, the one
@@ -126,6 +127,8 @@ pub enum Entry {
NewPassword,
RepeatPassword { first: String },
Rename { machine: String, name: String },
+ /// An address to share this computer with (services/sharedMachines.ts).
+ ShareEmail,
}
/// What a yes does.
@@ -139,6 +142,11 @@ pub enum Act {
Remove { machine: String, name: String },
Unpair { fingerprint: String, name: String },
ArmPhone,
+ /// This computer shared with these addresses and, or, everyone at its owner's domain; [said] is
+ /// what the footer says once it is.
+ Share { emails: Vec<String>, same_domain: bool, said: String },
+ /// A machine shared with this account's domain added to its machines, or ([remove]) taken out.
+ AddShared { machine: String, name: String, remove: bool },
}
/// The panel is asking, in a dialog over it: a line to type (a password shown as dots; the caret
@@ -156,6 +164,9 @@ struct PromptActions { size: (u16, u16), accept: Rect, cancel: Rect, input: Opti
pub struct Devices {
/// `remote-password status --json` ({hasPassword, fingerprint, setAt}), or why it is unknown.
pub password: Option<Result<Value, String>>,
+ /// This computer's sharing (`shared_machines get`: {emails, sameDomain, domain, members}), or why
+ /// it is unknown.
+ pub sharing: Option<Result<Value, String>>,
pub links: Option<Result<Vec<Linked>, String>>,
/// `GET /api/machines`'s rows, by machine id (what the fleet does not keep: when it was seen).
pub account: HashMap<String, Value>,
@@ -181,7 +192,7 @@ pub struct Devices {
impl Default for Devices {
fn default() -> Devices {
Devices {
- password: None, links: None, account: HashMap::new(), link: None, phone: Phone::default(), ask: None, prompt_actions: Default::default(), prompt_row: Default::default(), prompt_focus: Default::default(), unfit: Default::default(), sub: None, footer: None, loading: Vec::new(), runner: default_runner(),
+ password: None, sharing: None, links: None, account: HashMap::new(), link: None, phone: Phone::default(), ask: None, prompt_actions: Default::default(), prompt_row: Default::default(), prompt_focus: Default::default(), unfit: Default::default(), sub: None, footer: None, loading: Vec::new(), runner: default_runner(),
}
}
}
@@ -209,6 +220,8 @@ pub enum Req {
Cli { args: Vec<String>, stdin: Option<String> },
/// This computer's daemon, over its REST.
Http { method: &'static str, path: String, body: Option<Value> },
+ /// A request to this computer's daemon over its socket, answered `<ty>_result`.
+ Rpc { ty: &'static str, payload: Value },
/// Text for the clipboard of the computer you sit at.
Copy(String),
/// A pause, then the next round (the phone's pairing, its sign-in code).
@@ -220,6 +233,8 @@ pub enum Reply {
Cli { ok: bool, out: String, err: String },
/// The body (its `data`, when enveloped), or (code, message).
Http(Result<Value, (String, String)>),
+ /// The reply, or (code, message): an `error` in it is a refusal.
+ Rpc(Result<Value, (String, String)>),
Done,
}
@@ -248,6 +263,11 @@ pub fn ask(app: &mut App, req: Req, line: Option<fn(&mut App, &str)>, then: impl
let wait = Duration::from_secs(if path == "/api/pair" { 65 } else { 20 });
app.spawn(async move { Reply::Http(crate::daemon::http_json_for(port, method, &path, body.as_ref(), wait).await.map_err(|e| (e.code, e.detail))) }, then)
}
+ Req::Rpc { ty, payload } => {
+ let here = app.fleet.local_id.clone();
+ let Some(link) = app.link(&here) else { return then(app, Reply::Rpc(Err(("DAEMON_DOWN".into(), "Harness is not running on this computer.".into())))) };
+ app.spawn(async move { Reply::Rpc(link.rpc(ty, payload, Duration::from_secs(30)).await.map_err(|e| (e.code, e.detail))) }, then)
+ }
Req::Copy(text) => { crate::clipboard::store(&text); then(app, Reply::Done) }
Req::Wait(d) => app.spawn(async move { tokio::time::sleep(d).await; Reply::Done }, then),
}
@@ -473,7 +493,7 @@ fn opened(app: &mut App, view: View) {
crate::account::refresh(app, false);
match view {
View::Connect => { load_me(app); load_account(app) }
- View::Machines => { load_password(app); load_links(app); load_account(app); load_me(app) }
+ View::Machines => { load_password(app); load_sharing(app); load_links(app); load_account(app); load_me(app) }
View::Phone => {
load_me(app);
let generation = app.devices.phone.generation;
@@ -524,6 +544,36 @@ fn load_password(app: &mut App) {
});
}
+/// The answer to a `shared_machines` request: what it said, or why it said nothing.
+fn shared_answer(reply: Reply) -> Result<Value, String> {
+ match reply {
+ Reply::Rpc(Ok(v)) => match v.get("error").and_then(Value::as_str) {
+ None => Ok(v),
+ Some("UNSUPPORTED") => Err("Update Harness on this computer to share it.".into()),
+ Some(code) => Err(v.get("message").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| format!("Could not share it ({code}).")))
+ },
+ Reply::Rpc(Err((_, message))) => Err(message),
+ _ => Err("Sharing is unavailable.".into()),
+ }
+}
+
+fn load_sharing(app: &mut App) {
+ loading(app, "sharing", true);
+ ask(app, Req::Rpc { ty: "shared_machines", payload: json!({ "action": "get" }) }, None, |app, reply| {
+ loading(app, "sharing", false);
+ app.devices.sharing = Some(shared_answer(reply));
+ again(app);
+ });
+}
+
+/// This computer's sharing as last read: (addresses, everyone at the domain, the domain), or nothing
+/// while it is unknown.
+fn sharing_now(app: &App) -> Option<(Vec<String>, bool, Option<String>)> {
+ let v = app.devices.sharing.as_ref()?.as_ref().ok()?;
+ let emails = v.get("emails").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
+ Some((emails, v.get("sameDomain") == Some(&Value::Bool(true)), v.get("domain").and_then(Value::as_str).map(str::to_string)))
+}
+
fn load_links(app: &mut App) {
loading(app, "links", true);
ask(app, cli(&["link", "list"], None), None, |app, reply| {
@@ -747,6 +797,39 @@ fn run_act(app: &mut App, act: Act) {
again(app);
});
}
+ Act::Share { emails, same_domain, said } => {
+ note(app, "Saving…");
+ let payload = json!({ "action": "set", "emails": emails, "sameDomain": same_domain });
+ ask(app, Req::Rpc { ty: "shared_machines", payload }, None, move |app, reply| {
+ match shared_answer(reply) {
+ Ok(v) => { app.devices.sharing = Some(Ok(v)); note(app, said) }
+ Err(message) => fail(app, message),
+ }
+ again(app);
+ });
+ }
+ Act::AddShared { machine, name, remove } => {
+ note(app, if remove { "Removing…" } else { "Adding…" });
+ let payload = json!({ "action": if remove { "remove" } else { "add" }, "machineId": machine });
+ ask(app, Req::Rpc { ty: "shared_machines", payload }, None, move |app, reply| {
+ match shared_answer(reply) {
+ Ok(_) => {
+ if remove {
+ app.fleet.shares.remove(&machine);
+ app.account_machine_removed(&machine);
+ if app.devices.sub.as_deref() == Some(&format!("m:{machine}")) { app.devices.sub = None }
+ note(app, format!("Removed {name} from your machines"));
+ } else {
+ app.fleet.to_add.retain(|(id, ..)| id != &machine);
+ note(app, format!("Added {name}. It connects in a moment."));
+ }
+ if app.devices.runner.is_none() { app.refresh_machines() }
+ }
+ Err(message) => fail(app, message),
+ }
+ again(app);
+ });
+ }
Act::ArmPhone => {
app.devices.phone.armed = true;
again(app);
@@ -820,7 +903,7 @@ fn at_char(value: &str, caret: usize) -> usize { value.char_indices().nth(caret)
fn confirm(app: &mut App, question: impl Into<String>, act: Act) {
app.devices.prompt_actions.set(None);
// A destructive yes starts on Cancel, a safe one on Yes.
- let risky = matches!(act, Act::ClearPassword | Act::Unlink { .. } | Act::Remove { .. } | Act::Unpair { .. });
+ let risky = matches!(act, Act::ClearPassword | Act::Unlink { .. } | Act::Remove { .. } | Act::Unpair { .. } | Act::AddShared { remove: true, .. });
app.devices.prompt_row.set(usize::from(!risky));
app.devices.prompt_focus.set(true);
app.devices.ask = Some(Ask::Confirm { question: question.into(), act });
@@ -887,6 +970,18 @@ fn submit(app: &mut App, what: Entry, value: String) {
if value != first { entry(app, Entry::NewPassword, "New remote password", "", true); return fail(app, "Passwords do not match") }
confirm(app, "Set this computer's remote password? Anyone with it can link a machine here.", Act::SetPassword(value));
}
+ Entry::ShareEmail => {
+ let typed: Vec<String> = value.split(|c: char| c == ',' || c == ';' || c.is_whitespace()).map(|e| e.trim().to_lowercase()).filter(|e| !e.is_empty()).collect();
+ if typed.is_empty() { return note(app, "Nothing changed") }
+ if let Some(bad) = typed.iter().find(|e| !is_email(e)) { entry(app, Entry::ShareEmail, "Email address", &value, false); return fail(app, format!("Not an email address: {bad}")) }
+ let Some((mut emails, same_domain, _)) = sharing_now(app) else { return fail(app, "Sharing is unavailable. Try again.") };
+ let new: Vec<String> = typed.into_iter().filter(|e| !emails.contains(e)).collect();
+ if new.is_empty() { return note(app, "Already shared with them") }
+ emails.extend(new.iter().cloned());
+ let here = app.fleet.local_machine_name();
+ confirm(app, format!("Share {here} with {}? They use it as their own: its harnesses, terminals and files.", new.join(", ")),
+ Act::Share { emails, same_domain, said: format!("Shared with {}", new.join(", ")) });
+ }
Entry::Rename { machine, name } => {
let new = value.trim().to_string();
if new.is_empty() { entry(app, Entry::Rename { machine, name: name.clone() }, "Machine name", &name, false); return fail(app, "Name cannot be empty") }
@@ -1031,6 +1126,12 @@ pub fn choose(app: &mut App, view: View, picker: Picker, enter: bool) {
(_, "account") => { crate::account::open(app); return }
(View::Connect, "m") => { let name = name_of(app, &rest); start_link(app, rest, name) }
(_, "m") => sub(app, format!("m:{rest}")),
+ (_, "share") => sub(app, "share:".into()),
+ (_, "shr") => share_action(app, &rest),
+ (_, "addshared") => {
+ let name = app.fleet.to_add.iter().find(|(id, ..)| *id == rest).map(|(_, name, _)| name.clone()).unwrap_or_else(|| name_of(app, &rest));
+ run_act(app, Act::AddShared { machine: rest, name, remove: false })
+ }
(_, "act") => machine_action(app, &rest),
(_, "pw") => match rest.as_str() {
"set" => entry(app, Entry::NewPassword, "New remote password", "", true),
@@ -1092,6 +1193,7 @@ fn machine_action(app: &mut App, rest: &str) {
match verb {
"rename" => entry(app, Entry::Rename { machine, name: name.clone() }, "Machine name", &name, false),
"remove" => confirm(app, format!("Delete {name} from your account?"), Act::Remove { machine, name }),
+ "unshare" => confirm(app, format!("Remove {name} from your machines? You can add it again from Shared with your team."), Act::AddShared { machine, name, remove: true }),
"connect" => { switch(app, View::Connect); if let Some(p) = picker_mut(app) { p.select(&format!("m:{machine}")) } start_link(app, machine, name) }
"open" => {
app.devices.sub = None;
@@ -1101,6 +1203,45 @@ fn machine_action(app: &mut App, rest: &str) {
}
}
+/// Enter on a row of this computer's sharing.
+fn share_action(app: &mut App, rest: &str) {
+ if rest == "reload" { return load_sharing(app) }
+ let Some((emails, same_domain, domain)) = sharing_now(app) else { return fail(app, "Sharing is unavailable. Try again.") };
+ let here = app.fleet.local_machine_name();
+ match rest.split_once(':').unwrap_or((rest, "")) {
+ ("add", _) => entry(app, Entry::ShareEmail, "Email address", "", false),
+ ("domain", _) => {
+ let Some(domain) = domain else { return };
+ if same_domain {
+ run_act(app, Act::Share { emails, same_domain: false, said: format!("No longer shared with everyone at @{domain}") })
+ } else {
+ confirm(app, format!("Share {here} with everyone at @{domain}? They add it from Machines and use it as their own."),
+ Act::Share { emails, same_domain: true, said: format!("Shared with everyone at @{domain}") })
+ }
+ }
+ ("rm", email) => {
+ let rest: Vec<String> = emails.into_iter().filter(|e| e != email).collect();
+ confirm(app, format!("Stop sharing {here} with {email}?"), Act::Share { emails: rest, same_domain, said: format!("No longer shared with {email}") })
+ }
+ _ => {}
+ }
+}
+
+/// Whether [text] is an address the backend takes (zod's `email()`, by hand: this regex has no
+/// lookahead): one it would refuse is refused as it is typed, by name, never as a failed save.
+fn is_email(text: &str) -> bool {
+ let Some((name, domain)) = text.split_once('@') else { return false };
+ let local_ok = !name.is_empty() && !name.starts_with('.') && !name.contains("..")
+ && name.chars().all(|c| c.is_ascii_alphanumeric() || "_'+-.".contains(c))
+ && name.chars().last().is_some_and(|c| c.is_ascii_alphanumeric() || "_+-".contains(c));
+ let labels: Vec<&str> = domain.split('.').collect();
+ let (tld, rest) = labels.split_last().unwrap_or((&"", &[]));
+ let domain_ok = !rest.is_empty()
+ && rest.iter().all(|l| l.chars().next().is_some_and(|c| c.is_ascii_alphanumeric()) && l.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'))
+ && tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic());
+ local_ok && domain_ok && text.len() <= 254
+}
+
/// Machines & devices on [machine]: its own actions (rename, connect, remove…).
pub(crate) fn open_machine(app: &mut App, machine: &str) {
open(app, View::Machines);
@@ -1154,7 +1295,11 @@ pub fn fill(app: &App, view: View, picker: &mut Picker) {
picker.keep_order = true;
let rows = match view {
View::Connect => connect_rows(app),
- View::Machines => match app.devices.sub.as_deref().and_then(|s| s.strip_prefix("m:")) { Some(id) => action_rows(app, id), None => machines_rows(app) },
+ View::Machines => match app.devices.sub.as_deref() {
+ Some("share:") => share_rows(app),
+ Some(sub) => match sub.strip_prefix("m:") { Some(id) => action_rows(app, id), None => machines_rows(app) },
+ None => machines_rows(app),
+ },
View::Phone => phone_rows(app),
};
// (Rebuilt in their own order, not the last one's: a row that arrives lands in its group.)
@@ -1213,9 +1358,25 @@ fn machines_rows(app: &App) -> Vec<Row> {
.lead(dot(if set == Some(true) { "✓" } else { "·" }, color)).detail(vec![span("the remote password another machine links here with", fg(theme::MUTED))]).right(state));
if set == Some(true) { rows.push(Row::new("pw:clear", "Clear password…").group(here).extra("remote password").lead(dot(" ", theme::MUTED)).detail(vec![span("no new links by password", fg(theme::MUTED))])) }
if matches!(password, Some(Err(_))) { rows.push(Row::new("pw:status", "Retry").group(here).extra("password status").lead(dot("↻", theme::MUTED)).detail(vec![span("Password status is unavailable.", fg(theme::WARN))])) }
+ // Sharing this computer with other accounts: off until its owner shares it.
+ if !app.devices.phone.signed_out && app.account.status != crate::account::Status::SignedOut {
+ let state = match (&app.devices.sharing, sharing_now(app)) {
+ (_, Some((emails, same_domain, domain))) => {
+ let mut said = Vec::new();
+ if !emails.is_empty() { said.push(if emails.len() == 1 { "1 person".to_string() } else { format!("{} people", emails.len()) }) }
+ if same_domain { if let Some(d) = domain { said.push(format!("@{d}")) } }
+ if said.is_empty() { "off".to_string() } else { said.join(" · ") }
+ }
+ (Some(Err(_)), _) => "unavailable".into(),
+ _ if is_loading(app, "sharing") => "reading…".into(),
+ _ => "…".into(),
+ };
+ rows.push(Row::new("share:", "Share this computer…").group(here).extra("share sharing people team domain").lead(dot("⇆", theme::TEAL))
+ .detail(vec![span("with people you choose; they use it as their own", fg(theme::MUTED))]).right(state));
+ }
let yours = "Your machines";
- for m in app.fleet.machines.iter().filter(|m| !m.shared) {
+ for m in app.fleet.machines.iter().filter(|m| !m.shared && !app.fleet.shares.contains_key(&m.id)) {
if crate::local::is_local(&m.id) { continue }
let (glyph, color, word) = reach(app, m);
let rtt = app.rtt.get(&m.id).filter(|_| m.usable()).map(|d| format!("{}ms ", d.as_millis())).unwrap_or_default();
@@ -1223,6 +1384,21 @@ fn machines_rows(app: &App) -> Vec<Row> {
}
if app.fleet.machines.iter().all(|m| crate::local::is_local(&m.id)) { rows.push(info("m-none", if app.daemon_down { "Harness is not running on this computer" } else { "Loading machines…" }, yours)) }
+ // Other accounts' machines shared with this one: used as its own.
+ let with_you = "Shared with you";
+ for m in app.fleet.machines.iter() {
+ let Some(share) = app.fleet.shares.get(&m.id) else { continue };
+ let (glyph, color, word) = reach(app, m);
+ rows.push(Row::new(format!("m:{}", m.id), m.name.clone()).group(with_you).extra(format!("{} {} {}", m.id, share.owner, share.email)).lead(dot(glyph, color))
+ .detail(vec![span(format!("shared by {} · ", share.owner), fg(theme::MUTED)), span(word, fg(color))]).right(counts(app, &m.id)));
+ }
+ // Shared with this account's domain: Enter adds one.
+ let team = "Shared with your team";
+ for (id, name, share) in &app.fleet.to_add {
+ rows.push(Row::new(format!("addshared:{id}"), format!("Add {name}")).group(team).extra(format!("{id} {} {}", share.owner, share.email)).lead(dot("+", theme::TEAL))
+ .detail(vec![span(format!("shared by {} with everyone at your company", share.owner), fg(theme::MUTED))]).right("add"));
+ }
+
let linked = "Linked from here";
match &app.devices.links {
None => rows.push(info("ln-loading", "Loading linked machines…", linked)),
@@ -1255,9 +1431,47 @@ fn action_rows(app: &App, id: &str) -> Vec<Row> {
let mut rows = Vec::new();
let act = |verb: &str, label: &str, hint: &str, glyph: &str| Row::new(format!("act:{verb}:{id}"), label).group(group.clone()).lead(dot(glyph, theme::TEAL)).detail(vec![span(hint.to_string(), fg(theme::MUTED))]);
if m.usable() { rows.push(act("open", "Open its harnesses", "the harnesses list, on this machine", "→")) }
- if m.reach == Reach::NeedsLink && m.online() { rows.push(act("connect", "Connect…", "its remote password, then link", "⇄")) }
- rows.push(act("rename", "Rename…", "the name every device on the account shows", "✎"));
- if !m.local { rows.push(act("remove", "Remove from account…", "delete it from your account", "✗")) }
+ // (A machine shared with this account links by its key once both daemons read the sharing: no password.)
+ if m.reach == Reach::NeedsLink && m.online() && !app.fleet.shares.contains_key(id) { rows.push(act("connect", "Connect…", "its remote password, then link", "⇄")) }
+ match app.fleet.shares.get(id) {
+ // Another account's: its owner renames, removes and shares it.
+ Some(share) => {
+ rows.push(info("shared-by", format!("Shared with you by {}{}", share.owner, if share.email.is_empty() || share.email == share.owner { String::new() } else { format!(" ({})", share.email) }), &group));
+ if share.team { rows.push(act("unshare", "Remove from my machines…", "add it again from Shared with your team", "✗")) }
+ }
+ None => {
+ rows.push(act("rename", "Rename…", "the name every device on the account shows", "✎"));
+ if !m.local { rows.push(act("remove", "Remove from account…", "delete it from your account", "✗")) }
+ }
+ }
+ rows
+}
+
+/// This computer's sharing: everyone at its domain, the addresses, and who uses it now.
+fn share_rows(app: &App) -> Vec<Row> {
+ let here = format!("Share {}", app.fleet.local_machine_name());
+ let mut rows = vec![info("share-what", "People you share it with use it as their own: its harnesses, terminals and files.", &here)];
+ let Some((emails, same_domain, domain)) = sharing_now(app) else {
+ match &app.devices.sharing {
+ Some(Err(message)) => {
+ rows.push(info("share-error", message.clone(), &here));
+ rows.push(Row::new("shr:reload", "Retry").group(here.clone()).lead(dot("↻", theme::MUTED)));
+ }
+ _ => rows.push(info("share-loading", "Reading its sharing…", &here)),
+ }
+ return rows;
+ };
+ if let Some(domain) = &domain {
+ rows.push(Row::new("shr:domain", format!("Everyone at @{domain}")).group(here.clone()).extra("domain team company").lead(dot(if same_domain { "✓" } else { "·" }, if same_domain { theme::ONLINE } else { theme::MUTED }))
+ .detail(vec![span("they add it from Machines", fg(theme::MUTED))]).right(if same_domain { "on" } else { "off" }));
+ }
+ rows.push(Row::new("shr:add", "Add an email…").group(here.clone()).extra("add email person").lead(dot("+", theme::TEAL)).detail(vec![span("they see it in their Machines", fg(theme::MUTED))]));
+ for email in &emails {
+ rows.push(Row::new(format!("shr:rm:{email}"), email.clone()).group(here.clone()).extra("remove").lead(dot("·", theme::MUTED)).right("remove"));
+ }
+ let using: Vec<&str> = app.devices.sharing.as_ref().and_then(|s| s.as_ref().ok()).and_then(|v| v.get("members")).and_then(Value::as_array)
+ .into_iter().flatten().filter_map(|m| m.get("email").and_then(Value::as_str)).collect();
+ if !using.is_empty() { rows.push(info("share-using", format!("Using it now: {}", using.join(", ")), &here)) }
rows
}
@@ -1436,7 +1650,10 @@ fn stage_lines(app: &App, machine: &str) -> Vec<Line<'static>> {
/// A title, where you are inside it, and the way out.
fn head(buf: &mut Buffer, app: &App, title: &str, x: u16, y: u16, right: u16, c: &Chrome) {
let mut at = x + settings::put(buf, x, y, right.saturating_sub(x), title, c.base.add_modifier(Modifier::BOLD));
- let level = app.devices.sub.as_deref().and_then(|s| s.strip_prefix("m:")).map(|id| name_of(app, id));
+ let level = match app.devices.sub.as_deref() {
+ Some("share:") => Some(format!("Share {}", app.fleet.local_machine_name())),
+ sub => sub.and_then(|s| s.strip_prefix("m:")).map(|id| name_of(app, id)),
+ };
if let Some(level) = level {
at += settings::put(buf, at, y, right.saturating_sub(at), " › ", c.muted);
settings::put(buf, at, y, right.saturating_sub(at), &level, c.accent);
@@ -1509,6 +1726,8 @@ fn ask_title(app: &App, ask: &Ask) -> String {
Ask::Confirm { act: Act::Remove { name, .. }, .. } => format!("Remove from Account · {name}"),
Ask::Confirm { act: Act::Unpair { name, .. }, .. } => format!("Remove Access · {name}"),
Ask::Confirm { act: Act::ArmPhone, .. } => "Add Your Phone".into(),
+ Ask::Entry { what: Entry::ShareEmail, .. } | Ask::Confirm { act: Act::Share { .. }, .. } => format!("Share · {}", app.fleet.local_machine_name()),
+ Ask::Confirm { act: Act::AddShared { name, .. }, .. } => format!("Remove from My Machines · {name}"),
}
}
@@ -1519,6 +1738,7 @@ fn action(ask: &Ask, room: u16) -> &'static str {
Ask::Confirm { .. } => return "Yes",
Ask::Entry { what: Entry::Link { .. }, .. } => "Connect",
Ask::Entry { what: Entry::Rename { .. }, .. } => "Save",
+ Ask::Entry { what: Entry::ShareEmail, .. } => "Add",
Ask::Entry { .. } => "Continue",
};
if "[ Cancel ] [ ]".width() + word.width() > room as usize { "Next" } else { word }
@@ -1746,6 +1966,136 @@ mod tests {
((0..h).map(|y| (0..w).map(|x| buf[(x, y)].symbol().to_string()).collect::<String>()).collect::<Vec<_>>().join("\n"), buf)
}
+ /// The world, and this computer's daemon answering `shared_machines` as services/sharedMachines.ts does.
+ fn sharing_world(app: &mut App) -> Arc<Mutex<Vec<Req>>> {
+ let log = Arc::new(Mutex::new(Vec::new()));
+ let seen = log.clone();
+ let policy = Arc::new(Mutex::new(json!({ "emails": [], "sameDomain": false, "domain": "acme.io", "members": [] })));
+ app.devices.runner = Some(Box::new(move |req: &Req| {
+ seen.lock().unwrap().push(req.clone());
+ let Req::Rpc { ty: "shared_machines", payload } = req else { return world(req) };
+ Some(Reply::Rpc(Ok(match payload["action"].as_str() {
+ Some("get") => policy.lock().unwrap().clone(),
+ Some("set") => {
+ let mut p = policy.lock().unwrap();
+ p["emails"] = payload["emails"].clone();
+ p["sameDomain"] = payload["sameDomain"].clone();
+ p.clone()
+ }
+ _ => json!({ "ok": true }),
+ })))
+ }));
+ log
+ }
+ fn rpc(action: &str, rest: Value) -> Req {
+ let mut payload = json!({ "action": action });
+ for (k, v) in rest.as_object().unwrap() { payload[k] = v.clone() }
+ Req::Rpc { ty: "shared_machines", payload }
+ }
+ fn row_of<'a>(app: &'a App, id: &str) -> Option<&'a Row> {
+ match &app.modal { Some(Modal::Picker { picker, .. }) => picker.rows.iter().find(|r| r.id == id), _ => None }
+ }
+
+ #[test]
+ fn machines_shared_with_this_account_are_its_to_use_and_the_teams_are_added_with_enter() {
+ const SHARED: &str = "abababababababababababababababab";
+ const TEAM: &str = "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd";
+ let mut app = app((150, 42));
+ let log = sharing_world(&mut app);
+ app.fleet.machines.push(crate::fleet::Machine { shared: false, id: SHARED.into(), name: "dee-studio".into(), local: false, status: "running".into(), reach: Reach::Ready });
+ let dee = crate::fleet::MachineShare { owner: "Dee".into(), email: "[email protected]".into(), team: true };
+ app.fleet.shares.insert(SHARED.into(), dee.clone());
+ app.fleet.to_add.push((TEAM.into(), "gpu-box-2".into(), dee));
+ open(&mut app, View::Machines);
+ assert_eq!(row_of(&app, &format!("m:{SHARED}")).and_then(|r| r.group.as_deref()), Some("Shared with you"));
+ assert_eq!(row_of(&app, &format!("addshared:{TEAM}")).map(|r| (r.label.as_str(), r.group.as_deref())), Some(("Add gpu-box-2", Some("Shared with your team"))));
+ assert_eq!(row_of(&app, &format!("m:{REMOTE}")).and_then(|r| r.group.as_deref()), Some("Your machines"));
+
+ // Enter adds the team's machine, through this computer's daemon.
+ go_to(&mut app, &format!("addshared:{TEAM}"));
+ press(&mut app, KeyCode::Enter);
+ assert!(has(&log, &rpc("add", json!({ "machineId": TEAM }))));
+ assert!(app.fleet.to_add.is_empty());
+ assert!(app.devices.footer.as_ref().is_some_and(|(t, err, _)| !err && t.starts_with("Added gpu-box-2")));
+
+ // A machine shared with you is its owner's to rename or remove; one from the team can leave your list.
+ go_to(&mut app, &format!("m:{SHARED}"));
+ press(&mut app, KeyCode::Enter);
+ let here = ids(&app);
+ assert!(here.contains(&format!("act:unshare:{SHARED}")) && here.contains(&"shared-by".to_string()), "{here:?}");
+ assert!(!here.contains(&format!("act:rename:{SHARED}")) && !here.contains(&format!("act:remove:{SHARED}")));
+ go_to(&mut app, &format!("act:unshare:{SHARED}"));
+ press(&mut app, KeyCode::Enter);
+ press(&mut app, KeyCode::Char('Y'));
+ assert!(has(&log, &rpc("remove", json!({ "machineId": SHARED }))));
+ assert!(!app.fleet.shares.contains_key(SHARED));
+ assert!(app.fleet.machine(SHARED).is_none());
+ }
+
+ #[test]
+ fn this_computer_is_shared_with_its_domain_and_with_addresses_each_after_a_yes() {
+ let mut app = app((150, 42));
+ let log = sharing_world(&mut app);
+ open(&mut app, View::Machines);
+ assert!(has(&log, &rpc("get", json!({}))));
+ assert_eq!(row_of(&app, "share:").map(|r| r.right.clone()), Some("off".into()));
+ go_to(&mut app, "share:");
+ press(&mut app, KeyCode::Enter);
+ assert_eq!(ids(&app)[1..], ["shr:domain", "shr:add"]);
+
+ go_to(&mut app, "shr:domain");
+ press(&mut app, KeyCode::Enter);
+ assert!(app.devices.ask.is_some(), "everyone at the domain is asked first");
+ press(&mut app, KeyCode::Char('Y'));
+ assert!(has(&log, &rpc("set", json!({ "emails": [], "sameDomain": true }))));
+ assert_eq!(row_of(&app, "shr:domain").map(|r| r.right.clone()), Some("on".into()));
+
+ go_to(&mut app, "shr:add");
+ press(&mut app, KeyCode::Enter);
+ typed(&mut app, "not-an-address");
+ press(&mut app, KeyCode::Enter);
+ assert!(app.devices.footer.as_ref().is_some_and(|(t, err, _)| *err && t.contains("Not an email address")));
+ press(&mut app, KeyCode::Esc);
+ go_to(&mut app, "shr:add");
+ press(&mut app, KeyCode::Enter);
+ typed(&mut app, "[email protected]");
+ press(&mut app, KeyCode::Enter);
+ press(&mut app, KeyCode::Char('Y'));
+ assert!(has(&log, &rpc("set", json!({ "emails": ["[email protected]"], "sameDomain": true }))));
+ assert!(ids(&app).contains(&"shr:rm:[email protected]".to_string()));
+
+ // Turning the domain off needs no yes; taking an address off does.
+ go_to(&mut app, "shr:domain");
+ press(&mut app, KeyCode::Enter);
+ assert!(has(&log, &rpc("set", json!({ "emails": ["[email protected]"], "sameDomain": false }))));
+ go_to(&mut app, "shr:rm:[email protected]");
+ press(&mut app, KeyCode::Enter);
+ press(&mut app, KeyCode::Char('Y'));
+ assert!(has(&log, &rpc("set", json!({ "emails": [], "sameDomain": false }))));
+ // Back out of the level, onto its row.
+ press(&mut app, KeyCode::Esc);
+ assert_eq!(match &app.modal { Some(Modal::Picker { picker, .. }) => picker.current_id(), _ => None }.as_deref(), Some("share:"));
+ }
+
+ #[test]
+ fn sharing_that_cannot_be_read_says_why_and_offers_a_retry() {
+ let mut app = app((150, 42));
+ let _log = fake(&mut app);
+ open(&mut app, View::Machines);
+ assert_eq!(row_of(&app, "share:").map(|r| r.right.clone()), Some("unavailable".into()));
+ go_to(&mut app, "share:");
+ press(&mut app, KeyCode::Enter);
+ assert!(ids(&app).contains(&"shr:reload".to_string()));
+ assert_eq!(shared_answer(Reply::Rpc(Ok(json!({ "error": "UNSUPPORTED" })))), Err("Update Harness on this computer to share it.".into()));
+ assert_eq!(shared_answer(Reply::Rpc(Ok(json!({ "error": "PUBLIC_DOMAIN", "message": "It is a public email domain." })))), Err("It is a public email domain.".into()));
+ assert_eq!(shared_answer(Reply::Rpc(Ok(json!({ "error": "X" })))), Err("Could not share it (X).".into()));
+ assert_eq!(shared_answer(Reply::Rpc(Err(("DOWN".into(), "Harness is not running on this computer.".into())))), Err("Harness is not running on this computer.".into()));
+ assert!(is_email("[email protected]") && !is_email("a@b") && !is_email("@b.io") && !is_email("a [email protected]"));
+ // As the backend reads them: one typed `name@!gmail.com` once failed a whole save there.
+ for good in ["[email protected]", "[email protected]", "o'[email protected]", "[email protected]"] { assert!(is_email(good), "{good}") }
+ for bad in ["bitcoinbuilder.ai@!gmail.com", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "a@@x.io"] { assert!(!is_email(bad), "{bad}") }
+ }
+
#[test]
fn the_commands_panel_lists_connect_machines_and_add_phone_under_machines() {
let app = app((150, 42));
diff --git a/tui/src/fleet.rs b/tui/src/fleet.rs
index 2372ed59d..54721975b 100644
--- a/tui/src/fleet.rs
+++ b/tui/src/fleet.rs
@@ -486,11 +486,35 @@ pub fn answer_text(q: &Question, typed: &str) -> Option<String> {
}
}
+/// A whole machine another account shares with this one (backend lib/machineAccess.ts): its owner
+/// named this account's address, or shared it with everyone at their domain ([team]) and this account
+/// added it. Used as the account's own; its owner alone renames, removes or shares it.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct MachineShare {
+ pub owner: String,
+ pub email: String,
+ pub team: bool,
+}
+
+impl MachineShare {
+ /// From a `sharedMachines` row's `share`.
+ pub fn of(share: &Value) -> MachineShare {
+ let text = |key: &str| share.get(key).and_then(Value::as_str).unwrap_or("").trim().to_string();
+ let (name, email) = (text("ownerName"), text("ownerEmail"));
+ MachineShare { owner: if name.is_empty() { email.clone() } else { name }, email, team: share.get("via").and_then(Value::as_str) == Some("domain") }
+ }
+}
+
#[derive(Default)]
pub struct Fleet {
pub local_id: String,
pub machines: Vec<Machine>,
pub agents: HashMap<(String, String), Agent>,
+ /// The machines in [machines] another account shares with this one, by id.
+ pub shares: HashMap<String, MachineShare>,
+ /// Machines shared with this account's domain, not added yet: (id, name, share). Machines &
+ /// devices lists them, and Enter adds one.
+ pub to_add: Vec<(String, String, MachineShare)>,
}
/// Match the desktop and phone: the app's saved name, or its stable machine-id label.
@@ -500,6 +524,34 @@ pub fn machine_display_name(id: &str, name: Option<&str>) -> String {
}
impl Fleet {
+ /// The machine list's rows to keep: the account's own ([owned]) and the whole machines other
+ /// accounts share with it that are its to use (named for it, or added), noted in [shares]; one
+ /// shared with its domain and not added goes to [to_add]. A list that could not say ([shared]
+ /// absent) keeps the shared machines it had.
+ pub fn take_shared(&mut self, owned: &[Value], shared: Option<&Vec<Value>>) -> Vec<Value> {
+ let mut rows = owned.to_vec();
+ let Some(shared) = shared else {
+ rows.extend(self.shares.keys().filter_map(|id| self.machine(id))
+ .map(|m| serde_json::json!({ "machineId": m.id, "name": m.name, "status": m.status })));
+ return rows;
+ };
+ self.shares.clear();
+ self.to_add.clear();
+ for row in shared {
+ let id = row.get("machineId").and_then(Value::as_str).unwrap_or("").to_string();
+ if id.is_empty() || owned.iter().any(|o| o["machineId"] == row["machineId"]) { continue }
+ let share = MachineShare::of(&row["share"]);
+ if row["share"]["added"] == true {
+ self.shares.insert(id, share);
+ rows.push(row.clone());
+ } else {
+ let name = machine_display_name(&id, row.get("name").and_then(Value::as_str));
+ self.to_add.push((id, name, share));
+ }
+ }
+ rows
+ }
+
pub fn machine(&self, id: &str) -> Option<&Machine> { self.machines.iter().find(|m| m.id == id) }
pub fn machine_mut(&mut self, id: &str) -> Option<&mut Machine> { self.machines.iter_mut().find(|m| m.id == id) }
/// The account's record for this computer; the local PTY transport is not another machine.
@@ -674,6 +726,33 @@ pub fn ago(ms: u64) -> String {
mod tests {
use super::*;
+ #[test]
+ fn whole_machines_shared_with_the_account_are_kept_and_one_for_the_team_waits_to_be_added() {
+ use serde_json::json;
+ let mut fleet = Fleet::default();
+ let owned = vec![json!({ "machineId": "own", "name": "studio" })];
+ let share = |via: &str, added: bool| json!({ "ownerName": "Dee", "ownerEmail": "[email protected]", "via": via, "added": added });
+ let shared = vec![
+ json!({ "machineId": "named", "name": "Dee's Mac", "share": share("email", true) }),
+ json!({ "machineId": "team", "name": "GPU box", "share": share("domain", true) }),
+ json!({ "machineId": "waiting", "name": null, "share": share("domain", false) }),
+ // Also the account's own: its own row wins.
+ json!({ "machineId": "own", "share": share("email", true) }),
+ ];
+ let rows = fleet.take_shared(&owned, Some(&shared));
+ assert_eq!(rows.iter().map(|r| r["machineId"].as_str().unwrap()).collect::<Vec<_>>(), ["own", "named", "team"]);
+ assert_eq!(fleet.shares.get("named"), Some(&MachineShare { owner: "Dee".into(), email: "[email protected]".into(), team: false }));
+ assert!(fleet.shares["team"].team);
+ assert_eq!(fleet.to_add, vec![("waiting".to_string(), "machine-waiting".to_string(), MachineShare { owner: "Dee".into(), email: "[email protected]".into(), team: true })]);
+ // A list that could not say what is shared keeps what it had.
+ fleet.machines.push(Machine { shared: false, id: "named".into(), name: "Dee's Mac".into(), local: false, status: "running".into(), reach: Reach::Ready });
+ let kept = fleet.take_shared(&owned, None);
+ assert_eq!(kept.iter().map(|r| r["machineId"].as_str().unwrap()).collect::<Vec<_>>(), ["own", "named"]);
+ assert!(fleet.shares.contains_key("named"));
+ // An owner with no name is shown by address.
+ assert_eq!(MachineShare::of(&json!({ "ownerName": " ", "ownerEmail": "[email protected]" })).owner, "[email protected]");
+ }
+
#[test]
fn cache_needs_the_current_accounts_owner_and_drops_legacy_unscoped_data() {
let mut cached = serde_json::json!({