Repository navigation
Expand file tree
/
Copy pathauth.lua
More file actions
78 lines (64 loc) · 2.04 KB
/
Copy pathauth.lua
File metadata and controls
78 lines (64 loc) · 2.04 KB
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
local config = require('opencode.config')
local M = {}
---@type {password: string | nil, username: string} | nil
local cache = nil
--- Resolve a credential value that may be a string or a function returning a string.
--- Returns nil for nil, empty string, or function errors.
---@param val string | (fun(): string | nil) | nil
---@return string | nil
local function resolve_credential(val)
if type(val) == 'function' then
local ok, result = pcall(val)
if ok and result and result ~= '' then
return result
end
return nil
end
if val and val ~= '' then
return val
end
return nil
end
--- Resolve and cache credentials from config + env vars.
---@return string|nil password
---@return string username
local function ensure_resolved()
if cache == nil then
local password = resolve_credential(config.server.password) or vim.env.OPENCODE_SERVER_PASSWORD
local username = resolve_credential(config.server.username) or vim.env.OPENCODE_SERVER_USERNAME or 'opencode'
cache = {
password = password,
username = username,
}
end
return cache.password, cache.username
end
--- Reset cached credentials. Call after changing config values.
function M.clear_cache()
cache = nil
end
--- Resolve credentials and return Authorization headers for HTTP Basic Auth.
--- Returns an empty table if no password is configured (server doesn't require auth).
---@return table<string, string> headers
function M.get_auth_headers()
local password, username = ensure_resolved()
if not password then
return {}
end
local encoded = vim.base64.encode(username .. ':' .. password)
return { ['Authorization'] = 'Basic ' .. encoded }
end
--- Resolve credentials and return environment variables for a spawned server.
--- Returns an empty table if no password is configured.
---@return table<string, string> env
function M.get_env()
local password, username = ensure_resolved()
if not password then
return {}
end
return {
OPENCODE_SERVER_PASSWORD = password,
OPENCODE_SERVER_USERNAME = username,
}
end
return M