From e6057b3c13f004477f4963f3cdf054e5ca1bf2f4 Mon Sep 17 00:00:00 2001 From: kongjun Date: Tue, 29 Apr 2025 04:05:35 +0000 Subject: feat: lock the encrypted file to read-only mode to avoid unintended corruption --- lua/encrypt/decrypt.lua | 1 + lua/encrypt/helpers.lua | 8 +++++++- lua/encrypt/init.lua | 4 ++-- lua/encrypt/setup-buffer.lua | 9 ++++++++- 4 files changed, 18 insertions(+), 4 deletions(-) (limited to 'lua/encrypt') diff --git a/lua/encrypt/decrypt.lua b/lua/encrypt/decrypt.lua index 2ae4e2a..72e93c3 100644 --- a/lua/encrypt/decrypt.lua +++ b/lua/encrypt/decrypt.lua @@ -20,6 +20,7 @@ local function decrypt() end vim.fn.timer_start(0, function() + vim.bo.modifiable = true vim.api.nvim_buf_set_lines(0, 0, -1, false, decrypted_lines) vim.bo.modified = false end) diff --git a/lua/encrypt/helpers.lua b/lua/encrypt/helpers.lua index ff8baef..a2ccc51 100644 --- a/lua/encrypt/helpers.lua +++ b/lua/encrypt/helpers.lua @@ -15,4 +15,10 @@ end local getPassword = getPasswordFactory() local ENCRYPTED_PREFIX = "# <<>>" -return { getPassword = getPassword, ENCRYPTED_PREFIX = ENCRYPTED_PREFIX } +---@enum buftype +local BUFTYPE = { + encrypted = 1, + plaintext = 2, +} + +return { getPassword = getPassword, ENCRYPTED_PREFIX = ENCRYPTED_PREFIX, BUFTYPE = BUFTYPE} diff --git a/lua/encrypt/init.lua b/lua/encrypt/init.lua index 53fc259..cfa1aa6 100644 --- a/lua/encrypt/init.lua +++ b/lua/encrypt/init.lua @@ -5,7 +5,7 @@ local helpers = require("encrypt.helpers") local function setup() vim.api.nvim_create_user_command("X", function() - setupBuffer() + setupBuffer(helpers.BUFTYPE.decrypted) encrypt() end, {}) @@ -13,7 +13,7 @@ local function setup() callback = function() local first_line = vim.api.nvim_buf_get_lines(0, 0, 1, false)[1] if first_line == helpers.ENCRYPTED_PREFIX then - setupBuffer() + setupBuffer(helpers.BUFTYPE.encrypted) decrypt() end end, diff --git a/lua/encrypt/setup-buffer.lua b/lua/encrypt/setup-buffer.lua index 8b950ec..e03f71c 100644 --- a/lua/encrypt/setup-buffer.lua +++ b/lua/encrypt/setup-buffer.lua @@ -1,4 +1,5 @@ local encrypt = require("encrypt.encrypt") +local helpers = require("encrypt.helpers") local function createWriteAutoCmd() if vim.b["encryptionAutoCmd"] ~= nil then @@ -18,12 +19,18 @@ local function createWriteAutoCmd() }) end -local function setupBuffer() +---@param buftype buftype +local function setupBuffer(buftype) -- buftype="acwrite" means save using the BufWriteCmd command vim.bo.buftype = "acwrite" vim.bo.swapfile = false vim.bo.undofile = false vim.b["encrypted"] = true + -- Lock the encrypted file to read-only mode to avoid corruption + -- caused by unintended modifications. + if buftype == helpers.BUFTYPE.encrypted then + vim.bo.modifiable = false + end createWriteAutoCmd() end -- cgit v1.2.3