@gitsang/dsh-gateway 0.3.0 → 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/README.md CHANGED
@@ -8,9 +8,10 @@ the `web` profile: a gateway that starts beside `dsh web`, reverse proxies HTTP
8
8
  and WebSocket traffic to it, relays dsh's own token authentication, and can
9
9
  deliver the page as an installable PWA.
10
10
 
11
- Authentication is **dsh's**, not the gateway's. The gateway owns no password,
12
- no session store and no credential of its own: it forwards the signed cookie
13
- dsh minted and lets dsh decide.
11
+ Authentication is **dsh's**, not the gateway's. The gateway owns no password
12
+ and no session store: it forwards the signed cookie dsh minted and lets dsh
13
+ decide. Its one credential-related job is keeping the sign-in token stable
14
+ across restarts (see [Long-lived sign-in token](#long-lived-sign-in-token)).
14
15
 
15
16
  ## Why "gateway"
16
17
 
@@ -25,7 +26,8 @@ The package, bundle row, environment prefix and data directory all use
25
26
  ## How authentication works
26
27
 
27
28
  dsh mints one random launch token per process and prints (and usually opens) its
28
- application URL with `?token=…`. `GET /?token=…` exchanges that token for a
29
+ application URL with `?token=…` (the gateway replaces that per-process token
30
+ with a persistent one; see below). `GET /?token=…` exchanges the token for a
29
31
  signed browser cookie and redirects to the clean `./`. The cookie is:
30
32
 
31
33
  - named `dsh-auth-<base64url sha256 of the request authority>`,
@@ -59,13 +61,39 @@ cookie. Sign in with the URL the gateway prints:
59
61
 
60
62
  ```
61
63
  dsh-gateway: http://127.0.0.1:3081 -> http://127.0.0.1:3080
62
- dsh-gateway: sign in with http://127.0.0.1:3081/?token=…
64
+ dsh-gateway: sign in with http://127.0.0.1:3081/?token=… (stable across restarts)
63
65
  ```
64
66
 
65
- That URL is derived from dsh's own launch token, so it is only as secret as
66
- dsh's startup line. The token changes every time `dsh web` restarts; after a
67
- restart an existing browser keeps working while its cookie is valid, but a
68
- **new** browser needs the new URL.
67
+ ### Long-lived sign-in token
68
+
69
+ dsh itself mints a fresh random launch token per process, which would force
70
+ every new browser to fetch the new startup URL after each restart. The gateway
71
+ installs a **persistent token** instead, so the sign-in URL above never changes
72
+ and can be bookmarked or stored in a password manager:
73
+
74
+ - By default the gateway generates one random 256-bit token on first run and
75
+ persists it to `~/.dsh/gateway/token.txt` (owner-only permissions,
76
+ git-ignored).
77
+ - `DSH_GATEWAY_TOKEN` overrides it with a token you choose (at least 22
78
+ base64url characters, `[A-Za-z0-9_-]`). The env value is never written to
79
+ disk; removing the env falls back to the persisted/generated token.
80
+ - **Rotate** by deleting `token.txt` (or changing the env value) and restarting
81
+ `dsh web`. The old URL stops working; browsers that already hold a cookie
82
+ keep working, because cookies are signed with dsh's separate persistent
83
+ secret, not the launch token.
84
+ - Revoking every *cookie* is still dsh's operation: delete the
85
+ `client-connection/browser-session` record from `$DSH_HOME/.credentials.yaml`
86
+ and restart.
87
+
88
+ Implementation note: dsh exposes no configuration for a stable token, so the
89
+ gateway assigns its token to the Connection service's
90
+ `browserAuth.launchToken` at boot and verifies through the public
91
+ `authenticatedUrl()` that the assignment took effect. This is a deliberate
92
+ dependency on a dsh internal. If a future dsh version moves that field, the
93
+ gateway logs a warning and falls back to the stock behavior (a fresh token per
94
+ restart, printed in the startup line) — sign-in keeps working either way. The
95
+ configuration page shows which mode is active (**登录 Token**: 长期有效 /
96
+ 每次重启更换).
69
97
 
70
98
  ### Signing out
71
99
 
@@ -113,8 +141,23 @@ Revoking *every* session is dsh's own operation, not the gateway's:
113
141
  references the SVG icon only. This makes the gateway origin installable as a
114
142
  standalone web app on `localhost`/HTTPS.
115
143
 
116
- On first run the gateway creates a `~/.dsh/profiles/gateway/.gitignore` keeping
117
- `settings.json` out of git.
144
+ Gateway data is split by scope:
145
+
146
+ - **`token.txt`** (credential) lives in the home-level data directory
147
+ **`~/.dsh/gateway`**, beside `profiles/` — not inside it. `profiles/` is
148
+ reserved for bootable dsh profiles. On first run the gateway creates a
149
+ `~/.dsh/gateway/.gitignore` keeping the token out of git.
150
+ - **`settings.json`** (the PWA / Host-mode toggles) is profile-scoped
151
+ configuration and lives at **`<profile dir>/gateway/settings.json`**
152
+ (e.g. `~/.dsh/profiles/web/gateway/settings.json`), so a dotfiles-style
153
+ config repository can track it and carry it to another machine.
154
+
155
+ Versions before 0.5 kept both files in `~/.dsh/profiles/gateway`. On the first
156
+ boot after upgrading, the token is copied to `~/.dsh/gateway/` and the settings
157
+ file is moved into the running profile's `gateway/` directory automatically
158
+ (the current file always wins; stale copies are left in place and can be
159
+ deleted — if that directory was also booted as a real `gateway` profile,
160
+ remove the profile itself separately).
118
161
 
119
162
  ## Gateway configuration page
120
163
 
@@ -131,8 +174,9 @@ The page contains:
131
174
  caches.
132
175
  - **兼容性** — Host mode switch, with the security warning and restart
133
176
  requirement stated inline.
134
- - **访问控制** — the authentication provider and exact cookie name, the
135
- sign-in hint, and a **退出登录** button that expires this browser's cookie.
177
+ - **访问控制** — the authentication provider, whether the sign-in token is
178
+ persistent, the exact cookie name, the sign-in hint, and a **退出登录**
179
+ button that expires this browser's cookie.
136
180
  - **运行状态** — listen address, upstream dsh, uptime, version and data
137
181
  directory.
138
182
 
@@ -141,9 +185,10 @@ The page contains:
141
185
  Saving the form stages both switches and writes on **Save**. PWA changes take
142
186
  effect on the next page request. Host mode requires a restart of `dsh web`,
143
187
  because dsh's index injection is composed during boot. Settings saved on this
144
- page live in `settings.json`; they deliberately do not use dsh's own settings
145
- store, because turning Host mode off removes the browser's Host-settings
146
- transport and the gateway page must still be able to turn it back on.
188
+ page live in `<profile dir>/gateway/settings.json`; they deliberately do not
189
+ use dsh's own settings store, because turning Host mode off removes the
190
+ browser's Host-settings transport and the gateway page must still be able to
191
+ turn it back on.
147
192
 
148
193
  Environment variables win over the configuration page. When a toggle is managed
149
194
  by an environment variable, the page shows it as read-only.
@@ -193,9 +238,10 @@ All configuration is optional and read from environment variables at boot.
193
238
  | ----------------------- | ------------------------- | ----------------------------------------------------- |
194
239
  | `DSH_GATEWAY_HOST` | `127.0.0.1` | Gateway bind host |
195
240
  | `DSH_GATEWAY_PORT` | `dsh web port + 1` | Gateway listen port (overrides the default) |
196
- | `DSH_GATEWAY_DATA_DIR` | `~/.dsh/profiles/gateway` | Directory for gateway settings |
241
+ | `DSH_GATEWAY_DATA_DIR` | `~/.dsh/gateway` | Directory for gateway settings and token |
197
242
  | `DSH_GATEWAY_PWA` | `1` | Serve PWA assets and inject PWA tags into HTML |
198
243
  | `DSH_GATEWAY_HOST_MODE` | `1` | Declare the page a host-owning page (Host settings) |
244
+ | `DSH_GATEWAY_TOKEN` | generated, persisted | Fixed sign-in token (≥22 base64url chars); see above |
199
245
  | `DSH_HOME` | `~/.dsh` | dsh home (used when `DSH_GATEWAY_DATA_DIR` is unset) |
200
246
 
201
247
  ### PWA (installable web app)
@@ -349,10 +395,13 @@ to provide:
349
395
  limit, and no per-device revocation; revoking means deleting dsh's
350
396
  `client-connection/browser-session` credential record and restarting dsh,
351
397
  which signs out everyone.
352
- - **The launch token appears in a startup line and in the URL.** Treat the
353
- printed sign-in URL like a password, keep it out of logs and screenshots, and
354
- remember that query strings can land in reverse-proxy access logs. The token
355
- rotates on every `dsh web` restart.
398
+ - **The sign-in token is a long-lived credential in a URL.** Treat the printed
399
+ sign-in URL like a password: keep it out of logs and screenshots, and remember
400
+ that query strings can land in reverse-proxy access logs. Unlike dsh's stock
401
+ per-process token, the gateway's persistent token does **not** rotate on
402
+ restart — a leaked URL stays valid until you rotate it (delete `token.txt` or
403
+ change `DSH_GATEWAY_TOKEN`, then restart). `token.txt` is written with
404
+ owner-only permissions.
356
405
  - **Cookies last 30 days.** dsh's `connection.cookieMaxAgeDays` controls that.
357
406
  - **Plain HTTP leaks the cookie in transit.** dsh sets `Secure` only on a TLS
358
407
  listener; behind a TLS proxy the gateway adds it, but the gateway-to-dsh hop
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@gitsang/dsh-gateway",
3
3
  "description": "An installable gateway for the dsh web UI: reverse proxy on dsh token authentication, PWA delivery and Host-mode injection.",
4
- "version": "0.3.0",
4
+ "version": "0.5.0",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "test": "node --test"
package/src/client.js CHANGED
@@ -46,6 +46,11 @@ window.__ModuleLoader__.load({
46
46
  access: '访问控制',
47
47
  authProvider: '认证方式',
48
48
  authProviderValue: 'dsh launch token',
49
+ tokenLife: '登录 Token',
50
+ tokenPersistent: '长期有效(重启不变)',
51
+ tokenProcess: '每次重启更换',
52
+ tokenSourceEnv: '环境变量指定',
53
+ tokenSourceFile: '已持久化到数据目录',
49
54
  cookieName: '会话 Cookie',
50
55
  signOut: '退出登录',
51
56
  signOutDesc: '清除本浏览器持有的 dsh 会话 Cookie。dsh 没有登出接口,撤销全部会话需要删除凭据记录并重启 dsh。',
@@ -95,6 +100,11 @@ window.__ModuleLoader__.load({
95
100
  access: 'Access control',
96
101
  authProvider: 'Authentication',
97
102
  authProviderValue: 'dsh launch token',
103
+ tokenLife: 'Sign-in token',
104
+ tokenPersistent: 'Persistent (survives restarts)',
105
+ tokenProcess: 'Rotates on every restart',
106
+ tokenSourceEnv: 'Set by environment',
107
+ tokenSourceFile: 'Persisted in the data directory',
98
108
  cookieName: 'Session cookie',
99
109
  signOut: 'Sign out',
100
110
  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.',
@@ -395,6 +405,12 @@ window.__ModuleLoader__.load({
395
405
  React.createElement('h3', { className: 'dshGatewayHeading' }, t('access')),
396
406
  React.createElement('dl', { className: 'dshGatewayRows' },
397
407
  React.createElement(StatusFact, { label: t('authProvider'), value: t('authProviderValue') }),
408
+ React.createElement(StatusFact, {
409
+ label: t('tokenLife'),
410
+ value: state.auth.persistentToken
411
+ ? `${t('tokenPersistent')}${state.auth.tokenSource === 'env' ? ` · ${t('tokenSourceEnv')}` : ` · ${t('tokenSourceFile')}`}`
412
+ : t('tokenProcess')
413
+ }),
398
414
  React.createElement(StatusFact, { label: t('cookieName'), value: state.auth.cookieName })
399
415
  ),
400
416
  React.createElement('div', { className: 'dshGatewayField' },
package/src/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { createServer } from 'node:http'
2
2
  import { readFileSync } from 'node:fs'
3
+ import { copyFile, mkdir, stat } from 'node:fs/promises'
3
4
  import { networkInterfaces, homedir } from 'node:os'
4
5
  import { join } from 'node:path'
5
6
  import { Service } from '@deepseek-ai/cordis'
@@ -8,6 +9,7 @@ import { dshCookieName, probeBrowserSession, proxyRequest, proxyUpgrade, targetA
8
9
  import { readRequestBody } from './pages.js'
9
10
  import { ICON_SVG, MANIFEST, SW_DISABLED_JS, SW_JS } from './pwa.js'
10
11
  import { GatewaySettingsStore } from './settings-store.js'
12
+ import { LaunchTokenStore } from './token-store.js'
11
13
 
12
14
  export const name = 'gateway'
13
15
  // `connection` is optional: the gateway still proxies when a composition omits
@@ -24,6 +26,7 @@ const PORT_ENV = ['DSH_GATEWAY_PORT']
24
26
  const DATA_DIR_ENV = ['DSH_GATEWAY_DATA_DIR']
25
27
  const PWA_ENV = ['DSH_GATEWAY_PWA']
26
28
  const HOST_MODE_ENV = ['DSH_GATEWAY_HOST_MODE']
29
+ const TOKEN_ENV = ['DSH_GATEWAY_TOKEN']
27
30
 
28
31
  /** Read the first non-empty environment variable from a compatibility list. */
29
32
  function envValue(names) {
@@ -60,11 +63,58 @@ function envBoolOverride(names) {
60
63
  return raw === undefined ? undefined : parseBool(raw)
61
64
  }
62
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
+ */
63
75
  function defaultDataDir() {
64
76
  const explicit = envValue(DATA_DIR_ENV)
65
77
  if (explicit !== undefined) return explicit
66
78
  const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
67
- return join(dshHome, 'profiles', 'gateway')
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
+ }
68
118
  }
69
119
 
70
120
  export const Config = z.object({
@@ -96,13 +146,65 @@ function lanAddresses() {
96
146
  .map((iface) => iface.address)
97
147
  }
98
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
+
99
183
  class DshGateway extends Service {
100
184
  static Config = Config
101
185
 
102
186
  constructor(ctx, config) {
103
187
  super(ctx, 'gateway')
104
188
  this.config = config
105
- this.settings = new GatewaySettingsStore(join(config.dataDir, 'settings.json'))
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
106
208
  this.envOverrides = {
107
209
  pwa: envBoolOverride(PWA_ENV),
108
210
  hostMode: envBoolOverride(HOST_MODE_ENV)
@@ -118,7 +220,8 @@ class DshGateway extends Service {
118
220
  }
119
221
 
120
222
  async [Service.init]() {
121
- await this.settings.init()
223
+ await migrateLegacyDataDir(this.config.dataDir, this.ctx.logger)
224
+ await Promise.all([this.settings.init(), this.launchToken.init()])
122
225
 
123
226
  const saved = this.settings.snapshot()
124
227
  this.runtimePwa = this.envOverrides.pwa ?? saved.pwa ?? this.config.pwa
@@ -193,7 +296,12 @@ class DshGateway extends Service {
193
296
  // Connection mounts after this row in the shipped web composition, so the
194
297
  // launch token only exists once that service appears. Waiving readiness is
195
298
  // safe: this is a log line, not part of serving traffic.
196
- this.ctx.inject(['connection'], () => {
299
+ this.ctx.inject(['connection'], (connCtx) => {
300
+ this.persistentToken = installLaunchToken(
301
+ connCtx.get('connection'),
302
+ this.launchToken.token,
303
+ this.ctx.logger
304
+ )
197
305
  this.printSignInUrl(target)
198
306
  })
199
307
  }
@@ -286,7 +394,9 @@ class DshGateway extends Service {
286
394
  provider: 'dsh',
287
395
  // dsh's cookie name is a deterministic hash of the authority it was
288
396
  // minted for; the gateway always forwards the loopback authority.
289
- cookieName: dshCookieName(targetAuthority(this.target))
397
+ cookieName: dshCookieName(targetAuthority(this.target)),
398
+ persistentToken: this.persistentToken,
399
+ tokenSource: this.persistentToken ? this.launchToken.source : 'process'
290
400
  },
291
401
  pwa: {
292
402
  value: this.runtimePwa,
@@ -438,11 +548,12 @@ class DshGateway extends Service {
438
548
  /**
439
549
  * Print the one URL that signs a browser in.
440
550
  *
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.
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.
446
557
  */
447
558
  printSignInUrl(target) {
448
559
  const tokenized = this.tokenizedUrl(targetAuthority(target))
@@ -453,7 +564,8 @@ class DshGateway extends Service {
453
564
  }
454
565
  const host = this.config.host === '0.0.0.0' ? '127.0.0.1' : this.config.host
455
566
  const urlHost = host.includes(':') ? `[${host}]` : host
456
- console.log(`dsh-gateway: sign in with http://${urlHost}:${String(this.proxyPort)}/?token=${encodeURIComponent(token)}`)
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}`)
457
569
  }
458
570
 
459
571
  async close() {
@@ -1,11 +1,15 @@
1
+ import { access, mkdir, rename } from 'node:fs/promises'
1
2
  import { dirname } from 'node:path'
2
- import { atomicWrite, ensureDataDir, readJsonFile } from './stores.js'
3
+ import { atomicWrite, readJsonFile } from './stores.js'
3
4
 
4
5
  /** Toggles owned by the gateway settings page. */
5
6
  export const GATEWAY_SETTING_KEYS = ['pwa', 'hostMode']
6
7
 
7
8
  /**
8
- * User-facing gateway preferences, kept separate from auth.json/session.json.
9
+ * User-facing gateway preferences: profile-scoped configuration stored at
10
+ * `<profile dir>/gateway/settings.json`, so the file travels with the
11
+ * profile's config repository. Credentials (`token.txt`) are a different
12
+ * scope and stay in the home-level data directory, git-ignored.
9
13
  *
10
14
  * These deliberately do not live in dsh's own settings store: turning Host
11
15
  * mode off removes the browser's Host-settings transport, and this page must
@@ -13,14 +17,20 @@ export const GATEWAY_SETTING_KEYS = ['pwa', 'hostMode']
13
17
  * the only bootstrap-safe place for the switch.
14
18
  */
15
19
  export class GatewaySettingsStore {
16
- constructor(file) {
20
+ /**
21
+ * @param file - current settings path (`<profile dir>/gateway/settings.json`).
22
+ * @param legacyFiles - pre-0.5.0 locations, newest first; adopted on init.
23
+ */
24
+ constructor(file, legacyFiles = []) {
17
25
  this.file = file
26
+ this.legacyFiles = legacyFiles.filter((candidate) => candidate !== file)
18
27
  this.values = {}
19
28
  this.writeQueue = Promise.resolve()
20
29
  }
21
30
 
22
31
  async init() {
23
- await ensureDataDir(dirname(this.file))
32
+ await mkdir(dirname(this.file), { recursive: true })
33
+ await this.adoptLegacyFile()
24
34
  const data = await readJsonFile(this.file)
25
35
  this.values = {}
26
36
  for (const key of GATEWAY_SETTING_KEYS) {
@@ -28,6 +38,32 @@ export class GatewaySettingsStore {
28
38
  }
29
39
  }
30
40
 
41
+ /**
42
+ * Move a pre-0.5.0 settings file to the profile-scoped location once. The
43
+ * current file always wins; a failed move is non-fatal because the legacy
44
+ * copy stays readable and the next init retries.
45
+ */
46
+ async adoptLegacyFile() {
47
+ const exists = async (file) => {
48
+ try {
49
+ await access(file)
50
+ return true
51
+ } catch {
52
+ return false
53
+ }
54
+ }
55
+ if (await exists(this.file)) return
56
+ for (const legacy of this.legacyFiles) {
57
+ if (!(await exists(legacy))) continue
58
+ try {
59
+ await rename(legacy, this.file)
60
+ } catch {
61
+ // Leave the legacy copy in place; values below still fall back to it.
62
+ }
63
+ return
64
+ }
65
+ }
66
+
31
67
  has(key) {
32
68
  return Object.prototype.hasOwnProperty.call(this.values, key)
33
69
  }
@@ -56,4 +92,4 @@ export class GatewaySettingsStore {
56
92
  this.writeQueue = this.writeQueue.then(write, write)
57
93
  return this.writeQueue
58
94
  }
59
- }
95
+ }
package/src/stores.js CHANGED
@@ -14,22 +14,25 @@ export async function atomicWrite(file, data) {
14
14
 
15
15
  /**
16
16
  * Create the data directory and a `.gitignore` that keeps the gateway's local
17
- * settings file out of git. The profile directory itself may be a git checkout
18
- * or sit beside one; ignore entries are added only when the file does not
19
- * already exist.
17
+ * settings and credential files out of git. The profile directory itself may be
18
+ * a git checkout or sit beside one. Entries are merged into an existing file so
19
+ * an upgrade adds `token.txt` to a `.gitignore` written by an older version.
20
20
  */
21
21
  export async function ensureDataDir(dir) {
22
22
  await mkdir(dir, { recursive: true })
23
23
  const gitignore = join(dir, '.gitignore')
24
+ const required = ['settings.json', 'token.txt']
25
+ let existing = ''
24
26
  try {
25
- await readFile(gitignore, 'utf8')
27
+ existing = await readFile(gitignore, 'utf8')
26
28
  } catch (err) {
27
- if (err?.code === 'ENOENT') {
28
- await writeFile(gitignore, 'settings.json\n', 'utf8')
29
- return
30
- }
31
- throw err
29
+ if (err?.code !== 'ENOENT') throw err
32
30
  }
31
+ const lines = existing.split('\n').map((line) => line.trim())
32
+ const missing = required.filter((entry) => !lines.includes(entry))
33
+ if (missing.length === 0) return
34
+ const prefix = existing === '' || existing.endsWith('\n') ? existing : `${existing}\n`
35
+ await writeFile(gitignore, `${prefix}${missing.join('\n')}\n`, 'utf8')
33
36
  }
34
37
 
35
38
  export async function readJsonFile(file) {
@@ -0,0 +1,77 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises'
3
+ import { dirname } from 'node:path'
4
+
5
+ /**
6
+ * A launch token dsh will accept: base64url text. dsh compares the query token
7
+ * to its own with a constant-time byte comparison, so any such string works;
8
+ * the length floor keeps a casually chosen secret from being guessable.
9
+ */
10
+ const TOKEN_PATTERN = /^[A-Za-z0-9_-]{22,}$/
11
+
12
+ /** Whether `value` is usable as a launch token. */
13
+ export function isValidToken(value) {
14
+ return typeof value === 'string' && TOKEN_PATTERN.test(value)
15
+ }
16
+
17
+ /**
18
+ * The gateway's persistent launch token.
19
+ *
20
+ * dsh mints a fresh random launch token per process, which forces every new
21
+ * browser to fetch the new startup URL after each restart. The gateway keeps
22
+ * one stable token instead — from `DSH_GATEWAY_TOKEN` when set, otherwise a
23
+ * generated secret persisted in the data directory — and installs it into
24
+ * dsh's Connection at boot (see `installLaunchToken` in index.js). The sign-in
25
+ * URL then survives restarts and can be bookmarked.
26
+ *
27
+ * The token is a credential: the file is written with owner-only permissions
28
+ * and listed in the data directory's .gitignore.
29
+ */
30
+ export class LaunchTokenStore {
31
+ /**
32
+ * @param file - path of the persisted token file.
33
+ * @param envToken - `DSH_GATEWAY_TOKEN` value, or undefined.
34
+ * @param logger - optional logger for a rejected env value.
35
+ */
36
+ constructor(file, envToken, logger) {
37
+ this.file = file
38
+ this.envToken = envToken
39
+ this.logger = logger
40
+ this.token = null
41
+ this.source = 'generated'
42
+ }
43
+
44
+ async init() {
45
+ await mkdir(dirname(this.file), { recursive: true })
46
+
47
+ if (this.envToken !== undefined && this.envToken !== '') {
48
+ if (isValidToken(this.envToken)) {
49
+ this.token = this.envToken
50
+ this.source = 'env'
51
+ return
52
+ }
53
+ this.logger?.warn(
54
+ 'dsh-gateway: DSH_GATEWAY_TOKEN must be at least 22 base64url characters ([A-Za-z0-9_-]); ignoring it'
55
+ )
56
+ }
57
+
58
+ let stored
59
+ try {
60
+ stored = (await readFile(this.file, 'utf8')).trim()
61
+ } catch (err) {
62
+ if (err?.code !== 'ENOENT') throw err
63
+ }
64
+ if (isValidToken(stored)) {
65
+ this.token = stored
66
+ this.source = 'file'
67
+ // Repair permissions on a file an older version or a copy left open.
68
+ await chmod(this.file, 0o600).catch(() => {})
69
+ return
70
+ }
71
+
72
+ this.token = randomBytes(32).toString('base64url')
73
+ this.source = 'generated'
74
+ await writeFile(this.file, `${this.token}\n`, { encoding: 'utf8', mode: 0o600 })
75
+ await chmod(this.file, 0o600).catch(() => {})
76
+ }
77
+ }