/
raiden
/
obsidian-git-encrypt
Обзор
Документация
Войти
/
raiden
/
obsidian-git-encrypt
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/mirror/atomicWriter.ts
69 строк
2 KB
Robert Kuzhin
feat: add encrypted mirror and manifest store
09 авг 2026, 10:06
09 авг 2026, 10:06
7f1b7fe
Код
Авторство
О чём код?
import { open, realpath, rename, unlink } from "node:fs/promises"; import path from "node:path"; import { PathSafetyError } from "./errors.js"; import { isWithin } from "./pathSafety.js"; export async function writeFileAtomic( allowedRoot: string, targetPath: string, data: Uint8Array, ): Promise<void> { const canonicalRoot = await realpath(allowedRoot); const resolvedTarget = path.resolve(targetPath); const targetParent = path.dirname(resolvedTarget); const canonicalParent = await realpath(targetParent); const canonicalTarget = path.join(canonicalParent, path.basename(resolvedTarget)); if (!isWithin(canonicalRoot, canonicalParent) || !isWithin(canonicalRoot, canonicalTarget)) { throw new PathSafetyError("Atomic write target escapes the encrypted repository"); } const temporaryPath = path.join( canonicalParent, `.${path.basename(canonicalTarget)}.${globalThis.crypto.randomUUID()}.tmp`, ); let temporaryExists = false; try { const file = await open(temporaryPath, "wx", 0o600); temporaryExists = true; try { await file.writeFile(data); await file.sync(); } finally { await file.close(); } await rename(temporaryPath, canonicalTarget); temporaryExists = false; await syncDirectory(canonicalParent); } finally { if (temporaryExists) { await unlink(temporaryPath).catch((error: unknown) => { if (!isNodeError(error) || error.code !== "ENOENT") throw error; }); } } } async function syncDirectory(directory: string): Promise<void> { try { const handle = await open(directory, "r"); try { await handle.sync(); } finally { await handle.close(); } } catch (error) { if ( !isNodeError(error) || typeof error.code !== "string" || !["EACCES", "EISDIR", "EINVAL", "ENOTSUP", "EPERM"].includes(error.code) ) { throw error; } } } function isNodeError(error: unknown): error is NodeJS.ErrnoException { return error instanceof Error && "code" in error; }