Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(shared-computers): a paired phone sees the PC its desktop lends on a server of one's own (#5508)

AdityaUmale48893c4baf95
diff --git a/server/index.ts b/server/index.ts
index f8906fd387..d13175c499 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -634,7 +634,7 @@ import { clearInternalTurn, isInternalTurn, markInternalTurn } from "./internal-
import { createReactionRoutes } from "./routes/reactions.ts";
import { createReactions, withReactionNotes, type Reactor } from "./reactions.ts";
import { createPersonReplies } from "./person-replies.ts";
-import { personKey, relayedPersonKey } from "./person-key.ts";
+import { lendingPerson, lendingPersonKey, personKey, relayedPersonKey } from "./person-key.ts";
import { createOutsideLineage, OUTSIDE_STAYS_HERE } from "./host/outside-lineage.ts"; import { OUTSIDE_REFUSAL, outsideRouteRefused } from "./host/outside-fence.ts"; import { createOutsideWrites } from "./host/outside-writes.ts";
import { teamAiOwner } from "./host/team-ai-owner.ts"; import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { createTeamAwayHost } from "./host/team-away-host.ts"; import { createPlaceInbox, guestNameIn, placeInboxViewer } from "./host/place-inbox.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";
import { createDevsReports } from "./host/devs-reports.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";
@@ -897,8 +897,8 @@ function turnOrigin(capability: Pick<InternalCapability, "threadId" | "generatio
/** Fail closed: only the person whose own message provably started this exact turn generation. Deliberately not the usage ledger's trigger, which defaults to the owner. */
function sharedComputerPrincipal(capability: Pick<InternalCapability, "botId" | "threadId" | "generation">): string | null {
if (CLOUD_HOME) return cloudLendingRefusal(capability) === null ? CLOUD_HOME_LENDER : null;
- return provenRequestPerson(directRequestOwners.get(capability.threadId), capability.generation,
- (messageId) => linePersonKey(store.messagesFor(capability.threadId).find((message) => message.id === messageId)));
+ return lendingPerson(provenRequestPerson(directRequestOwners.get(capability.threadId), capability.generation,
+ (messageId) => linePersonKey(store.messagesFor(capability.threadId).find((message) => message.id === messageId))), ownHome.oneOwner(), () => sessions.list());
}
/** The only conversations that may feed a bot's memory, daily log, recall or brief; dropped whenever a session is revoked. */
@@ -931,7 +931,7 @@ function foreignTurnRunning(botId: string): boolean {
/** On a Cloud home only the owner's own devices see the lent Mac, never a guest or a local process. */
function sessionLendingPrincipal(auth: RequestAuth): string | null {
if (CLOUD_HOME) return CLOUD_PERSONAL && cloudOwnerSession(auth) ? CLOUD_HOME_LENDER : null;
- return auth.kind === "session" ? personKey(auth.session) : null;
+ return auth.kind === "session" ? lendingPersonKey(auth.session, ownHome.oneOwner()) : null;
}
const CLOUD_OWNER_PROFILE_FIELDS = ["name", "title", "description", "soul", "notifications"] as const;
@@ -12090,7 +12090,7 @@ ROUTES.push(createHostedSlackRoutes({ bot: (id) => store.bot(id), hostedReady: (
const orgInstallStatuses = () => orgLibrary?.installStatuses() ?? new Map();
ROUTES.push(createBotPresetRoutes({ presets: presetStore, orgStatuses: orgInstallStatuses })); ROUTES.push(createWorkspaceBannerRoutes({ changed: () => broadcast({ kind: "config", ...configStatus() }) })); ROUTES.push(createStarterAwakeRoutes({ awake: starterAwake }));
ROUTES.push(createSharedComputerRoutes({ enabled: (auth) => lendingEnabled() || (ownerLends() && ownHome.owner(auth)), computers: sharedComputers, sessionLive: (id) => sessions.isLive(id), environmentId: ENVIRONMENT_ID,
- cloudHomeLender: CLOUD_HOME ? CLOUD_HOME_LENDER : null, principal: sessionLendingPrincipal, personKey, power: () => cloudPower, links: CLOUD_HOME ? deviceLinks : null, upgrades, asks: computerAsks?.asks ?? null, answerer: cardAnswererFor }));
+ cloudHomeLender: CLOUD_HOME ? CLOUD_HOME_LENDER : null, principal: sessionLendingPrincipal, personKey: (session) => lendingPersonKey(session, ownHome.oneOwner()), power: () => cloudPower, links: CLOUD_HOME ? deviceLinks : null, upgrades, asks: computerAsks?.asks ?? null, answerer: cardAnswererFor }));
// `routines` is assigned at boot, so it is read per request.
ROUTES.push(createBotMessageRoutes({
store, registry, handoffs, liveTurn: (threadId) => liveTurns.running(threadId), phoneSecretSubmissions, directTurnDispatchClaims, groupSpeakers,
diff --git a/server/own-home.ts b/server/own-home.ts
index d8ee357c2d..270517f1ed 100644
--- a/server/own-home.ts
+++ b/server/own-home.ts
@@ -32,6 +32,7 @@ export function ownServerOwner(facts: OwnServerFacts, auth: RequestAuth): boolea
export function createOwnHome({ facts, dataDir }: { facts(): OwnServerFacts; dataDir: string }) {
return {
owner: (auth: RequestAuth): auth is Extract<RequestAuth, { kind: "session" }> => ownServerOwner(facts(), auth),
+ oneOwner: () => oneOwner(facts()),
takesMove: () => oneOwner(facts()),
here: () => oneOwner(facts()) && movedFrom(dataDir) !== null,
};
diff --git a/server/person-key.test.ts b/server/person-key.test.ts
new file mode 100644
index 0000000000..856533395e
--- /dev/null
+++ b/server/person-key.test.ts
@@ -0,0 +1,57 @@
+import { randomUUID } from "node:crypto";
+import { describe, expect, it } from "vitest";
+
+import { lendingPerson, lendingPersonKey, PAIRED_DEVICES_LENDER, personKey } from "./person-key.ts";
+import { SharedComputers } from "./shared-computers.ts";
+
+type Device = Parameters<typeof lendingPersonKey>[0];
+const device = (fields: Partial<Device> = {}): Device => ({ id: randomUUID(), scopes: ["admin", "client"], ...fields });
+
+describe("shared computers on a self-hosted server without email sign-in", () => {
+ it("a paired phone with full access sees the PC its desktop lends", () => {
+ const desktop = device(), phone = device();
+ expect(personKey(desktop)).not.toBe(personKey(phone));
+ const broker = new SharedComputers((id) => id === desktop.id);
+ const computer = { id: randomUUID(), name: "PC B", environmentId: randomUUID(), folders: [], terminal: true, computer: false };
+ broker.register(computer, { session: desktop.id, person: lendingPersonKey(desktop, true) }, "a".repeat(64));
+ // A turn the phone started is known only by the key on its message.
+ const fromPhone = lendingPerson(personKey(phone), true, () => [desktop, phone]);
+ expect(broker.list(fromPhone).map((entry) => entry.id)).toEqual([computer.id]);
+ broker.close();
+ });
+
+ it("every full-access device without email is one lender; nothing else changes who is who", () => {
+ const desktop = device(), phone = device({ scopes: ["admin"] });
+ expect(lendingPersonKey(desktop, true)).toBe(PAIRED_DEVICES_LENDER);
+ expect(lendingPersonKey(phone, true)).toBe(PAIRED_DEVICES_LENDER);
+ expect(personKey(desktop)).not.toBe(PAIRED_DEVICES_LENDER);
+ });
+
+ it("on a server more than one person uses, each device stays its own person", () => {
+ const desktop = device(), phone = device({ scopes: ["admin"] });
+ expect(lendingPersonKey(desktop, false)).toBe(personKey(desktop));
+ expect(lendingPerson(personKey(phone), false, () => [desktop, phone])).toBe(personKey(phone));
+ expect(lendingPerson(null, true, () => [desktop])).toBeNull();
+ });
+
+ it("a guest or limited pairing, a team member, a script token or an email sign-in keeps its own key", () => {
+ const others = [
+ device({ scopes: ["client"] }),
+ device({ teamRole: "admin" }),
+ device({ token: true }),
+ device({ owner: "[email protected]" }),
+ device({ email: "[email protected]" }),
+ ];
+ const desktop = device();
+ for (const other of others) {
+ expect(lendingPersonKey(other, true)).toBe(personKey(other));
+ expect(lendingPerson(personKey(other), true, () => [desktop, other])).toBe(personKey(other));
+ }
+ });
+
+ it("a device that is no longer paired, or a person relayed from another app, sees nothing of the lent PC", () => {
+ const desktop = device(), revoked = device();
+ expect(lendingPerson(personKey(revoked), true, () => [desktop])).toBe(personKey(revoked));
+ expect(lendingPerson("p_relayed", true, () => [desktop])).toBe("p_relayed");
+ });
+});
diff --git a/server/person-key.ts b/server/person-key.ts
index 4828c9b80f..52428cb8cf 100644
--- a/server/person-key.ts
+++ b/server/person-key.ts
@@ -14,3 +14,27 @@ export function personKey(session: Pick<SessionRecord, "id" | "email">): string
export function relayedPersonKey(person: { email?: string; name?: string }): string {
return person.email ? personKey({ id: "", email: person.email }) : hashed(`name:${(person.name ?? "").trim()}`);
}
+
+type DeviceSession = Pick<SessionRecord, "id" | "email" | "scopes" | "owner" | "teamRole" | "token">;
+
+/** Every full-access paired device of a server of one person's own, for shared computers only. */
+export const PAIRED_DEVICES_LENDER = hashed("lender:full-access-paired-devices");
+
+/** A device paired with full access and no email: not a guest, a limited pairing, a team member or a script token. */
+function fullAccessPairedDevice(session: DeviceSession): boolean {
+ return !session.email && !session.owner && !session.teamRole && !session.token && session.scopes.includes("admin");
+}
+
+/** Who lends and uses a shared computer on a self-hosted server. Without email sign-in each paired device is its own
+ * person, so a phone could never use the PC its owner's desktop lends: all full-access paired devices count as one
+ * lender there. Everyone else keeps their own key. Only where one person signs in (own-home.ts oneOwner). */
+export function lendingPersonKey(session: DeviceSession, oneOwner: boolean): string {
+ return oneOwner && fullAccessPairedDevice(session) ? PAIRED_DEVICES_LENDER : personKey(session);
+}
+
+/** The same for a person known only by the key on their message: only while that key belongs to a live full-access
+ * paired device; otherwise (a revoked device, a guest, a relayed person) it stays as it is. */
+export function lendingPerson(person: string | null, oneOwner: boolean, sessions: () => readonly DeviceSession[]): string | null {
+ if (!person || !oneOwner) return person;
+ return sessions().some((session) => fullAccessPairedDevice(session) && personKey(session) === person) ? PAIRED_DEVICES_LENDER : person;
+}
diff --git a/server/routes/shared-computers.ts b/server/routes/shared-computers.ts
index f258c9e319..7909927a23 100644
--- a/server/routes/shared-computers.ts
+++ b/server/routes/shared-computers.ts
@@ -21,7 +21,7 @@ export function createSharedComputerRoutes(deps: {
/** On a Cloud home every lent computer is the owner's, under this one name. */
cloudHomeLender: string | null;
principal: (auth: RequestAuth) => string | null;
- personKey: (session: Pick<SessionRecord, "id" | "email">) => string;
+ personKey: (session: SessionRecord) => string;
/** A Cloud home that agreed to sleep sends the desktop away until it wakes (server/cloud-power.ts). */
power: () => Pick<CloudPower, "sleeping" | "sleepSignal"> | null;
/** A Cloud home's device links (a lent computer's internet connection); null elsewhere, where the path 404s. */
diff --git a/server/shared-computers.gate.test.ts b/server/shared-computers.gate.test.ts
index 66edecf832..2568f46bc1 100644
--- a/server/shared-computers.gate.test.ts
+++ b/server/shared-computers.gate.test.ts
@@ -155,14 +155,17 @@ it("the desktop lends to a server of the person's own once they allow it, with n
expect(await sharing.ownServer(env)).toMatchObject({ sessionId: owner.id });
const offered = await sharing.ownOffer(env);
expect(offered).toMatchObject({ sessionId: owner.id });
+ // Every full-access pairing lends as one person here, so this one also sees the earlier tests' computers.
+ const listed = async () => ((await api("GET", "/api/shared-computers", undefined, bearer(owner.token))).body.computers ?? []) as Array<{ id: string; online: boolean; scopes: { screen: boolean; terminal: boolean } }>;
+ const earlier = new Set((await listed()).map((computer) => computer.id));
+ const ours = async () => (await listed()).filter((computer) => !earlier.has(computer.id));
const lent = await sharing.lendOwn(env, { computer: true });
expect(lent).toMatchObject({ enabled: true, own: true, computer: true, terminal: false, folders: [] });
- const listed = async () => ((await api("GET", "/api/shared-computers", undefined, bearer(owner.token))).body.computers ?? []) as Array<{ online: boolean; scopes: { screen: boolean; terminal: boolean } }>;
- await vi.waitFor(async () => expect((await listed()).some((computer) => computer.online && computer.scopes.screen && !computer.scopes.terminal)).toBe(true), { timeout: 15_000 });
+ await vi.waitFor(async () => expect((await ours()).some((computer) => computer.online && computer.scopes.screen && !computer.scopes.terminal)).toBe(true), { timeout: 15_000 });
expect(await sharing.ownOffer(env), "answered for this pairing: not asked again").toBeNull();
expect((await internal("GET", "/api/internal/shared-computers")).status, "the bots' route once a computer is lent").toBe(200);
sharing.revoke(env);
- await vi.waitFor(async () => expect((await listed()).some((computer) => computer.online)).toBe(false), { timeout: 15_000 });
+ await vi.waitFor(async () => expect((await ours()).some((computer) => computer.online)).toBe(false), { timeout: 15_000 });
} finally { sharing.close(); }
});