All files / lib/esm/Service/VaultRecovery fileBlobScan.js

0% Statements 0/114
0% Branches 0/76
0% Functions 0/18
0% Lines 0/107

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                                                                                                                                                                                                                                                                                                                                                                                               
import { File } from "../../Model/File";
import { PassmanCrypto } from "../PassmanCrypto";
import { orderPreferredFirst, rawDecryptJsonField } from "./payloadCrypto";
import { collectFileRefs } from "./fileRefs";
import { ACL_KEY_PROBE_ID, SHARED_KEY_PROBE_ID } from "./types";
function fillMissingFileFieldFromKey(encrypted, preview, field, internal) {
    if (internal.payload.fieldKeyIds[field] !== undefined) {
        return;
    }
    const extraKeys = [internal.sharedKeyPlain, internal.aclKeyPlain].filter((key) => !!key);
    for (const key of extraKeys) {
        try {
            const decrypted = rawDecryptJsonField(encrypted, field, key);
            if (Array.isArray(decrypted)) {
                preview[field] = decrypted;
                return;
            }
        }
        catch (e) {
            // try next extra key
        }
    }
}
export function resolveFileRefs(encrypted, internal) {
    const preview = { ...internal.payload.recoveredPreview };
    fillMissingFileFieldFromKey(encrypted, preview, 'files', internal);
    fillMissingFileFieldFromKey(encrypted, preview, 'custom_fields', internal);
    return collectFileRefs(preview);
}
function promoteHitIfFilesNeedRewrap(hit, preferredKeyId) {
    if (hit.kind === 'shared_with_us') {
        return;
    }
    if (!hit.fileHits.some((fileHit) => fileHit.status === 'needs_rewrap')) {
        return;
    }
    if (hit.status !== 'ok') {
        return;
    }
    hit.status = 'needs_rewrap';
    hit.suggestedStrategy = hit.kind === 'owned' ? 'rewrap_owned' : 'rewrap_shared_by_us_wrapper';
    if (hit.workingKeyId === undefined) {
        hit.workingKeyId = preferredKeyId;
    }
}
function collectBlobKeyProbes(internal, candidates, preferred) {
    const probes = [];
    const seenIds = new Set();
    const add = (id, key) => {
        if (!key || seenIds.has(id)) {
            return;
        }
        seenIds.add(id);
        probes.push({ id, key });
    };
    if (internal.hit.kind === 'shared_by_us' && internal.sharedKeyPlain) {
        add(SHARED_KEY_PROBE_ID, internal.sharedKeyPlain);
    }
    if (internal.hit.kind === 'shared_with_us' && internal.aclKeyPlain) {
        add(ACL_KEY_PROBE_ID, internal.aclKeyPlain);
    }
    for (const candidate of orderPreferredFirst(candidates, preferred?.id)) {
        add(candidate.id, candidate.password);
    }
    return probes;
}
function destinationProbeIds(kind, preferredKeyId, probes) {
    const ids = new Set();
    if (kind === 'owned' && preferredKeyId) {
        ids.add(preferredKeyId);
    }
    if (kind === 'shared_by_us' && probes.some((probe) => probe.id === SHARED_KEY_PROBE_ID)) {
        ids.add(SHARED_KEY_PROBE_ID);
    }
    else if (kind === 'shared_by_us' && preferredKeyId) {
        // shared_key did not yield a payload key. Repair clears it and the credential becomes owned.
        ids.add(preferredKeyId);
    }
    if (kind === 'shared_with_us' && probes.some((probe) => probe.id === ACL_KEY_PROBE_ID)) {
        ids.add(ACL_KEY_PROBE_ID);
    }
    return ids;
}
function isSentinelProbeId(id) {
    return id === SHARED_KEY_PROBE_ID || id === ACL_KEY_PROBE_ID;
}
function blobDecryptsWith(fileData, key) {
    try {
        PassmanCrypto.decryptString(fileData, key);
        return true;
    }
    catch (e) {
        return false;
    }
}
export async function downloadRawFileBlob(credential, kind, file, vault) {
    try {
        if (kind === 'shared_with_us') {
            if (!file.guid) {
                return;
            }
            return await File.downloadSharedFile(credential, file, vault.getServer());
        }
        if (file.file_id === undefined || file.file_id === null) {
            return;
        }
        return await File.downloadFile(file, vault.getServer());
    }
    catch (e) {
        return;
    }
}
async function probeOneFileBlob(credential, kind, ref, probes, vault, preferredKeyId) {
    const filename = typeof ref.file.filename === 'string' && ref.file.filename.length > 0
        ? ref.file.filename
        : '(unnamed)';
    const base = {
        file_id: ref.file.file_id,
        guid: ref.file.guid,
        filename,
        source: ref.source,
        status: 'broken'
    };
    const downloaded = await downloadRawFileBlob(credential, kind, ref.file, vault);
    if (!downloaded || typeof downloaded.file_data !== 'string') {
        return base;
    }
    const destinationIds = destinationProbeIds(kind, preferredKeyId, probes);
    const destinationProbes = probes.filter((probe) => destinationIds.has(probe.id));
    const otherProbes = probes.filter((probe) => !destinationIds.has(probe.id));
    for (const probe of destinationProbes) {
        if (blobDecryptsWith(downloaded.file_data, probe.key)) {
            return {
                ...base,
                status: 'ok',
                workingKeyId: isSentinelProbeId(probe.id) ? undefined : probe.id
            };
        }
    }
    for (const probe of otherProbes) {
        if (blobDecryptsWith(downloaded.file_data, probe.key)) {
            return {
                ...base,
                status: 'needs_rewrap',
                workingKeyId: isSentinelProbeId(probe.id) ? undefined : probe.id
            };
        }
    }
    return base;
}
export async function probeFileBlobs(vault, internals, candidates, preferred, progress, onProgress) {
    const jobs = [];
    for (const internal of internals) {
        if (internal.hit.status === 'skipped' || internal.hit.status === 'broken') {
            internal.hit.fileHits = [];
            continue;
        }
        const credential = vault.getCredentialByGuid(internal.hit.guid);
        if (!credential) {
            internal.hit.fileHits = [];
            continue;
        }
        const refs = resolveFileRefs(credential.getEncrypted(), internal);
        jobs.push({ internal, credential, refs });
    }
    const totalFiles = jobs.reduce((sum, job) => sum + job.refs.length, 0);
    if (totalFiles === 0) {
        for (const job of jobs) {
            job.internal.hit.fileHits = [];
        }
        return;
    }
    // now as the pre-filtering and selection of candidates is done, we can do the real work :)
    progress.stage = 'files';
    progress.doneSteps = 0;
    progress.totalSteps = totalFiles;
    onProgress?.(progress);
    for (const job of jobs) {
        const probes = collectBlobKeyProbes(job.internal, candidates, preferred);
        const fileHits = [];
        for (const ref of job.refs) {
            const fileHit = await probeOneFileBlob(job.credential, job.internal.hit.kind, ref, probes, vault, preferred?.id);
            fileHits.push(fileHit);
            progress.doneSteps++;
            progress.messages.push(`file ${fileHit.status}: ${job.internal.hit.label} / ${fileHit.filename}`);
            onProgress?.(progress);
        }
        job.internal.hit.fileHits = fileHits;
        promoteHitIfFilesNeedRewrap(job.internal.hit, preferred?.id);
    }
}