@riceawa/dsh-lan-gateway 0.5.2 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +134 -238
- package/lib/client.js +68 -32
- package/lib/client.js.map +1 -1
- package/lib/index.d.ts +34 -3
- package/lib/index.js +426 -83
- package/package.json +3 -2
- package/skills/lan-gateway.md +8 -4
- package/src/auth.ts +98 -26
- package/src/client/lan-gateway-card.tsx +46 -2
- package/src/gateway.ts +238 -28
- package/src/index.ts +82 -16
- package/src/state.ts +77 -7
- package/src/tls.ts +33 -0
- package/src/upstream-session.ts +60 -7
package/src/gateway.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The reverse-proxy gateway: a `node:http(s)` server bound to
|
|
3
|
-
*
|
|
2
|
+
* The reverse-proxy gateway: a `node:http(s)` server bound to the unspecified
|
|
3
|
+
* address (dual-stack, so IPv6 clients reach it too) that forwards every
|
|
4
|
+
* request to the loopback dsh web server.
|
|
4
5
|
*
|
|
5
6
|
* Security model (post-QVD / session-base):
|
|
6
7
|
* - Source is classified from `socket.remoteAddress` only (never
|
|
@@ -23,22 +24,25 @@
|
|
|
23
24
|
* authority-bound session cookie). The gateway therefore relays one shared
|
|
24
25
|
* upstream session acquired through the launch-token exchange and replays it
|
|
25
26
|
* on every forwarded request. See `upstream-session.ts`.
|
|
26
|
-
* - Sessions
|
|
27
|
-
*
|
|
28
|
-
*
|
|
27
|
+
* - Sessions are revocable two ways. Each carries a random id, so signing out
|
|
28
|
+
* retires exactly that session and the WebSockets it opened; and each
|
|
29
|
+
* carries a revocation epoch, so a password change or secret rotation kills
|
|
30
|
+
* every session at once — cookie, socket, and all.
|
|
29
31
|
*
|
|
30
32
|
* @module @riceawa/dsh-lan-gateway/gateway
|
|
31
33
|
*/
|
|
32
34
|
|
|
33
35
|
import http from 'node:http'
|
|
34
36
|
import https from 'node:https'
|
|
37
|
+
import { randomBytes } from 'node:crypto'
|
|
35
38
|
import type { Duplex } from 'node:stream'
|
|
36
39
|
import {
|
|
37
40
|
classifySource,
|
|
38
41
|
originMatchesHost,
|
|
39
42
|
RateLimiter,
|
|
40
43
|
signCookie,
|
|
41
|
-
|
|
44
|
+
verifySession,
|
|
45
|
+
type SessionClaims,
|
|
42
46
|
type SourceClass,
|
|
43
47
|
} from './auth.ts'
|
|
44
48
|
import {
|
|
@@ -49,12 +53,17 @@ import {
|
|
|
49
53
|
serveLoginGet,
|
|
50
54
|
type LoginPageOptions,
|
|
51
55
|
} from './login.ts'
|
|
52
|
-
import {
|
|
56
|
+
import {
|
|
57
|
+
isSessionRevoked,
|
|
58
|
+
revokeSession,
|
|
59
|
+
verifyPassword,
|
|
60
|
+
type GatewayState,
|
|
61
|
+
} from './state.ts'
|
|
53
62
|
import type { UpstreamSession } from './upstream-session.ts'
|
|
54
63
|
|
|
55
64
|
/** Configuration the gateway needs at listen time. */
|
|
56
65
|
export interface GatewayConfig {
|
|
57
|
-
/** Port to bind on
|
|
66
|
+
/** Port to bind on the unspecified address (dual-stack; see {@link LanGateway.listen}). */
|
|
58
67
|
gatewayPort: number
|
|
59
68
|
/** The loopback dsh web server port to forward to. */
|
|
60
69
|
dshPort: number
|
|
@@ -74,6 +83,12 @@ export interface GatewayConfig {
|
|
|
74
83
|
classifySource?: (req: http.IncomingMessage) => SourceClass
|
|
75
84
|
/** Optional shared upstream session relayed onto every forwarded request. */
|
|
76
85
|
upstreamSession?: UpstreamSession
|
|
86
|
+
/**
|
|
87
|
+
* Called after the gateway revokes a session itself (sign-out), so the plugin
|
|
88
|
+
* can persist a state the gateway changed on its own. The gateway has already
|
|
89
|
+
* installed it locally by then.
|
|
90
|
+
*/
|
|
91
|
+
onStateChange?: (state: GatewayState) => void
|
|
77
92
|
}
|
|
78
93
|
|
|
79
94
|
const DEFAULT_BODY_LIMIT_BYTES = 64 * 1024
|
|
@@ -83,15 +98,102 @@ const LOGIN_ATTEMPTS_WINDOW_MS = 60_000
|
|
|
83
98
|
/** Methods a browser never attaches a CSRF-meaningful body to; safe without an Origin. */
|
|
84
99
|
const READ_ONLY_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
|
|
85
100
|
|
|
101
|
+
/** The upstream browser-session cookie name prefix; the relay owns this namespace. */
|
|
102
|
+
const UPSTREAM_COOKIE_PREFIX = 'dsh-auth-'
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Headers a proxy must not forward in either direction (RFC 9110 §7.6.1), plus
|
|
106
|
+
* the non-standard proxy-connection.
|
|
107
|
+
*/
|
|
108
|
+
const HOP_BY_HOP_HEADERS = new Set([
|
|
109
|
+
'connection',
|
|
110
|
+
'keep-alive',
|
|
111
|
+
'proxy-authenticate',
|
|
112
|
+
'proxy-authorization',
|
|
113
|
+
'proxy-connection',
|
|
114
|
+
'te',
|
|
115
|
+
'trailer',
|
|
116
|
+
'transfer-encoding',
|
|
117
|
+
'upgrade',
|
|
118
|
+
])
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Headers by which a client asserts where a request came from. The gateway
|
|
122
|
+
* classifies on `socket.remoteAddress` and never reads these, so relaying a
|
|
123
|
+
* caller's own values only hands the next hop a forgeable claim.
|
|
124
|
+
*/
|
|
125
|
+
const FORWARDING_HEADERS = [
|
|
126
|
+
'forwarded',
|
|
127
|
+
'x-forwarded-for',
|
|
128
|
+
'x-forwarded-host',
|
|
129
|
+
'x-forwarded-port',
|
|
130
|
+
'x-forwarded-proto',
|
|
131
|
+
'x-real-ip',
|
|
132
|
+
]
|
|
133
|
+
|
|
134
|
+
/** Whether a Cookie fragment names the upstream session cookie. */
|
|
135
|
+
function isUpstreamSessionPair(pair: string): boolean {
|
|
136
|
+
return pair.startsWith(UPSTREAM_COOKIE_PREFIX)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Drop every `dsh-auth-*` pair from a Cookie header, returning the remainder
|
|
141
|
+
* (possibly '').
|
|
142
|
+
*
|
|
143
|
+
* `attachUpstreamSession` appends the relay's session to the client's own
|
|
144
|
+
* cookie, and upstream reads the FIRST name match. A client that holds any
|
|
145
|
+
* `dsh-auth-<hash>` — typically one minted before dsh's signing secret was
|
|
146
|
+
* reset, so still present but no longer verifying — would therefore shadow the
|
|
147
|
+
* relay's session on every request. That draws a 401, the gateway reads the
|
|
148
|
+
* 401 as "upstream revoked our session" and discards it, the next request
|
|
149
|
+
* re-acquires, and the client's stale cookie shadows that one too: a loop that
|
|
150
|
+
* never converges. Stripping the namespace makes the relay's copy the only one.
|
|
151
|
+
*/
|
|
152
|
+
function withoutUpstreamSessionPairs(cookie: string): string {
|
|
153
|
+
return cookie
|
|
154
|
+
.split(';')
|
|
155
|
+
.map((pair) => pair.trim())
|
|
156
|
+
.filter((pair) => pair !== '' && !isUpstreamSessionPair(pair))
|
|
157
|
+
.join('; ')
|
|
158
|
+
}
|
|
159
|
+
|
|
86
160
|
/** Prefixes the gateway owns and must never relay to dsh. */
|
|
87
161
|
function isOwnedPath(pathname: string): boolean {
|
|
88
162
|
return pathname === '/lan-gateway' || pathname.startsWith('/lan-gateway/')
|
|
89
163
|
}
|
|
90
164
|
|
|
91
|
-
/**
|
|
165
|
+
/**
|
|
166
|
+
* The pathname a request is routed by: the one dsh's router resolves it to
|
|
167
|
+
* (WHATWG URL parsing, which strips the query and collapses dot segments),
|
|
168
|
+
* with trailing slashes then removed for the gateway's own surface tests.
|
|
169
|
+
*
|
|
170
|
+
* The decision paths below (owned prefix, login, logout) must use this rather
|
|
171
|
+
* than the raw request target. dsh normalizes before matching, so a raw-string
|
|
172
|
+
* test disagrees with it on `/foo/../lan-gateway/config` — that is not an owned
|
|
173
|
+
* path by string prefix, stays in the relay, and lands on the plugin's own
|
|
174
|
+
* config route once Host has been rewritten to loopback. Forwarding still
|
|
175
|
+
* relays the raw target: dsh applies the same normalization itself.
|
|
176
|
+
*
|
|
177
|
+
* WHATWG parsing does not drop a trailing slash, and neither does dsh's
|
|
178
|
+
* router, so `/__login/` is not the login page to either of them. The gateway
|
|
179
|
+
* recognizes its own surfaces there anyway: `/__logout/` must still sign out,
|
|
180
|
+
* and `/lan-gateway/config/` must be refused rather than relayed into dsh's
|
|
181
|
+
* single-page fallback. Blocking a trailing-slash spelling of an owned prefix
|
|
182
|
+
* errs toward refusing, which costs nothing — no upstream route lives under it.
|
|
183
|
+
*/
|
|
92
184
|
function pathOf(url: string): string {
|
|
93
|
-
|
|
94
|
-
|
|
185
|
+
try {
|
|
186
|
+
return new URL(url, 'http://gateway.invalid').pathname.replace(/\/+$/, '') || '/'
|
|
187
|
+
} catch {
|
|
188
|
+
// Unparseable here means unparseable for dsh too; the raw target routes
|
|
189
|
+
// nowhere and is relayed as-is.
|
|
190
|
+
return url
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** A fresh per-session id: 128 random bits, URL-safe. */
|
|
195
|
+
function newSessionId(): string {
|
|
196
|
+
return randomBytes(16).toString('base64url')
|
|
95
197
|
}
|
|
96
198
|
|
|
97
199
|
/**
|
|
@@ -104,8 +206,14 @@ export class LanGateway {
|
|
|
104
206
|
private readonly loginLimiter = new RateLimiter(LOGIN_ATTEMPTS_LIMIT, LOGIN_ATTEMPTS_WINDOW_MS)
|
|
105
207
|
private state: GatewayState
|
|
106
208
|
private disposed = false
|
|
107
|
-
/**
|
|
108
|
-
|
|
209
|
+
/**
|
|
210
|
+
* Established WebSockets (upgraded client sockets), each keyed by the session
|
|
211
|
+
* that opened it. A socket outlives the request that authenticated it, so it
|
|
212
|
+
* has to be closable by session: on an epoch bump every socket dies, and on
|
|
213
|
+
* sign-out only that session's. The value is undefined for a cookie minted
|
|
214
|
+
* before per-session ids existed, which only a wholesale revocation reaches.
|
|
215
|
+
*/
|
|
216
|
+
private readonly activeDuplexes = new Map<Duplex, string | undefined>()
|
|
109
217
|
|
|
110
218
|
constructor(
|
|
111
219
|
private readonly config: GatewayConfig,
|
|
@@ -131,7 +239,14 @@ export class LanGateway {
|
|
|
131
239
|
this.state = state
|
|
132
240
|
}
|
|
133
241
|
|
|
134
|
-
/**
|
|
242
|
+
/**
|
|
243
|
+
* Start listening on the configured port. The listener is dual-stack: with
|
|
244
|
+
* no host given, node binds the unspecified IPv6 address `::` — which also
|
|
245
|
+
* accepts IPv4 clients, arriving as `::ffff:a.b.c.d` for the classifier to
|
|
246
|
+
* unwrap — when the host has IPv6, and falls back to `0.0.0.0` when it does
|
|
247
|
+
* not. Binding IPv4 only used to leave every IPv6 client (including `::1`)
|
|
248
|
+
* unable to reach a gateway that classifies them.
|
|
249
|
+
*/
|
|
135
250
|
async listen(): Promise<void> {
|
|
136
251
|
return new Promise((resolve, reject) => {
|
|
137
252
|
const onError = (err: Error): void => {
|
|
@@ -144,10 +259,18 @@ export class LanGateway {
|
|
|
144
259
|
}
|
|
145
260
|
this.server.once('error', onError)
|
|
146
261
|
this.server.once('listening', onListening)
|
|
147
|
-
this.server.listen(this.config.gatewayPort
|
|
262
|
+
this.server.listen(this.config.gatewayPort)
|
|
148
263
|
})
|
|
149
264
|
}
|
|
150
265
|
|
|
266
|
+
/** The address actually bound, for logs and status (never a claim about it). */
|
|
267
|
+
boundAddress(): string {
|
|
268
|
+
const address = this.server.address()
|
|
269
|
+
if (address === null || typeof address === 'string') return `port ${this.config.gatewayPort}`
|
|
270
|
+
const host = address.family === 'IPv6' ? `[${address.address}]` : address.address
|
|
271
|
+
return `${host}:${address.port}`
|
|
272
|
+
}
|
|
273
|
+
|
|
151
274
|
/** Close the server, drop upgraded sockets, and stop accepting connections. */
|
|
152
275
|
async close(): Promise<void> {
|
|
153
276
|
if (this.disposed) return
|
|
@@ -160,14 +283,23 @@ export class LanGateway {
|
|
|
160
283
|
}
|
|
161
284
|
|
|
162
285
|
private destroyActiveDuplexes(): void {
|
|
163
|
-
for (const socket of this.activeDuplexes) {
|
|
286
|
+
for (const socket of this.activeDuplexes.keys()) {
|
|
164
287
|
socket.destroy()
|
|
165
288
|
}
|
|
166
289
|
this.activeDuplexes.clear()
|
|
167
290
|
}
|
|
168
291
|
|
|
169
|
-
|
|
170
|
-
|
|
292
|
+
/** Close the sockets one session opened, so signing out ends its live streams too. */
|
|
293
|
+
private destroyDuplexesFor(sid: string): void {
|
|
294
|
+
for (const [socket, owner] of this.activeDuplexes) {
|
|
295
|
+
if (owner !== sid) continue
|
|
296
|
+
this.activeDuplexes.delete(socket)
|
|
297
|
+
socket.destroy()
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
private trackDuplex(socket: Duplex, sid: string | undefined): void {
|
|
302
|
+
this.activeDuplexes.set(socket, sid)
|
|
171
303
|
socket.on('close', () => {
|
|
172
304
|
this.activeDuplexes.delete(socket)
|
|
173
305
|
})
|
|
@@ -192,15 +324,27 @@ export class LanGateway {
|
|
|
192
324
|
return undefined
|
|
193
325
|
}
|
|
194
326
|
|
|
195
|
-
/**
|
|
196
|
-
|
|
327
|
+
/**
|
|
328
|
+
* The session a request carries, or undefined when it presents none, presents
|
|
329
|
+
* one that no longer verifies under the current epoch, or presents one whose
|
|
330
|
+
* id has been signed out.
|
|
331
|
+
*/
|
|
332
|
+
private session(req: http.IncomingMessage): SessionClaims | undefined {
|
|
197
333
|
const cookie = this.sessionCookie(req)
|
|
198
|
-
|
|
334
|
+
if (cookie === undefined) return undefined
|
|
335
|
+
const claims = verifySession(
|
|
199
336
|
this.state.cookieSecret,
|
|
200
337
|
cookie,
|
|
201
338
|
Date.now(),
|
|
202
339
|
this.state.sessionEpoch,
|
|
203
340
|
)
|
|
341
|
+
if (claims === undefined) return undefined
|
|
342
|
+
return isSessionRevoked(this.state, claims.sid) ? undefined : claims
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Whether a request carries a session valid under the current epoch. */
|
|
346
|
+
private authorized(req: http.IncomingMessage): boolean {
|
|
347
|
+
return this.session(req) !== undefined
|
|
204
348
|
}
|
|
205
349
|
|
|
206
350
|
/** Whether this source must present a gateway session (default: everyone). */
|
|
@@ -312,7 +456,7 @@ export class LanGateway {
|
|
|
312
456
|
return
|
|
313
457
|
}
|
|
314
458
|
|
|
315
|
-
void readBody(req, DEFAULT_BODY_LIMIT_BYTES, res).then((body) => {
|
|
459
|
+
void readBody(req, DEFAULT_BODY_LIMIT_BYTES, res).then(async (body) => {
|
|
316
460
|
if (body === undefined) return // response already sent (413/400)
|
|
317
461
|
let password: string | undefined
|
|
318
462
|
try {
|
|
@@ -321,23 +465,47 @@ export class LanGateway {
|
|
|
321
465
|
} catch {
|
|
322
466
|
password = undefined
|
|
323
467
|
}
|
|
324
|
-
|
|
468
|
+
const accepted = password !== undefined && await verifyPassword(this.state, password)
|
|
469
|
+
if (!accepted) {
|
|
325
470
|
this.serveLoginError(res, 'Incorrect password.')
|
|
326
471
|
return
|
|
327
472
|
}
|
|
328
473
|
const maxAgeSeconds = this.config.cookieMaxAgeDays * 86_400
|
|
329
474
|
const expiresMs = Date.now() + maxAgeSeconds * 1000
|
|
330
|
-
|
|
475
|
+
// Every session gets its own id so signing out can retire this one alone.
|
|
476
|
+
const cookie = signCookie(
|
|
477
|
+
this.state.cookieSecret,
|
|
478
|
+
expiresMs,
|
|
479
|
+
this.state.sessionEpoch,
|
|
480
|
+
newSessionId(),
|
|
481
|
+
)
|
|
331
482
|
res.writeHead(302, {
|
|
332
483
|
location: '/',
|
|
333
484
|
...this.securityHeaders(),
|
|
334
485
|
'set-cookie': [this.sessionSetCookie(cookie, maxAgeSeconds)],
|
|
335
486
|
})
|
|
336
487
|
res.end()
|
|
488
|
+
}).catch(() => {
|
|
489
|
+
// The body reader reports its own failures through the response; this
|
|
490
|
+
// catches the async verification path so it cannot become an unhandled
|
|
491
|
+
// rejection.
|
|
492
|
+
if (!res.headersSent) {
|
|
493
|
+
res.writeHead(500, this.securityHeaders())
|
|
494
|
+
res.end('login failed')
|
|
495
|
+
}
|
|
337
496
|
})
|
|
338
497
|
}
|
|
339
498
|
|
|
340
|
-
/**
|
|
499
|
+
/**
|
|
500
|
+
* POST /__logout: revoke this session and clear the cookie.
|
|
501
|
+
*
|
|
502
|
+
* The session is stateless, so clearing the cookie only stops the browser
|
|
503
|
+
* that ran the sign-out; a copy of the same value held anywhere else would
|
|
504
|
+
* keep working until it expired. Revoking the id in the cookie retires that
|
|
505
|
+
* one session for good, and leaves the account's other sessions — other
|
|
506
|
+
* devices, other browsers — alone. Bumping the session epoch here would be
|
|
507
|
+
* the blunter instrument: it signs out every session there is.
|
|
508
|
+
*/
|
|
341
509
|
private handleLogout(req: http.IncomingMessage, res: http.ServerResponse): void {
|
|
342
510
|
if (req.method !== 'POST') {
|
|
343
511
|
res.writeHead(405, { allow: 'POST' })
|
|
@@ -350,6 +518,12 @@ export class LanGateway {
|
|
|
350
518
|
res.end('forbidden')
|
|
351
519
|
return
|
|
352
520
|
}
|
|
521
|
+
const claims = this.session(req)
|
|
522
|
+
if (claims?.sid !== undefined) {
|
|
523
|
+
this.state = revokeSession(this.state, claims.sid, claims.exp)
|
|
524
|
+
this.config.onStateChange?.(this.state)
|
|
525
|
+
this.destroyDuplexesFor(claims.sid)
|
|
526
|
+
}
|
|
353
527
|
res.writeHead(302, {
|
|
354
528
|
location: '/',
|
|
355
529
|
...this.securityHeaders(),
|
|
@@ -371,6 +545,14 @@ export class LanGateway {
|
|
|
371
545
|
delete headers.connection
|
|
372
546
|
delete headers.upgrade
|
|
373
547
|
}
|
|
548
|
+
// A caller's own forwarding claims are not ours to relay.
|
|
549
|
+
for (const name of FORWARDING_HEADERS) delete headers[name]
|
|
550
|
+
// The relay is the only authority on the upstream session cookie.
|
|
551
|
+
if (typeof headers.cookie === 'string') {
|
|
552
|
+
const kept = withoutUpstreamSessionPairs(headers.cookie)
|
|
553
|
+
if (kept === '') delete headers.cookie
|
|
554
|
+
else headers.cookie = kept
|
|
555
|
+
}
|
|
374
556
|
return headers
|
|
375
557
|
}
|
|
376
558
|
|
|
@@ -387,6 +569,31 @@ export class LanGateway {
|
|
|
387
569
|
return true
|
|
388
570
|
}
|
|
389
571
|
|
|
572
|
+
/**
|
|
573
|
+
* The headers to send back to the client: hop-by-hop headers dropped, and
|
|
574
|
+
* the upstream session cookie withheld. Upstream's one cookie-minting route
|
|
575
|
+
* is the launch-token exchange at `/`, so a client that already holds a
|
|
576
|
+
* gateway session could otherwise post the token through the gateway and
|
|
577
|
+
* walk away with a durable upstream credential the relay exists to keep on
|
|
578
|
+
* this side. Cookies from other routes (plugins) still pass through.
|
|
579
|
+
*/
|
|
580
|
+
private downstreamHeaders(upstream: http.IncomingHttpHeaders): http.OutgoingHttpHeaders {
|
|
581
|
+
const headers: http.OutgoingHttpHeaders = {}
|
|
582
|
+
for (const [key, value] of Object.entries(upstream)) {
|
|
583
|
+
if (value === undefined) continue
|
|
584
|
+
const lower = key.toLowerCase()
|
|
585
|
+
if (HOP_BY_HOP_HEADERS.has(lower)) continue
|
|
586
|
+
if (lower === 'set-cookie') {
|
|
587
|
+
const list = (Array.isArray(value) ? value : [value])
|
|
588
|
+
.filter((entry) => !isUpstreamSessionPair(entry.trim()))
|
|
589
|
+
if (list.length > 0) headers[key] = list
|
|
590
|
+
continue
|
|
591
|
+
}
|
|
592
|
+
headers[key] = value
|
|
593
|
+
}
|
|
594
|
+
return headers
|
|
595
|
+
}
|
|
596
|
+
|
|
390
597
|
/** Forward an HTTP request to dsh, replaying the shared upstream session. */
|
|
391
598
|
private async relayHttp(req: http.IncomingMessage, res: http.ServerResponse, url: string): Promise<void> {
|
|
392
599
|
const session = this.config.upstreamSession
|
|
@@ -407,7 +614,7 @@ export class LanGateway {
|
|
|
407
614
|
if (attached && session !== undefined && proxyRes.statusCode === 401) {
|
|
408
615
|
session.invalidate()
|
|
409
616
|
}
|
|
410
|
-
res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers)
|
|
617
|
+
res.writeHead(proxyRes.statusCode ?? 502, this.downstreamHeaders(proxyRes.headers))
|
|
411
618
|
proxyRes.pipe(res)
|
|
412
619
|
})
|
|
413
620
|
proxyReq.on('error', () => {
|
|
@@ -436,7 +643,10 @@ export class LanGateway {
|
|
|
436
643
|
return
|
|
437
644
|
}
|
|
438
645
|
|
|
439
|
-
|
|
646
|
+
// The session is read once: the socket this upgrade ends up holding stays
|
|
647
|
+
// attributable to it, so signing that session out can close the socket.
|
|
648
|
+
const claims = this.session(req)
|
|
649
|
+
if (this.requiresLogin(source) && claims === undefined) {
|
|
440
650
|
refuse(401)
|
|
441
651
|
return
|
|
442
652
|
}
|
|
@@ -462,7 +672,7 @@ export class LanGateway {
|
|
|
462
672
|
headers,
|
|
463
673
|
})
|
|
464
674
|
proxyReq.on('upgrade', (proxyRes, proxySocket, proxyHead) => {
|
|
465
|
-
this.trackDuplex(socket)
|
|
675
|
+
this.trackDuplex(socket, claims?.sid)
|
|
466
676
|
// node's http client has already consumed the 101 response headers, so
|
|
467
677
|
// reconstruct them on the client socket before splicing.
|
|
468
678
|
const statusLine = `HTTP/1.1 ${proxyRes.statusCode ?? 101} ${proxyRes.statusMessage ?? 'Switching Protocols'}\r\n`
|
package/src/index.ts
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
*
|
|
5
5
|
* dsh's web CLI hard-refuses `--host 0.0.0.0` (exposing remote code execution
|
|
6
6
|
* to the network), so this plugin leaves dsh bound to 127.0.0.1 and starts its
|
|
7
|
-
* own reverse-proxy gateway on
|
|
7
|
+
* own reverse-proxy gateway on the unspecified address — both families, so
|
|
8
|
+
* IPv6 clients reach it too — that forwards to the loopback dsh port,
|
|
8
9
|
* rewriting Host/Origin so the request reaches the dsh web server as if it came
|
|
9
10
|
* from the loopback authority it names.
|
|
10
11
|
*
|
|
@@ -22,8 +23,10 @@
|
|
|
22
23
|
* TLS-terminating proxy, or an explicit `allowInsecurePlaintext` opt-in is
|
|
23
24
|
* present.
|
|
24
25
|
* - The gateway never relays its own surface (`/lan-gateway/*`, the login and
|
|
25
|
-
* logout pages)
|
|
26
|
-
*
|
|
26
|
+
* logout pages). Sessions are revocable: each carries a random id, so signing
|
|
27
|
+
* out retires that one session and the WebSockets it opened, and each carries
|
|
28
|
+
* a revocation epoch, so a password change or secret rotation kills every
|
|
29
|
+
* session at once.
|
|
27
30
|
*
|
|
28
31
|
* Every tunable is also exposed as the `lan-gateway` user-settings namespace
|
|
29
32
|
* (`ctx.settings`), so the official DSH Settings → Plugins page can adjust
|
|
@@ -56,6 +59,7 @@ import {
|
|
|
56
59
|
describeCert,
|
|
57
60
|
loadCustomCert,
|
|
58
61
|
loadOrCreateSelfSigned,
|
|
62
|
+
loadOrRenewSelfSigned,
|
|
59
63
|
parseSelfSignedHosts,
|
|
60
64
|
regenerateSelfSigned,
|
|
61
65
|
type TlsMaterial,
|
|
@@ -113,7 +117,7 @@ export interface GatewayController {
|
|
|
113
117
|
export interface Config {
|
|
114
118
|
/** Whether the gateway listener is started at boot. Default false (safe). */
|
|
115
119
|
enabled: boolean
|
|
116
|
-
/** Port to bind on
|
|
120
|
+
/** Port to bind on the unspecified address, both address families. */
|
|
117
121
|
gatewayPort: number
|
|
118
122
|
/** Explicit dsh target port; defaults to the live `ctx.webServer.port`. */
|
|
119
123
|
dshTargetPort?: number
|
|
@@ -145,7 +149,18 @@ export interface Config {
|
|
|
145
149
|
tlsKeyPath?: string
|
|
146
150
|
/** Self-signed mode: comma/space separated DNS names and IPs for the SANs. */
|
|
147
151
|
tlsSelfSignedHosts?: string
|
|
148
|
-
/**
|
|
152
|
+
/**
|
|
153
|
+
* Self-signed certificate validity in days (default 825 ≈ 27 months).
|
|
154
|
+
*
|
|
155
|
+
* 825 is the ceiling Apple states for TLS server certificates, and the
|
|
156
|
+
* well-known 398-day limit — which this default is sometimes mistaken for
|
|
157
|
+
* exceeding — applies only to certificates chaining to a root preinstalled
|
|
158
|
+
* by the platform: Apple exempts user- and administrator-added roots
|
|
159
|
+
* outright, and a self-signed certificate is always one of those. Since a
|
|
160
|
+
* self-signed certificate is either clicked through or trusted by hand,
|
|
161
|
+
* there is nothing to gain from the shorter window and a re-trust to lose
|
|
162
|
+
* every time it lapses.
|
|
163
|
+
*/
|
|
149
164
|
tlsCertMaxAgeDays: number
|
|
150
165
|
/**
|
|
151
166
|
* Escape hatch (default false): permit plaintext HTTP. Never derived from
|
|
@@ -158,6 +173,14 @@ export interface Config {
|
|
|
158
173
|
* encrypted-ingress gate) without this listener sending HSTS.
|
|
159
174
|
*/
|
|
160
175
|
trustedTerminator?: string
|
|
176
|
+
/**
|
|
177
|
+
* Explicit override for the session cookie's `Secure` attribute. Unset =
|
|
178
|
+
* automatic: Secure when the gateway serves TLS itself or a
|
|
179
|
+
* `trustedTerminator` is declared. Set `false` when the trusted proxy fronts
|
|
180
|
+
* a plaintext browser ingress — browsers refuse to store a Secure cookie over
|
|
181
|
+
* plain HTTP, so every login would bounce straight back to `/__login`.
|
|
182
|
+
*/
|
|
183
|
+
secureCookies?: boolean
|
|
161
184
|
}
|
|
162
185
|
|
|
163
186
|
/**
|
|
@@ -189,6 +212,7 @@ export const Config: z<Config> = z.object({
|
|
|
189
212
|
tlsCertMaxAgeDays: z.natural().min(1).max(3650).default(825),
|
|
190
213
|
allowInsecurePlaintext: z.boolean().default(false),
|
|
191
214
|
trustedTerminator: z.string(),
|
|
215
|
+
secureCookies: z.boolean(),
|
|
192
216
|
})
|
|
193
217
|
|
|
194
218
|
/** Facts the fail-closed start guard needs to judge a config. */
|
|
@@ -227,18 +251,39 @@ export function gatewayStartProblems(cfg: Config, facts: StartFacts): string[] {
|
|
|
227
251
|
return problems
|
|
228
252
|
}
|
|
229
253
|
|
|
254
|
+
/**
|
|
255
|
+
* Resolve the effective `Secure` attribute for the session cookie: an explicit
|
|
256
|
+
* `secureCookies` always wins; unset falls back to automatic — Secure when the
|
|
257
|
+
* gateway terminates TLS itself or a trusted terminator is declared. The
|
|
258
|
+
* override exists for a trusted proxy that authenticates users but speaks plain
|
|
259
|
+
* HTTP to browsers: `encryptedIngress` is a fair proxy for "a proxy is in front"
|
|
260
|
+
* but not for "the browser leg is encrypted", and a Secure cookie on a plain
|
|
261
|
+
* HTTP origin is silently dropped, looping the login.
|
|
262
|
+
*
|
|
263
|
+
* Exported for tests.
|
|
264
|
+
*/
|
|
265
|
+
export function resolveSecureCookies(
|
|
266
|
+
cfg: Pick<Config, 'secureCookies' | 'tlsEnabled' | 'trustedTerminator'>,
|
|
267
|
+
): boolean {
|
|
268
|
+
// Test for a real boolean, not just `!== undefined`: the settings route
|
|
269
|
+
// clears a key by posting null and schemastery passes that through rather
|
|
270
|
+
// than coercing it to undefined, so `null` reaches here on the save path.
|
|
271
|
+
// Only an explicit true/false overrides the automatic rule.
|
|
272
|
+
if (typeof cfg.secureCookies === 'boolean') return cfg.secureCookies
|
|
273
|
+
return cfg.tlsEnabled || cfg.trustedTerminator !== undefined
|
|
274
|
+
}
|
|
275
|
+
|
|
230
276
|
/** Resolve the TLS material for a config, or undefined when TLS is off. */
|
|
231
|
-
function resolveTls(cfg: Config): TlsMaterial | undefined {
|
|
277
|
+
function resolveTls(cfg: Config): { material: TlsMaterial; renewed: boolean } | undefined {
|
|
232
278
|
if (!cfg.tlsEnabled) return undefined
|
|
233
279
|
if (cfg.tlsMode === 'custom') {
|
|
234
|
-
return loadCustomCert(cfg.tlsCertPath ?? '', cfg.tlsKeyPath ?? '')
|
|
280
|
+
return { material: loadCustomCert(cfg.tlsCertPath ?? '', cfg.tlsKeyPath ?? ''), renewed: false }
|
|
235
281
|
}
|
|
236
282
|
const hosts = parseSelfSignedHosts(cfg.tlsSelfSignedHosts)
|
|
237
283
|
if (hosts.length === 0) {
|
|
238
284
|
throw new Error('tlsSelfSignedHosts must name at least one host (DNS name or IP)')
|
|
239
285
|
}
|
|
240
|
-
|
|
241
|
-
return material
|
|
286
|
+
return loadOrRenewSelfSigned({ hosts, days: cfg.tlsCertMaxAgeDays })
|
|
242
287
|
}
|
|
243
288
|
|
|
244
289
|
/**
|
|
@@ -265,6 +310,7 @@ function listenerKey(cfg: Config, relayAvailable: boolean): string {
|
|
|
265
310
|
cfg.tlsCertMaxAgeDays,
|
|
266
311
|
cfg.allowInsecurePlaintext,
|
|
267
312
|
cfg.trustedTerminator,
|
|
313
|
+
cfg.secureCookies,
|
|
268
314
|
relayAvailable,
|
|
269
315
|
])
|
|
270
316
|
}
|
|
@@ -351,8 +397,10 @@ export function apply(ctx: Context, config: Config): void {
|
|
|
351
397
|
throw new Error(`dsh-lan-gateway: cannot start — ${problems.join(' ')}`)
|
|
352
398
|
}
|
|
353
399
|
const dshPort = cfg.dshTargetPort ?? ctx.webServer.port
|
|
354
|
-
const
|
|
400
|
+
const resolved = resolveTls(cfg)
|
|
401
|
+
const tls = resolved?.material
|
|
355
402
|
const encryptedIngress = cfg.tlsEnabled || cfg.trustedTerminator !== undefined
|
|
403
|
+
const secureCookies = resolveSecureCookies(cfg)
|
|
356
404
|
const next = new LanGateway({
|
|
357
405
|
gatewayPort: cfg.gatewayPort,
|
|
358
406
|
dshPort,
|
|
@@ -360,18 +408,31 @@ export function apply(ctx: Context, config: Config): void {
|
|
|
360
408
|
lanPasswordless: cfg.lanPasswordless,
|
|
361
409
|
cookieMaxAgeDays: cfg.cookieMaxAgeDays,
|
|
362
410
|
cookieName: cfg.cookieName,
|
|
363
|
-
secureCookies
|
|
411
|
+
secureCookies,
|
|
364
412
|
...(tls !== undefined ? { tls } : {}),
|
|
365
413
|
...(makeRelay !== undefined ? { upstreamSession: makeRelay(dshPort) } : {}),
|
|
414
|
+
onStateChange: (updated) => {
|
|
415
|
+
// The gateway retired a session itself (sign-out). Keep the plugin's
|
|
416
|
+
// copy and the state file in step, or a restart would resurrect a
|
|
417
|
+
// session the user signed out of.
|
|
418
|
+
state = updated
|
|
419
|
+
saveState(state)
|
|
420
|
+
},
|
|
366
421
|
}, state)
|
|
367
422
|
await next.listen()
|
|
368
423
|
gateway = next
|
|
369
424
|
startedWith = listenerKey(cfg, makeRelay !== undefined)
|
|
370
425
|
ctx.logger.info(
|
|
371
|
-
`dsh-lan-gateway: listening on
|
|
426
|
+
`dsh-lan-gateway: listening on ${next.boundAddress()}${tls !== undefined ? ' (TLS)' : ''}`
|
|
372
427
|
+ ` -> 127.0.0.1:${dshPort}${encryptedIngress ? '' : ' (plaintext, explicit allowInsecurePlaintext)'}`
|
|
373
428
|
+ `${makeRelay !== undefined ? ' [shared upstream session relay]' : ' [no upstream session relay: base has no browser-session auth]'}`,
|
|
374
429
|
)
|
|
430
|
+
if (resolved?.renewed === true) {
|
|
431
|
+
ctx.logger.warn(
|
|
432
|
+
'dsh-lan-gateway: the self-signed certificate had expired and was replaced with a fresh one '
|
|
433
|
+
+ '— clients that had trusted the old certificate must trust the new one.',
|
|
434
|
+
)
|
|
435
|
+
}
|
|
375
436
|
}
|
|
376
437
|
|
|
377
438
|
const stopGateway = async (): Promise<void> => {
|
|
@@ -435,9 +496,13 @@ export function apply(ctx: Context, config: Config): void {
|
|
|
435
496
|
// gateway forwards without a relay, and lanPasswordless stays refused.
|
|
436
497
|
ctx.inject(['connection'], (ccx) => {
|
|
437
498
|
upstreamSessionAvailable = true
|
|
499
|
+
ctx.logger.info('dsh-lan-gateway: connection service attached; upstream session relay enabled')
|
|
438
500
|
makeRelay = (dshPort) => new UpstreamSessionRelay({
|
|
439
501
|
port: dshPort,
|
|
440
502
|
authenticatedUrl: () => ccx.connection.authenticatedUrl(`http://127.0.0.1:${dshPort}`),
|
|
503
|
+
// The relay never throws, so a failing exchange is otherwise invisible
|
|
504
|
+
// and looks exactly like a base with no browser sessions.
|
|
505
|
+
log: (message) => ctx.logger.info(`dsh-lan-gateway relay: ${message}`),
|
|
441
506
|
})
|
|
442
507
|
// A listener that started before the connection service appeared must
|
|
443
508
|
// restart so it picks up the relay (and the now-correct fail-closed facts).
|
|
@@ -553,14 +618,15 @@ export function apply(ctx: Context, config: Config): void {
|
|
|
553
618
|
return {
|
|
554
619
|
ok: true,
|
|
555
620
|
message:
|
|
556
|
-
`LAN gateway: ${gateway !== undefined ? `LISTENING on
|
|
621
|
+
`LAN gateway: ${gateway !== undefined ? `LISTENING on ${gateway.boundAddress()}` : 'stopped'}`
|
|
557
622
|
+ `\n- dsh target: 127.0.0.1:${dshPort}`
|
|
558
623
|
+ `\n- password: ${state.password !== undefined ? 'set' : 'NOT SET'}`
|
|
559
624
|
+ `\n- login required for all sources: true${cfg.lanPasswordless ? ' (LAN/loopback exempt via lanPasswordless)' : ''}`
|
|
560
625
|
+ `\n- session epoch: ${state.sessionEpoch}`
|
|
626
|
+
+ `\n- signed-out sessions still held: ${Object.keys(state.revokedSessions ?? {}).length} (each drops when its own cookie would have expired)`
|
|
561
627
|
+ `\n- upstream session relay: ${upstreamSessionAvailable ? 'active (dsh browser-session auth present)' : 'absent (older dsh base)'}`
|
|
562
|
-
+ `\n- ingress: ${cfg.tlsEnabled ? `TLS (${tlsStatusLine(cfg)})` : cfg.trustedTerminator !== undefined ? `
|
|
563
|
-
+ `\n- session cookie: ${cfg.cookieName}, ${cfg.cookieMaxAgeDays}d`
|
|
628
|
+
+ `\n- ingress: ${cfg.tlsEnabled ? `TLS (${tlsStatusLine(cfg)})` : cfg.trustedTerminator !== undefined ? `trusted proxy (${cfg.trustedTerminator}, ${resolveSecureCookies(cfg) ? 'TLS' : 'plaintext'} browser ingress)` : encrypted ? 'encrypted' : cfg.allowInsecurePlaintext ? 'PLAINTEXT (explicit allowInsecurePlaintext)' : 'plaintext — will not start'}`
|
|
629
|
+
+ `\n- session cookie: ${cfg.cookieName}, ${cfg.cookieMaxAgeDays}d, ${resolveSecureCookies(cfg) ? 'Secure' : 'no Secure attribute (plaintext browser ingress)'}`
|
|
564
630
|
+ (manualOverride !== undefined
|
|
565
631
|
? `\n- manual override: ${manualOverride ? 'enabled' : 'disabled'}`
|
|
566
632
|
: '')
|
|
@@ -571,7 +637,7 @@ export function apply(ctx: Context, config: Config): void {
|
|
|
571
637
|
manualOverride = true
|
|
572
638
|
await syncGateway('tool enable')
|
|
573
639
|
return gateway !== undefined
|
|
574
|
-
? { ok: true, message: `Gateway enabled: listening on
|
|
640
|
+
? { ok: true, message: `Gateway enabled: listening on ${gateway.boundAddress()}` }
|
|
575
641
|
: { ok: false, message: `Failed to enable gateway: ${lastError ?? 'unknown error'}` }
|
|
576
642
|
},
|
|
577
643
|
async disable(): Promise<ToolResult> {
|