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 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | import Credential from "./Credential";
import { PassmanCrypto } from "../Service/PassmanCrypto";
import { ShareService } from "../Service/ShareService";
import { File } from "./File";
import { NextcloudServer } from "./NextcloudServer";
export default 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.generateRSAKeypair(2048).then(async (value) => {
if (value.keypair) {
const pemKeyPair = PassmanCrypto.rsaKeyPairToPEM(value.keypair);
await creator_only_vault.updateSharingKeys(pemKeyPair.publicKey, pemKeyPair.privateKey);
// todo: create hidden test credential
let testCredential = new Credential(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);
// todo: check if a creation of vault.private_sharing_key for old vaults is required
// set vaultKey if it is valid
if (vaultKey && vault.testVaultKey(vaultKey)) {
vault.vaultKey = vaultKey;
}
await vault.refresh(getCachedIfPossible, specificVaultResponse);
return vault;
}
}
/**
* The configured model store of the underlying persistence, or undefined if none is configured.
*/
getModelStore() {
return this.server.persistence.getModelStore();
}
/**
* Upsert this vault (metadata + its credentials) as encrypted serializable DTO into the model store (no-op without a configured store).
*/
persistToModelStore() {
return this.getModelStore()?.putVault(this.server.getConnectionId(), this.getAsSerializable());
}
/**
* Remove this vault (metadata + all its credentials) from the model store.
* Replaces the former, unused clearRequestCache() which cleared the legacy raw-GET request cache.
*/
clearFromModelStore() {
return this.getModelStore()?.deleteVault(this.server.getConnectionId(), this.guid);
}
/**
* Clear all request caches for this vault. (not for the specific credentials that's managed by the Credential model)
* @deprecated use clearFromModelStore() instead.
*/
clearRequestCache() {
return this.server.persistence.getRequestCacheHandler()?.set(NextcloudServer.getRequestCachePrefix + '/vaults/' + this.guid, undefined);
}
/**
* Reload current vault's metadata and credentials (as well as shared credentials) from the server.
* @param getCachedIfPossible
* @param specificVaultResponse if provided, no subsequent refresh request for specific vault information is being made (useful if you did that manually before)
*/
async refresh(getCachedIfPossible = false, specificVaultResponse) {
// only load vault raw data (and metadata) if not externally provided
if (!specificVaultResponse) {
let _specificVaultResponse = await this.server.getJson('/vaults/' + this.guid, (response) => {
this.server.logger.onError(response.message);
}, getCachedIfPossible);
if (_specificVaultResponse) {
specificVaultResponse = _specificVaultResponse;
}
}
// should not be undefined here, but in case of a void response above, prevent breaking the vault instance
if (specificVaultResponse) {
this._specificVaultInformation = specificVaultResponse;
// 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 (this.vaultKey && this.testVaultKey(this.vaultKey)) {
vaultIsUnlocked = true;
}
const credentials = [];
let collectedTags = [];
for (const encryptedCredentialDataFromServer of specificVaultResponse.credentials) {
try {
const credential = Credential.fromData(encryptedCredentialDataFromServer, this, this.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) {
this.server.logger.anyError(e);
this.server.logger.onError('Failed to decrypt credential: ' + encryptedCredentialDataFromServer.label);
}
}
this.collectedTags = new Set(collectedTags);
const credentialsSharedWithUs = await ShareService.getCredentialsSharedWithUs(this, this.server, getCachedIfPossible);
for (const credential of credentialsSharedWithUs) {
credentials.push(credential);
}
this._credentials = credentials;
// keep the model store (primary read/reconstruction path) in sync with the freshly loaded full vault
await this.persistToModelStore();
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');
if (result === null) {
// incremental model-store write of the updated vault metadata
await this.persistToModelStore();
return true;
}
return false;
}
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.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;
}
if (deleteVaultResponse.ok) {
// incremental model-store removal of the deleted vault (metadata + credentials)
await this.clearFromModelStore();
}
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.encryptString(private_sharing_key, this.vaultKey),
}, (response) => {
this.server.logger.onError(response.message);
});
}
testVaultKey(vaultKey) {
try {
if (this.challenge_password) {
PassmanCrypto.decryptString(this.challenge_password, vaultKey);
return true;
}
else if (this.credentials.length > 0) {
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 if (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) {
if (!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.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.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;
}
}
|