forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
255 lines (219 loc) · 6.23 KB
/
main.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package main
import (
"context"
"flag"
"fmt"
"net"
"net/http"
"os"
"time"
"github.com/gnolang/gno/gno.land/pkg/gnoweb"
"github.com/gnolang/gno/gno.land/pkg/log"
"github.com/gnolang/gno/tm2/pkg/commands"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type webCfg struct {
chainid string
remote string
remoteHelp string
bind string
faucetURL string
assetsDir string
timeout time.Duration
analytics bool
json bool
html bool
noStrict bool
verbose bool
}
var defaultWebOptions = webCfg{
chainid: "dev",
remote: "127.0.0.1:26657",
bind: ":8888",
timeout: time.Minute,
}
func main() {
var cfg webCfg
stdio := commands.NewDefaultIO()
cmd := commands.NewCommand(
commands.Metadata{
Name: "gnoweb",
ShortUsage: "gnoweb [flags] [path ...]",
ShortHelp: "runs gno.land web interface",
LongHelp: `gnoweb web interface`,
},
&cfg,
func(ctx context.Context, args []string) error {
run, err := setupWeb(&cfg, args, stdio)
if err != nil {
return err
}
return run()
})
cmd.Execute(context.Background(), os.Args[1:])
}
func (c *webCfg) RegisterFlags(fs *flag.FlagSet) {
fs.StringVar(
&c.remote,
"remote",
defaultWebOptions.remote,
"remote gno.land node address",
)
fs.StringVar(
&c.remoteHelp,
"help-remote",
defaultWebOptions.remoteHelp,
"help page's remote address",
)
fs.StringVar(
&c.assetsDir,
"assets-dir",
defaultWebOptions.assetsDir,
"if not empty, will be use as assets directory",
)
fs.StringVar(
&c.chainid,
"help-chainid",
defaultWebOptions.chainid,
"Deprecated: use `chainid` instead",
)
fs.StringVar(
&c.chainid,
"chainid",
defaultWebOptions.chainid,
"target chain id",
)
fs.StringVar(
&c.bind,
"bind",
defaultWebOptions.bind,
"gnoweb listener",
)
fs.StringVar(
&c.faucetURL,
"faucet-url",
defaultWebOptions.faucetURL,
"The faucet URL will redirect the user when they access `/faucet`.",
)
fs.BoolVar(
&c.json,
"json",
defaultWebOptions.json,
"display log in json format",
)
fs.BoolVar(
&c.html,
"html",
defaultWebOptions.html,
"enable unsafe html",
)
fs.BoolVar(
&c.analytics,
"with-analytics",
defaultWebOptions.analytics,
"enable privacy-first analytics",
)
fs.BoolVar(
&c.noStrict,
"no-strict",
defaultWebOptions.noStrict,
"allow cross-site resource forgery and disable https enforcement",
)
fs.BoolVar(
&c.verbose,
"v",
defaultWebOptions.verbose,
"verbose logging mode",
)
fs.DurationVar(
&c.timeout,
"timeout",
defaultWebOptions.timeout,
"set read/write/idle timeout for server connections",
)
}
func setupWeb(cfg *webCfg, _ []string, io commands.IO) (func() error, error) {
// Setup logger
level := zapcore.InfoLevel
if cfg.verbose {
level = zapcore.DebugLevel
}
var zapLogger *zap.Logger
if cfg.json {
zapLogger = log.NewZapJSONLogger(io.Out(), level)
} else {
zapLogger = log.NewZapConsoleLogger(io.Out(), level)
}
defer zapLogger.Sync()
logger := log.ZapLoggerToSlog(zapLogger)
// Setup app
appcfg := gnoweb.NewDefaultAppConfig()
appcfg.ChainID = cfg.chainid
appcfg.NodeRemote = cfg.remote
appcfg.RemoteHelp = cfg.remoteHelp
if appcfg.RemoteHelp == "" {
appcfg.RemoteHelp = appcfg.NodeRemote
}
appcfg.Analytics = cfg.analytics
appcfg.UnsafeHTML = cfg.html
appcfg.FaucetURL = cfg.faucetURL
appcfg.AssetsDir = cfg.assetsDir
app, err := gnoweb.NewRouter(logger, appcfg)
if err != nil {
return nil, fmt.Errorf("unable to start gnoweb app: %w", err)
}
// Resolve binding address
bindaddr, err := net.ResolveTCPAddr("tcp", cfg.bind)
if err != nil {
return nil, fmt.Errorf("unable to resolve listener %q: %w", cfg.bind, err)
}
logger.Info("Running", "listener", bindaddr.String())
// Setup security headers
secureHandler := SecureHeadersMiddleware(app, !cfg.noStrict)
// Setup server
server := &http.Server{
Handler: secureHandler,
Addr: bindaddr.String(),
ReadTimeout: cfg.timeout, // Time to read the request
WriteTimeout: cfg.timeout, // Time to write the entire response
IdleTimeout: cfg.timeout, // Time to keep idle connections open
ReadHeaderTimeout: time.Minute, // Time to read request headers
}
return func() error {
if err := server.ListenAndServe(); err != nil {
logger.Error("HTTP server stopped", "error", err)
return commands.ExitCodeError(1)
}
return nil
}, nil
}
func SecureHeadersMiddleware(next http.Handler, strict bool) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Prevent MIME type sniffing by browsers. This ensures that the browser
// does not interpret files as a different MIME type than declared.
w.Header().Set("X-Content-Type-Options", "nosniff")
// Prevent the page from being embedded in an iframe. This mitigates
// clickjacking attacks by ensuring the page cannot be loaded in a frame.
w.Header().Set("X-Frame-Options", "DENY")
// Control the amount of referrer information sent in the Referer header.
// 'no-referrer' ensures that no referrer information is sent, which
// enhances privacy and prevents leakage of sensitive URLs.
w.Header().Set("Referrer-Policy", "no-referrer")
// In `strict` mode, prevent cross-site ressources forgery and enforce https
if strict {
// Define a Content Security Policy (CSP) to restrict the sources of
// scripts, styles, images, and other resources. This helps prevent
// cross-site scripting (XSS) and other code injection attacks.
// - 'self' allows resources from the same origin.
// - 'data:' allows inline images (e.g., base64-encoded images).
// - 'https://gnolang.github.io' allows images from this specific domain - used by gno.land. TODO: use a proper generic whitelisted service
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' https://sa.gno.services; style-src 'self'; img-src 'self' data: https://gnolang.github.io https://sa.gno.services; font-src 'self'")
// Enforce HTTPS by telling browsers to only access the site over HTTPS
// for a specified duration (1 year in this case). This also applies to
// subdomains and allows preloading into the browser's HSTS list.
w.Header().Set("Strict-Transport-Security", "max-age=31536000")
}
next.ServeHTTP(w, r)
})
}