Skip to content

Commit 751a1dc

Browse files
committed
Add tool to migrate logins between origins
App checks at startup for an existing session, if there isn't one, it will start the tool to check for a login in the file:// origin. If there is one, it will copy the login over to the vector://vector origin. In principle this could also be used to migrate logins between other origins on the web if this were ever required. This includes a minified copy of the browserified js-sdk with a getAllEndToEndSessions() function added to the crypto store (matrix-org/matrix-js-sdk#812). This is not great, but for a short-lived tool this seems better than introducing more entry points into webpack only used for the electron app.
1 parent b6d70f4 commit 751a1dc

11 files changed

Lines changed: 486 additions & 10 deletions

File tree

‎electron_app/src/electron-main.js‎

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ const tray = require('./tray');
3232
const vectorMenu = require('./vectormenu');
3333
const webContentsHandler = require('./webcontents-handler');
3434
const updater = require('./updater');
35+
const { migrateFromOldOrigin } = require('./originMigrator');
3536

3637
const windowStateKeeper = require('electron-window-state');
3738

@@ -110,7 +111,7 @@ autoUpdater.on('update-downloaded', (ev, releaseNotes, releaseName, releaseDate,
110111
});
111112
});
112113

113-
ipcMain.on('ipcCall', function(ev, payload) {
114+
ipcMain.on('ipcCall', async function(ev, payload) {
114115
if (!mainWindow) return;
115116

116117
const args = payload.args || [];
@@ -141,10 +142,13 @@ ipcMain.on('ipcCall', function(ev, payload) {
141142
} else {
142143
mainWindow.focus();
143144
}
145+
case 'origin_migrate':
146+
await migrateFromOldOrigin();
147+
break;
144148
default:
145149
mainWindow.webContents.send('ipcReply', {
146150
id: payload.id,
147-
error: new Error("Unknown IPC Call: "+payload.name),
151+
error: "Unknown IPC Call: " + payload.name,
148152
});
149153
return;
150154
}
@@ -210,19 +214,42 @@ app.on('ready', () => {
210214
}
211215

212216
const target = parsedUrl.pathname.split('/');
217+
218+
// path starts with a '/'
219+
if (target[0] !== '') {
220+
callback({error: -6}); // FILE_NOT_FOUND
221+
return;
222+
}
223+
213224
if (target[target.length - 1] == '') {
214225
target[target.length - 1] = 'index.html';
215226
}
216227

228+
let baseDir;
229+
// first part of the path determines where we serve from
230+
if (target[1] === 'origin_migrator_dest') {
231+
// the origin migrator destination page
232+
// (only the destination script needs to come from the
233+
// custom protocol: the source part is loaded from a
234+
// file:// as that's the origin we're migrating from).
235+
baseDir = __dirname + "/../../origin_migrator/dest";
236+
} else if (target[1] === 'webapp') {
237+
baseDir = __dirname + "/../../webapp";
238+
} else {
239+
callback({error: -6}); // FILE_NOT_FOUND
240+
return;
241+
}
242+
217243
// Normalise the base dir and the target path separately, then make sure
218244
// the target path isn't trying to back out beyond its root
219-
const appBaseDir = path.normalize(__dirname + "/../../webapp");
220-
const relTarget = path.normalize(path.join(...target));
245+
baseDir = path.normalize(baseDir);
246+
247+
const relTarget = path.normalize(path.join(...target.slice(2)));
221248
if (relTarget.startsWith('..')) {
222249
callback({error: -6}); // FILE_NOT_FOUND
223250
return;
224251
}
225-
const absTarget = path.join(appBaseDir, relTarget);
252+
const absTarget = path.join(baseDir, relTarget);
226253

227254
callback({
228255
path: absTarget,
@@ -231,8 +258,6 @@ app.on('ready', () => {
231258
if (error) console.error('Failed to register protocol')
232259
});
233260

234-
235-
236261
if (vectorConfig['update_base_url']) {
237262
console.log(`Starting auto update with base URL: ${vectorConfig['update_base_url']}`);
238263
updater.start(vectorConfig['update_base_url']);
@@ -271,7 +296,7 @@ app.on('ready', () => {
271296
webgl: false,
272297
},
273298
});
274-
mainWindow.loadURL('vector://vector/');
299+
mainWindow.loadURL('vector://vector/webapp/');
275300
Menu.setApplicationMenu(vectorMenu);
276301

277302
// explicitly hide because setApplicationMenu on Linux otherwise shows...

‎electron_app/src/originMigrator.js‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
Copyright 2018 New Vector Ltd
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
const { BrowserWindow, ipcMain } = require('electron');
18+
const path = require('path');
19+
20+
async function migrateFromOldOrigin() {
21+
console.log("Attempting to migrate data between origins");
22+
23+
// We can use the same preload script: we just need ipcRenderer exposed
24+
const preloadScript = path.normalize(`${__dirname}/preload.js`);
25+
await new Promise(resolve => {
26+
const migrateWindow = new BrowserWindow({
27+
show: false,
28+
webPreferences: {
29+
preload: preloadScript,
30+
nodeIntegration: false,
31+
sandbox: true,
32+
enableRemoteModule: false,
33+
webgl: false,
34+
},
35+
});
36+
ipcMain.on('origin_migration_complete', (e, success, sentSummary, storedSummary) => {
37+
if (success) {
38+
console.log("Origin migration completed successfully!");
39+
} else {
40+
console.error("Origin migration failed!");
41+
}
42+
console.error("Data sent", sentSummary);
43+
console.error("Data stored", storedSummary);
44+
migrateWindow.close();
45+
resolve();
46+
});
47+
ipcMain.on('origin_migration_nodata', (e) => {
48+
console.log("No session to migrate from old origin");
49+
migrateWindow.close();
50+
resolve();
51+
});
52+
// Normalise the path because in the distribution, __dirname will be inside the
53+
// electron asar.
54+
const sourcePagePath = path.normalize(__dirname + '/../../origin_migrator/source.html');
55+
console.log("Loading path: " + sourcePagePath);
56+
migrateWindow.loadURL('file://' + sourcePagePath);
57+
});
58+
}
59+
60+
module.exports = {
61+
migrateFromOldOrigin,
62+
};

‎origin_migrator/dest/browser-matrix.min.js‎

Lines changed: 19 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎origin_migrator/dest/dest.html‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<html>
2+
<body>
3+
<script src="browser-matrix.min.js"></script>
4+
<script src="dest.js"></script>
5+
</body>
6+
</html>

‎origin_migrator/dest/dest.js‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
/*
2+
Copyright 2018 New Vector Ltd
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
const SOURCE_ORIGIN = 'file://';
18+
19+
const IndexedDBCryptoStore = window.matrixcs.IndexedDBCryptoStore;
20+
const cryptoStore = new IndexedDBCryptoStore(window.indexedDB, 'matrix-js-sdk:crypto');
21+
22+
let accountStored = 0;
23+
let sessionsStored = 0;
24+
let inboundGroupSessionsStored = 0;
25+
let deviceDataStored = 0;
26+
let roomsStored = 0;
27+
let localStorageKeysStored = 0;
28+
29+
const promises = [];
30+
31+
async function onMessage(e) {
32+
if (e.origin !== SOURCE_ORIGIN) return;
33+
34+
const data = e.data.data; // bleh, naming clash
35+
switch (e.data.cmd) {
36+
case 'init':
37+
// start with clean stores before we migrate data in
38+
window.localStorage.clear();
39+
await cryptoStore.deleteAllData();
40+
41+
e.source.postMessage({
42+
cmd: 'initOK',
43+
}, SOURCE_ORIGIN);
44+
break;
45+
case 'storeAccount':
46+
promises.push(cryptoStore.doTxn(
47+
'readwrite', [IndexedDBCryptoStore.STORE_ACCOUNT],
48+
(txn) => {
49+
cryptoStore.storeAccount(txn, data);
50+
},
51+
).then(() => {
52+
++accountStored;
53+
}));
54+
break;
55+
case 'storeSessions':
56+
promises.push(cryptoStore.doTxn(
57+
'readwrite', [IndexedDBCryptoStore.STORE_SESSIONS],
58+
(txn) => {
59+
for (const sess of data) {
60+
cryptoStore.storeEndToEndSession(sess.deviceKey, sess.sessionId, sess, txn);
61+
}
62+
},
63+
).then(() => {
64+
sessionsStored += data.length;
65+
}));
66+
break;
67+
case 'storeInboundGroupSessions':
68+
promises.push(cryptoStore.doTxn(
69+
'readwrite', [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS],
70+
(txn) => {
71+
for (const sess of data) {
72+
cryptoStore.addEndToEndInboundGroupSession(
73+
sess.senderKey, sess.sessionId, sess.sessionData, txn,
74+
);
75+
}
76+
},
77+
).then(() => {
78+
inboundGroupSessionsStored += data.length;
79+
}));
80+
break;
81+
case 'storeDeviceData':
82+
promises.push(cryptoStore.doTxn(
83+
'readwrite', [IndexedDBCryptoStore.STORE_DEVICE_DATA],
84+
(txn) => {
85+
cryptoStore.storeEndToEndDeviceData(data, txn);
86+
},
87+
).then(() => {
88+
++deviceDataStored;
89+
}));
90+
break;
91+
case 'storeRooms':
92+
promises.push(cryptoStore.doTxn(
93+
'readwrite', [IndexedDBCryptoStore.STORE_ROOMS],
94+
(txn) => {
95+
for (const [roomId, roomInfo] of Object.entries(data)) {
96+
cryptoStore.storeEndToEndRoom(roomId, roomInfo, txn);
97+
}
98+
},
99+
).then(() => {
100+
++roomsStored;
101+
}));
102+
break;
103+
case 'storeLocalStorage':
104+
window.localStorage.setItem(data.key, data.val);
105+
++localStorageKeysStored;
106+
break;
107+
case 'getSummary':
108+
await Promise.all(promises);
109+
e.source.postMessage({
110+
cmd: 'summary',
111+
data: {
112+
accountStored,
113+
sessionsStored,
114+
inboundGroupSessionsStored,
115+
deviceDataStored,
116+
roomsStored,
117+
localStorageKeysStored,
118+
},
119+
}, SOURCE_ORIGIN);
120+
break;
121+
}
122+
}
123+
124+
window.addEventListener('message', onMessage);
125+

‎origin_migrator/source.html‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<html>
2+
<body>
3+
<script src="dest/browser-matrix.min.js"></script>
4+
<script src="source.js"></script>
5+
<iframe name="dest" src="vector://vector/origin_migrator_dest/dest.html" onload="doMigrate()"></iframe>
6+
</body>
7+
</html>

0 commit comments

Comments
 (0)