Skip to content

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

You menu: who you're signed in as, and Sign out

milind-soni0e4220ad6434
diff --git a/electron/account-places.mjs b/electron/account-places.mjs
new file mode 100644
index 0000000000..3d5a0e863d
--- /dev/null
+++ b/electron/account-places.mjs
@@ -0,0 +1,27 @@
+// The saved places that belong to the signed-in account: My Cloud, its other Clouds and its teams' Clouds. Servers
+// connected by hand and This computer belong to nobody's account and stay.
+//
+// Security: a team's Cloud can be shared by two accounts on this device, at one address, so nothing the window kept for it
+// under one account may be there for the other: every kind of storage goes for a team's Cloud. A Cloud of one account's own
+// has no other account's person in it, so only its session goes and its page keeps what it remembers.
+import environments from "./environments.cjs";
+
+const SHARED_STORAGE = Object.freeze(["cookies", "localstorage", "indexdb", "cachestorage", "serviceworkers"]);
+const OWN_STORAGE = Object.freeze(["cookies"]);
+
+/** `mine`: My Cloud's verified address, for a My Cloud that was saved by hand before it was known to be one. */
+export const accountPlace = (entry, mine = null) => entry?.kind !== "local" && Boolean(entry?.home === true || entry?.team || entry?.cloud || (mine && entry?.origin === mine));
+
+/** The saved places without the account's, and which those were. The window goes to This computer if it showed one of them. */
+export function withoutAccountPlaces(saved, mine = null) {
+ const left = saved.environments.filter((entry) => accountPlace(entry, mine));
+ if (!left.length) return { saved, left };
+ const active = left.some((entry) => entry.id === saved.activeId) ? environments.LOCAL_ID : saved.activeId;
+ return { saved: { ...saved, environments: saved.environments.filter((entry) => !left.includes(entry)), activeId: active }, left };
+}
+
+/** What the window holds for each of these places goes: the next opening signs in with the Admin's one-time code. */
+export async function clearPlaceStorage(session, places, log = () => {}) {
+ await Promise.all(places.filter((entry) => entry.origin).map((entry) => session.clearStorageData({ origin: entry.origin, storages: [...(entry.team ? SHARED_STORAGE : OWN_STORAGE)] })
+ .catch((error) => log(`accounts: could not clear what the window kept for a place (${error?.message ?? error})`))));
+}
diff --git a/electron/accounts-main.mjs b/electron/accounts-main.mjs
new file mode 100644
index 0000000000..59b0f5313d
--- /dev/null
+++ b/electron/accounts-main.mjs
@@ -0,0 +1,74 @@
+// Who is signed in on this device, for the You menu. The list goes only to this app's own pages: this computer's and the
+// rail's. A Cloud's or a server's page never reads it, because it would learn the addresses of the person's other accounts;
+// it may only ask main, from the person's click, to open the sheet on the rail's page.
+import { withoutAccountPlaces, clearPlaceStorage } from "./account-places.mjs";
+
+/** The sign-in as the You menu shows it: never a token, and no account while none is signed in. */
+export function accountsView(state) {
+ const account = state?.account;
+ if (!account?.id || state.status === "signed-out" || state.status === "connecting") return { active: null, others: [] };
+ return { active: { id: account.id, email: account.email, ...(state.status === "reauth-required" ? { signIn: true } : {}) }, others: [] };
+}
+
+/** Everything of the account this window held: its places leave the list, the window leaves them, and their sessions go. */
+export function createAccountLeave({ saved, persist, session, mine, leaveWindow, log = () => {} }) {
+ return async () => {
+ const { saved: next, left } = withoutAccountPlaces(saved(), mine());
+ if (left.length) persist(next);
+ await leaveWindow();
+ await clearPlaceStorage(session(), left, log);
+ return left;
+ };
+}
+
+/**
+ * @param {{
+ * ipcMain: { handle(channel: string, handler: (event: unknown, ...args: any[]) => unknown): void },
+ * ownPage(event: unknown): boolean,
+ * placePage(event: unknown): boolean,
+ * account(): { state(): any } | null,
+ * client(): { state(): any, signOut(): Promise<any> },
+ * holdSheet(open: boolean): void,
+ * tellSheet(): void,
+ * leaving(): void,
+ * leave(): Promise<unknown>,
+ * show(): Promise<unknown>,
+ * tell(): void,
+ * }} deps `ownPage`: this app's own page in the window, or the rail's. `placePage`: the page of a place of the person's own
+ * or their team's, which may offer the sheet. `holdSheet`: the rail's page stays up for the sheet, even for someone who hid
+ * the rail. `leaving`: the home window lets go of what it was doing for this account; `leave`: createAccountLeave's;
+ * `show`: the window goes where it belongs now; `tell`: this app's pages read the list again.
+ */
+export function installAccounts({ ipcMain, ownPage, placePage, account, client, holdSheet, tellSheet, leaving, leave, show, tell }) {
+ let sheetPending = false, queue = Promise.resolve();
+ const view = () => accountsView(account()?.state());
+ const serial = (work) => { const run = queue.then(work, work); queue = run.catch(() => {}); return run; };
+ const own = (channel, handler) => ipcMain.handle(channel, (event, ...args) => {
+ if (!ownPage(event)) throw new Error(`${channel} is only available on this app's own page`);
+ return handler(...args);
+ });
+ const signOutActive = () => serial(async () => {
+ leaving();
+ const after = await client().signOut();
+ await leave();
+ await show();
+ tell();
+ return after;
+ });
+ own("accounts:list", view);
+ own("accounts:sign-out", async (id) => {
+ if (view().active?.id !== id) throw new Error("That account isn't signed in here any more.");
+ await signOutActive();
+ return view();
+ });
+ own("accounts:sheet-pending", () => { const pending = sheetPending; sheetPending = false; return pending; });
+ own("accounts:sheet-closed", () => { sheetPending = false; holdSheet(false); });
+ ipcMain.handle("accounts:offered", (event) => placePage(event) === true);
+ ipcMain.handle("accounts:open", (event) => {
+ if (!placePage(event)) throw new Error("accounts:open is only available on a page of the person's own");
+ sheetPending = true;
+ holdSheet(true);
+ tellSheet();
+ });
+ return { view, signOutActive, tell };
+}
diff --git a/electron/accounts-main.node-test.mjs b/electron/accounts-main.node-test.mjs
new file mode 100644
index 0000000000..9c299918d0
--- /dev/null
+++ b/electron/accounts-main.node-test.mjs
@@ -0,0 +1,97 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { accountPlace, clearPlaceStorage, withoutAccountPlaces } from "./account-places.mjs";
+import { accountsView, createAccountLeave, installAccounts } from "./accounts-main.mjs";
+
+const signedIn = { status: "connected", account: { id: "a", email: "[email protected]" }, deviceId: "d" };
+
+function harness({ state = signedIn, placePage = () => true, ownPage = () => true } = {}) {
+ const handlers = new Map(), calls = [];
+ let current = state;
+ const client = { state: () => current, signOut: async () => { calls.push("sign-out"); current = { status: "signed-out" }; return current; } };
+ const accounts = installAccounts({
+ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, ownPage, placePage, account: () => client, client: () => client,
+ holdSheet: (open) => calls.push(`hold:${open}`), tellSheet: () => calls.push("tell-sheet"), leaving: () => calls.push("leaving"), leave: async () => calls.push("leave"), show: async () => calls.push("show"), tell: () => calls.push("tell"),
+ });
+ return { handlers, calls, accounts, call: (channel, ...args) => handlers.get(channel)({}, ...args) };
+}
+
+test("the view names the account and its address, never a token, and nothing while signed out", () => {
+ assert.deepEqual(accountsView({ ...signedIn, token: "omc_secret", machine: { origin: "https://a.test" } }), { active: { id: "a", email: "[email protected]" }, others: [] });
+ assert.deepEqual(accountsView({ status: "reauth-required", account: signedIn.account }).active.signIn, true);
+ assert.deepEqual(accountsView({ status: "signed-out" }), { active: null, others: [] });
+ assert.deepEqual(accountsView({ status: "connecting" }), { active: null, others: [] });
+ assert.deepEqual(accountsView(null), { active: null, others: [] });
+});
+
+test("only this app's own pages read the list or sign out; another page only opens the sheet, from main", async () => {
+ const f = harness({ ownPage: () => false });
+ for (const channel of ["accounts:list", "accounts:sign-out", "accounts:sheet-pending", "accounts:sheet-closed"]) await assert.rejects(async () => f.call(channel, "a"), /only available/);
+ assert.equal(await f.call("accounts:offered"), true);
+ assert.equal(await f.call("accounts:open"), undefined);
+ assert.deepEqual(f.calls, ["hold:true", "tell-sheet"]);
+ const refused = harness({ ownPage: () => false, placePage: () => false });
+ assert.equal(await refused.call("accounts:offered"), false);
+ await assert.rejects(async () => refused.call("accounts:open"), /only available/);
+ assert.deepEqual(refused.calls, []);
+});
+
+test("the sheet asked for before the rail's page was up opens once when that page asks, and closing lets the rail go", async () => {
+ const f = harness();
+ await f.call("accounts:open");
+ assert.equal(await f.call("accounts:sheet-pending"), true);
+ assert.equal(await f.call("accounts:sheet-pending"), false);
+ await f.call("accounts:sheet-closed");
+ assert.deepEqual(f.calls, ["hold:true", "tell-sheet", "hold:false"]);
+});
+
+test("sign out: the window lets go first, the sign-in ends, the account's places leave, then the window goes where it belongs", async () => {
+ const f = harness();
+ assert.deepEqual(await f.call("accounts:sign-out", "a"), { active: null, others: [] });
+ assert.deepEqual(f.calls, ["leaving", "sign-out", "leave", "show", "tell"]);
+});
+
+test("signing out an account that isn't the one here changes nothing", async () => {
+ const f = harness();
+ await assert.rejects(f.call("accounts:sign-out", "other"), /isn't signed in here/);
+ assert.deepEqual(f.calls, []);
+});
+
+const places = {
+ activeId: "cloud-a",
+ environments: [
+ { id: "home-a", origin: "https://home-a.test", name: "My Cloud", home: true },
+ { id: "cloud-a", origin: "https://second-a.test", name: "Second", cloud: { id: "c2", role: "owner" } },
+ { id: "team-a", origin: "https://shared-team.test", name: "Team", team: { id: "t1", role: "member" } },
+ { id: "by-hand", origin: "https://mine.example", name: "By hand" },
+ { id: "local-2", kind: "local", dataDir: "/x", name: "Another" },
+ ],
+};
+
+test("an account's places are its Clouds and its teams'; a server saved by hand and a local workspace stay", () => {
+ assert.equal(accountPlace(places.environments[3]), false);
+ assert.equal(accountPlace(places.environments[3], "https://mine.example"), true, "My Cloud saved by hand before it was known to be one");
+ assert.equal(accountPlace(places.environments[4], "https://mine.example"), false);
+ const { saved, left } = withoutAccountPlaces(places);
+ assert.deepEqual(left.map((entry) => entry.id), ["home-a", "cloud-a", "team-a"]);
+ assert.deepEqual(saved.environments.map((entry) => entry.id), ["by-hand", "local-2"]);
+ assert.equal(saved.activeId, "local", "the window showed one of them: This computer");
+ assert.equal(withoutAccountPlaces({ ...places, activeId: "by-hand" }).saved.activeId, "by-hand");
+});
+
+test("a team's Cloud, which another account here may share, loses all it kept; a Cloud of one's own only its session", async () => {
+ const cleared = [];
+ await clearPlaceStorage({ clearStorageData: async (options) => { cleared.push(options); } }, places.environments.slice(0, 3));
+ assert.deepEqual(cleared.find((entry) => entry.origin === "https://home-a.test").storages, ["cookies"]);
+ assert.deepEqual(cleared.find((entry) => entry.origin === "https://second-a.test").storages, ["cookies"]);
+ assert.deepEqual(cleared.find((entry) => entry.origin === "https://shared-team.test").storages, ["cookies", "localstorage", "indexdb", "cachestorage", "serviceworkers"]);
+});
+
+test("leaving: the list changes, then the window leaves, and only then the sessions go, so its page can't sign in again", async () => {
+ const order = [];
+ const leave = createAccountLeave({ saved: () => places, persist: () => order.push("persist"), mine: () => null, leaveWindow: async () => order.push("window"),
+ session: () => ({ clearStorageData: async () => { order.push("clear"); } }) });
+ const left = await leave();
+ assert.equal(left.length, 3);
+ assert.deepEqual(order, ["persist", "window", "clear", "clear", "clear"]);
+});
diff --git a/electron/chrome-rail.mjs b/electron/chrome-rail.mjs
index bc328bcfec..2700a0e0cb 100644
--- a/electron/chrome-rail.mjs
+++ b/electron/chrome-rail.mjs
@@ -41,7 +41,7 @@ const ABORTED = -3;
* desktop keeps the person's choice to hide it; `changed()`: the rail came or went beside the page.
*/
export function createChromeRail({ createView, preload, args, url, wanted, prefs = () => null, changed = () => {}, log = () => {} }) {
- let view = null, win = null, shown = false, expanded = false;
+ let view = null, win = null, shown = false, expanded = false, held = false;
// Whether the page beside draws the frame; the window opens as if it does (windowChromeOptions).
let framed = true, frameGrace = null;
// The document beside the rail offered its button; a new one may still (`grace`); the page stopped responding.
@@ -112,7 +112,7 @@ export function createChromeRail({ createView, preload, args, url, wanted, prefs
/** The window the rail stands beside: its size moves the rail, and each of its documents gets the room again. */
attach(next) {
win = next;
- shown = false; expanded = false; offered = false; hung = false; told = "";
+ shown = false; expanded = false; held = false; offered = false; hung = false; told = "";
framed = prefs()?.windowFrame?.() !== false;
// The window's first document has the same time as any other to offer the button and to draw the frame.
if (choseHidden()) startGrace(); else stopGrace();
@@ -137,7 +137,7 @@ export function createChromeRail({ createView, preload, args, url, wanted, prefs
/** Shown while there are two places or more (railPlaces) and the person hasn't hidden it; the page beside it has the
* whole window otherwise. */
refresh() {
- const on = alive() && wanted() && !hidden();
+ const on = alive() && ((wanted() && !hidden()) || held);
if (on === shown) layout();
else {
shown = on;
@@ -153,6 +153,12 @@ export function createChromeRail({ createView, preload, args, url, wanted, prefs
}
tellState();
},
+ /** A sheet the rail's page shows for the page beside it (the person's accounts): the rail's page is up meanwhile, even
+ * for someone who hid the rail. */
+ holdOpen(on) {
+ held = on === true;
+ rail.refresh();
+ },
/** A sheet of the rail's is open: the view covers the window until it closes. */
expand(on) {
const was = expanded;
diff --git a/electron/chrome-rail.node-test.mjs b/electron/chrome-rail.node-test.mjs
index f568d3342f..0c7683f049 100644
--- a/electron/chrome-rail.node-test.mjs
+++ b/electron/chrome-rail.node-test.mjs
@@ -338,3 +338,20 @@ test("every page beside the rail, from any server, gets the button's bridge, lea
await local.bridge.rail.setHidden(false);
assert.deepEqual(plain(local.invoked), [["rail:hide", false]], "this app's own page, as for its other choices");
});
+
+test("the accounts sheet holds the rail's page up, even for someone who hid the rail or has one place, and letting go puts things back", () => {
+ const w = world({ wanted: false, hidden: true });
+ w.rail.attach(w.win);
+ assert.equal(w.rail.shown(), false);
+ w.rail.holdOpen(true);
+ assert.equal(w.rail.shown(), true);
+ w.rail.expand(true);
+ assert.equal(w.made[0].bounds.width, 1440, "the sheet has the whole window");
+ w.rail.expand(false);
+ w.rail.holdOpen(false);
+ assert.equal(w.rail.shown(), false);
+ w.state.hidden = false; w.state.wanted = true;
+ w.rail.refresh();
+ w.rail.holdOpen(true); w.rail.holdOpen(false);
+ assert.equal(w.rail.shown(), true, "a rail that was there stays");
+});
diff --git a/electron/cloud-account-ipc.node-test.mjs b/electron/cloud-account-ipc.node-test.mjs
index 32af05567e..31bcb7dc2e 100644
--- a/electron/cloud-account-ipc.node-test.mjs
+++ b/electron/cloud-account-ipc.node-test.mjs
@@ -35,6 +35,7 @@ test("production personal Cloud IPC guards exact local main frame and forwards n
rendererOrigin: () => origin, environmentsState: { environments: [], activeId: "local" },
ensureCloudAccount: () => Object.fromEntries(methods.map(method => [method, (...args) => { calls.push([method, ...args]); return { status: "signed-out" }; }])),
connectCloudHome: (...args) => { calls.push(["connectHome", ...args]); return { status: "connected" }; },
+ accounts: { signOutActive: (...args) => { calls.push(["signOut", ...args]); return { status: "signed-out" }; } },
});
vm.runInContext(source.slice(start, end), context);
for (const method of bridgeMethods) {
diff --git a/electron/cloud-account.d.mts b/electron/cloud-account.d.mts
index 5b22abb4e9..ffcfe742b0 100644
--- a/electron/cloud-account.d.mts
+++ b/electron/cloud-account.d.mts
@@ -172,6 +172,21 @@ export interface CloudAccountBridge {
onState(callback: (state: CloudAccountState) => void): () => void;
files?: import("./cloud-sync.mjs").CloudFilesBridge;
}
+/** Who is signed in on this device, as the You menu shows it. `signIn`: this account's sign-in has ended here. */
+export interface AccountRow { id: string; email: string; signIn?: true }
+export interface AccountsView { active: AccountRow | null; others: AccountRow[] }
+/** This app's own pages only: main refuses any other page. Absent on an older app. */
+export interface AccountsBridge {
+ list(): Promise<AccountsView>;
+ /** Removes that account from this device. */
+ signOut(id: string): Promise<AccountsView>;
+ sheetPending(): Promise<boolean>;
+ sheetClosed(): Promise<void>;
+ onChanged(callback: () => void): () => void;
+ onOpenSheet(callback: () => void): () => void;
+}
+/** Any place's own page, from the person's click: the accounts sheet opens on the rail's page, and this page learns nothing of them. */
+export interface AccountSheetBridge { offered(): Promise<boolean>; open(): Promise<void> }
/** On the person's own Cloud, open in this app's window: the plan, read
* only, Manage in the browser, and Sign in again. No account, credential or address. */
/** `signin`: this computer's sign-in ended; `tier` names the plan last verified, if any. */
diff --git a/electron/home-window.mjs b/electron/home-window.mjs
index 705201e279..64d3d3b3c5 100644
--- a/electron/home-window.mjs
+++ b/electron/home-window.mjs
@@ -640,6 +640,14 @@ export function createHomeWindow(deps) {
const moved = Boolean(next && (next.kind !== shown.kind || (next.origin ?? null) !== (shown.origin ?? null) || (next.id ?? null) !== (shown.id ?? null)));
if (moved || after.kind !== before.kind || after.origin !== before.origin || screen || status) await show();
},
+ /** The signed-in account is about to change: nothing under way for the one leaving goes on, and the next show() takes
+ * the window off whatever it shows of that account. */
+ accountLeaving() {
+ opens++;
+ clearRetry(); clearRenewal();
+ asked = null; naming = null; shown = null; opening = null; screen = null; status = null;
+ away = away || !shows(localOrigin());
+ },
/** A response the window got (Electron's webRequest): a 401 from the place's API means its session ended. */
responded({ url, statusCode, webContentsId }) {
const origin = placeOrigin(), win = window();
diff --git a/electron/home-window.node-test.mjs b/electron/home-window.node-test.mjs
index 786b03c5a7..93084e6929 100644
--- a/electron/home-window.node-test.mjs
+++ b/electron/home-window.node-test.mjs
@@ -846,3 +846,15 @@ test("another Cloud the Admin says is no longer theirs is dropped at once and My
assert.deepEqual(setup.home.view(), { screen: "setup", step: "starting", name: "Client A" });
assert.deepEqual(setup.ownPairs, [], "never paired while it is set up");
});
+
+test("an account leaving: nothing under way for it goes on, and the next show takes the window off its place", async () => {
+ const w = world({ journal: null, state: { status: "signed-out" }, url: `${CLOUD}/` });
+ w.home.accountLeaving();
+ assert.equal(w.home.shown(), null);
+ await w.home.show();
+ assert.deepEqual(w.local, [true], "the window showed that account's Cloud: this computer's page now");
+ const here = world({ journal: null, state: { status: "signed-out" }, url: `${LOCAL}/` });
+ here.home.accountLeaving();
+ await here.home.show();
+ assert.deepEqual(here.local, [false], "already on this computer's page: nothing moves");
+});
diff --git a/electron/main.mjs b/electron/main.mjs
index 962dc89b85..7c47b920ca 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -108,7 +108,7 @@ import { installOneHome } from "./one-home-main.mjs"; import { handSaved, instal
import { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";
import { createHomeWindow, installHomeWindowIpc } from "./home-window.mjs";
import { createTeamProfileSeeds } from "./team-profile-seed.mjs";
-import { createHomePlaces } from "./home-places.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { homeLook, otherOwnClouds, withoutOldCloudHome } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs";
+import { createHomePlaces } from "./home-places.mjs"; import { createAccountLeave, installAccounts } from "./accounts-main.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { homeLook, otherOwnClouds, withoutOldCloudHome } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs";
import { createWindowStateFile } from "./window-state-file.mjs";
import { createEnvironmentsFile } from "./environments-file.mjs";
import { createOrgLibrary } from "./org-library.mjs";
@@ -820,15 +820,12 @@ function syncPhoneSecretKey(proc) {
}
}
+const cloudEncryption = { available: async () => (await safeStorage.isAsyncEncryptionAvailable()) && (process.platform !== "linux" || safeStorage.getSelectedStorageBackend() !== "basic_text"), encrypt: value => safeStorage.encryptStringAsync(value), decrypt: value => safeStorage.decryptStringAsync(value) };
function ensureCloudAccount() {
if (cloudAccount) return cloudAccount;
if (!app.isPackaged || desktopRemoteAccess) throw new Error("MausBot Cloud sign-in requires the local desktop app.");
cloudAccount = createCloudAccountClient({
- store: createCloudAccountStore({ file: path.join(app.getPath("userData"), cloudTarget(process.env).file), encryption: {
- available: async () => (await safeStorage.isAsyncEncryptionAvailable()) &&
- (process.platform !== "linux" || safeStorage.getSelectedStorageBackend() !== "basic_text"),
- encrypt: value => safeStorage.encryptStringAsync(value), decrypt: value => safeStorage.decryptStringAsync(value),
- } }),
+ store: createCloudAccountStore({ file: path.join(app.getPath("userData"), cloudTarget(process.env).file), encryption: cloudEncryption }),
platform: process.platform, deviceName: os.hostname().slice(0, 100) || "My computer", appVersion: app.getVersion(), origin: cloudTarget(process.env).origin,
openBrowser: url => shell.openExternal(url), awaitingWake: () => cloudPower.awaiting(),
onState: state => {
@@ -836,7 +833,7 @@ function ensureCloudAccount() {
rememberedHome = rememberedCloudHome(rememberedHome, state);
sendUpdaterState();
cloudPower.changed(); computerSharing?.cloudChanged(); try { void oneHome.kick(); void homeWindow.changed(); announceAddedCloud(state); railChanged(); } catch {}
- void includedX.onState(state); void includedPages.onState(state); updatesConsent?.accountChanged(state);
+ void includedX.onState(state); void includedPages.onState(state); updatesConsent?.accountChanged(state); accounts.tell();
refreshCloudMenus();
announceCloudReady(state);
if (mainWindow && !mainWindow.isDestroyed() && mainWindow.webContents.mainFrame.url.startsWith(`${rendererOrigin()}/`) &&
@@ -2540,7 +2537,7 @@ const workspaceOnly = (handler) => (event, ...args) => {
const localWorkspaceOnly = (channel, handler) => localOnly(channel, workspaceOnly(handler));
// No renderer-supplied address, token, paid flag or callback can choose an account or activate Pro.
for (const method of ["state", "begin", "signInAgain", "reopen", "cancel", "refresh", "signOut", "openDashboard", "offer"]) {
- ipcMain.handle(`cloud-account:${method}`, localWorkspaceOnly(`cloud-account:${method}`, () => ensureCloudAccount()[method]()));
+ ipcMain.handle(`cloud-account:${method}`, localWorkspaceOnly(`cloud-account:${method}`, () => (method === "signOut" ? accounts.signOutActive() : ensureCloudAccount()[method]())));
}
ipcMain.handle("cloud-account:checkout", localWorkspaceOnly("cloud-account:checkout", async (_event, plan, source) => {
if (!(await cloudOffersReady())) throw new Error("MausBot Cloud isn't offered in this app.");
@@ -2690,6 +2687,8 @@ const chromeRail = createChromeRail({ createView: options => new WebContentsView
url: () => `${rendererOrigin()}${CHROME_RAIL_PATH}`, wanted: () => !desktopRemoteAccess && serverReady && railList().length > 0 });
chromeRail.install(ipcMain);
function railChanged() { chromeRail.refresh(); rail.changed(); }
+const accountPages = [() => (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents }) ? mainWindow.webContents : null), () => ({ send: channel => chromeRail.send(channel) })];
+const accounts = installAccounts({ ipcMain, ownPage: event => chromeRail.owns(event) || cloudPageAsking(event) === "local", placePage: event => cloudPageAsking(event) !== null || ownCloudPage(event) !== null || homeWindow.homePage(event) || (Boolean(ownHome?.home()) && activeEnvironment(environmentsState)?.origin === ownHome.home().origin && workspaceSenderAllowed(event, mainWindow?.webContents, environmentsState, rendererOrigin())), account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), client: ensureCloudAccount, holdSheet: open => chromeRail.holdOpen(open), tellSheet: () => chromeRail.send("accounts:open-sheet"), leaving: () => homeWindow.accountLeaving(), leave: createAccountLeave({ saved: () => environmentsState, persist: persistEnvironments, session: () => session.defaultSession, mine: () => myCloud(), leaveWindow: () => (mainWindow && !mainWindow.isDestroyed() && !senderIsLocal({ sender: mainWindow.webContents }) ? navigateMainWindow(rendererOrigin()) : null), log: slog }), show: () => showHome(), tell: () => { for (const page of accountPages) page()?.send("accounts:changed"); } });
const rail = installCloudRail({ ipcMain, clipboard, openCloud: openOwnCloud, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null),
guard: handler => (event, ...args) => (chromeRail.owns(event) ? handler(event, ...args) : workspaceOnly(handler)(event, ...args)),
lists: event => chromeRail.owns(event), trusted: event => chromeRail.owns(event) || senderIsLocal(event), beside: () => chromeRail.shown(),
diff --git a/electron/preload.cjs b/electron/preload.cjs
index 6a328b566f..c32ec6b923 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -64,7 +64,7 @@ function railKeepsItsSize() {
if (typeof window !== "undefined") {
for (const type of ["resize", "DOMContentLoaded"]) window.addEventListener(type, () => { leaveRailRoom(); railKeepsItsSize(); });
}
-const REMOTE_SAFE = new Set(["platform", "app", "getCapabilities", "onCapabilitiesChanged", "applySkin", "setUnreadCount", "permStatus", "workspaces", "rail", "cloudAdd", "cloudPlan", "cloudSendPage", "desktopNotices", "desktopAnalytics", "desktopLanguage", "updatesConsent", "windowControls", "onOpenAppSettings", "windowFrame"]);
+const REMOTE_SAFE = new Set(["platform", "app", "getCapabilities", "onCapabilitiesChanged", "applySkin", "setUnreadCount", "permStatus", "workspaces", "rail", "cloudAdd", "cloudPlan", "cloudSendPage", "accountSheet", "desktopNotices", "desktopAnalytics", "desktopLanguage", "updatesConsent", "windowControls", "onOpenAppSettings", "windowFrame"]);
/** My Cloud's own page once it is the person's home (main checks the sender again): it is this app's page then. */
const HOME_PAGE = ["home", "onChatLink", "onPackageInstall", "exportDiagnostics", "openLogsFolder", "openAtLogin", "callActive"];
function updaterOffered() {
@@ -497,6 +497,29 @@ const bridge = {
return () => ipcRenderer.removeListener("two-places:changed", handler);
},
},
+ // Who is signed in on this device: this app's own pages only (main checks the sender). No token ever comes through here.
+ accounts: process.argv.includes("--omb-company-desktop=1") ? {
+ list: () => ipcRenderer.invoke("accounts:list"),
+ signOut: id => ipcRenderer.invoke("accounts:sign-out", String(id)),
+ sheetPending: () => ipcRenderer.invoke("accounts:sheet-pending"),
+ sheetClosed: () => ipcRenderer.invoke("accounts:sheet-closed"),
+ onChanged: cb => {
+ const handler = () => cb();
+ ipcRenderer.on("accounts:changed", handler);
+ return () => ipcRenderer.removeListener("accounts:changed", handler);
+ },
+ onOpenSheet: cb => {
+ const handler = () => cb();
+ ipcRenderer.on("accounts:open-sheet", handler);
+ return () => ipcRenderer.removeListener("accounts:open-sheet", handler);
+ },
+ } : undefined,
+ // Any place's page: opens the accounts sheet on the rail's page, from the person's click. The page learns nothing of them.
+ accountSheet: process.argv.includes("--omb-company-desktop=1") ? {
+ offered: () => ipcRenderer.invoke("accounts:offered"),
+ open: () => isLocalPage || navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("accounts:open") : Promise.reject(new Error("Choose your account to open it.")),
+ } : undefined,
cloudPlan: process.argv.includes("--omb-company-desktop=1") ? {
state: () => ipcRenderer.invoke("cloud-plan:state"),
manage: () => isLocalPage || navigator.userActivation?.isActive === true
diff --git a/src/components/AccountMenu.test.ts b/src/components/AccountMenu.test.ts
new file mode 100644
index 0000000000..073b6b1bb4
--- /dev/null
+++ b/src/components/AccountMenu.test.ts
@@ -0,0 +1,26 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { accountMenuItems } from "./AccountMenu";
+
+afterEach(() => vi.unstubAllGlobals());
+const signOut = vi.fn();
+
+it("one account: its address, then Sign out", () => {
+ const items = accountMenuItems({ view: { active: { id: "a", email: "[email protected]" }, others: [] }, openSheet: null, signOut });
+ expect(items.map((item) => item.label)).toEqual(["[email protected]", "Sign out"]);
+ items[1].onSelect();
+ expect(signOut).toHaveBeenCalledWith("a");
+});
+
+it("signed out, or a page that isn't offered the sheet: no rows", () => {
+ expect(accountMenuItems({ view: { active: null, others: [] }, openSheet: null, signOut })).toEqual([]);
+ expect(accountMenuItems({ view: null, openSheet: null, signOut })).toEqual([]);
+});
+
+it("another place's page shows no address, only the row that asks main for the sheet", () => {
+ const openSheet = vi.fn();
+ const items = accountMenuItems({ view: null, openSheet, signOut });
+ expect(items.map((item) => item.label)).toEqual(["Account and sign out"]);
+ expect(JSON.stringify(items)).not.toContain("@");
+ items[0].onSelect();
+ expect(openSheet).toHaveBeenCalled();
+});
diff --git a/src/components/AccountMenu.tsx b/src/components/AccountMenu.tsx
new file mode 100644
index 0000000000..b126a82dfd
--- /dev/null
+++ b/src/components/AccountMenu.tsx
@@ -0,0 +1,98 @@
+import { useEffect, useState } from "react";
+import { Check, LogOut, UserRound, X } from "lucide-react";
+import type { AccountsView } from "../../electron/cloud-account.mjs";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import { CLOSE, Heading, PRIMARY, SCREEN, SHEET } from "./cloud-buy/parts";
+import type { SidebarMenuItem } from "./SidebarPopoverMenu";
+
+export interface AccountsAccess {
+ /** This app's own page: the list itself. Any other page has none. */
+ view: AccountsView | null;
+ /** Another page: main opens the sheet on the rail's page for it. */
+ openSheet: (() => void) | null;
+ signOut(id: string): void;
+}
+
+/** Who is signed in on this device, on this app's own page; on any other page, only whether main offers the sheet. */
+export function useAccounts(): AccountsAccess {
+ const bridge = window.ogb?.remoteClient?.active ? undefined : window.ogb?.accounts;
+ const sheet = window.ogb?.accountSheet;
+ const own = window.ogb?.app?.ownPage === true && Boolean(bridge);
+ const [view, setView] = useState<AccountsView | null>(null);
+ const [offered, setOffered] = useState(false);
+ useEffect(() => {
+ if (!own) return;
+ const read = () => { void bridge!.list().then(setView).catch(() => {}); };
+ read();
+ return bridge!.onChanged(read);
+ }, [own, bridge]);
+ useEffect(() => {
+ if (own || !sheet) return;
+ let alive = true;
+ void sheet.offered().then((yes) => { if (alive) setOffered(yes === true); }).catch(() => {});
+ return () => { alive = false; };
+ }, [own, sheet]);
+ return {
+ view: own ? view : null,
+ openSheet: !own && offered && sheet ? () => { void sheet.open().catch(() => {}); } : null,
+ signOut: (id) => { void bridge?.signOut(id).then(setView).catch(() => {}); },
+ };
+}
+
+/** The You menu's last rows. On another page, one row that opens the sheet. Signed out: nothing, as Settings has the sign-in. */
+export function accountMenuItems({ view, openSheet, signOut }: AccountsAccess): SidebarMenuItem[] {
+ if (openSheet) return [{ key: "accounts-sheet", label: t("accounts.manage"), icon: <UserRound size={18} />, onSelect: openSheet }];
+ const active = view?.active;
+ if (!active) return [];
+ return [
+ { key: "accounts-active", heading: t("accounts.heading"), label: active.email, title: active.email, icon: <Check size={18} />, disabled: true, onSelect: () => {} },
+ { key: "accounts-sign-out", label: t("accounts.signOut"), icon: <LogOut size={18} />, onSelect: () => signOut(active.id) },
+ ];
+}
+
+/** Over any place's page, on the rail's own page: who is signed in here and Sign out. */
+export function AccountsSheet({ onClose }: { onClose: () => void }) {
+ const bridge = window.ogb?.accounts;
+ const [view, setView] = useState<AccountsView | null>(null);
+ const [failed, setFailed] = useState(false);
+ useEffect(() => {
+ if (!bridge) return;
+ const read = () => { void bridge.list().then(setView).catch(() => setFailed(true)); };
+ read();
+ return bridge.onChanged(read);
+ }, [bridge]);
+ const active = view?.active ?? null;
+ const signOut = (id: string) => {
+ setFailed(false);
+ void bridge?.signOut(id).then((next) => { setView(next); if (!next.active) onClose(); }, () => setFailed(true));
+ };
+ return <div className="ui-scrim fixed inset-0 z-[60] flex items-center justify-center p-4" onMouseDown={(event) => event.target === event.currentTarget && onClose()}>
+ <div role="dialog" aria-modal="true" aria-labelledby="cloud-add-title" data-accounts-sheet className={cn(SHEET, "relative w-full max-w-[420px]")}>
+ <button type="button" onClick={onClose} aria-label={t("accounts.close")} className={cn(CLOSE, "absolute end-4 top-4 z-10")}><X size={16} /></button>
+ <div className={SCREEN}>
+ <Heading title={t("accounts.title")} />
+ {active && <p data-accounts-active className="truncate text-[14px] text-ink" title={active.email}>{t("accounts.heading")} {active.email}</p>}
+ {active && <button type="button" data-accounts-sign-out className={PRIMARY} onClick={() => signOut(active.id)}>{t("accounts.signOut")}</button>}
+ {failed && <p role="alert" className="text-[13px] text-danger">{t("accounts.failed")}</p>}
+ </div>
+ </div>
+ </div>;
+}
+
+/** The sheet as the rail's page keeps it: asked for by main, from the person's click on the page beside the rail. */
+export function useAccountsSheet(): { open: boolean; close: () => void } {
+ const bridge = window.ogb?.accounts;
+ const [open, setOpen] = useState(false);
+ useEffect(() => {
+ if (!bridge) return;
+ void bridge.sheetPending().then((pending) => { if (pending) setOpen(true); }).catch(() => {});
+ return bridge.onOpenSheet(() => setOpen(true));
+ }, [bridge]);
+ useEffect(() => { if (open) void window.ogb?.rail?.expand?.(true)?.catch(() => {}); }, [open]);
+ return { open, close: () => {
+ setOpen(false);
+ void window.ogb?.rail?.expand?.(false)?.catch(() => {});
+ void bridge?.sheetClosed().catch(() => {});
+ } };
+}
diff --git a/src/components/ChromeRail.tsx b/src/components/ChromeRail.tsx
index 9374e87b76..2d89d5f54d 100644
--- a/src/components/ChromeRail.tsx
+++ b/src/components/ChromeRail.tsx
@@ -1,6 +1,7 @@
import { useEffect } from "react";
import { effectiveLanguage, useLanguageChoice, usePageLanguage } from "@/lib/language-preference";
import { wearSkin } from "@/lib/skins";
+import { AccountsSheet, useAccountsSheet } from "./AccountMenu";
import { DesktopCapabilitiesProvider } from "./DesktopCapabilities";
import { PlacesRail } from "./PlacesRail";
@@ -11,5 +12,6 @@ export function ChromeRail() {
usePageLanguage(effectiveLanguage(useLanguageChoice(), undefined));
// The page beside the rail chose its skin: the rail wears the same one.
useEffect(() => window.ogb?.rail?.onSkin?.(wearSkin), []);
- return <DesktopCapabilitiesProvider><div data-chrome-rail className="h-full"><PlacesRail chrome /></div></DesktopCapabilitiesProvider>;
+ const accounts = useAccountsSheet();
+ return <DesktopCapabilitiesProvider><div data-chrome-rail className="h-full"><PlacesRail chrome /></div>{accounts.open && <AccountsSheet onClose={accounts.close} />}</DesktopCapabilitiesProvider>;
}
diff --git a/src/components/SidebarProfileMenu.tsx b/src/components/SidebarProfileMenu.tsx
index 5ec8dcccfc..9b6622abc3 100644
--- a/src/components/SidebarProfileMenu.tsx
+++ b/src/components/SidebarProfileMenu.tsx
@@ -23,6 +23,7 @@ import {
Zap,
} from "lucide-react";
+import { accountMenuItems, useAccounts } from "./AccountMenu";
import { AccountMoveStatus, useAccountMove, type AccountMoveKind } from "./AccountMove";
import { InitialsAvatar } from "./Avatar";
import { DiscordIcon } from "./DiscordIcon";
@@ -456,6 +457,7 @@ export function profileMenuItems({
updateTop = null,
move = [],
account,
+ accounts = [],
simple,
onUsage,
onSettings,
@@ -473,6 +475,8 @@ export function profileMenuItems({
/** the move to My Cloud's own rows, first of all (AccountMove) */
move?: SidebarMenuItem[];
account: string | null;
+ /** who is signed in on this device: the last rows, next to where the menu opens */
+ accounts?: SidebarMenuItem[];
simple?: { tools: SidebarMenuItem[]; places: SidebarMenuItem[] };
onUsage: () => void;
onSettings: () => void;
@@ -508,7 +512,7 @@ export function profileMenuItems({
const accountItem: SidebarMenuItem | null = account ? { key: "account", label: account, icon: <CircleUserRound size={18} />, onSelect: onAccount } : null;
const present = (...items: Array<SidebarMenuItem | null | false>) => items.filter((item): item is SidebarMenuItem => Boolean(item));
if (!simple) {
- const rest = [...present(usageItem), ...phone, support, settings, ...present(update), ...(accountItem ? [{ ...accountItem, separatorBefore: true }] : [])];
+ const rest = [...present(usageItem), ...phone, support, settings, ...present(update), ...(accountItem ? [{ ...accountItem, separatorBefore: true }] : []), ...accounts.map((item, index) => (index === 0 ? { ...item, separatorBefore: true } : item))];
return [...move, ...rest.map((item, index) => (move.length && index === 0 ? { ...item, separatorBefore: true } : item))];
}
const raised: SidebarMenuItem | null = update && updateTop ? {
@@ -524,6 +528,7 @@ export function profileMenuItems({
[...present(usageItem), ...phone, { ...support, submenu: raised ? help : [...help, ...present(update)] }, settings],
simple.tools,
[...simple.places, ...present(accountItem)],
+ accounts,
].filter((group) => group.length > 0);
return groups.flatMap((group, at) => group.map((item, index) => (at > 0 && index === 0 ? { ...item, separatorBefore: true } : item)));
}
@@ -582,6 +587,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
const cloudAccount = !remote && Boolean(window.ogb?.cloudAccount || (window.ogb?.cloudPlan && state.config?.cloudHome === true));
const openCloudAccount = () => dispatch({ type: "toggleAppSettings", open: true, section: "cloudAccount" });
const move = useAccountMove(state.config?.cloudHome === true, { onOpen: openCloudAccount, onPairPhone: () => dispatch(phonePairingSettingsAction()) });
+ const accounts = useAccounts();
const items = profileMenuItems({
phone: simple
@@ -598,6 +604,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
updateTop: simple ? simpleUpdateTop(update) : null,
move: move.items,
account: cloudAccount ? t("settings.section.cloudAccount") : null,
+ accounts: accountMenuItems(accounts),
...(account ? { simple: {
tools: toolMenuItems({
activeView: state.activeView,
diff --git a/src/locales/en.json b/src/locales/en.json
index f7dc6421cb..82b4bb89bf 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -2179,6 +2179,13 @@
"phoneApp.android": "Android",
"phoneApp.androidAction": "Download the APK",
"phoneApp.next": "Installed? Connect your phone next, and scan the pairing code with the app.",
+ "accounts.heading": "Signed in as",
+ "accounts.signOut": "Sign out",
+ "accounts.signInAgain": "Sign in again",
+ "accounts.manage": "Account and sign out",
+ "accounts.title": "Your account",
+ "accounts.close": "Close",
+ "accounts.failed": "That didn't work. Try again in a moment.",
"sidebar.menu.settings": "Settings",
"sidebar.menu.about": "About",
"about.version": "Version {version}",
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index f8bf402e0c..df2fd31d88 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -122,6 +122,8 @@ const __APP_VERSION__: string;
app?: { version: string; ownPage: boolean };
organization?: import("../../electron/managed-desktop.mjs").ManagedDesktopBridge;
cloudAccount?: import("../../electron/cloud-account.mjs").CloudAccountBridge;
+ accounts?: import("../../electron/cloud-account.mjs").AccountsBridge;
+ accountSheet?: import("../../electron/cloud-account.mjs").AccountSheetBridge;
/** Either page in this app: the one-time move's line (on its way, what arrived, coming home). */
cloudSendPage?: import("../../electron/cloud-send.mjs").CloudSendPageBridge;
/** This computer's page only: bots in two places, and the one tap that brings them together on one (electron/two-places.mjs). */