fix: enforce strict online backup keyring entries
This commit is contained in:
@@ -4,6 +4,8 @@ const crypto = require('node:crypto');
|
||||
const secretStore = require('./secret-store');
|
||||
const { parseOnlineBackupKey } = require('./online-backup');
|
||||
|
||||
const STORED_ENTRY_KEYS = ['createdAt', 'encryptedKey', 'id'];
|
||||
|
||||
function isObject(value) {
|
||||
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
@@ -24,8 +26,11 @@ function createOnlineBackupKeyring({
|
||||
let mutation = Promise.resolve();
|
||||
|
||||
function validateEntry(entry) {
|
||||
if (!isObject(entry)) return null;
|
||||
const keys = Object.keys(entry).sort();
|
||||
if (
|
||||
!isObject(entry)
|
||||
keys.length !== STORED_ENTRY_KEYS.length
|
||||
|| !keys.every((key, index) => key === STORED_ENTRY_KEYS[index])
|
||||
|| typeof entry.id !== 'string'
|
||||
|| !entry.id
|
||||
|| typeof entry.encryptedKey !== 'string'
|
||||
@@ -53,7 +58,7 @@ function createOnlineBackupKeyring({
|
||||
return { id: entry.id, encryptedKey: entry.encryptedKey, createdAt, key };
|
||||
}
|
||||
|
||||
async function readEntries() {
|
||||
async function readEntries(rejectInvalidEntries = false) {
|
||||
let contents;
|
||||
try {
|
||||
contents = await fsImpl.readFile(filePath, 'utf8');
|
||||
@@ -70,7 +75,11 @@ function createOnlineBackupKeyring({
|
||||
if (!isObject(document) || document.version !== 1 || !Array.isArray(document.entries)) {
|
||||
throw new Error('Gespeicherter Online-Schlüsselbund ist ungültig');
|
||||
}
|
||||
return document.entries.map(validateEntry).filter(Boolean);
|
||||
const entries = document.entries.map(validateEntry);
|
||||
if (rejectInvalidEntries && entries.some((entry) => !entry)) {
|
||||
throw new Error('Gespeicherter Online-Schlüsselbund ist ungültig');
|
||||
}
|
||||
return entries.filter(Boolean);
|
||||
}
|
||||
|
||||
async function writeEntries(entries) {
|
||||
@@ -135,7 +144,7 @@ function createOnlineBackupKeyring({
|
||||
return serialize(async () => {
|
||||
const validated = validateEntry(entry);
|
||||
if (!validated) throw new Error('Online-Sicherungsschlüssel ist ungültig');
|
||||
const entries = await readEntries();
|
||||
const entries = await readEntries(true);
|
||||
if (entries.some((current) => current.id === validated.id)) return;
|
||||
await writeEntries([...entries, validated]);
|
||||
});
|
||||
@@ -143,7 +152,7 @@ function createOnlineBackupKeyring({
|
||||
|
||||
function remove(id) {
|
||||
return serialize(async () => {
|
||||
const entries = await readEntries();
|
||||
const entries = await readEntries(true);
|
||||
const remaining = entries.filter((entry) => entry.id !== id);
|
||||
if (remaining.length === entries.length) return false;
|
||||
await writeEntries(remaining);
|
||||
|
||||
Reference in New Issue
Block a user