All files / lib/Service/VaultRecovery credentialScan.js

95.79% Statements 114/119
86.36% Branches 76/88
100% Functions 17/17
95.68% Lines 111/116

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  1x 1x 1x 1x 1x 1x   649x 80x   569x 167x   402x     570x           490x     328x 3179x 328x 328x 328x 3179x   328x 328x 328x 328x 328x 328x     328x             485x 485x 80x   405x 405x 405x               405x 81x   324x 1167x   324x 324x 324x 324x 90x   234x     323x 323x 323x             163x     1666x               167x 167x     167x 167x 167x 248x 248x 163x 163x 163x 163x               167x 167x             167x 167x 167x 167x     82x 82x   818x   82x           85x             85x 81x                               4x                               80x 80x 80x           80x   155x 155x     75x   80x 80x 80x                         649x           649x 649x 649x 79x   570x     570x 167x   403x 80x   323x     80x                     80x 649x 5x   649x   84x 84x   240x 240x   83x 83x   83x 83x   80x 80x   79x 79x     80x    
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.scanCredential = scanCredential;
exports.buildScanReport = buildScanReport;
const PassmanCrypto_1 = require("../PassmanCrypto");
const payloadCrypto_1 = require("./payloadCrypto");
const types_1 = require("./types");
function determineKind(credential) {
    if (credential.encryptedSharedCredentialEncryptionKey !== undefined) {
        return 'shared_with_us';
    }
    if (credential.hasValidSharedKey()) {
        return 'shared_by_us';
    }
    return 'owned';
}
function hasAnyProbeField(encrypted) {
    return types_1.PAYLOAD_FIELDS.some((field) => encrypted[field] !== undefined && encrypted[field] !== null);
}
/**
 * Spreadable `malformedFields` hit property, omitted when there are none.
 */
function malformedFieldsOf(payload) {
    return payload.malformedFields.length > 0 ? { malformedFields: [...payload.malformedFields] } : {};
}
function pickWorkingKeyId(fieldKeyIds, preferredKeyId) {
    const ids = Object.values(fieldKeyIds);
    const pool = ids.filter((id) => id !== preferredKeyId);
    const counted = (pool.length > 0 ? pool : ids);
    const counts = new Map();
    for (const id of counted) {
        counts.set(id, (counts.get(id) ?? 0) + 1);
    }
    let best = counted[0];
    let bestCount = 0;
    for (const [id, count] of counts) {
        Eif (count > bestCount) {
            best = id;
            bestCount = count;
        }
    }
    return best;
}
/**
 * Turns a per-field decrypt result into a scan hit. `ok` omits the preview; partials keep decryptable fields
 * only and stay repairable via `suggestedStrategy`.
 */
function classifyPayloadHit(base, payload, preferredKeyId, suggestedStrategy, workingKeyIdOverride) {
    const fileHits = base.fileHits ?? [];
    if (Object.keys(payload.fieldKeyIds).length === 0) {
        return { ...base, fileHits, status: 'broken', brokenFields: payload.brokenFields };
    }
    const workingKeyId = workingKeyIdOverride ?? pickWorkingKeyId(payload.fieldKeyIds, preferredKeyId);
    const malformed = malformedFieldsOf(payload);
    const recoverable = {
        workingKeyId,
        fieldKeyIds: payload.fieldKeyIds,
        recoveredPreview: payload.recoveredPreview,
        brokenFields: payload.brokenFields,
        ...malformed,
        suggestedStrategy
    };
    if (payload.brokenFields.length > 0) {
        return { ...base, fileHits, ...recoverable, status: 'partially_broken' };
    }
    const allOnPreferred = preferredKeyId !== undefined
        && Object.values(payload.fieldKeyIds).every((id) => id === preferredKeyId);
    // shared-with-us payload is not writable; do not keep scanning as needs_rewrap for values we cannot persist
    const writable = base.kind !== 'shared_with_us';
    const shouldRepairCoercedCompromised = payload.coercedCompromised && writable;
    const shouldRepairMalformedFields = payload.malformedFields.length > 0 && writable;
    if (allOnPreferred && !shouldRepairCoercedCompromised && !shouldRepairMalformedFields) {
        return { ...base, fileHits, status: 'ok', workingKeyId: preferredKeyId, brokenFields: [], ...malformed };
    }
    return { ...base, fileHits, ...recoverable, status: 'needs_rewrap' };
}
function scanOwned(credential, candidates, preferredKeyId, base) {
    const encrypted = credential.getEncrypted();
    const payload = (0, payloadCrypto_1.decryptPayloadPerCandidate)(encrypted, (0, payloadCrypto_1.orderPreferredFirst)(candidates, preferredKeyId), credential.label);
    return { hit: classifyPayloadHit(base, payload, preferredKeyId, 'rewrap_owned'), payload };
}
/**
 * A decrypted shared_key that a client would actually use as the payload key.
 * `Credential.getFieldEncryptionKey` ignores only real null; `""` and the literal `"null"` are not usable keys.
 */
