Debian Codegraph @

Hledger/Web/WebOptions.hs

raw
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE OverloadedStrings #-}
3 {-# LANGUAGE TemplateHaskell #-}
4 {-# LANGUAGE RecordWildCards #-}
5 {-# LANGUAGE LambdaCase #-}
6
7 module Hledger.Web.WebOptions where
8
9 import Data.ByteString (ByteString)
10 import Data.ByteString.Char8 qualified as BC
11 import Data.ByteString.UTF8 (fromString)
12 import Data.Default (Default(def))
13 import Data.Maybe (fromMaybe)
14 import Data.Text (Text)
15 import GitHash (tGitInfoCwdTry)
16 import System.Environment (getArgs)
17 import Network.Wai as WAI
18 import Network.Wai.Middleware.Cors
19 import Safe (lastMay)
20
21 import Hledger.Cli hiding (packageversion, progname, prognameandversion)
22 import Hledger.Web.Settings (defhost, defport, defbaseurl)
23 import Data.Text qualified as T
24 import Data.Char (toLower)
25 import Data.List (isPrefixOf)
26 import Data.Either (fromRight)
27
28 -- cf Hledger.Cli.Version
29
30 packageversion :: PackageVersionString
31 packageversion =
32 #ifdef VERSION
33 VERSION
34 #else
35 ""
36 #endif
37
38 -- | The name of this program's executable.
39 progname :: ProgramName
40 progname = "hledger-web"
41
42 -- | Generate the version string for this program.
43 -- The template haskell call is here rather than in Hledger.Cli.Version to avoid wasteful recompilation.
44 prognameandversion :: String
45 prognameandversion =
46 versionStringWith
47 $$tGitInfoCwdTry
48 #ifdef GHCDEBUG
49 True
50 #else
51 False
52 #endif
53 progname
54 packageversion
55
56 binaryinfo :: HledgerBinaryInfo
57 binaryinfo = fromRight nullbinaryinfo $ parseHledgerVersion prognameandversion
58
59 webflags :: [Flag RawOpts]
60 webflags =
61 [ flagNone
62 ["serve-browse"]
63 (setboolopt "serve-browse")
64 (serveprefix ++ "serve the web UI and JSON API, and open a browser, and exit if inactive for 2m (default)")
65 , flagNone
66 ["serve"]
67 (setboolopt "serve")
68 (serveprefix ++ "just serve the web UI and JSON API")
69 , flagNone
70 ["serve-api"]
71 (setboolopt "serve-api")
72 (serveprefix ++ "just serve the JSON API")
73 , flagReq
74 ["allow"]
75 (\s opts -> Right $ setopt "allow" s opts)
76 "view|add|edit"
77 "set the user's access level for changing data (default: `add`). It also accepts `sandstorm` for use on that platform (reads permissions from the `X-Sandstorm-Permissions` request header)."
78 , flagReq
79 ["cors"]
80 (\s opts -> Right $ setopt "cors" s opts)
81 "ORIGIN"
82 ("allow cross-origin requests from the specified origin; setting ORIGIN to \"*\" allows requests from any origin")
83 , flagReq
84 ["host"]
85 (\s opts -> Right $ setopt "host" s opts)
86 "IPADDR"
87 ("listen on this IP address (default: " ++ defhost ++ ")")
88 , flagReq
89 ["port"]
90 (\s opts -> Right $ setopt "port" s opts)
91 "PORT"
92 ("listen on this TCP port (default: " ++ show defport ++ ")")
93 , flagReq
94 ["socket"]
95 (\s opts -> Right $ setopt "socket" s opts)
96 "SOCKET"
97 "listen on the given unix socket instead of an IP address and port (only on unix)"
98 , flagReq
99 ["base-url"]
100 (\s opts -> Right $ setopt "base-url" s opts)
101 "BASEURL"
102 "set the base url (default: http://IPADDR:PORT)"
103 -- XXX #2139
104 -- , flagReq
105 -- ["file-url"]
106 -- (\s opts -> Right $ setopt "file-url" s opts)
107 -- "FILEURL"
108 -- "set a different base url for static files (default: `BASEURL/static/`)"
109 , flagNone
110 ["test"]
111 (setboolopt "test")
112 "run hledger-web's tests and exit. hspec test runner args may follow a --, eg: hledger-web --test -- --help"
113 ]
114 where
115 serveprefix = "server mode: "
116
117 webmode :: Mode RawOpts
118 webmode =
119 (mode
120 "hledger-web"
121 (setopt "command" "web" def)
122 "start serving the hledger web interface"
123 (argsFlag "[PATTERNS]")
124 [])
125 { modeGroupFlags =
126 Group
127 { groupUnnamed = webflags
128 , groupHidden = hiddenflags
129 ++
130 [flagNone ["server"] (setboolopt "serve") "old flag, use --serve instead"]
131 , groupNamed = mkgeneralflagsgroups1 helpflags
132 }
133 , modeHelpSuffix = []
134 }
135
136 data ServerMode = ServeBrowse | Serve | ServeJson deriving (Show, Eq)
137
138 -- hledger-web options, used in hledger-web and above
139 data WebOpts = WebOpts
140 { server_mode_ :: !ServerMode
141 , cors_ :: !(Maybe String)
142 , host_ :: !String
143 , port_ :: !Int
144 , base_url_ :: !String
145 , file_url_ :: !(Maybe String)
146 , allow_ :: !AccessLevel
147 , cliopts_ :: !CliOpts
148 , socket_ :: !(Maybe String)
149 } deriving (Show)
150
151 defwebopts :: WebOpts
152 defwebopts = WebOpts
153 { server_mode_ = ServeBrowse
154 , cors_ = Nothing
155 , host_ = ""
156 , port_ = def
157 , base_url_ = ""
158 , file_url_ = Nothing
159 , allow_ = AddAccess
160 , cliopts_ = def
161 , socket_ = Nothing
162 }
163
164 instance Default WebOpts where def = defwebopts
165
166 rawOptsToWebOpts :: RawOpts -> IO WebOpts
167 rawOptsToWebOpts rawopts =
168 checkWebOpts <$> do
169 cliopts <- rawOptsToCliOpts rawopts
170 let
171 h = fromMaybe defhost $ maybestringopt "host" rawopts
172 p = fromMaybe defport $ maybeposintopt "port" rawopts
173 -- Always set a base-url, constructing it from host and port if not specified.
174 -- This will be used when opening a web browser, eg.
175 -- App.hs approot will use it if it was specified by --base-url,
176 -- otherwise it will infer a better one from the request, which browsers prefer.
177 b = maybe (defbaseurl h p) stripTrailingSlash $ maybestringopt "base-url" rawopts
178 sock = stripTrailingSlash <$> maybestringopt "socket" rawopts
179 access =
180 case lastMay $ listofstringopt "allow" rawopts of
181 Nothing -> AddAccess
182 Just t ->
183 case parseAccessLevel t of
184 Right al -> al
185 Left err -> error' ("Unknown access level: " ++ err) -- PARTIAL:
186 return
187 defwebopts
188 { server_mode_ = servermodeopt rawopts
189 , cors_ = maybestringopt "cors" rawopts
190 , host_ = h
191 , port_ = p
192 , base_url_ = b
193 , file_url_ = stripTrailingSlash <$> maybestringopt "file-url" rawopts
194 , allow_ = access
195 , cliopts_ = cliopts
196 , socket_ = sock
197 }
198 where
199 stripTrailingSlash = reverse . dropWhile (== '/') . reverse -- yesod don't like it
200
201 servermodeopt :: RawOpts -> ServerMode
202 servermodeopt =
203 fromMaybe ServeBrowse . choiceopt parse
204 where
205 parse = \case
206 "serve-browse" -> Just ServeBrowse
207 "serve" -> Just Serve
208 "serve-api" -> Just ServeJson
209 _ -> Nothing
210
211 checkWebOpts :: WebOpts -> WebOpts
212 checkWebOpts wopts@WebOpts{..}
213 | not $ null base_url_ || "http://" `isPrefixOf` base_url_ || "https://" `isPrefixOf` base_url_ =
214 error' "please begin the --base-url value with http:// or https://"
215 | otherwise = wopts
216
217 getHledgerWebOpts :: IO WebOpts
218 getHledgerWebOpts = do
219 args <- fmap (ensureDebugFlagHasVal . replaceNumericFlags) . expandArgsAt =<< getArgs
220 rawOptsToWebOpts . either usageError id $ process webmode args
221
222 data Permission
223 = ViewPermission -- ^ allow viewing things (read only)
224 | AddPermission -- ^ allow adding transactions, or more generally allow appending text to input files
225 | EditPermission -- ^ allow editing input files
226 deriving (Eq, Ord, Bounded, Enum, Show)
227
228 parsePermission :: ByteString -> Either Text Permission
229 parsePermission "view" = Right ViewPermission
230 parsePermission "add" = Right AddPermission
231 parsePermission "edit" = Right EditPermission
232 parsePermission x = Left $ T.pack $ BC.unpack x
233
234 -- | Convert to the lower case permission name.
235 showPermission :: Permission -> String
236 showPermission p = map toLower $ reverse $ drop 10 $ reverse $ show p
237
238 -- | For the --allow option: how much access to allow to hledger-web users ?
239 data AccessLevel =
240 ViewAccess -- ^ view permission only
241 | AddAccess -- ^ view and add permissions
242 | EditAccess -- ^ view, add and edit permissions
243 | SandstormAccess -- ^ the permissions specified by the X-Sandstorm-Permissions HTTP request header
244 deriving (Eq, Ord, Bounded, Enum, Show)
245
246 parseAccessLevel :: String -> Either String AccessLevel
247 parseAccessLevel "view" = Right ViewAccess
248 parseAccessLevel "add" = Right AddAccess
249 parseAccessLevel "edit" = Right EditAccess
250 parseAccessLevel "sandstorm" = Right SandstormAccess
251 parseAccessLevel s = Left $ s <> ", should be one of: view, add, edit, sandstorm"
252
253 -- | Convert an --allow access level to the permissions used internally.
254 -- SandstormAccess generates an empty list, to be filled in later.
255 accessLevelToPermissions :: AccessLevel -> [Permission]
256 accessLevelToPermissions ViewAccess = [ViewPermission]
257 accessLevelToPermissions AddAccess = [ViewPermission, AddPermission]
258 accessLevelToPermissions EditAccess = [ViewPermission, AddPermission, EditPermission]
259 accessLevelToPermissions SandstormAccess = [] -- detected from request header
260
261 simplePolicyWithOrigin :: Origin -> CorsResourcePolicy
262 simplePolicyWithOrigin origin =
263 simpleCorsResourcePolicy { corsOrigins = Just ([origin], False) }
264
265 corsPolicyFromString :: String -> WAI.Middleware
266 corsPolicyFromString origin =
267 let
268 policy = case origin of
269 "*" -> simpleCorsResourcePolicy
270 url -> simplePolicyWithOrigin $ fromString url
271 in
272 cors (const $ Just policy)
273
274 corsPolicy :: WebOpts -> (Application -> Application)
275 corsPolicy opts =
276 maybe id corsPolicyFromString $ cors_ opts