2020-09-17 18:46:01 +05:30
|
|
|
/*
|
|
|
|
Copyright 2020 The Matrix.org Foundation C.I.C.
|
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
limitations under the License.
|
|
|
|
*/
|
|
|
|
|
|
|
|
import {KeyDescription, Key} from "./common.js";
|
|
|
|
import {keyFromPassphrase} from "./passphrase.js";
|
|
|
|
import {keyFromRecoveryKey} from "./recoveryKey.js";
|
|
|
|
|
|
|
|
async function readDefaultKeyDescription(storage) {
|
2020-09-25 20:12:41 +05:30
|
|
|
const txn = storage.readTxn([
|
2020-09-17 18:46:01 +05:30
|
|
|
storage.storeNames.accountData
|
|
|
|
]);
|
|
|
|
const defaultKeyEvent = await txn.accountData.get("m.secret_storage.default_key");
|
|
|
|
const id = defaultKeyEvent?.content?.key;
|
|
|
|
if (!id) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const keyAccountData = await txn.accountData.get(`m.secret_storage.key.${id}`);
|
|
|
|
if (!keyAccountData) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
return new KeyDescription(id, keyAccountData);
|
|
|
|
}
|
|
|
|
|
2020-09-17 19:28:46 +05:30
|
|
|
export async function writeKey(key, txn) {
|
|
|
|
txn.session.set("ssssKey", {id: key.id, binaryKey: key.binaryKey});
|
2020-09-17 18:46:01 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
export async function readKey(txn) {
|
|
|
|
const keyData = await txn.session.get("ssssKey");
|
|
|
|
if (!keyData) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const keyAccountData = await txn.accountData.get(`m.secret_storage.key.${keyData.id}`);
|
|
|
|
return new Key(new KeyDescription(keyData.id, keyAccountData), keyData.binaryKey);
|
|
|
|
}
|
|
|
|
|
2021-02-11 21:59:48 +05:30
|
|
|
export async function keyFromCredential(type, credential, storage, platform, olm) {
|
2020-09-17 18:46:01 +05:30
|
|
|
const keyDescription = await readDefaultKeyDescription(storage);
|
|
|
|
if (!keyDescription) {
|
2020-09-18 15:42:52 +05:30
|
|
|
throw new Error("Could not find a default secret storage key in account data");
|
2020-09-17 18:46:01 +05:30
|
|
|
}
|
|
|
|
let key;
|
2020-10-19 21:59:13 +05:30
|
|
|
if (type === "phrase") {
|
2021-02-11 21:59:48 +05:30
|
|
|
key = await keyFromPassphrase(keyDescription, credential, platform);
|
2020-10-19 21:59:13 +05:30
|
|
|
} else if (type === "key") {
|
2020-09-17 22:26:02 +05:30
|
|
|
key = keyFromRecoveryKey(olm, keyDescription, credential);
|
2020-09-17 18:46:01 +05:30
|
|
|
} else {
|
|
|
|
throw new Error(`Invalid type: ${type}`);
|
|
|
|
}
|
|
|
|
return key;
|
|
|
|
}
|