@gitsang/dsh-gateway 0.0.0-stage → 0.3.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/src/index.js ADDED
@@ -0,0 +1,470 @@
1
+ import { createServer } from 'node:http'
2
+ import { readFileSync } from 'node:fs'
3
+ import { networkInterfaces, homedir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import { Service } from '@deepseek-ai/cordis'
6
+ import z from '@deepseek-ai/schemastery'
7
+ import { dshCookieName, probeBrowserSession, proxyRequest, proxyUpgrade, targetAuthority } from './proxy.js'
8
+ import { readRequestBody } from './pages.js'
9
+ import { ICON_SVG, MANIFEST, SW_DISABLED_JS, SW_JS } from './pwa.js'
10
+ import { GatewaySettingsStore } from './settings-store.js'
11
+
12
+ export const name = 'gateway'
13
+ // `connection` is optional: the gateway still proxies when a composition omits
14
+ // the browser transport, it just cannot print a tokenized sign-in URL then.
15
+ export const inject = ['webServer']
16
+
17
+ export const GATEWAY_API_PREFIX = '/__dsh_gateway'
18
+ const PACKAGE_VERSION = JSON.parse(
19
+ readFileSync(new URL('../package.json', import.meta.url), 'utf8')
20
+ ).version
21
+
22
+ const HOST_ENV = ['DSH_GATEWAY_HOST']
23
+ const PORT_ENV = ['DSH_GATEWAY_PORT']
24
+ const DATA_DIR_ENV = ['DSH_GATEWAY_DATA_DIR']
25
+ const PWA_ENV = ['DSH_GATEWAY_PWA']
26
+ const HOST_MODE_ENV = ['DSH_GATEWAY_HOST_MODE']
27
+
28
+ /** Read the first non-empty environment variable from a compatibility list. */
29
+ function envValue(names) {
30
+ for (const name of names) {
31
+ const value = process.env[name]
32
+ if (value !== undefined && value !== '') return value
33
+ }
34
+ return undefined
35
+ }
36
+
37
+ function envString(names, fallback) {
38
+ return envValue(names) ?? fallback
39
+ }
40
+
41
+ function envInt(names, fallback) {
42
+ const raw = envValue(names)
43
+ if (raw === undefined) return fallback
44
+ const value = Number(raw)
45
+ return Number.isInteger(value) && value >= 0 ? value : fallback
46
+ }
47
+
48
+ function parseBool(raw) {
49
+ return raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on'
50
+ }
51
+
52
+ function envBool(names, fallback) {
53
+ const raw = envValue(names)
54
+ return raw === undefined ? fallback : parseBool(raw)
55
+ }
56
+
57
+ /** `undefined` means the setting is not environment-locked. */
58
+ function envBoolOverride(names) {
59
+ const raw = envValue(names)
60
+ return raw === undefined ? undefined : parseBool(raw)
61
+ }
62
+
63
+ function defaultDataDir() {
64
+ const explicit = envValue(DATA_DIR_ENV)
65
+ if (explicit !== undefined) return explicit
66
+ const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
67
+ return join(dshHome, 'profiles', 'gateway')
68
+ }
69
+
70
+ export const Config = z.object({
71
+ host: z.string().default(envString(HOST_ENV, '127.0.0.1')),
72
+ // The default port is derived from the dsh web port at startup; this env
73
+ // var only overrides it when explicitly set.
74
+ port: z.natural().max(65535).default(envInt(PORT_ENV)),
75
+ dataDir: z.string().default(defaultDataDir()),
76
+ pwa: z.boolean().default(envBool(PWA_ENV, true)),
77
+ // Declare the proxied page as a host-owning page so dsh uses Host settings
78
+ // (Models page, "open configuration file") instead of its read-only memory
79
+ // fallback. On by default because a remote dsh web UI is unusable without it;
80
+ // it does hand every signed-in user the same configuration-write surface the
81
+ // Desktop shell has, so the settings page can turn it off.
82
+ hostMode: z.boolean().default(envBool(HOST_MODE_ENV, true))
83
+ })
84
+
85
+ function upstreamTarget(webServer) {
86
+ return {
87
+ host: '127.0.0.1',
88
+ port: webServer.port
89
+ }
90
+ }
91
+
92
+ function lanAddresses() {
93
+ return Object.values(networkInterfaces())
94
+ .flat()
95
+ .filter((iface) => iface !== undefined && iface.family === 'IPv4' && !iface.internal)
96
+ .map((iface) => iface.address)
97
+ }
98
+
99
+ class DshGateway extends Service {
100
+ static Config = Config
101
+
102
+ constructor(ctx, config) {
103
+ super(ctx, 'gateway')
104
+ this.config = config
105
+ this.settings = new GatewaySettingsStore(join(config.dataDir, 'settings.json'))
106
+ this.envOverrides = {
107
+ pwa: envBoolOverride(PWA_ENV),
108
+ hostMode: envBoolOverride(HOST_MODE_ENV)
109
+ }
110
+ this.runtimePwa = config.pwa
111
+ this.bootHostMode = config.hostMode
112
+ this.configuredHostMode = config.hostMode
113
+ this.startedAt = Date.now()
114
+ this.target = null
115
+ this.server = null
116
+ this.proxyPort = null
117
+ this.sockets = new Set()
118
+ }
119
+
120
+ async [Service.init]() {
121
+ await this.settings.init()
122
+
123
+ const saved = this.settings.snapshot()
124
+ this.runtimePwa = this.envOverrides.pwa ?? saved.pwa ?? this.config.pwa
125
+ this.bootHostMode = this.envOverrides.hostMode ?? saved.hostMode ?? this.config.hostMode
126
+ this.configuredHostMode = this.bootHostMode
127
+ this.config = { ...this.config, pwa: this.runtimePwa, hostMode: this.bootHostMode }
128
+
129
+ const target = upstreamTarget(this.ctx.webServer)
130
+ this.target = target
131
+ // The gateway listens next to dsh web by default (web port + 1).
132
+ // DSH_GATEWAY_PORT can still override this.
133
+ this.config = { ...this.config, port: this.config.port ?? Number(target.port) + 1 }
134
+ const listenPort = this.config.port
135
+ this.server = createServer((req, res) => {
136
+ this.handle(req, res, target).catch((err) => {
137
+ this.ctx.logger.error(err)
138
+ if (res.headersSent) {
139
+ res.destroy()
140
+ return
141
+ }
142
+ res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
143
+ res.end('dsh-gateway: internal error')
144
+ })
145
+ })
146
+
147
+ this.server.on('connection', (socket) => {
148
+ this.sockets.add(socket)
149
+ socket.on('close', () => this.sockets.delete(socket))
150
+ })
151
+
152
+ this.server.on('upgrade', (req, socket, head) => {
153
+ this.sockets.add(socket)
154
+ socket.on('close', () => this.sockets.delete(socket))
155
+ this.handleUpgrade(req, socket, head, target).catch((err) => {
156
+ this.ctx.logger.error(err)
157
+ socket.destroy()
158
+ })
159
+ })
160
+
161
+ await new Promise((resolve, reject) => {
162
+ const onError = (err) => {
163
+ this.server.off('listening', onListening)
164
+ reject(err)
165
+ }
166
+ const onListening = () => {
167
+ this.server.off('error', onError)
168
+ this.server.on('error', (err) => this.ctx.logger.error(err))
169
+ const address = this.server.address()
170
+ this.proxyPort = typeof address === 'object' && address !== null ? address.port : listenPort
171
+ resolve()
172
+ }
173
+ this.server.once('error', onError)
174
+ this.server.once('listening', onListening)
175
+ this.server.listen(listenPort, this.config.host)
176
+ })
177
+
178
+ this.ctx.effect(() => async () => this.close(), 'gateway.proxy')
179
+
180
+ // Primary Host-mode carrier: declare the transport flag inside dsh's own
181
+ // index.html, so it survives proxies that cache or rewrite our responses.
182
+ // The switch is evaluated at boot; changing it needs a restart.
183
+ if (this.bootHostMode) {
184
+ this.ctx.inject(['webServer'], (webCtx) => {
185
+ webCtx.on('webserver/index-inject', (table) => {
186
+ table.push({ kind: 'global', name: '__DSH_TRANSPORT__', value: { ownsHost: true } })
187
+ })
188
+ })
189
+ }
190
+
191
+ this.printUrl(target)
192
+
193
+ // Connection mounts after this row in the shipped web composition, so the
194
+ // launch token only exists once that service appears. Waiving readiness is
195
+ // safe: this is a log line, not part of serving traffic.
196
+ this.ctx.inject(['connection'], () => {
197
+ this.printSignInUrl(target)
198
+ })
199
+ }
200
+
201
+ /**
202
+ * A tokenized application URL for the loopback `authority`, from dsh's
203
+ * Connection service. dsh exchanges that token for its own signed cookie on
204
+ * `GET /`, and the exchange also works through this proxy: the gateway
205
+ * forwards `Host` as loopback, which is exactly the authority dsh binds the
206
+ * cookie to.
207
+ */
208
+ tokenizedUrl(authority) {
209
+ const connection = this.ctx.get('connection')
210
+ if (connection === undefined) return undefined
211
+ return connection.authenticatedUrl(`http://${authority}/`)
212
+ }
213
+
214
+ async handle(req, res, target) {
215
+ const url = new URL(req.url ?? '/', 'http://dsh-gateway.invalid')
216
+ const pathname = url.pathname
217
+
218
+ // The PWA worker must remain reachable when PWA support is switched off so
219
+ // an already-installed worker can be updated into its cleanup version.
220
+ if (pathname === '/sw.js') {
221
+ res.writeHead(200, {
222
+ 'content-type': 'text/javascript; charset=utf-8',
223
+ 'cache-control': 'no-cache'
224
+ })
225
+ res.end(this.runtimePwa ? SW_JS : SW_DISABLED_JS)
226
+ return
227
+ }
228
+
229
+ if (pathname === '/manifest.webmanifest' || pathname === '/favicon.svg') {
230
+ if (!this.runtimePwa) {
231
+ res.writeHead(404, { 'cache-control': 'no-store' })
232
+ res.end()
233
+ return
234
+ }
235
+ if (pathname === '/manifest.webmanifest') {
236
+ res.writeHead(200, {
237
+ 'content-type': 'application/manifest+json; charset=utf-8',
238
+ 'cache-control': 'no-cache'
239
+ })
240
+ res.end(JSON.stringify(MANIFEST))
241
+ return
242
+ }
243
+ res.writeHead(200, {
244
+ 'content-type': 'image/svg+xml; charset=utf-8',
245
+ 'cache-control': 'no-cache'
246
+ })
247
+ res.end(ICON_SVG)
248
+ return
249
+ }
250
+
251
+ if (pathname === GATEWAY_API_PREFIX || pathname.startsWith(`${GATEWAY_API_PREFIX}/`)) {
252
+ // The settings page is reachable only to a browser dsh already accepts;
253
+ // there is no gateway-owned session to check instead.
254
+ if (!(await probeBrowserSession(target, req.headers.cookie))) {
255
+ this.sendJson(res, 401, { error: 'unauthorized' })
256
+ return
257
+ }
258
+ await this.handleGatewayApi(req, res, pathname)
259
+ return
260
+ }
261
+
262
+ // Everything else is dsh's request. The gateway translates identity to
263
+ // loopback and relays; dsh's own cookie decides whether the browser is
264
+ // authenticated.
265
+ await proxyRequest(req, res, target, {
266
+ pwa: this.runtimePwa,
267
+ hostMode: this.bootHostMode
268
+ })
269
+ }
270
+
271
+ settingSource(key) {
272
+ if (this.envOverrides[key] !== undefined) return 'env'
273
+ if (this.settings.has(key)) return 'settings'
274
+ return 'default'
275
+ }
276
+
277
+ gatewayState() {
278
+ return {
279
+ name: 'dsh-gateway',
280
+ version: PACKAGE_VERSION,
281
+ listen: { host: this.config.host, port: this.proxyPort },
282
+ upstream: { host: this.target.host, port: this.target.port },
283
+ uptimeMs: Date.now() - this.startedAt,
284
+ dataDir: this.config.dataDir,
285
+ auth: {
286
+ provider: 'dsh',
287
+ // dsh's cookie name is a deterministic hash of the authority it was
288
+ // minted for; the gateway always forwards the loopback authority.
289
+ cookieName: dshCookieName(targetAuthority(this.target))
290
+ },
291
+ pwa: {
292
+ value: this.runtimePwa,
293
+ source: this.settingSource('pwa'),
294
+ locked: this.envOverrides.pwa !== undefined
295
+ },
296
+ hostMode: {
297
+ value: this.bootHostMode,
298
+ configured: this.configuredHostMode,
299
+ source: this.settingSource('hostMode'),
300
+ locked: this.envOverrides.hostMode !== undefined,
301
+ restartRequired: this.configuredHostMode !== this.bootHostMode
302
+ }
303
+ }
304
+ }
305
+
306
+ sendJson(res, status, body) {
307
+ res.writeHead(status, {
308
+ 'content-type': 'application/json; charset=utf-8',
309
+ 'cache-control': 'no-store'
310
+ })
311
+ res.end(JSON.stringify(body))
312
+ }
313
+
314
+ async readJsonBody(req) {
315
+ const raw = await readRequestBody(req)
316
+ if (raw === '') return {}
317
+ return JSON.parse(raw)
318
+ }
319
+
320
+ /**
321
+ * The settings page mutates host state, so require both a same-origin fetch
322
+ * and a custom header. A cross-site form can send neither; requiring the
323
+ * header also keeps a cross-origin `fetch` in the CORS preflight path.
324
+ */
325
+ isTrustedApiRequest(req) {
326
+ if (req.headers['x-dsh-gateway'] !== '1') return false
327
+ const site = req.headers['sec-fetch-site']
328
+ return site === undefined || site === 'same-origin' || site === 'none'
329
+ }
330
+
331
+ /** The browser-facing origin uses HTTPS? */
332
+ isSecureRequest(req) {
333
+ const proto = req.headers['x-forwarded-proto']
334
+ if (typeof proto === 'string' && proto !== '') return proto.split(',', 1)[0].trim() === 'https'
335
+ return false
336
+ }
337
+
338
+ async handleGatewayApi(req, res, pathname) {
339
+ if (pathname === `${GATEWAY_API_PREFIX}/state` && req.method === 'GET') {
340
+ this.sendJson(res, 200, this.gatewayState())
341
+ return
342
+ }
343
+
344
+ if (req.method !== 'POST') {
345
+ res.writeHead(405, { allow: 'GET, POST', 'cache-control': 'no-store' })
346
+ res.end()
347
+ return
348
+ }
349
+ if (!this.isTrustedApiRequest(req)) {
350
+ this.sendJson(res, 403, { error: 'forbidden' })
351
+ return
352
+ }
353
+
354
+ if (pathname === `${GATEWAY_API_PREFIX}/logout`) {
355
+ this.signOut(req, res)
356
+ return
357
+ }
358
+
359
+ let body
360
+ try {
361
+ body = await this.readJsonBody(req)
362
+ } catch {
363
+ this.sendJson(res, 400, { error: 'invalid JSON body' })
364
+ return
365
+ }
366
+
367
+ if (pathname === `${GATEWAY_API_PREFIX}/settings`) {
368
+ await this.updateGatewaySettings(res, body)
369
+ return
370
+ }
371
+
372
+ this.sendJson(res, 404, { error: 'not found' })
373
+ }
374
+
375
+ /**
376
+ * End this browser's dsh session by expiring the cookie dsh minted.
377
+ *
378
+ * dsh has no logout endpoint — its documented model is "clearing the browser
379
+ * cookie ends one browser session" — so the gateway does exactly that for the
380
+ * one cookie name it knows, the loopback authority's. Other browsers are
381
+ * unaffected; revoking every session needs deleting dsh's
382
+ * `client-connection/browser-session` credential and restarting dsh.
383
+ */
384
+ signOut(req, res) {
385
+ const name = dshCookieName(targetAuthority(this.target))
386
+ const secure = this.isSecureRequest(req) ? '; Secure' : ''
387
+ res.writeHead(200, {
388
+ 'content-type': 'application/json; charset=utf-8',
389
+ 'cache-control': 'no-store',
390
+ 'set-cookie': `${name}=; Max-Age=0; Path=/; HttpOnly; SameSite=Strict${secure}`
391
+ })
392
+ res.end(JSON.stringify({ ok: true }))
393
+ }
394
+
395
+ async updateGatewaySettings(res, body) {
396
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
397
+ this.sendJson(res, 400, { error: 'settings must be an object' })
398
+ return
399
+ }
400
+ const patch = {}
401
+ for (const key of ['pwa', 'hostMode']) {
402
+ if (!Object.prototype.hasOwnProperty.call(body, key)) continue
403
+ if (typeof body[key] !== 'boolean') {
404
+ this.sendJson(res, 400, { error: `${key} must be a boolean` })
405
+ return
406
+ }
407
+ if (this.envOverrides[key] !== undefined) {
408
+ this.sendJson(res, 409, { error: `${key} is managed by an environment variable` })
409
+ return
410
+ }
411
+ patch[key] = body[key]
412
+ }
413
+ if (Object.keys(patch).length === 0) {
414
+ this.sendJson(res, 400, { error: 'no supported settings supplied' })
415
+ return
416
+ }
417
+ if (patch.pwa !== undefined) this.runtimePwa = patch.pwa
418
+ if (patch.hostMode !== undefined) this.configuredHostMode = patch.hostMode
419
+ await this.settings.update(patch)
420
+ this.sendJson(res, 200, this.gatewayState())
421
+ }
422
+
423
+ async handleUpgrade(req, socket, head, target) {
424
+ proxyUpgrade(req, socket, head, target)
425
+ }
426
+
427
+ printUrl(target) {
428
+ const host = this.config.host === '0.0.0.0' ? '127.0.0.1' : this.config.host
429
+ const lan = this.config.host === '0.0.0.0' ? lanAddresses()[0] : undefined
430
+ const lanText = lan === undefined ? '' : ` (LAN: http://${lan}:${String(this.proxyPort)})`
431
+ const base = `http://${host}:${String(this.proxyPort)}`
432
+ console.log(`dsh-gateway: ${base} -> http://${target.host}:${String(target.port)}${lanText}`)
433
+ if (this.bootHostMode) {
434
+ console.log('dsh-gateway: host mode is ON — every signed-in user can edit this profile\'s settings and plugins')
435
+ }
436
+ }
437
+
438
+ /**
439
+ * Print the one URL that signs a browser in.
440
+ *
441
+ * The gateway owns no credential: authentication is dsh's launch token,
442
+ * exchanged for dsh's own signed cookie. dsh only accepts that token on
443
+ * `GET /`, and the exchange works through this proxy because the gateway
444
+ * forwards `Host` as the loopback authority dsh binds the cookie to. Rewriting
445
+ * dsh's URL to the gateway port is therefore all that is needed.
446
+ */
447
+ printSignInUrl(target) {
448
+ const tokenized = this.tokenizedUrl(targetAuthority(target))
449
+ const token = tokenized === undefined ? undefined : new URL(tokenized).searchParams.get('token')
450
+ if (token === undefined || token === '') {
451
+ console.log('dsh-gateway: open the tokenized URL printed by dsh web to sign in through this gateway')
452
+ return
453
+ }
454
+ const host = this.config.host === '0.0.0.0' ? '127.0.0.1' : this.config.host
455
+ const urlHost = host.includes(':') ? `[${host}]` : host
456
+ console.log(`dsh-gateway: sign in with http://${urlHost}:${String(this.proxyPort)}/?token=${encodeURIComponent(token)}`)
457
+ }
458
+
459
+ async close() {
460
+ if (this.server !== null) {
461
+ this.server.closeAllConnections?.()
462
+ for (const socket of this.sockets) socket.destroy()
463
+ this.sockets.clear()
464
+ await new Promise((resolve) => this.server.close(() => resolve()))
465
+ }
466
+ }
467
+ }
468
+
469
+ export { DshGateway }
470
+ export default DshGateway
package/src/pages.js ADDED
@@ -0,0 +1,149 @@
1
+ import { PWA_HEAD_TAGS } from './pwa.js'
2
+
3
+ function escapeHtml(value) {
4
+ return String(value)
5
+ .replaceAll('&', '&')
6
+ .replaceAll('<', '&lt;')
7
+ .replaceAll('>', '&gt;')
8
+ .replaceAll('"', '&quot;')
9
+ .replaceAll("'", '&#39;')
10
+ }
11
+
12
+ /**
13
+ * Read a request body as UTF-8. Keeps an upper bound so a stray client cannot
14
+ * make the gateway buffer an unbounded body. Used for the gateway's own JSON
15
+ * settings API; proxied traffic streams through untouched.
16
+ */
17
+ export function readRequestBody(req, limit = 64 * 1024) {
18
+ return new Promise((resolve, reject) => {
19
+ const chunks = []
20
+ let received = 0
21
+ req.on('data', (chunk) => {
22
+ received += chunk.length
23
+ if (received > limit) {
24
+ reject(new Error('request body too large'))
25
+ req.destroy()
26
+ return
27
+ }
28
+ chunks.push(chunk)
29
+ })
30
+ req.on('end', () => {
31
+ resolve(Buffer.concat(chunks).toString('utf8'))
32
+ })
33
+ req.on('error', reject)
34
+ })
35
+ }
36
+
37
+ // Mirrors the dsh web design tokens (@deepseek-ai/dsh-client-ui-theme).
38
+ // This standalone page cannot read the web settings store, so it follows the
39
+ // system color scheme; that is also the web UI's default theme preference.
40
+ const PAGE_THEME_CSS = `
41
+ :root {
42
+ color-scheme: light dark;
43
+ --dsw-font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC',
44
+ 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
45
+ --dsw-alias-bg-base: #ffffff;
46
+ --dsw-alias-bg-layer-1: #ffffff;
47
+ --dsw-alias-border-l2: rgba(0, 0, 0, 0.10);
48
+ --dsw-alias-brand-primary: #0f1115;
49
+ --dsw-alias-label-primary: #0f1115;
50
+ --dsw-alias-label-secondary: #61666b;
51
+ --dsw-alias-label-tertiary: #81858c;
52
+ --dsw-alias-label-dimmed: #e1e5ee;
53
+ --dsw-shadow-lv3: 0 0 1px 0 rgba(0, 0, 0, 0.20), 0 0 4px 0 rgba(0, 0, 0, 0.02), 0 12px 32px 0 rgba(0, 0, 0, 0.08);
54
+ }
55
+
56
+ @media (prefers-color-scheme: dark) {
57
+ :root {
58
+ --dsw-alias-bg-base: #151517;
59
+ --dsw-alias-bg-layer-1: #232325;
60
+ --dsw-alias-border-l2: rgba(255, 255, 255, 0.12);
61
+ --dsw-alias-brand-primary: #f9fafb;
62
+ --dsw-alias-label-primary: #f9fafb;
63
+ --dsw-alias-label-secondary: #cfd3d6;
64
+ --dsw-alias-label-tertiary: #adb2b8;
65
+ --dsw-alias-label-dimmed: #43454a;
66
+ }
67
+ }
68
+
69
+ body {
70
+ margin: 0;
71
+ min-height: 100vh;
72
+ display: flex;
73
+ align-items: center;
74
+ justify-content: center;
75
+ background: var(--dsw-alias-bg-base);
76
+ color: var(--dsw-alias-label-primary);
77
+ font-family: var(--dsw-font-family);
78
+ }
79
+
80
+ main {
81
+ width: 100%;
82
+ max-width: 380px;
83
+ margin: 0 auto;
84
+ padding: 32px;
85
+ box-sizing: border-box;
86
+ background: var(--dsw-alias-bg-layer-1);
87
+ border: 0.5px solid var(--dsw-alias-border-l2);
88
+ border-radius: 16px;
89
+ box-shadow: var(--dsw-shadow-lv3);
90
+ }
91
+
92
+ h1 {
93
+ margin: 0 0 8px;
94
+ font-size: 20px;
95
+ line-height: 28px;
96
+ font-weight: 600;
97
+ }
98
+
99
+ p {
100
+ margin: 0 0 12px;
101
+ font-size: 14px;
102
+ line-height: 22px;
103
+ color: var(--dsw-alias-label-secondary);
104
+ }
105
+
106
+ p.hint {
107
+ color: var(--dsw-alias-label-tertiary);
108
+ }
109
+
110
+ code {
111
+ font-family: var(--dsw-font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
112
+ font-size: 12px;
113
+ padding: 1px 4px;
114
+ border-radius: 4px;
115
+ background: var(--dsw-alias-bg-base);
116
+ border: 0.5px solid var(--dsw-alias-border-l2);
117
+ }
118
+ `
119
+
120
+ /**
121
+ * Render the page shown when dsh rejects a browser that has no valid session.
122
+ *
123
+ * The gateway no longer authenticates anyone itself: authentication is dsh's
124
+ * launch token exchanged for a signed cookie, and the only way to obtain it is
125
+ * the URL printed by `dsh web` (or a `?token=` URL the gateway relays). This
126
+ * page exists so a plain visit explains that instead of showing dsh's bare
127
+ * one-line 401.
128
+ */
129
+ export function renderUnauthorizedPage({ pwa }) {
130
+ return `<!doctype html>
131
+ <html lang="zh-CN">
132
+ <head>
133
+ <meta charset="utf-8">
134
+ <meta name="viewport" content="width=device-width, initial-scale=1">
135
+ <title>需要登录 · dsh gateway</title>
136
+ ${pwa === false ? '' : PWA_HEAD_TAGS}
137
+ <style>${PAGE_THEME_CSS}</style>
138
+ </head>
139
+ <body>
140
+ <main>
141
+ <h1>需要登录</h1>
142
+ <p>网关已把请求转给 dsh,但 dsh 没有收到有效的登录凭据。</p>
143
+ <p>请用 <code>dsh web</code> 启动时打印的链接打开本页,地址里带一个一次性的 <code>?token=</code> 参数。它会被换成 dsh 自己的签名 cookie,随后地址栏里的 token 会自动去掉。</p>
144
+ <p class="hint">dsh 重启后 launch token 会变,旧 cookie 也会失效:重新打开一次新的启动链接即可。</p>
145
+ </main>
146
+ </body>
147
+ </html>
148
+ `
149
+ }