robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 8c77b5be50c50ab119

master
7.0 KiB249 linesraw
1local M = {}
2
3local fileformat_newlines = {
4  unix = '\n',
5  dos = '\r\n',
6  mac = '\r',
7}
8
9--- Reads trust database from $XDG_STATE_HOME/nvim/trust.
10---
11---@return table<string, string> Contents of trust database, if it exists. Empty table otherwise.
12local function read_trust()
13  local trust = {} ---@type table<string, string>
14  local f = io.open(vim.fn.stdpath('state') .. '/trust', 'r')
15  if f then
16    local contents = f:read('*a')
17    if contents then
18      for line in vim.gsplit(contents, '\n') do
19        local hash, file = string.match(line, '^(%S+) (.+)$')
20        if hash and file then
21          trust[file] = hash
22        end
23      end
24    end
25    f:close()
26  end
27  return trust
28end
29
30--- If {fullpath} is a file, read the contents of {fullpath} (or the contents of {bufnr}
31--- if given) and returns the contents and a hash of the contents.
32---
33--- If {fullpath} is a directory, then nothing is read from the filesystem, and
34--- `contents = true` and `hash = "directory"` is returned instead.
35---
36---@param fullpath string Path to a file or directory to read.
37---@param bufnr integer? The number of the buffer.
38---@return string|boolean? contents the contents of the file, or true if it's a directory
39---@return string? hash the hash of the contents, or "directory" if it's a directory
40local function compute_hash(fullpath, bufnr)
41  local contents ---@type string|boolean?
42  local hash ---@type string
43  if vim.fn.isdirectory(fullpath) == 1 then
44    return true, 'directory'
45  end
46
47  if bufnr then
48    local is_unchanged_empty = vim.api.nvim_buf_call(bufnr, function()
49      return not vim.bo[bufnr].modified and vim.fn.line2byte(1) == -1
50    end)
51    if is_unchanged_empty then
52      contents = ''
53    else
54      local newline = fileformat_newlines[vim.bo[bufnr].fileformat]
55      contents =
56        table.concat(vim.api.nvim_buf_get_lines(bufnr --[[@as integer]], 0, -1, false), newline)
57      if vim.bo[bufnr].endofline then
58        contents = contents .. newline
59      end
60    end
61  else
62    do
63      local f = io.open(fullpath, 'rb')
64      if not f then
65        return nil, nil
66      end
67      contents = f:read('*a')
68      f:close()
69    end
70
71    if not contents then
72      return nil, nil
73    end
74  end
75
76  hash = vim.fn.sha256(contents)
77
78  return contents, hash
79end
80
81--- Writes provided {trust} table to trust database at
82--- $XDG_STATE_HOME/nvim/trust.
83---
84---@param trust table<string, string> Trust table to write
85local function write_trust(trust)
86  vim.validate('trust', trust, 'table')
87  local f = assert(io.open(vim.fn.stdpath('state') .. '/trust', 'w'))
88
89  local t = {} ---@type string[]
90  for p, h in pairs(trust) do
91    t[#t + 1] = string.format('%s %s\n', h, p)
92  end
93  f:write(table.concat(t))
94  f:close()
95end
96
97--- If {path} is a file: attempt to read the file, prompting the user if the file should be
98--- trusted.
99---
100--- If {path} is a directory: return true if the directory is trusted (non-recursive), prompting
101--- the user as necessary.
102---
103--- The user's choice is persisted in a trust database at
104--- $XDG_STATE_HOME/nvim/trust.
105---
106---@since 11
107---@see |:trust|
108---
109---@param path (string) Path to a file or directory to read.
110---
111---@return (boolean|string|nil) If {path} is not trusted or does not exist, returns `nil`. Otherwise,
112---        returns the contents of {path} if it is a file, or true if {path} is a directory.
113function M.read(path)
114  vim.validate('path', path, 'string')
115  local fullpath = vim.uv.fs_realpath(vim.fs.normalize(path))
116  if not fullpath then
117    return nil
118  end
119  fullpath = vim.fs.normalize(fullpath) -- Ensure "/" slashes, even on Windows.
120
121  local trust = read_trust()
122
123  if trust[fullpath] == '!' then
124    -- File is denied
125    return nil
126  end
127
128  local contents, hash = compute_hash(fullpath, nil)
129  if not contents then
130    return nil
131  end
132
133  if trust[fullpath] == hash then
134    -- File already exists in trust database
135    return contents
136  end
137
138  local msg2 = ' To enable it, choose (v)iew then run `:trust`:'
139  local choices = '&ignore\n&view\n&deny'
140  if hash == 'directory' then
141    msg2 = ' DIRECTORY trust is decided only by name, not contents:'
142    choices = '&ignore\n&view\n&deny\n&allow'
143  end
144
145  -- File either does not exist in trust database or the hash does not match
146  local ok, result = pcall(
147    vim.fn.confirm,
148    string.format('exrc: Found untrusted code.%s\n%s', msg2, fullpath),
149    choices,
150    1
151  )
152
153  if not ok and result ~= 'Keyboard interrupt' then
154    error(result)
155  elseif not ok or result == 0 or result == 1 then
156    -- Cancelled or ignored
157    return nil
158  elseif result == 2 then
159    -- View
160    vim.cmd(('sview %s'):format(vim.fn.fnameescape(fullpath)))
161    return nil
162  elseif result == 3 then
163    -- Deny
164    trust[fullpath] = '!'
165    contents = nil
166  elseif hash == 'directory' and result == 4 then
167    -- Allow
168    trust[fullpath] = hash
169  end
170
171  write_trust(trust)
172
173  return contents
174end
175
176--- @class vim.trust.opts
177--- @inlinedoc
178---
179--- One of:
180---   - `'allow'` to add a file to the trust database and trust it,
181---   - `'deny'` to add a file to the trust database and deny it,
182---   - `'remove'` to remove file from the trust database
183--- @field action 'allow'|'deny'|'remove'
184---
185--- Path to a file to update. Mutually exclusive with {bufnr}.
186--- @field path? string
187--- Buffer number to update. Mutually exclusive with {path}.
188--- @field bufnr? integer
189
190--- Manage the trust database.
191---
192--- The trust database is located at |$XDG_STATE_HOME|/nvim/trust.
193---
194---@since 11
195---@param opts vim.trust.opts
196---@return boolean success true if operation was successful
197---@return string msg full path if operation was successful, else error message
198function M.trust(opts)
199  vim.validate('path', opts.path, 'string', true)
200  vim.validate('bufnr', opts.bufnr, 'number', true)
201  vim.validate('action', opts.action, function(m)
202    return m == 'allow' or m == 'deny' or m == 'remove'
203  end, [["allow" or "deny" or "remove"]])
204
205  ---@cast opts vim.trust.opts
206  local path = opts.path
207  local bufnr = opts.bufnr
208  local action = opts.action
209
210  assert(not path or not bufnr, '"path" and "bufnr" are mutually exclusive')
211
212  local fullpath ---@type string?
213  if path then
214    fullpath = vim.uv.fs_realpath(vim.fs.normalize(path))
215  elseif bufnr then
216    local bufname = vim.api.nvim_buf_get_name(bufnr)
217    if bufname == '' then
218      return false, 'buffer is not associated with a file'
219    end
220    fullpath = vim.uv.fs_realpath(vim.fs.normalize(bufname))
221  else
222    error('one of "path" or "bufnr" is required')
223  end
224
225  if not fullpath then
226    return false, string.format('invalid path: %s', path)
227  end
228  fullpath = vim.fs.normalize(fullpath) -- Ensure "/" slashes, even on Windows.
229
230  local trust = read_trust()
231
232  if action == 'allow' then
233    local contents, hash = compute_hash(fullpath, bufnr)
234    if not contents then
235      return false, string.format('could not read path: %s', fullpath)
236    end
237
238    trust[fullpath] = hash
239  elseif action == 'deny' then
240    trust[fullpath] = '!'
241  elseif action == 'remove' then
242    trust[fullpath] = nil
243  end
244
245  write_trust(trust)
246  return true, fullpath
247end
248
249return M