function usableSharedKeyPlaintext(value) {
    return value !== undefined && value !== '' && value !== 'null';
}
function vaultOnlyFieldKeyIds(fieldKeyIds) {
    return Object.fromEntries(Object.entries(fieldKeyIds).filter(([, id]) => id !== types_1.SHARED_KEY_PROBE_ID));
}
/**
 * Clients treat a present `shared_key` as "shared by us" and decrypt every payload field with that key only.
 * This scan does the same first, then tries vault candidates for fields the shared key does not open, so a
 * half-applied share (or an undecryptable wrapper) is still recoverable.
 */
function scanSharedByUs(credential, candidates, preferredKeyId, base) {
    const encrypted = credential.getEncrypted();
    const ordered = (0, payloadCrypto_1.orderPreferredFirst)(candidates, preferredKeyId);
    let wrapperCandidate;
    let sharedKeyPlain;
    const wrapperCiphertext = encrypted.shared_key;
    Eif (wrapperCiphertext !== undefined && wrapperCiphertext !== null) {
        for (const candidate of ordered) {
            try {
                const decrypted = PassmanCrypto_1.PassmanCrypto.decryptString(wrapperCiphertext, candidate.password);
                Eif (usableSharedKeyPlaintext(decrypted)) {
                    sharedKeyPlain = decrypted;
                    wrapperCandidate = candidate;
                    break;
                }
            }
            catch (e) {
                // try next candidate
            }
        }
    }
    const payload = (0, payloadCrypto_1.decryptPayloadWithKeyThenCandidates)(encrypted, sharedKeyPlain, types_1.SHARED_KEY_PROBE_ID, ordered, credential.label);
    Iif (Object.keys(payload.fieldKeyIds).length === 0) {
        return {
            hit: { ...base, status: 'broken', brokenFields: (0, payloadCrypto_1.getPresentPayloadFields)(encrypted) },
            payload: (0, payloadCrypto_1.emptyPayloadResult)(credential.label),
            sharedKeyPlain
        };
    }
    const openedWrapper = wrapperCandidate;
    const openedSharedKey = sharedKeyPlain;
    const vaultFieldKeyIds = vaultOnlyFieldKeyIds(payload.fieldKeyIds);
    if (Object.keys(vaultFieldKeyIds).length === 0 && openedWrapper !== undefined && openedSharedKey !== undefined) {
        // Every recovered field really is under the shared key. Report the wrapper candidate id, matching
        // the pre-existing contract (allOnPreferred compares field ids to the preferred vault key).
        const wrapperId = openedWrapper.id;
        const normalized = {
            ...payload,
            fieldKeyIds: Object.fromEntries(Object.keys(payload.fieldKeyIds).map((field) => [field, wrapperId]))
        };
        return {
            hit: classifyPayloadHit(base, normalized, preferredKeyId, 'rewrap_shared_by_us_wrapper', wrapperId),
            payload: normalized,
            sharedKeyPlain: openedSharedKey
        };
    }
    Iif (Object.keys(vaultFieldKeyIds).length === 0) {
        return {
            hit: { ...base, status: 'broken', brokenFields: (0, payloadCrypto_1.getPresentPayloadFields)(encrypted) },
            payload: (0, payloadCrypto_1.emptyPayloadResult)(credential.label),
            sharedKeyPlain: openedSharedKey
        };
    }
    if (openedWrapper !== undefined && openedSharedKey !== undefined) {
        return {
            hit: {
                ...base,
                status: payload.brokenFields.length > 0 ? 'partially_broken' : 'shared_key_mismatch',
                workingKeyId: pickWorkingKeyId(vaultFieldKeyIds, preferredKeyId),
                wrapperKeyId: openedWrapper.id,
                fieldKeyIds: payload.fieldKeyIds,
                recoveredPreview: payload.recoveredPreview,
                brokenFields: payload.brokenFields,
                ...malformedFieldsOf(payload),
                suggestedStrategy: 'fix_shared_key_mismatch'
            },
            payload,
            sharedKeyPlain: openedSharedKey
        };
    }
    return {
        hit: {
            ...base,
            status: payload.brokenFields.length > 0 ? 'partially_broken' : 'shared_key_mismatch',
            workingKeyId: pickWorkingKeyId(vaultFieldKeyIds, preferredKeyId),
            fieldKeyIds: payload.fieldKeyIds,
            recoveredPreview: payload.recoveredPreview,
            brokenFields: payload.brokenFields,
            ...malformedFieldsOf(payload),
            suggestedStrategy: 'clear_undecryptable_shared_key'
        },
        payload,
        sharedKeyPlain: openedSharedKey
    };
}
function scanSharedWithUs(credential, candidates, preferredKeyId, base) {
    const encrypted = credential.getEncrypted();
    const aclCiphertext = credential.encryptedSharedCredentialEncryptionKey;
    Iif (aclCiphertext === undefined) {
        return {
            hit: { ...base, status: 'broken', brokenFields: (0, payloadCrypto_1.getPresentPayloadFields)(encrypted) },
            payload: (0, payloadCrypto_1.emptyPayloadResult)(credential.label)
        };
    }
    for (const candidate of (0, payloadCrypto_1.orderPreferredFirst)(candidates, preferredKeyId)) {
        let aclKeyPlain;
        try {
            aclKeyPlain = PassmanCrypto_1.PassmanCrypto.decryptString(aclCiphertext, candidate.password);
        }
        catch (e) {
            continue;
        }
        const payload = (0, payloadCrypto_1.decryptPayloadWithKey)(encrypted, aclKeyPlain, candidate.id, credential.label);
        Eif (Object.keys(payload.fieldKeyIds).length > 0) {
            return {
                hit: classifyPayloadHit(base, payload, preferredKeyId, 'rewrap_acl_shared_with_us', candidate.id),
                payload,
                aclKeyPlain
            };
        }
    }
    return {
        hit: { ...base, status: 'broken', brokenFields: (0, payloadCrypto_1.getPresentPayloadFields)(encrypted) },
        payload: (0, payloadCrypto_1.emptyPayloadResult)(credential.label)
    };
}
function scanCredential(credential, candidates, preferredKeyId, skipDeleted = true) {
    const base = {
        guid: credential.guid,
        label: credential.label ?? credential.guid,
        kind: determineKind(credential),
        fileHits: []
    };
    const encrypted = credential.getEncrypted();
    const emptyPayload = (0, payloadCrypto_1.emptyPayloadResult)(credential.label);
    if (skipDeleted && credential.delete_time !== null && credential.delete_time !== undefined && credential.delete_time > 0) {
        return { hit: { ...base, status: 'skipped', brokenFields: [] }, payload: emptyPayload };
    }
    Iif (!hasAnyProbeField(encrypted)) {
        return { hit: { ...base, status: 'skipped', brokenFields: [] }, payload: emptyPayload };
    }
    if (base.kind === 'shared_by_us') {
        return scanSharedByUs(credential, candidates, preferredKeyId, base);
    }
    if (base.kind === 'shared_with_us') {
        return scanSharedWithUs(credential, candidates, preferredKeyId, base);
    }
    return scanOwned(credential, candidates, preferredKeyId, base);
}
function buildScanReport(hits) {
    const report = {
        hits,
        scannedCount: hits.length,
        okCount: 0,
        needsRewrapCount: 0,
        sharedKeyMismatchCount: 0,
        partiallyBrokenCount: 0,
        brokenCount: 0,
        skippedCount: 0,
        malformedCount: 0
    };
    for (const hit of hits) {
        if ((hit.malformedFields?.length ?? 0) > 0) {
            report.malformedCount++;
        }
        switch (hit.status) {
            case 'ok':
                report.okCount++;
                break;
            case 'needs_rewrap':
                report.needsRewrapCount++;
                break;
            case 'shared_key_mismatch':
                report.sharedKeyMismatchCount++;
                break;
            case 'partially_broken':
                report.partiallyBrokenCount++;
                break;
            case 'broken':
                report.brokenCount++;
                break;
            case 'skipped':
                report.skippedCount++;
                break;
        }
    }
    return report;
}