All files / lib/Model Vault.js

30.13% Statements 44/146
21.05% Branches 12/57
42.22% Functions 19/45
29.86% Lines 43/144

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333  3x 3x   3x 3x 3x 3x 3x 3x         7x     7x 7x 7x                   6x                                                                                                                                                                                                                                                                                                                           1x 1x     1x                                     1x 1x       1x 1x 1x               1x   1x 1x                     1x 1x 1x                       1x 1x   1x                 1x       1x 1x 1x     2x     7x     82x     8x     7x     2x                                               1x                             11x     3x  
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Credential_1 = __importDefault(require("./Credential"));
const PassmanCrypto_1 = require("../Service/PassmanCrypto");
const ShareService_1 = require("../Service/ShareService");
const File_1 = require("./File");
const NextcloudServer_1 = require("./NextcloudServer");
class Vault {
    _specificVaultInformation;
    server;
    _vaultKey;
    collectedTags = new Set();
    _credentials;
    constructor(_specificVaultInformation, server) {
        this._specificVaultInformation = _specificVaultInformation;
        this.server = server;
        this._credentials = [];
    }
    /**
     * Filler for the now private Vault constructor. Use this carefully, or even better: do not use it!
     * The constructor was previously used for custom re-creation from cache, this is now handled using a custom persistence service (when constructing PassmanClient).
     * @param _specificVaultInformation
     * @param server
     * @deprecated use Vault.create() or Vault.fetchFullVaultFromServer() (with the option of setting getCachedIfPossible: boolean) instead.
     */
    static createManually(_specificVaultInformation, server) {
        return new Vault(_specificVaultInformation, server);
    }
    /**
     * Create a new vault on the server and return an unlocked full-featured vault instance with fresh data.
     * @param vaultName
     * @param vaultPassword
     * @param server
     * @return new fresh vault instance or void if something went wrong
     */
    static async create(vaultName, vaultPassword, server) {
        let vaultResponse = await server.postJson('/vaults', { vault_name: vaultName }, (response) => {
            server.logger.onError(response.message);
        });
        if (vaultResponse) {
            const creator_only_vault = new Vault(vaultResponse, server);
            creator_only_vault._vaultKey = vaultPassword;
            await PassmanCrypto_1.PassmanCrypto.generateRSAKeypair(2048).then(async (value) => {
                if (value.keypair) {
                    const pemKeyPair = PassmanCrypto_1.PassmanCrypto.rsaKeyPairToPEM(value.keypair);
                    await creator_only_vault.updateSharingKeys(pemKeyPair.publicKey, pemKeyPair.privateKey);
                    // todo: create hidden test credential
                    let testCredential = new Credential_1.default(creator_only_vault, server);
                    testCredential.label = 'Test key for vault ' + vaultName;
                    testCredential.hidden = true;
                    testCredential.password = 'lorum ipsum';
                    if (await testCredential.save()) {
                        // todo: refresh / log in to the new vault
                        server.logger.onSuccess('Vault successfully created');
                    }
                    else {
                        server.logger.onError('Failed saving test credential in new vault');
                    }
                }
                else {
                    server.logger.onError('Failed to create a new vault rsa key-pair');
                }
            });
            return await Vault.fetchFullVaultFromServer(server, creator_only_vault.guid, vaultPassword, false);
        }
    }
    /**
     * Creates a locked full-featured vault instance with fresh data (metadata, credentials, shared credentials) from the passman server.
     * Optional: directly unlock by providing the correct vault key.
     */
    static async fetchFullVaultFromServer(server, guid, vaultKey, getCachedIfPossible = false) {
        let specificVaultResponse = await server.getJson('/vaults/' + guid, (response) => {
            server.logger.onError(response.message);
        }, getCachedIfPossible);
        if (specificVaultResponse) {
            const vault = new Vault(specificVaultResponse, server);
            // test vault key with the challenge_password value, to have a definite unlock state for restoring decrypted credential data from cache
            let vaultIsUnlocked = false;
            if (vaultKey && vault.testVaultKey(vaultKey)) {
                vault.vaultKey = vaultKey;
                vaultIsUnlocked = true;
            }
            const credentials = [];
            let collectedTags = [];
            for (const encryptedCredentialDataFromServer of specificVaultResponse.credentials) {
                try {
                    const credential = Credential_1.default.fromData(encryptedCredentialDataFromServer, vault, server);
                    // restore and counting tags only if the correct vaultKey is given (current vault can then be assumed as unlocked)
                    if (vaultIsUnlocked === true) {
                        if (getCachedIfPossible) {
                            await credential.restoreSerializedDecryptedDataCache();
                        }
                        if (credential.tags && credential.tags.length > 0) {
                            collectedTags = collectedTags.concat(credential.tags.map(value => value.text).filter(Boolean));
                        }
                    }
                    credentials.push(credential);
                }
                catch (e) {
                    server.logger.anyError(e);
                    server.logger.onError('Failed to decrypt credential: ' + encryptedCredentialDataFromServer.label);
                }
            }
            vault.collectedTags = new Set(collectedTags);
            const credentialsSharedWithUs = await ShareService_1.ShareService.getCredentialsSharedWithUs(vault, server, getCachedIfPossible);
            for (const credential of credentialsSharedWithUs) {
                credentials.push(credential);
            }
            vault._credentials = credentials;
            // we could also test vault key here when we have all credentials, but it would make it harder to restore decrypted credential cache
            return vault;
        }
    }
    /**
     * Clear all request caches for this vault. (not for the specific credentials that's managed by the Credential model)
     */
    clearRequestCache() {
        return this.server.persistence.getRequestCacheHandler()?.set(NextcloudServer_1.NextcloudServer.getRequestCachePrefix + '/vaults/' + this.guid, undefined);
    }
    /**
     * Reload current vault's metadata and credentials (as well as shared credentials) from the server.
     * @param getCachedIfPossible
     */
    async refresh(getCachedIfPossible = false) {
        const vaultFromServer = await Vault.fetchFullVaultFromServer(this.server, this.guid, this.vaultKey, getCachedIfPossible);
        if (vaultFromServer) {
            this.collectedTags = vaultFromServer.collectedTags;
            this._credentials = vaultFromServer.credentials;
            // todo: check if a creation of vault.private_sharing_key for old vaults is required
            this._specificVaultInformation = vaultFromServer._specificVaultInformation;
            return true;
        }
        return false;
    }
    async update() {
        const result = await this.server.postJson('/vaults/' + this._specificVaultInformation.guid, {
            guid: this._specificVaultInformation.guid,
            vault_id: this._specificVaultInformation.vault_id,
            name: this._specificVaultInformation.name,
            created: this._specificVaultInformation.created,
            public_sharing_key: this._specificVaultInformation.public_sharing_key,
            last_access: this._specificVaultInformation.last_access,
            delete_request_pending: this._specificVaultInformation.delete_request_pending,
            sharing_keys_generated: this._specificVaultInformation.sharing_keys_generated,
            vault_settings: this._specificVaultInformation.vault_settings
        }, (response) => {
            this.server.logger.onError(response.message);
        }, 'PATCH');
        return result === null;
    }
    async delete(currentPassword) {
        if (!this.testVaultKey(currentPassword)) {
            this.server.logger.onError('Invalid password!');
            return false;
        }
        let fileIds = [];
        for (const credential of this.credentials) {
            for (const file of credential.files) {
                if (file.file_id) {
                    fileIds.push(file.file_id);
                }
            }
        }
        const deleteFilesResponse = await File_1.File.deleteFiles({ file_ids: JSON.stringify(fileIds) }, this.server);
        if (!deleteFilesResponse) {
            // void response should "never" happen with a working server side
            this.server.logger.onError('Abort! Failed to request files deletion.');
            return false;
        }
        if (!deleteFilesResponse.ok) {
            // minor file deletion issues; continue vault deletion
            this.server.logger.onError('Failed to delete files: ' + deleteFilesResponse.failed.toString());
        }
        let deleteVaultResponse = await this.server.deleteJson('/vaults/' + this.guid, (response) => {
            this.server.logger.onError(response.message);
        });
        if (!deleteVaultResponse) {
            // void response should "never" happen with a working server side
            this.server.logger.onError('Abort! Failed to request vault deletion.');
            return false;
        }
        return deleteVaultResponse.ok;
    }
    lock() {
        this.vaultKey = null;
        this.collectedTags.clear();
        // clear decrypted credential cache from memory
        // no need to touch _specificVaultInformation.credentials since these are fully encrypted
        for (const credential of this._credentials) {
            credential.clearDecryptedDataCache();
        }
    }
    /**
     * Set the given sharing keys for the current vault on the server. Does not (!) store the given keys in the current vault object.
     * @param public_sharing_key
     * @param private_sharing_key
     */
    async updateSharingKeys(public_sharing_key, private_sharing_key) {
        return await this.server.postJson('/vaults/' + this._specificVaultInformation.guid + '/sharing-keys', {
            guid: this._specificVaultInformation.guid,
            public_sharing_key: public_sharing_key,
            private_sharing_key: PassmanCrypto_1.PassmanCrypto.encryptString(private_sharing_key, this.vaultKey),
        }, (response) => {
            this.server.logger.onError(response.message);
        });
    }
    testVaultKey(vaultKey) {
        try {
            Iif (this.challenge_password) {
                PassmanCrypto_1.PassmanCrypto.decryptString(this.challenge_password, vaultKey);
                return true;
            }
            else Eif (this.credentials.length > 0) {
                PassmanCrypto_1.PassmanCrypto.decryptString(this.getChallengingFieldValue(), vaultKey);
                return true;
            }
        }
        catch (e) {
        }
        return false;
    }
    getChallengingFieldValue() {
        const testCredential = this.getFirstOwnedCredential();
        // use getEncrypted to prevent trying to decrypt an already decrypted or cached value
        if (testCredential.getEncrypted().username != null) {
            return testCredential.getEncrypted().username;
        }
        else Eif (testCredential.getEncrypted().password != null) {
            return testCredential.getEncrypted().password;
        }
        else if (testCredential.getEncrypted().email != null) {
            return testCredential.getEncrypted().email;
        }
        return null;
    }
    getFirstOwnedCredential() {
        for (let credential of this.credentials) {
            Eif (!credential.hasValidSharedKey() && credential.encryptedSharedCredentialEncryptionKey === undefined) {
                return credential;
            }
        }
    }
    getCredentialByGuid(guid) {
        for (let credential of this.credentials) {
            if (credential.guid === guid) {
                return credential;
            }
        }
    }
    getAsSerializable() {
        const { credentials, ...serializableSpecificVaultInformation } = this._specificVaultInformation;
        return {
            serializableSpecificVaultInformation,
            encryptedSerializableCredentials: this.credentials.map(credential => credential.getAsSerializable()),
        };
    }
    /**
     * Returns a locked vault, made out of SerializableTransferFullVaultInterface data.
     * @param serializable
     * @param server
     */
    static fromSerializable(serializable, server) {
        const specificVaultInformation = {
            credentials: [],
            ...serializable.serializableSpecificVaultInformation
        };
        const vault = new Vault(specificVaultInformation, server);
        vault._credentials = serializable.encryptedSerializableCredentials.map(serializableCredential => Credential_1.default.fromSerializable(serializableCredential, vault, server));
        return vault;
    }
    getServer() {
        return this.server;
    }
    get vaultId() {
        return this._specificVaultInformation.vault_id;
    }
    get vaultKey() {
        return this._vaultKey;
    }
    set vaultKey(value) {
        this._vaultKey = value;
    }
    get guid() {
        return this._specificVaultInformation.guid;
    }
    get name() {
        return this._specificVaultInformation.name;
    }
    set name(value) {
        this._specificVaultInformation.name = value;
    }
    get created() {
        return this._specificVaultInformation.created;
    }
    get public_sharing_key() {
        return this._specificVaultInformation.public_sharing_key;
    }
    get private_sharing_key() {
        return PassmanCrypto_1.PassmanCrypto.decryptString(this._specificVaultInformation.private_sharing_key, this.vaultKey);
    }
    get sharing_keys_generated() {
        return this._specificVaultInformation.sharing_keys_generated;
    }
    set sharing_keys_generated(value) {
        this._specificVaultInformation.sharing_keys_generated = value;
    }
    get last_access() {
        return this._specificVaultInformation.last_access;
    }
    get challenge_password() {
        return this._specificVaultInformation.challenge_password;
    }
    get delete_request_pending() {
        return this._specificVaultInformation.delete_request_pending;
    }
    set delete_request_pending(value) {
        this._specificVaultInformation.delete_request_pending = value;
    }
    get vault_settings() {
        return this._specificVaultInformation.vault_settings;
    }
    set vault_settings(value) {
        this._specificVaultInformation.vault_settings = value;
    }
    get credentials() {
        return this._credentials;
    }
}
exports.default = Vault;