-
Notifications
You must be signed in to change notification settings - Fork 2
/
ngrok.go
304 lines (247 loc) · 7.44 KB
/
ngrok.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package ngroklistener
import (
"context"
"encoding/json"
"fmt"
"net"
"net/url"
"time"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"go.uber.org/zap"
"golang.ngrok.com/ngrok"
"golang.ngrok.com/ngrok/config"
ngrokZap "golang.ngrok.com/ngrok/log/zap"
)
func init() {
caddy.RegisterModule(new(Ngrok))
}
type Tunnel interface {
NgrokTunnel() config.Tunnel
}
// Ngrok is a `listener_wrapper` whose address is an ngrok-ingress address
type Ngrok struct {
opts []ngrok.ConnectOption
// The user's ngrok authentication token
AuthToken string `json:"auth_token,omitempty"`
// The ngrok tunnel type and configuration; defaults to 'tcp'
TunnelRaw json.RawMessage `json:"tunnel,omitempty" caddy:"namespace=caddy.listeners.ngrok.tunnels inline_key=type"`
// Opaque, machine-readable metadata string for this session.
// Metadata is made available to you in the ngrok dashboard and the
// Agents API resource. It is a useful way to allow you to uniquely identify
// sessions. We suggest encoding the value in a structured format like JSON.
Metadata string `json:"metadata,omitempty"`
// Region configures the session to connect to a specific ngrok region.
// If unspecified, ngrok will connect to the fastest region, which is usually what you want.
// The [full list of ngrok regions] can be found in the ngrok documentation.
Region string `json:"region,omitempty"`
// Server configures the network address to dial to connect to the ngrok
// service. Use this option only if you are connecting to a custom agent
// ingress.
//
// See the [server_addr parameter in the ngrok docs] for additional details.
Server string `json:"server,omitempty"`
// HeartbeatTolerance configures the duration to wait for a response to a heartbeat
// before assuming the session connection is dead and attempting to reconnect.
//
// See the [heartbeat_tolerance parameter in the ngrok docs] for additional details.
HeartbeatTolerance caddy.Duration `json:"heartbeat_tolerance,omitempty"`
// HeartbeatInterval configures how often the session will send heartbeat
// messages to the ngrok service to check session liveness.
//
// See the [heartbeat_interval parameter in the ngrok docs] for additional details.
HeartbeatInterval caddy.Duration `json:"heartbeat_interval,omitempty"`
// https://github.com/ngrok/ngrok-go/blob/main/session.go
// ProxyURL configures the session to connect to ngrok through an outbound
// HTTP or SOCKS5 proxy. This parameter is ignored if you override the dialer
// with [WithDialer].
//
// See the [proxy url parameter in the ngrok docs] for additional details.
ProxyURL string `json:"proxy_url,omitempty"`
tunnel Tunnel
ctx context.Context
l *zap.Logger
}
// Provisions the ngrok listener wrapper
func (n *Ngrok) Provision(ctx caddy.Context) error {
n.ctx = ctx
n.l = ctx.Logger()
if n.TunnelRaw == nil {
n.TunnelRaw = json.RawMessage(`{"type": "tcp"}`)
}
tmod, err := ctx.LoadModule(n, "TunnelRaw")
if err != nil {
return fmt.Errorf("loading ngrok tunnel module: %v", err)
}
var ok bool
n.tunnel, ok = tmod.(Tunnel)
if !ok {
return fmt.Errorf("loading ngrok tunnel module: %v", err)
}
n.doReplace()
if err = n.provisionOpts(); err != nil {
return fmt.Errorf("provisioning ngrok opts: %v", err)
}
return nil
}
func (n *Ngrok) provisionOpts() error {
simpleVersion, _ := caddy.Version()
n.opts = append(
n.opts,
ngrok.WithLogger(ngrokZap.NewLogger(n.l)),
ngrok.WithClientInfo("caddy", simpleVersion),
)
if n.AuthToken == "" {
n.opts = append(n.opts, ngrok.WithAuthtokenFromEnv())
} else {
n.opts = append(n.opts, ngrok.WithAuthtoken(n.AuthToken))
}
if n.Metadata != "" {
n.opts = append(n.opts, ngrok.WithMetadata(n.Metadata))
}
if n.Region != "" {
n.opts = append(n.opts, ngrok.WithRegion(n.Region))
}
if n.Server != "" {
n.opts = append(n.opts, ngrok.WithServer(n.Server))
}
n.opts = append(n.opts, ngrok.WithHeartbeatInterval(time.Duration(n.HeartbeatInterval)))
n.opts = append(n.opts, ngrok.WithHeartbeatTolerance(time.Duration(n.HeartbeatTolerance)))
if n.ProxyURL != "" {
url, err := url.Parse(n.ProxyURL)
if err != nil {
return fmt.Errorf("provisioning proxy_url: %v", err)
}
n.opts = append(n.opts, ngrok.WithProxyURL(url))
}
return nil
}
func (n *Ngrok) doReplace() {
repl := caddy.NewReplacer()
replaceableFields := []*string{
&n.AuthToken,
&n.Metadata,
&n.Region,
&n.Server,
&n.ProxyURL,
}
for _, field := range replaceableFields {
actual := repl.ReplaceKnown(*field, "")
*field = actual
}
}
func (*Ngrok) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "caddy.listeners.ngrok",
New: func() caddy.Module {
return new(Ngrok)
},
}
}
// WrapListener return an ngrok listener instead the listener passed by Caddy
func (n *Ngrok) WrapListener(net.Listener) net.Listener {
ln, err := ngrok.Listen(
n.ctx,
n.tunnel.NgrokTunnel(),
n.opts...,
)
if err != nil {
panic(err)
}
n.l.Info("ngrok listening", zap.String("address", ln.Addr().String()))
return ln
}
func (n *Ngrok) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
for d.Next() {
if d.NextArg() {
return d.ArgErr()
}
for nesting := d.Nesting(); d.NextBlock(nesting); {
subdirective := d.Val()
switch subdirective {
case "auth_token":
if !d.AllArgs(&n.AuthToken) {
n.AuthToken = ""
}
case "metadata":
if !d.AllArgs(&n.Metadata) {
return d.ArgErr()
}
case "region":
if !d.AllArgs(&n.Region) {
return d.ArgErr()
}
case "server":
if !d.AllArgs(&n.Server) {
return d.ArgErr()
}
case "heartbeat_tolerance":
if err := n.unmarshalHeartbeatTolerance(d); err != nil {
return err
}
case "heartbeat_interval":
if err := n.unmarshalHeartbeatInterval(d); err != nil {
return err
}
case "proxy_url":
if !d.AllArgs(&n.ProxyURL) {
return d.ArgErr()
}
case "tunnel":
if err := n.unmarshalTunnel(d); err != nil {
return err
}
default:
return d.Errf("unrecognized subdirective %s", subdirective)
}
}
}
return nil
}
func (n *Ngrok) unmarshalHeartbeatTolerance(d *caddyfile.Dispenser) error {
var toleranceStr string
if !d.AllArgs(&toleranceStr) {
return d.ArgErr()
}
heartbeatTolerance, err := caddy.ParseDuration(toleranceStr)
if err != nil {
return d.Errf("parsing heartbeat_tolerance duration: %v", err)
}
n.HeartbeatTolerance = caddy.Duration(heartbeatTolerance)
return nil
}
func (n *Ngrok) unmarshalHeartbeatInterval(d *caddyfile.Dispenser) error {
var intervalStr string
if !d.AllArgs(&intervalStr) {
return d.ArgErr()
}
heartbeatInterval, err := caddy.ParseDuration(intervalStr)
if err != nil {
return d.Errf("parsing heartbeat_interval duration: %v", err)
}
n.HeartbeatInterval = caddy.Duration(heartbeatInterval)
return nil
}
func (n *Ngrok) unmarshalTunnel(d *caddyfile.Dispenser) error {
var tunnelName string
if !d.Args(&tunnelName) {
tunnelName = "tcp"
}
unm, err := caddyfile.UnmarshalModule(d, "caddy.listeners.ngrok.tunnels."+tunnelName)
if err != nil {
return err
}
tun, ok := unm.(Tunnel)
if !ok {
return d.Errf("module %s is not an ngrok tunnel; is %T", tunnelName, unm)
}
n.TunnelRaw = caddyconfig.JSONModuleObject(tun, "type", tunnelName, nil)
return nil
}
var (
_ caddy.Module = (*Ngrok)(nil)
_ caddy.Provisioner = (*Ngrok)(nil)
_ caddy.ListenerWrapper = (*Ngrok)(nil)
_ caddyfile.Unmarshaler = (*Ngrok)(nil)
)