@gitsang/dsh-gateway 0.0.0-stage → 0.5.0
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/LICENSE +21 -0
- package/README.md +421 -2
- package/cordis.patch.yml +15 -0
- package/package.json +63 -4
- package/src/client.js +469 -0
- package/src/index.js +582 -0
- package/src/pages.js +149 -0
- package/src/proxy.js +599 -0
- package/src/pwa.js +271 -0
- package/src/settings-store.js +95 -0
- package/src/stores.js +51 -0
- package/src/token-store.js +77 -0
package/src/index.js
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
import { createServer } from 'node:http'
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
3
|
+
import { copyFile, mkdir, stat } from 'node:fs/promises'
|
|
4
|
+
import { networkInterfaces, homedir } from 'node:os'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import { Service } from '@deepseek-ai/cordis'
|
|
7
|
+
import z from '@deepseek-ai/schemastery'
|
|
8
|
+
import { dshCookieName, probeBrowserSession, proxyRequest, proxyUpgrade, targetAuthority } from './proxy.js'
|
|
9
|
+
import { readRequestBody } from './pages.js'
|
|
10
|
+
import { ICON_SVG, MANIFEST, SW_DISABLED_JS, SW_JS } from './pwa.js'
|
|
11
|
+
import { GatewaySettingsStore } from './settings-store.js'
|
|
12
|
+
import { LaunchTokenStore } from './token-store.js'
|
|
13
|
+
|
|
14
|
+
export const name = 'gateway'
|
|
15
|
+
// `connection` is optional: the gateway still proxies when a composition omits
|
|
16
|
+
// the browser transport, it just cannot print a tokenized sign-in URL then.
|
|
17
|
+
export const inject = ['webServer']
|
|
18
|
+
|
|
19
|
+
export const GATEWAY_API_PREFIX = '/__dsh_gateway'
|
|
20
|
+
const PACKAGE_VERSION = JSON.parse(
|
|
21
|
+
readFileSync(new URL('../package.json', import.meta.url), 'utf8')
|
|
22
|
+
).version
|
|
23
|
+
|
|
24
|
+
const HOST_ENV = ['DSH_GATEWAY_HOST']
|
|
25
|
+
const PORT_ENV = ['DSH_GATEWAY_PORT']
|
|
26
|
+
const DATA_DIR_ENV = ['DSH_GATEWAY_DATA_DIR']
|
|
27
|
+
const PWA_ENV = ['DSH_GATEWAY_PWA']
|
|
28
|
+
const HOST_MODE_ENV = ['DSH_GATEWAY_HOST_MODE']
|
|
29
|
+
const TOKEN_ENV = ['DSH_GATEWAY_TOKEN']
|
|
30
|
+
|
|
31
|
+
/** Read the first non-empty environment variable from a compatibility list. */
|
|
32
|
+
function envValue(names) {
|
|
33
|
+
for (const name of names) {
|
|
34
|
+
const value = process.env[name]
|
|
35
|
+
if (value !== undefined && value !== '') return value
|
|
36
|
+
}
|
|
37
|
+
return undefined
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function envString(names, fallback) {
|
|
41
|
+
return envValue(names) ?? fallback
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function envInt(names, fallback) {
|
|
45
|
+
const raw = envValue(names)
|
|
46
|
+
if (raw === undefined) return fallback
|
|
47
|
+
const value = Number(raw)
|
|
48
|
+
return Number.isInteger(value) && value >= 0 ? value : fallback
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function parseBool(raw) {
|
|
52
|
+
return raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on'
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function envBool(names, fallback) {
|
|
56
|
+
const raw = envValue(names)
|
|
57
|
+
return raw === undefined ? fallback : parseBool(raw)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** `undefined` means the setting is not environment-locked. */
|
|
61
|
+
function envBoolOverride(names) {
|
|
62
|
+
const raw = envValue(names)
|
|
63
|
+
return raw === undefined ? undefined : parseBool(raw)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The gateway's data directory: `$DSH_HOME/gateway` unless overridden.
|
|
68
|
+
*
|
|
69
|
+
* This is plugin state, not a dsh profile. `profiles/` is reserved for
|
|
70
|
+
* bootable profiles — anything placed there can be booted (`dsh gateway`),
|
|
71
|
+
* and dsh writes profile scaffolding (cordis.yml, package.json) into it. The
|
|
72
|
+
* gateway's own files therefore live beside `profiles/`, like dsh's other
|
|
73
|
+
* home-level state (`bridge/`, `daemon/`, `.credentials.yaml`).
|
|
74
|
+
*/
|
|
75
|
+
function defaultDataDir() {
|
|
76
|
+
const explicit = envValue(DATA_DIR_ENV)
|
|
77
|
+
if (explicit !== undefined) return explicit
|
|
78
|
+
const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
79
|
+
return join(dshHome, 'gateway')
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Copy the token forward from the pre-0.5 location (`$DSH_HOME/profiles/gateway`).
|
|
84
|
+
*
|
|
85
|
+
* Only the default location migrates, and only files the new directory does
|
|
86
|
+
* not already have: an explicit DSH_GATEWAY_DATA_DIR or an existing new-style
|
|
87
|
+
* file always wins. The old files are left in place — that directory may
|
|
88
|
+
* double as a real dsh profile, so the gateway must not delete from it.
|
|
89
|
+
* Settings migrate separately, into the profile directory (GatewaySettingsStore).
|
|
90
|
+
*
|
|
91
|
+
* @param dataDir - resolved data directory.
|
|
92
|
+
* @param logger - logger for the one-time migration notice.
|
|
93
|
+
*/
|
|
94
|
+
export async function migrateLegacyDataDir(dataDir, logger) {
|
|
95
|
+
if (envValue(DATA_DIR_ENV) !== undefined) return
|
|
96
|
+
const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
97
|
+
if (dataDir !== join(dshHome, 'gateway')) return
|
|
98
|
+
const legacy = join(dshHome, 'profiles', 'gateway')
|
|
99
|
+
const migrated = []
|
|
100
|
+
for (const name of ['token.txt']) {
|
|
101
|
+
try {
|
|
102
|
+
await stat(join(dataDir, name))
|
|
103
|
+
continue // The new location already owns this file.
|
|
104
|
+
} catch {
|
|
105
|
+
// Not present yet; try the legacy copy.
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
await mkdir(dataDir, { recursive: true })
|
|
109
|
+
await copyFile(join(legacy, name), join(dataDir, name))
|
|
110
|
+
migrated.push(name)
|
|
111
|
+
} catch (err) {
|
|
112
|
+
if (err?.code !== 'ENOENT') throw err
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (migrated.length > 0) {
|
|
116
|
+
logger?.info(`dsh-gateway: moved ${migrated.join(', ')} from ${legacy} to ${dataDir}; the old copies are unused and can be deleted`)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export const Config = z.object({
|
|
121
|
+
host: z.string().default(envString(HOST_ENV, '127.0.0.1')),
|
|
122
|
+
// The default port is derived from the dsh web port at startup; this env
|
|
123
|
+
// var only overrides it when explicitly set.
|
|
124
|
+
port: z.natural().max(65535).default(envInt(PORT_ENV)),
|
|
125
|
+
dataDir: z.string().default(defaultDataDir()),
|
|
126
|
+
pwa: z.boolean().default(envBool(PWA_ENV, true)),
|
|
127
|
+
// Declare the proxied page as a host-owning page so dsh uses Host settings
|
|
128
|
+
// (Models page, "open configuration file") instead of its read-only memory
|
|
129
|
+
// fallback. On by default because a remote dsh web UI is unusable without it;
|
|
130
|
+
// it does hand every signed-in user the same configuration-write surface the
|
|
131
|
+
// Desktop shell has, so the settings page can turn it off.
|
|
132
|
+
hostMode: z.boolean().default(envBool(HOST_MODE_ENV, true))
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
function upstreamTarget(webServer) {
|
|
136
|
+
return {
|
|
137
|
+
host: '127.0.0.1',
|
|
138
|
+
port: webServer.port
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function lanAddresses() {
|
|
143
|
+
return Object.values(networkInterfaces())
|
|
144
|
+
.flat()
|
|
145
|
+
.filter((iface) => iface !== undefined && iface.family === 'IPv4' && !iface.internal)
|
|
146
|
+
.map((iface) => iface.address)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Replace dsh's per-process launch token with the gateway's persistent one.
|
|
151
|
+
*
|
|
152
|
+
* dsh keeps the token as a plain property on its Connection service's
|
|
153
|
+
* BrowserAuth (`connection.browserAuth.launchToken`); every consumer —
|
|
154
|
+
* `authenticatedUrl`, the index exchange, `/connect` — reads that property at
|
|
155
|
+
* call time, so assigning it before any request arrives changes the accepted
|
|
156
|
+
* token for the whole process. This is a deliberate dependency on a dsh
|
|
157
|
+
* internal: the field is verified through the public `authenticatedUrl()`
|
|
158
|
+
* afterwards, and a dsh version that moves it degrades to the stock behavior
|
|
159
|
+
* (fresh token per restart) with a warning instead of breaking sign-in.
|
|
160
|
+
*
|
|
161
|
+
* @param connection - dsh's Connection service.
|
|
162
|
+
* @param token - the persistent token to install.
|
|
163
|
+
* @param logger - logger for the compatibility warning.
|
|
164
|
+
* @returns true when the installed token is the one dsh now advertises.
|
|
165
|
+
*/
|
|
166
|
+
export function installLaunchToken(connection, token, logger) {
|
|
167
|
+
const auth = connection?.browserAuth
|
|
168
|
+
if (auth === undefined || typeof auth.launchToken !== 'string') {
|
|
169
|
+
logger?.warn('dsh-gateway: this dsh version exposes no browserAuth.launchToken; the sign-in token rotates on every restart')
|
|
170
|
+
return false
|
|
171
|
+
}
|
|
172
|
+
auth.launchToken = token
|
|
173
|
+
try {
|
|
174
|
+
const advertised = new URL(connection.authenticatedUrl('http://127.0.0.1/')).searchParams.get('token')
|
|
175
|
+
if (advertised === token) return true
|
|
176
|
+
} catch {
|
|
177
|
+
// Fall through to the warning.
|
|
178
|
+
}
|
|
179
|
+
logger?.warn('dsh-gateway: installing the persistent launch token did not take effect; the sign-in token rotates on every restart')
|
|
180
|
+
return false
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
class DshGateway extends Service {
|
|
184
|
+
static Config = Config
|
|
185
|
+
|
|
186
|
+
constructor(ctx, config) {
|
|
187
|
+
super(ctx, 'gateway')
|
|
188
|
+
this.config = config
|
|
189
|
+
// Settings are profile-scoped configuration: they live inside the profile
|
|
190
|
+
// directory so a dotfiles checkout carries them. The token is a credential
|
|
191
|
+
// and stays in the home-level data directory. Pre-0.5.0 settings locations
|
|
192
|
+
// are adopted on first init; the current file always wins.
|
|
193
|
+
const profileDir = ctx.get('profileContext')?.dir
|
|
194
|
+
const settingsFile = profileDir !== undefined
|
|
195
|
+
? join(profileDir, 'gateway', 'settings.json')
|
|
196
|
+
: join(config.dataDir, 'settings.json')
|
|
197
|
+
const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
198
|
+
this.settings = new GatewaySettingsStore(settingsFile, [
|
|
199
|
+
join(config.dataDir, 'settings.json'),
|
|
200
|
+
join(dshHome, 'profiles', 'gateway', 'settings.json'),
|
|
201
|
+
])
|
|
202
|
+
this.launchToken = new LaunchTokenStore(
|
|
203
|
+
join(config.dataDir, 'token.txt'),
|
|
204
|
+
envValue(TOKEN_ENV),
|
|
205
|
+
ctx.logger
|
|
206
|
+
)
|
|
207
|
+
this.persistentToken = false
|
|
208
|
+
this.envOverrides = {
|
|
209
|
+
pwa: envBoolOverride(PWA_ENV),
|
|
210
|
+
hostMode: envBoolOverride(HOST_MODE_ENV)
|
|
211
|
+
}
|
|
212
|
+
this.runtimePwa = config.pwa
|
|
213
|
+
this.bootHostMode = config.hostMode
|
|
214
|
+
this.configuredHostMode = config.hostMode
|
|
215
|
+
this.startedAt = Date.now()
|
|
216
|
+
this.target = null
|
|
217
|
+
this.server = null
|
|
218
|
+
this.proxyPort = null
|
|
219
|
+
this.sockets = new Set()
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async [Service.init]() {
|
|
223
|
+
await migrateLegacyDataDir(this.config.dataDir, this.ctx.logger)
|
|
224
|
+
await Promise.all([this.settings.init(), this.launchToken.init()])
|
|
225
|
+
|
|
226
|
+
const saved = this.settings.snapshot()
|
|
227
|
+
this.runtimePwa = this.envOverrides.pwa ?? saved.pwa ?? this.config.pwa
|
|
228
|
+
this.bootHostMode = this.envOverrides.hostMode ?? saved.hostMode ?? this.config.hostMode
|
|
229
|
+
this.configuredHostMode = this.bootHostMode
|
|
230
|
+
this.config = { ...this.config, pwa: this.runtimePwa, hostMode: this.bootHostMode }
|
|
231
|
+
|
|
232
|
+
const target = upstreamTarget(this.ctx.webServer)
|
|
233
|
+
this.target = target
|
|
234
|
+
// The gateway listens next to dsh web by default (web port + 1).
|
|
235
|
+
// DSH_GATEWAY_PORT can still override this.
|
|
236
|
+
this.config = { ...this.config, port: this.config.port ?? Number(target.port) + 1 }
|
|
237
|
+
const listenPort = this.config.port
|
|
238
|
+
this.server = createServer((req, res) => {
|
|
239
|
+
this.handle(req, res, target).catch((err) => {
|
|
240
|
+
this.ctx.logger.error(err)
|
|
241
|
+
if (res.headersSent) {
|
|
242
|
+
res.destroy()
|
|
243
|
+
return
|
|
244
|
+
}
|
|
245
|
+
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
|
|
246
|
+
res.end('dsh-gateway: internal error')
|
|
247
|
+
})
|
|
248
|
+
})
|
|
249
|
+
|
|
250
|
+
this.server.on('connection', (socket) => {
|
|
251
|
+
this.sockets.add(socket)
|
|
252
|
+
socket.on('close', () => this.sockets.delete(socket))
|
|
253
|
+
})
|
|
254
|
+
|
|
255
|
+
this.server.on('upgrade', (req, socket, head) => {
|
|
256
|
+
this.sockets.add(socket)
|
|
257
|
+
socket.on('close', () => this.sockets.delete(socket))
|
|
258
|
+
this.handleUpgrade(req, socket, head, target).catch((err) => {
|
|
259
|
+
this.ctx.logger.error(err)
|
|
260
|
+
socket.destroy()
|
|
261
|
+
})
|
|
262
|
+
})
|
|
263
|
+
|
|
264
|
+
await new Promise((resolve, reject) => {
|
|
265
|
+
const onError = (err) => {
|
|
266
|
+
this.server.off('listening', onListening)
|
|
267
|
+
reject(err)
|
|
268
|
+
}
|
|
269
|
+
const onListening = () => {
|
|
270
|
+
this.server.off('error', onError)
|
|
271
|
+
this.server.on('error', (err) => this.ctx.logger.error(err))
|
|
272
|
+
const address = this.server.address()
|
|
273
|
+
this.proxyPort = typeof address === 'object' && address !== null ? address.port : listenPort
|
|
274
|
+
resolve()
|
|
275
|
+
}
|
|
276
|
+
this.server.once('error', onError)
|
|
277
|
+
this.server.once('listening', onListening)
|
|
278
|
+
this.server.listen(listenPort, this.config.host)
|
|
279
|
+
})
|
|
280
|
+
|
|
281
|
+
this.ctx.effect(() => async () => this.close(), 'gateway.proxy')
|
|
282
|
+
|
|
283
|
+
// Primary Host-mode carrier: declare the transport flag inside dsh's own
|
|
284
|
+
// index.html, so it survives proxies that cache or rewrite our responses.
|
|
285
|
+
// The switch is evaluated at boot; changing it needs a restart.
|
|
286
|
+
if (this.bootHostMode) {
|
|
287
|
+
this.ctx.inject(['webServer'], (webCtx) => {
|
|
288
|
+
webCtx.on('webserver/index-inject', (table) => {
|
|
289
|
+
table.push({ kind: 'global', name: '__DSH_TRANSPORT__', value: { ownsHost: true } })
|
|
290
|
+
})
|
|
291
|
+
})
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
this.printUrl(target)
|
|
295
|
+
|
|
296
|
+
// Connection mounts after this row in the shipped web composition, so the
|
|
297
|
+
// launch token only exists once that service appears. Waiving readiness is
|
|
298
|
+
// safe: this is a log line, not part of serving traffic.
|
|
299
|
+
this.ctx.inject(['connection'], (connCtx) => {
|
|
300
|
+
this.persistentToken = installLaunchToken(
|
|
301
|
+
connCtx.get('connection'),
|
|
302
|
+
this.launchToken.token,
|
|
303
|
+
this.ctx.logger
|
|
304
|
+
)
|
|
305
|
+
this.printSignInUrl(target)
|
|
306
|
+
})
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* A tokenized application URL for the loopback `authority`, from dsh's
|
|
311
|
+
* Connection service. dsh exchanges that token for its own signed cookie on
|
|
312
|
+
* `GET /`, and the exchange also works through this proxy: the gateway
|
|
313
|
+
* forwards `Host` as loopback, which is exactly the authority dsh binds the
|
|
314
|
+
* cookie to.
|
|
315
|
+
*/
|
|
316
|
+
tokenizedUrl(authority) {
|
|
317
|
+
const connection = this.ctx.get('connection')
|
|
318
|
+
if (connection === undefined) return undefined
|
|
319
|
+
return connection.authenticatedUrl(`http://${authority}/`)
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async handle(req, res, target) {
|
|
323
|
+
const url = new URL(req.url ?? '/', 'http://dsh-gateway.invalid')
|
|
324
|
+
const pathname = url.pathname
|
|
325
|
+
|
|
326
|
+
// The PWA worker must remain reachable when PWA support is switched off so
|
|
327
|
+
// an already-installed worker can be updated into its cleanup version.
|
|
328
|
+
if (pathname === '/sw.js') {
|
|
329
|
+
res.writeHead(200, {
|
|
330
|
+
'content-type': 'text/javascript; charset=utf-8',
|
|
331
|
+
'cache-control': 'no-cache'
|
|
332
|
+
})
|
|
333
|
+
res.end(this.runtimePwa ? SW_JS : SW_DISABLED_JS)
|
|
334
|
+
return
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
if (pathname === '/manifest.webmanifest' || pathname === '/favicon.svg') {
|
|
338
|
+
if (!this.runtimePwa) {
|
|
339
|
+
res.writeHead(404, { 'cache-control': 'no-store' })
|
|
340
|
+
res.end()
|
|
341
|
+
return
|
|
342
|
+
}
|
|
343
|
+
if (pathname === '/manifest.webmanifest') {
|
|
344
|
+
res.writeHead(200, {
|
|
345
|
+
'content-type': 'application/manifest+json; charset=utf-8',
|
|
346
|
+
'cache-control': 'no-cache'
|
|
347
|
+
})
|
|
348
|
+
res.end(JSON.stringify(MANIFEST))
|
|
349
|
+
return
|
|
350
|
+
}
|
|
351
|
+
res.writeHead(200, {
|
|
352
|
+
'content-type': 'image/svg+xml; charset=utf-8',
|
|
353
|
+
'cache-control': 'no-cache'
|
|
354
|
+
})
|
|
355
|
+
res.end(ICON_SVG)
|
|
356
|
+
return
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
if (pathname === GATEWAY_API_PREFIX || pathname.startsWith(`${GATEWAY_API_PREFIX}/`)) {
|
|
360
|
+
// The settings page is reachable only to a browser dsh already accepts;
|
|
361
|
+
// there is no gateway-owned session to check instead.
|
|
362
|
+
if (!(await probeBrowserSession(target, req.headers.cookie))) {
|
|
363
|
+
this.sendJson(res, 401, { error: 'unauthorized' })
|
|
364
|
+
return
|
|
365
|
+
}
|
|
366
|
+
await this.handleGatewayApi(req, res, pathname)
|
|
367
|
+
return
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// Everything else is dsh's request. The gateway translates identity to
|
|
371
|
+
// loopback and relays; dsh's own cookie decides whether the browser is
|
|
372
|
+
// authenticated.
|
|
373
|
+
await proxyRequest(req, res, target, {
|
|
374
|
+
pwa: this.runtimePwa,
|
|
375
|
+
hostMode: this.bootHostMode
|
|
376
|
+
})
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
settingSource(key) {
|
|
380
|
+
if (this.envOverrides[key] !== undefined) return 'env'
|
|
381
|
+
if (this.settings.has(key)) return 'settings'
|
|
382
|
+
return 'default'
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
gatewayState() {
|
|
386
|
+
return {
|
|
387
|
+
name: 'dsh-gateway',
|
|
388
|
+
version: PACKAGE_VERSION,
|
|
389
|
+
listen: { host: this.config.host, port: this.proxyPort },
|
|
390
|
+
upstream: { host: this.target.host, port: this.target.port },
|
|
391
|
+
uptimeMs: Date.now() - this.startedAt,
|
|
392
|
+
dataDir: this.config.dataDir,
|
|
393
|
+
auth: {
|
|
394
|
+
provider: 'dsh',
|
|
395
|
+
// dsh's cookie name is a deterministic hash of the authority it was
|
|
396
|
+
// minted for; the gateway always forwards the loopback authority.
|
|
397
|
+
cookieName: dshCookieName(targetAuthority(this.target)),
|
|
398
|
+
persistentToken: this.persistentToken,
|
|
399
|
+
tokenSource: this.persistentToken ? this.launchToken.source : 'process'
|
|
400
|
+
},
|
|
401
|
+
pwa: {
|
|
402
|
+
value: this.runtimePwa,
|
|
403
|
+
source: this.settingSource('pwa'),
|
|
404
|
+
locked: this.envOverrides.pwa !== undefined
|
|
405
|
+
},
|
|
406
|
+
hostMode: {
|
|
407
|
+
value: this.bootHostMode,
|
|
408
|
+
configured: this.configuredHostMode,
|
|
409
|
+
source: this.settingSource('hostMode'),
|
|
410
|
+
locked: this.envOverrides.hostMode !== undefined,
|
|
411
|
+
restartRequired: this.configuredHostMode !== this.bootHostMode
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
sendJson(res, status, body) {
|
|
417
|
+
res.writeHead(status, {
|
|
418
|
+
'content-type': 'application/json; charset=utf-8',
|
|
419
|
+
'cache-control': 'no-store'
|
|
420
|
+
})
|
|
421
|
+
res.end(JSON.stringify(body))
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
async readJsonBody(req) {
|
|
425
|
+
const raw = await readRequestBody(req)
|
|
426
|
+
if (raw === '') return {}
|
|
427
|
+
return JSON.parse(raw)
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* The settings page mutates host state, so require both a same-origin fetch
|
|
432
|
+
* and a custom header. A cross-site form can send neither; requiring the
|
|
433
|
+
* header also keeps a cross-origin `fetch` in the CORS preflight path.
|
|
434
|
+
*/
|
|
435
|
+
isTrustedApiRequest(req) {
|
|
436
|
+
if (req.headers['x-dsh-gateway'] !== '1') return false
|
|
437
|
+
const site = req.headers['sec-fetch-site']
|
|
438
|
+
return site === undefined || site === 'same-origin' || site === 'none'
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** The browser-facing origin uses HTTPS? */
|
|
442
|
+
isSecureRequest(req) {
|
|
443
|
+
const proto = req.headers['x-forwarded-proto']
|
|
444
|
+
if (typeof proto === 'string' && proto !== '') return proto.split(',', 1)[0].trim() === 'https'
|
|
445
|
+
return false
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
async handleGatewayApi(req, res, pathname) {
|
|
449
|
+
if (pathname === `${GATEWAY_API_PREFIX}/state` && req.method === 'GET') {
|
|
450
|
+
this.sendJson(res, 200, this.gatewayState())
|
|
451
|
+
return
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
if (req.method !== 'POST') {
|
|
455
|
+
res.writeHead(405, { allow: 'GET, POST', 'cache-control': 'no-store' })
|
|
456
|
+
res.end()
|
|
457
|
+
return
|
|
458
|
+
}
|
|
459
|
+
if (!this.isTrustedApiRequest(req)) {
|
|
460
|
+
this.sendJson(res, 403, { error: 'forbidden' })
|
|
461
|
+
return
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
if (pathname === `${GATEWAY_API_PREFIX}/logout`) {
|
|
465
|
+
this.signOut(req, res)
|
|
466
|
+
return
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
let body
|
|
470
|
+
try {
|
|
471
|
+
body = await this.readJsonBody(req)
|
|
472
|
+
} catch {
|
|
473
|
+
this.sendJson(res, 400, { error: 'invalid JSON body' })
|
|
474
|
+
return
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
if (pathname === `${GATEWAY_API_PREFIX}/settings`) {
|
|
478
|
+
await this.updateGatewaySettings(res, body)
|
|
479
|
+
return
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
this.sendJson(res, 404, { error: 'not found' })
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* End this browser's dsh session by expiring the cookie dsh minted.
|
|
487
|
+
*
|
|
488
|
+
* dsh has no logout endpoint — its documented model is "clearing the browser
|
|
489
|
+
* cookie ends one browser session" — so the gateway does exactly that for the
|
|
490
|
+
* one cookie name it knows, the loopback authority's. Other browsers are
|
|
491
|
+
* unaffected; revoking every session needs deleting dsh's
|
|
492
|
+
* `client-connection/browser-session` credential and restarting dsh.
|
|
493
|
+
*/
|
|
494
|
+
signOut(req, res) {
|
|
495
|
+
const name = dshCookieName(targetAuthority(this.target))
|
|
496
|
+
const secure = this.isSecureRequest(req) ? '; Secure' : ''
|
|
497
|
+
res.writeHead(200, {
|
|
498
|
+
'content-type': 'application/json; charset=utf-8',
|
|
499
|
+
'cache-control': 'no-store',
|
|
500
|
+
'set-cookie': `${name}=; Max-Age=0; Path=/; HttpOnly; SameSite=Strict${secure}`
|
|
501
|
+
})
|
|
502
|
+
res.end(JSON.stringify({ ok: true }))
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
async updateGatewaySettings(res, body) {
|
|
506
|
+
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
|
|
507
|
+
this.sendJson(res, 400, { error: 'settings must be an object' })
|
|
508
|
+
return
|
|
509
|
+
}
|
|
510
|
+
const patch = {}
|
|
511
|
+
for (const key of ['pwa', 'hostMode']) {
|
|
512
|
+
if (!Object.prototype.hasOwnProperty.call(body, key)) continue
|
|
513
|
+
if (typeof body[key] !== 'boolean') {
|
|
514
|
+
this.sendJson(res, 400, { error: `${key} must be a boolean` })
|
|
515
|
+
return
|
|
516
|
+
}
|
|
517
|
+
if (this.envOverrides[key] !== undefined) {
|
|
518
|
+
this.sendJson(res, 409, { error: `${key} is managed by an environment variable` })
|
|
519
|
+
return
|
|
520
|
+
}
|
|
521
|
+
patch[key] = body[key]
|
|
522
|
+
}
|
|
523
|
+
if (Object.keys(patch).length === 0) {
|
|
524
|
+
this.sendJson(res, 400, { error: 'no supported settings supplied' })
|
|
525
|
+
return
|
|
526
|
+
}
|
|
527
|
+
if (patch.pwa !== undefined) this.runtimePwa = patch.pwa
|
|
528
|
+
if (patch.hostMode !== undefined) this.configuredHostMode = patch.hostMode
|
|
529
|
+
await this.settings.update(patch)
|
|
530
|
+
this.sendJson(res, 200, this.gatewayState())
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
async handleUpgrade(req, socket, head, target) {
|
|
534
|
+
proxyUpgrade(req, socket, head, target)
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
printUrl(target) {
|
|
538
|
+
const host = this.config.host === '0.0.0.0' ? '127.0.0.1' : this.config.host
|
|
539
|
+
const lan = this.config.host === '0.0.0.0' ? lanAddresses()[0] : undefined
|
|
540
|
+
const lanText = lan === undefined ? '' : ` (LAN: http://${lan}:${String(this.proxyPort)})`
|
|
541
|
+
const base = `http://${host}:${String(this.proxyPort)}`
|
|
542
|
+
console.log(`dsh-gateway: ${base} -> http://${target.host}:${String(target.port)}${lanText}`)
|
|
543
|
+
if (this.bootHostMode) {
|
|
544
|
+
console.log('dsh-gateway: host mode is ON — every signed-in user can edit this profile\'s settings and plugins')
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Print the one URL that signs a browser in.
|
|
550
|
+
*
|
|
551
|
+
* Authentication is dsh's launch token exchanged for dsh's own signed
|
|
552
|
+
* cookie. dsh only accepts that token on `GET /`, and the exchange works
|
|
553
|
+
* through this proxy because the gateway forwards `Host` as the loopback
|
|
554
|
+
* authority dsh binds the cookie to. Rewriting dsh's URL to the gateway port
|
|
555
|
+
* is therefore all that is needed. With the persistent token installed the
|
|
556
|
+
* URL is stable across restarts and safe to bookmark.
|
|
557
|
+
*/
|
|
558
|
+
printSignInUrl(target) {
|
|
559
|
+
const tokenized = this.tokenizedUrl(targetAuthority(target))
|
|
560
|
+
const token = tokenized === undefined ? undefined : new URL(tokenized).searchParams.get('token')
|
|
561
|
+
if (token === undefined || token === '') {
|
|
562
|
+
console.log('dsh-gateway: open the tokenized URL printed by dsh web to sign in through this gateway')
|
|
563
|
+
return
|
|
564
|
+
}
|
|
565
|
+
const host = this.config.host === '0.0.0.0' ? '127.0.0.1' : this.config.host
|
|
566
|
+
const urlHost = host.includes(':') ? `[${host}]` : host
|
|
567
|
+
const stability = this.persistentToken ? ' (stable across restarts)' : ''
|
|
568
|
+
console.log(`dsh-gateway: sign in with http://${urlHost}:${String(this.proxyPort)}/?token=${encodeURIComponent(token)}${stability}`)
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
async close() {
|
|
572
|
+
if (this.server !== null) {
|
|
573
|
+
this.server.closeAllConnections?.()
|
|
574
|
+
for (const socket of this.sockets) socket.destroy()
|
|
575
|
+
this.sockets.clear()
|
|
576
|
+
await new Promise((resolve) => this.server.close(() => resolve()))
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
export { DshGateway }
|
|
582
|
+
export default DshGateway
|