@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/client.js ADDED
@@ -0,0 +1,453 @@
1
+ /**
2
+ * Browser half of dsh-gateway.
3
+ *
4
+ * One plugin row owns both the gateway and its configuration. The page lives
5
+ * on that Plugins row instead of inside Settings; PWA delivery and Host-mode
6
+ * injection share the proxy lifecycle and must never be turned off
7
+ * independently of access. The page therefore exposes the two safe modes,
8
+ * gateway status, and the sign-out/sign-in story.
9
+ *
10
+ * The gateway itself owns no credential: dsh's launch token and signed cookie
11
+ * are the only authentication, so this page has no password form.
12
+ *
13
+ * The form uses the same SettingsForm/field/switch primitives and the same
14
+ * section rhythm as the official plugin configuration pages.
15
+ */
16
+ window.__ModuleLoader__.load({
17
+ id: '@gitsang/dsh-gateway',
18
+ factory: (require) => {
19
+ const React = require('react')
20
+ const primitives = require('@deepseek-ai/dsh-client-ui-primitives')
21
+ const { Button, SettingsForm, Switch } = primitives
22
+ const module = { exports: {} }
23
+ const exports = module.exports
24
+
25
+ const NS = 'gatewaySettings'
26
+ const API = '/__dsh_gateway'
27
+ const CSS_ID = '@gitsang/dsh-gateway/GatewayConfig.css'
28
+
29
+ const zh = {
30
+ nav: '网关',
31
+ title: '网关',
32
+ intro: '管理 dsh 的安全入口、浏览器交付方式和上游连接。',
33
+ summary: '管理 dsh 的安全入口、浏览器交付方式和上游连接',
34
+ status: '运行状态',
35
+ listen: '监听地址',
36
+ upstream: '上游 dsh',
37
+ uptime: '运行时长',
38
+ version: '版本',
39
+ dataDir: '数据目录',
40
+ browser: '浏览器体验',
41
+ pwaTitle: 'PWA / 可安装应用',
42
+ pwaDesc: '提供 manifest、Service Worker 和离线应用外壳。关闭后下一次页面请求停止注入。',
43
+ clearCache: '清除离线缓存',
44
+ cacheCleared: '已清除网关离线缓存。',
45
+ cacheUnsupported: '当前浏览器不支持 Cache Storage。',
46
+ access: '访问控制',
47
+ authProvider: '认证方式',
48
+ authProviderValue: 'dsh launch token',
49
+ cookieName: '会话 Cookie',
50
+ signOut: '退出登录',
51
+ signOutDesc: '清除本浏览器持有的 dsh 会话 Cookie。dsh 没有登出接口,撤销全部会话需要删除凭据记录并重启 dsh。',
52
+ signOutConfirm: '确定要退出登录吗?',
53
+ signInHint: '登录入口是 dsh 启动时打印的带 ?token= 的链接。',
54
+ advanced: '兼容性',
55
+ hostModeTitle: 'Host mode 注入',
56
+ hostModeDesc: '允许 dsh 页面编辑 Host 设置、模型配置和插件。需要重启 dsh 后生效。',
57
+ hostModeWarning: '开启后,任何能登录网关的人都能修改配置并安装插件;插件代码会在主机上运行。',
58
+ envManaged: '由环境变量管理',
59
+ restartRequired: '重启后生效',
60
+ restartHint: '已保存。重启 dsh web 后 Host mode 才会切换。',
61
+ on: '已开启',
62
+ off: '已关闭',
63
+ saved: '设置已保存。',
64
+ loading: '正在读取网关状态…',
65
+ unknownError: '操作失败,请稍后重试。',
66
+ save: '保存',
67
+ saving: '保存中…',
68
+ saveFailed: '保存失败,请重试。',
69
+ readOnly: '当前部署的设置为只读。',
70
+ unavailable: '该组件当前不可配置。',
71
+ credentialRequired: '必填',
72
+ day: '天',
73
+ hour: '小时',
74
+ minute: '分钟',
75
+ second: '秒'
76
+ }
77
+
78
+ const en = {
79
+ nav: 'Gateway',
80
+ title: 'Gateway',
81
+ intro: 'Manage the secure entry point, browser delivery and upstream connection for dsh.',
82
+ summary: 'Manage the secure entry point, browser delivery and upstream connection for dsh',
83
+ status: 'Status',
84
+ listen: 'Listening on',
85
+ upstream: 'Upstream dsh',
86
+ uptime: 'Uptime',
87
+ version: 'Version',
88
+ dataDir: 'Data directory',
89
+ browser: 'Browser experience',
90
+ pwaTitle: 'PWA / installable app',
91
+ pwaDesc: 'Serves the manifest, service worker and offline app shell. Turning it off stops injection on the next page request.',
92
+ clearCache: 'Clear offline cache',
93
+ cacheCleared: 'Gateway offline caches cleared.',
94
+ cacheUnsupported: 'This browser does not support Cache Storage.',
95
+ access: 'Access control',
96
+ authProvider: 'Authentication',
97
+ authProviderValue: 'dsh launch token',
98
+ cookieName: 'Session cookie',
99
+ signOut: 'Sign out',
100
+ signOutDesc: 'Clears the dsh session cookie this browser holds. dsh has no logout endpoint; revoking every session means deleting its credential record and restarting dsh.',
101
+ signOutConfirm: 'Sign out of this browser?',
102
+ signInHint: 'Sign in by opening the tokenized URL dsh printed at startup.',
103
+ advanced: 'Compatibility',
104
+ hostModeTitle: 'Host mode injection',
105
+ hostModeDesc: 'Lets the dsh page edit Host settings, model configuration and plugins. Requires a dsh restart.',
106
+ hostModeWarning: 'When enabled, anyone who can sign in may change configuration and install plugin bundles; plugin code runs on this host.',
107
+ envManaged: 'Managed by environment',
108
+ restartRequired: 'Restart required',
109
+ restartHint: 'Saved. Restart dsh web to apply the Host mode change.',
110
+ on: 'On',
111
+ off: 'Off',
112
+ saved: 'Settings saved.',
113
+ loading: 'Loading gateway status…',
114
+ unknownError: 'The operation failed. Try again.',
115
+ save: 'Save',
116
+ saving: 'Saving…',
117
+ saveFailed: 'Could not save. Try again.',
118
+ readOnly: 'This deployment stores settings read-only.',
119
+ unavailable: 'This component cannot be configured right now.',
120
+ credentialRequired: 'Required',
121
+ day: 'd',
122
+ hour: 'h',
123
+ minute: 'm',
124
+ second: 's'
125
+ }
126
+
127
+ const CSS = [
128
+ '.dshGatewayPage{display:flex;flex-direction:column;gap:0;max-width:760px;color:var(--dsw-alias-label-primary)}',
129
+ '.dshGatewaySection{display:flex;flex-direction:column;gap:10px;padding:16px 0}',
130
+ '.dshGatewaySection+.dshGatewaySection{border-top:.5px solid var(--dsw-alias-border-l2)}',
131
+ '.dshGatewayHeading{margin:0;font-size:13px;font-weight:600;line-height:1.5;color:var(--dsw-alias-label-primary)}',
132
+ '.dshGatewayRows{display:flex;flex-direction:column;gap:8px;margin:0}',
133
+ '.dshGatewayRow{display:flex;align-items:flex-start;justify-content:space-between;gap:20px;font-size:12px;line-height:1.5}',
134
+ '.dshGatewayRow dt{color:var(--dsw-alias-label-tertiary)}',
135
+ '.dshGatewayRow dd{margin:0;min-width:0;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere;font-variant-numeric:tabular-nums}',
136
+ '.dshGatewayCode{font-family:var(--dsw-font-mono,ui-monospace,SFMono-Regular,Menlo,Consolas,monospace);font-size:11px}',
137
+ '.dshGatewayField{display:flex;flex-direction:column;gap:6px;padding:12px 0}',
138
+ '.dshGatewayField+.dshGatewayField{border-top:.5px solid var(--dsw-alias-border-l2)}',
139
+ '.dshGatewayToggleRow{display:flex;align-items:flex-start;justify-content:space-between;gap:16px}',
140
+ '.dshGatewayFieldText{display:flex;flex-direction:column;gap:3px;min-width:0;flex:1}',
141
+ '.dshGatewayLabel{font-size:13px;font-weight:500;line-height:1.5;color:var(--dsw-alias-label-primary)}',
142
+ '.dshGatewayHint{margin:0;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-tertiary)}',
143
+ '.dshGatewayWarning{margin:0;font-size:12px;line-height:1.5;color:var(--dsw-alias-state-error-primary)}',
144
+ '.dshGatewayActions{display:flex;gap:8px;flex-wrap:wrap;align-items:center}',
145
+ '.dshGatewayMessage{margin:0;font-size:12px;line-height:1.5}',
146
+ '.dshGatewayError{color:var(--dsw-alias-state-error-primary)}',
147
+ '.dshGatewayNotice{color:var(--dsw-alias-label-tertiary)}',
148
+ '.dshGatewayBadge{border:.5px solid var(--dsw-alias-border-l2);border-radius:999px;padding:0 8px;color:var(--dsw-alias-label-tertiary);font-size:11px;line-height:18px;white-space:nowrap}',
149
+ '.dshGatewayBadgeWarn{color:var(--dsw-alias-state-error-primary);border-color:currentColor}'
150
+ ].join('')
151
+ if (
152
+ typeof document !== 'undefined' &&
153
+ document.querySelector('style[data-plugin-css=' + JSON.stringify(CSS_ID) + ']') === null
154
+ ) {
155
+ const tag = document.createElement('style')
156
+ tag.dataset.plugin = '@gitsang/dsh-gateway'
157
+ tag.dataset.pluginCss = CSS_ID
158
+ tag.textContent = CSS
159
+ document.head.appendChild(tag)
160
+ }
161
+
162
+ /** Call the gateway's authenticated settings API. */
163
+ async function request(path, options = {}) {
164
+ const headers = { accept: 'application/json' }
165
+ if (options.method === 'POST') {
166
+ headers['content-type'] = 'application/json'
167
+ headers['x-dsh-gateway'] = '1'
168
+ }
169
+ const response = await fetch(API + path, {
170
+ credentials: 'same-origin',
171
+ ...options,
172
+ headers: { ...headers, ...(options.headers || {}) }
173
+ })
174
+ let body = null
175
+ try {
176
+ body = await response.json()
177
+ } catch {
178
+ // The status code still carries the failure.
179
+ }
180
+ if (!response.ok) {
181
+ throw new Error(body?.error || `HTTP ${String(response.status)}`)
182
+ }
183
+ return body
184
+ }
185
+
186
+ function formatUptime(ms, t) {
187
+ const total = Math.max(0, Math.floor(ms / 1000))
188
+ const days = Math.floor(total / 86400)
189
+ const hours = Math.floor((total % 86400) / 3600)
190
+ const minutes = Math.floor((total % 3600) / 60)
191
+ const seconds = total % 60
192
+ if (days > 0) return `${String(days)}${t('day')} ${String(hours)}${t('hour')}`
193
+ if (hours > 0) return `${String(hours)}${t('hour')} ${String(minutes)}${t('minute')}`
194
+ if (minutes > 0) return `${String(minutes)}${t('minute')} ${String(seconds)}${t('second')}`
195
+ return `${String(seconds)}${t('second')}`
196
+ }
197
+
198
+ function StatusFact({ label, value }) {
199
+ return React.createElement(React.Fragment, null,
200
+ React.createElement('dt', null, label),
201
+ React.createElement('dd', { className: 'dshGatewayCode' }, value)
202
+ )
203
+ }
204
+
205
+ function ToggleField({ label, hint, checked, disabled, badge, warning, onChange }) {
206
+ return React.createElement('div', { className: 'dshGatewayField' },
207
+ React.createElement('div', { className: 'dshGatewayToggleRow' },
208
+ React.createElement('div', { className: 'dshGatewayFieldText' },
209
+ React.createElement('span', { className: 'dshGatewayLabel' }, label),
210
+ hint === undefined ? null : React.createElement('p', { className: 'dshGatewayHint' }, hint)
211
+ ),
212
+ React.createElement('div', { className: 'dshGatewayActions' },
213
+ badge === undefined ? null : badge,
214
+ React.createElement(Switch, { checked, disabled, label, onChange })
215
+ )
216
+ ),
217
+ warning === undefined ? null : React.createElement('p', { className: 'dshGatewayWarning' }, warning)
218
+ )
219
+ }
220
+
221
+ function GatewayConfig({ view, t }) {
222
+ const [state, setState] = React.useState(null)
223
+ const [staged, setStaged] = React.useState(null)
224
+ const [error, setError] = React.useState('')
225
+ const [notice, setNotice] = React.useState('')
226
+ const [busy, setBusy] = React.useState('')
227
+ const [saving, setSaving] = React.useState(false)
228
+ const [saveFailed, setSaveFailed] = React.useState(false)
229
+
230
+ const applyState = React.useCallback((next) => {
231
+ setState(next)
232
+ setStaged({ pwa: next.pwa.value, hostMode: next.hostMode.configured })
233
+ }, [])
234
+
235
+ const refresh = React.useCallback(async () => {
236
+ const next = await request('/state')
237
+ applyState(next)
238
+ return next
239
+ }, [applyState])
240
+
241
+ React.useEffect(() => {
242
+ let alive = true
243
+ refresh().catch((err) => {
244
+ if (alive) setError(err?.message || t('unknownError'))
245
+ })
246
+ return () => {
247
+ alive = false
248
+ }
249
+ }, [refresh, t])
250
+
251
+ async function dropOfflineShell() {
252
+ try {
253
+ if (typeof caches !== 'undefined') {
254
+ const keys = await caches.keys()
255
+ await Promise.all(keys
256
+ .filter((key) => key.startsWith('dsh-gateway-'))
257
+ .map((key) => caches.delete(key)))
258
+ }
259
+ if ('serviceWorker' in navigator) {
260
+ const registrations = await navigator.serviceWorker.getRegistrations()
261
+ await Promise.all(registrations.map((registration) => registration.unregister()))
262
+ }
263
+ } catch {
264
+ // The server-side switch already took effect; a stale worker will
265
+ // disappear on its next update check even if this cleanup fails.
266
+ }
267
+ }
268
+
269
+ async function saveSettings() {
270
+ if (staged === null || state === null) return
271
+ setSaving(true)
272
+ setSaveFailed(false)
273
+ setError('')
274
+ setNotice('')
275
+ try {
276
+ const next = await request('/settings', {
277
+ method: 'POST',
278
+ body: JSON.stringify({ pwa: staged.pwa, hostMode: staged.hostMode })
279
+ })
280
+ if (staged.pwa === false) await dropOfflineShell()
281
+ applyState(next)
282
+ setNotice(t('saved'))
283
+ } catch (err) {
284
+ setSaveFailed(true)
285
+ setError(err?.message || t('unknownError'))
286
+ } finally {
287
+ setSaving(false)
288
+ }
289
+ }
290
+
291
+ async function clearCache() {
292
+ setError('')
293
+ setNotice('')
294
+ if (typeof caches === 'undefined') {
295
+ setNotice(t('cacheUnsupported'))
296
+ return
297
+ }
298
+ try {
299
+ const keys = await caches.keys()
300
+ await Promise.all(keys
301
+ .filter((key) => key.startsWith('dsh-gateway-'))
302
+ .map((key) => caches.delete(key)))
303
+ setNotice(t('cacheCleared'))
304
+ } catch (err) {
305
+ setError(err?.message || t('unknownError'))
306
+ }
307
+ }
308
+
309
+ async function signOut() {
310
+ if (!window.confirm(t('signOutConfirm'))) return
311
+ setBusy('logout')
312
+ setError('')
313
+ try {
314
+ await request('/logout', { method: 'POST', body: '{}' })
315
+ await dropOfflineShell()
316
+ window.location.assign('/')
317
+ } catch (err) {
318
+ setError(err?.message || t('unknownError'))
319
+ setBusy('')
320
+ }
321
+ }
322
+
323
+ if (view === 'summary') return t('summary')
324
+
325
+ if (state === null || staged === null) {
326
+ return React.createElement('p', { className: 'dshGatewayHint', role: 'status' }, error || t('loading'))
327
+ }
328
+
329
+ const busyNow = busy !== ''
330
+ const dirty = staged.pwa !== state.pwa.value || staged.hostMode !== state.hostMode.configured
331
+ const shell = {
332
+ available: true,
333
+ writable: true,
334
+ dirty,
335
+ invalid: false,
336
+ saving,
337
+ failed: saveFailed
338
+ }
339
+
340
+ return React.createElement('div', { className: 'dshGatewayPage' },
341
+ React.createElement(SettingsForm, {
342
+ labels: {
343
+ unavailable: t('unavailable'),
344
+ readOnly: t('readOnly'),
345
+ saveFailed: t('saveFailed'),
346
+ save: t('save'),
347
+ saving: t('saving')
348
+ },
349
+ state: shell,
350
+ onSave: () => { void saveSettings() },
351
+ onDiscard: () => {
352
+ setStaged({ pwa: state.pwa.value, hostMode: state.hostMode.configured })
353
+ setSaveFailed(false)
354
+ }
355
+ },
356
+ React.createElement('section', { className: 'dshGatewaySection' },
357
+ React.createElement('h3', { className: 'dshGatewayHeading' }, t('browser')),
358
+ React.createElement(ToggleField, {
359
+ label: t('pwaTitle'),
360
+ hint: t('pwaDesc'),
361
+ checked: staged.pwa,
362
+ disabled: busyNow || saving || state.pwa.locked,
363
+ badge: state.pwa.locked ? React.createElement('span', { className: 'dshGatewayBadge' }, t('envManaged')) : undefined,
364
+ onChange: (checked) => { setStaged((previous) => ({ ...previous, pwa: checked })) }
365
+ }),
366
+ React.createElement('div', { className: 'dshGatewayActions' },
367
+ React.createElement(Button, {
368
+ size: 'sm',
369
+ variant: 'outline',
370
+ disabled: busyNow,
371
+ onClick: () => { void clearCache() }
372
+ }, t('clearCache'))
373
+ )
374
+ ),
375
+ React.createElement('section', { className: 'dshGatewaySection' },
376
+ React.createElement('h3', { className: 'dshGatewayHeading' }, t('advanced')),
377
+ React.createElement(ToggleField, {
378
+ label: t('hostModeTitle'),
379
+ hint: t('hostModeDesc'),
380
+ checked: staged.hostMode,
381
+ disabled: busyNow || saving || state.hostMode.locked,
382
+ badge: state.hostMode.locked
383
+ ? React.createElement('span', { className: 'dshGatewayBadge' }, t('envManaged'))
384
+ : state.hostMode.restartRequired
385
+ ? React.createElement('span', { className: 'dshGatewayBadge dshGatewayBadgeWarn' }, t('restartRequired'))
386
+ : undefined,
387
+ warning: t('hostModeWarning'),
388
+ onChange: (checked) => { setStaged((previous) => ({ ...previous, hostMode: checked })) }
389
+ }),
390
+ state.hostMode.restartRequired
391
+ ? React.createElement('p', { className: 'dshGatewayHint' }, t('restartHint'))
392
+ : null
393
+ ),
394
+ React.createElement('section', { className: 'dshGatewaySection' },
395
+ React.createElement('h3', { className: 'dshGatewayHeading' }, t('access')),
396
+ React.createElement('dl', { className: 'dshGatewayRows' },
397
+ React.createElement(StatusFact, { label: t('authProvider'), value: t('authProviderValue') }),
398
+ React.createElement(StatusFact, { label: t('cookieName'), value: state.auth.cookieName })
399
+ ),
400
+ React.createElement('div', { className: 'dshGatewayField' },
401
+ React.createElement('span', { className: 'dshGatewayLabel' }, t('signOut')),
402
+ React.createElement('p', { className: 'dshGatewayHint' }, t('signOutDesc')),
403
+ React.createElement('p', { className: 'dshGatewayHint' }, t('signInHint')),
404
+ React.createElement('div', { className: 'dshGatewayActions' },
405
+ React.createElement(Button, {
406
+ size: 'sm',
407
+ variant: 'outline',
408
+ disabled: busyNow,
409
+ onClick: () => { void signOut() }
410
+ }, t('signOut'))
411
+ )
412
+ )
413
+ ),
414
+ React.createElement('section', { className: 'dshGatewaySection' },
415
+ React.createElement('h3', { className: 'dshGatewayHeading' }, t('status')),
416
+ React.createElement('dl', { className: 'dshGatewayRows' },
417
+ React.createElement(StatusFact, { label: t('listen'), value: `${state.listen.host}:${String(state.listen.port)}` }),
418
+ React.createElement(StatusFact, { label: t('upstream'), value: `${state.upstream.host}:${String(state.upstream.port)}` }),
419
+ React.createElement(StatusFact, { label: t('uptime'), value: formatUptime(state.uptimeMs, t) }),
420
+ React.createElement(StatusFact, { label: t('version'), value: state.version }),
421
+ React.createElement(StatusFact, { label: t('dataDir'), value: state.dataDir })
422
+ )
423
+ ),
424
+ error === '' ? null : React.createElement('p', { className: 'dshGatewayMessage dshGatewayError', role: 'alert' }, error),
425
+ notice === '' ? null : React.createElement('p', { className: 'dshGatewayMessage dshGatewayNotice', role: 'status' }, notice)
426
+ )
427
+ )
428
+ }
429
+
430
+ const inject = ['slots', 'locale']
431
+ const ROW_KEY = '@gitsang/dsh-gateway#gateway'
432
+
433
+ function apply(ctx) {
434
+ ctx.effect(
435
+ () => ctx.locale.register(NS, { zh, en }),
436
+ 'gateway: dictionaries'
437
+ )
438
+ ctx.slots.inject('plugins.row.config', () => ctx.slots.register(
439
+ {
440
+ name: 'plugins.row.config',
441
+ key: ROW_KEY,
442
+ locale: NS
443
+ },
444
+ GatewayConfig
445
+ ))
446
+ }
447
+
448
+ exports.apply = apply
449
+ exports.inject = inject
450
+ exports.__test = { formatUptime, GatewayConfig, ROW_KEY }
451
+ return module.exports
452
+ }
453
+ })