Skip to content

Commit 3cbc999

Browse files
authored
Merge pull request element-hq#13028 from vector-im/t3chguy/poc_riot_desktop_sso_multi_profile
Fix Electron SSO handling to support multiple profiles
2 parents 24dbbfa + a77ed6e commit 3cbc999

3 files changed

Lines changed: 92 additions & 28 deletions

File tree

‎electron_app/src/electron-main.js‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ const tray = require('./tray');
3535
const vectorMenu = require('./vectormenu');
3636
const webContentsHandler = require('./webcontents-handler');
3737
const updater = require('./updater');
38-
const protocolInit = require('./protocol');
38+
const {getProfileFromDeeplink, protocolInit, recordSSOSession} = require('./protocol');
3939

4040
const windowStateKeeper = require('electron-window-state');
4141
const Store = require('electron-store');
@@ -68,7 +68,11 @@ if (argv["help"]) {
6868
app.exit();
6969
}
7070

71-
if (argv['profile-dir']) {
71+
// check if we are passed a profile in the SSO callback url
72+
const userDataPathInProtocol = getProfileFromDeeplink(argv["_"]);
73+
if (userDataPathInProtocol) {
74+
app.setPath('userData', userDataPathInProtocol);
75+
} else if (argv['profile-dir']) {
7276
app.setPath('userData', argv['profile-dir']);
7377
} else if (argv['profile']) {
7478
app.setPath('userData', `${app.getPath('userData')}-${argv['profile']}`);
@@ -243,6 +247,9 @@ ipcMain.on('ipcCall', async function(ev, payload) {
243247
mainWindow.webContents.goForward();
244248
}
245249
break;
250+
case 'startSSOFlow':
251+
recordSSOSession(args[0]);
252+
break;
246253

247254
default:
248255
mainWindow.webContents.send('ipcReply', {

‎electron_app/src/protocol.js‎

Lines changed: 77 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -14,40 +14,91 @@ See the License for the specific language governing permissions and
1414
limitations under the License.
1515
*/
1616

17-
const {app} = require('electron');
17+
const {app} = require("electron");
18+
const path = require("path");
19+
const fs = require("fs");
20+
21+
const PROTOCOL = "riot://";
22+
const SEARCH_PARAM = "riot-desktop-ssoid";
23+
const STORE_FILE_NAME = "sso-sessions.json";
24+
25+
// we getPath userData before electron-main changes it, so this is the default value
26+
const storePath = path.join(app.getPath("userData"), STORE_FILE_NAME);
1827

1928
const processUrl = (url) => {
2029
if (!global.mainWindow) return;
2130
console.log("Handling link: ", url);
22-
global.mainWindow.loadURL(url.replace("riot://", "vector://"));
31+
global.mainWindow.loadURL(url.replace(PROTOCOL, "vector://"));
2332
};
2433

25-
module.exports = () => {
26-
// get all args except `hidden` as it'd mean the app would not get focused
27-
// XXX: passing args to protocol handlers only works on Windows,
28-
// so unpackaged deep-linking and --profile passing won't work on Mac/Linux
29-
const args = process.argv.slice(1).filter(arg => arg !== "--hidden" && arg !== "-hidden");
30-
if (app.isPackaged) {
31-
app.setAsDefaultProtocolClient('riot', process.execPath, args);
32-
} else if (process.platform === 'win32') { // on Mac/Linux this would just cause the electron binary to open
33-
// special handler for running without being packaged, e.g `electron .` by passing our app path to electron
34-
app.setAsDefaultProtocolClient('riot', process.execPath, [app.getAppPath(), ...args]);
34+
const readStore = () => {
35+
try {
36+
const s = fs.readFileSync(storePath, { encoding: "utf8" });
37+
const o = JSON.parse(s);
38+
return typeof o === "object" ? o : {};
39+
} catch (e) {
40+
return {};
3541
}
42+
};
3643

37-
if (process.platform === 'darwin') {
38-
// Protocol handler for macos
39-
app.on('open-url', function(ev, url) {
40-
ev.preventDefault();
41-
processUrl(url);
42-
});
43-
} else {
44-
// Protocol handler for win32/Linux
45-
app.on('second-instance', (ev, commandLine) => {
46-
const url = commandLine[commandLine.length - 1];
47-
if (!url.startsWith("riot://")) return;
48-
processUrl(url);
49-
});
50-
}
44+
const writeStore = (data) => {
45+
fs.writeFileSync(storePath, JSON.stringify(data));
46+
};
47+
48+
module.exports = {
49+
recordSSOSession: (sessionID) => {
50+
const userDataPath = app.getPath('userData');
51+
const store = readStore();
52+
for (const key in store) {
53+
// ensure each instance only has one (the latest) session ID to prevent the file growing unbounded
54+
if (store[key] === userDataPath) {
55+
delete store[key];
56+
break;
57+
}
58+
}
59+
store[sessionID] = userDataPath;
60+
writeStore(store);
61+
},
62+
getProfileFromDeeplink: (args) => {
63+
// check if we are passed a profile in the SSO callback url
64+
const deeplinkUrl = args.find(arg => arg.startsWith('riot://'));
65+
if (deeplinkUrl && deeplinkUrl.includes(SEARCH_PARAM)) {
66+
const parsedUrl = new URL(deeplinkUrl);
67+
if (parsedUrl.protocol === 'riot:') {
68+
const ssoID = parsedUrl.searchParams.get(SEARCH_PARAM);
69+
const store = readStore();
70+
console.log("Forwarding to profile: ", store[ssoID]);
71+
return store[ssoID];
72+
}
73+
}
74+
},
75+
protocolInit: () => {
76+
// get all args except `hidden` as it'd mean the app would not get focused
77+
// XXX: passing args to protocol handlers only works on Windows, so unpackaged deep-linking
78+
// --profile/--profile-dir are passed via the SEARCH_PARAM var in the callback url
79+
const args = process.argv.slice(1).filter(arg => arg !== "--hidden" && arg !== "-hidden");
80+
if (app.isPackaged) {
81+
app.setAsDefaultProtocolClient('riot', process.execPath, args);
82+
} else if (process.platform === 'win32') { // on Mac/Linux this would just cause the electron binary to open
83+
// special handler for running without being packaged, e.g `electron .` by passing our app path to electron
84+
app.setAsDefaultProtocolClient('riot', process.execPath, [app.getAppPath(), ...args]);
85+
}
86+
87+
if (process.platform === 'darwin') {
88+
// Protocol handler for macos
89+
app.on('open-url', function(ev, url) {
90+
ev.preventDefault();
91+
processUrl(url);
92+
});
93+
} else {
94+
// Protocol handler for win32/Linux
95+
app.on('second-instance', (ev, commandLine) => {
96+
const url = commandLine[commandLine.length - 1];
97+
if (!url.startsWith(PROTOCOL)) return;
98+
processUrl(url);
99+
});
100+
}
101+
},
51102
};
52103

53104

‎src/vector/platform/ElectronPlatform.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import Spinner from "matrix-react-sdk/src/components/views/elements/Spinner";
3232
import {Categories, Modifiers, registerShortcut} from "matrix-react-sdk/src/accessibility/KeyboardShortcuts";
3333
import {Key} from "matrix-react-sdk/src/Keyboard";
3434
import React from "react";
35+
import {randomString} from "matrix-js-sdk/src/randomstring";
3536

3637
const ipcRenderer = window.ipcRenderer;
3738
const isMac = navigator.platform.toUpperCase().includes('MAC');
@@ -250,6 +251,10 @@ export default class ElectronPlatform extends VectorBasePlatform {
250251
description: _td("Previous/next recently visited room or community"),
251252
});
252253
}
254+
255+
// this is the opaque token we pass to the HS which when we get it in our callback we can resolve to a profile
256+
this.ssoID = randomString(32);
257+
this._ipcCall("startSSOFlow", this.ssoID);
253258
}
254259

255260
async getConfig(): Promise<{}> {
@@ -446,6 +451,7 @@ export default class ElectronPlatform extends VectorBasePlatform {
446451
getSSOCallbackUrl(hsUrl: string, isUrl: string): URL {
447452
const url = super.getSSOCallbackUrl(hsUrl, isUrl);
448453
url.protocol = "riot";
454+
url.searchParams.set("riot-desktop-ssoid", this.ssoID);
449455
return url;
450456
}
451457

0 commit comments

Comments
 (0)