@linxin666/dsh-remote-web-ui 0.1.19 → 0.2.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.
Files changed (144) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +41 -19
  3. package/README.zh.md +17 -12
  4. package/assets/mobile-icon-192.png +0 -0
  5. package/assets/mobile-icon-512.png +0 -0
  6. package/assets/mobile-service-worker.js +64 -0
  7. package/lib/client.js +57 -13
  8. package/lib/client.js.map +1 -1
  9. package/lib/index.js +408 -130
  10. package/lib/mobile.js +296 -22
  11. package/lib/mobile.js.map +1 -1
  12. package/lib/types/client/FooterRemoteEntry.js +1 -1
  13. package/lib/types/client/PluginSettingsCard.d.ts +7 -1
  14. package/lib/types/client/PluginSettingsCard.d.ts.map +1 -1
  15. package/lib/types/client/PluginSettingsCard.js +5 -3
  16. package/lib/types/client/RemoteEntry.d.ts.map +1 -1
  17. package/lib/types/client/RemoteEntry.js +43 -13
  18. package/lib/types/client/RemotePanel.d.ts +1 -0
  19. package/lib/types/client/RemotePanel.d.ts.map +1 -1
  20. package/lib/types/client/RemotePanel.js +2 -2
  21. package/lib/types/client/RemoteSettingsCard.d.ts.map +1 -1
  22. package/lib/types/client/RemoteSettingsCard.js +3 -3
  23. package/lib/types/client/UpdateEntry.d.ts.map +1 -1
  24. package/lib/types/client/UpdateEntry.js +37 -4
  25. package/lib/types/client/UpdatePanel.js +1 -1
  26. package/lib/types/client/deep-link.js +2 -2
  27. package/lib/types/client/index.js +7 -7
  28. package/lib/types/client/locales.d.ts +2 -0
  29. package/lib/types/client/locales.d.ts.map +1 -1
  30. package/lib/types/client/locales.js +2 -0
  31. package/lib/types/client/settings-form.d.ts.map +1 -1
  32. package/lib/types/client/update-api.d.ts.map +1 -1
  33. package/lib/types/gate.d.ts +9 -0
  34. package/lib/types/gate.d.ts.map +1 -1
  35. package/lib/types/gate.js +16 -5
  36. package/lib/types/http.d.ts +14 -0
  37. package/lib/types/http.d.ts.map +1 -0
  38. package/lib/types/http.js +27 -0
  39. package/lib/types/index.d.ts +28 -1
  40. package/lib/types/index.d.ts.map +1 -1
  41. package/lib/types/index.js +41 -22
  42. package/lib/types/invariant.d.ts.map +1 -1
  43. package/lib/types/mobile/PairRequiredView.d.ts +7 -0
  44. package/lib/types/mobile/PairRequiredView.d.ts.map +1 -0
  45. package/lib/types/mobile/PairRequiredView.js +28 -0
  46. package/lib/types/mobile/PairRequiredView.test.d.ts +2 -0
  47. package/lib/types/mobile/PairRequiredView.test.d.ts.map +1 -0
  48. package/lib/types/mobile/PairRequiredView.test.js +24 -0
  49. package/lib/types/mobile/api.js +1 -1
  50. package/lib/types/mobile/index.js +17 -4
  51. package/lib/types/mobile/markdown.d.ts +6 -4
  52. package/lib/types/mobile/markdown.d.ts.map +1 -1
  53. package/lib/types/mobile/markdown.js +8 -4
  54. package/lib/types/mobile/markdown.test.js +5 -1
  55. package/lib/types/mobile/messages.d.ts.map +1 -1
  56. package/lib/types/mobile/messages.js +14 -1
  57. package/lib/types/mobile/messages.test.js +1 -1
  58. package/lib/types/mobile/mobile-styles.d.ts +1 -1
  59. package/lib/types/mobile/mobile-styles.d.ts.map +1 -1
  60. package/lib/types/mobile/mobile-styles.js +48 -0
  61. package/lib/types/mobile/mobile-theme.test.js +2 -2
  62. package/lib/types/mobile/mux.d.ts.map +1 -1
  63. package/lib/types/mobile/mux.js +1 -1
  64. package/lib/types/mobile/mux.test.js +1 -1
  65. package/lib/types/mobile/pairing.d.ts +31 -0
  66. package/lib/types/mobile/pairing.d.ts.map +1 -0
  67. package/lib/types/mobile/pairing.js +62 -0
  68. package/lib/types/mobile/rpc.d.ts.map +1 -1
  69. package/lib/types/mobile/theme-toggle.js +1 -1
  70. package/lib/types/mobile/views/App.d.ts +12 -16
  71. package/lib/types/mobile/views/App.d.ts.map +1 -1
  72. package/lib/types/mobile/views/App.js +39 -12
  73. package/lib/types/mobile/views/App.test.d.ts +2 -0
  74. package/lib/types/mobile/views/App.test.d.ts.map +1 -0
  75. package/lib/types/mobile/views/App.test.js +52 -0
  76. package/lib/types/mobile/views/ChatView.js +6 -6
  77. package/lib/types/mobile/views/ChatView.test.js +3 -3
  78. package/lib/types/mobile/views/SessionListView.js +3 -3
  79. package/lib/types/mobile/views/SessionListView.test.js +2 -2
  80. package/lib/types/mobile/views/WorkspaceView.js +3 -3
  81. package/lib/types/mobile/views/WorkspaceView.test.js +3 -3
  82. package/lib/types/mobile-api.d.ts +1 -1
  83. package/lib/types/mobile-api.d.ts.map +1 -1
  84. package/lib/types/mobile-api.js +11 -18
  85. package/lib/types/mobile-pwa.d.ts +6 -0
  86. package/lib/types/mobile-pwa.d.ts.map +1 -0
  87. package/lib/types/mobile-pwa.js +17 -0
  88. package/lib/types/mobile-routes.d.ts +5 -8
  89. package/lib/types/mobile-routes.d.ts.map +1 -1
  90. package/lib/types/mobile-routes.js +130 -39
  91. package/lib/types/mount-once.d.ts +25 -0
  92. package/lib/types/mount-once.d.ts.map +1 -0
  93. package/lib/types/mount-once.js +42 -0
  94. package/lib/types/pairing-access.d.ts +28 -0
  95. package/lib/types/pairing-access.d.ts.map +1 -0
  96. package/lib/types/pairing-access.js +26 -0
  97. package/lib/types/pairing.d.ts +27 -0
  98. package/lib/types/pairing.d.ts.map +1 -1
  99. package/lib/types/pairing.js +68 -0
  100. package/lib/types/pairing.persist.test.d.ts +2 -0
  101. package/lib/types/pairing.persist.test.d.ts.map +1 -0
  102. package/lib/types/pairing.persist.test.js +128 -0
  103. package/lib/types/routes.d.ts +6 -6
  104. package/lib/types/routes.d.ts.map +1 -1
  105. package/lib/types/routes.js +15 -20
  106. package/lib/types/tunnel.d.ts.map +1 -1
  107. package/lib/types/update-routes.d.ts +2 -2
  108. package/lib/types/update-routes.d.ts.map +1 -1
  109. package/lib/types/update-routes.js +1 -6
  110. package/lib/types/update.d.ts +3 -3
  111. package/lib/types/update.d.ts.map +1 -1
  112. package/lib/types/update.js +40 -14
  113. package/package.json +12 -12
  114. package/src/client/PluginSettingsCard.tsx +10 -0
  115. package/src/client/RemoteEntry.tsx +40 -8
  116. package/src/client/RemotePanel.tsx +1 -1
  117. package/src/client/RemoteSettingsCard.tsx +1 -0
  118. package/src/client/UpdateEntry.tsx +36 -4
  119. package/src/client/deep-link.ts +1 -1
  120. package/src/client/locales.ts +2 -0
  121. package/src/client/remote.module.css +26 -0
  122. package/src/gate.ts +15 -3
  123. package/src/http.ts +30 -0
  124. package/src/index.ts +50 -16
  125. package/src/mobile/PairRequiredView.test.tsx +28 -0
  126. package/src/mobile/PairRequiredView.tsx +58 -0
  127. package/src/mobile/index.tsx +15 -1
  128. package/src/mobile/markdown.test.ts +5 -0
  129. package/src/mobile/markdown.ts +7 -4
  130. package/src/mobile/messages.ts +14 -1
  131. package/src/mobile/mobile-styles.ts +48 -0
  132. package/src/mobile/pairing.ts +77 -0
  133. package/src/mobile/views/App.test.tsx +62 -0
  134. package/src/mobile/views/App.tsx +53 -18
  135. package/src/mobile-api.ts +9 -17
  136. package/src/mobile-pwa.ts +19 -0
  137. package/src/mobile-routes.ts +137 -38
  138. package/src/mount-once.ts +48 -0
  139. package/src/pairing-access.ts +36 -0
  140. package/src/pairing.persist.test.ts +145 -0
  141. package/src/pairing.ts +70 -1
  142. package/src/routes.ts +12 -18
  143. package/src/update-routes.ts +1 -7
  144. package/src/update.ts +46 -15
@@ -1,24 +1,26 @@
1
1
  /**
2
- * The mobile surface's page routes: `/m` serves the standalone phone UI
3
- * (an independent bundle, built to lib/mobile.js by the mobile tsdown
4
- * entry), `/m/mobile.js` serves the bundle itself. The page talks to the
5
- * host exclusively through the shared /api transport (paired-device cookie
6
- * already crosses the api/gate fence), so no host-side data plumbing is
7
- * needed here — only static serving, loopback+paired-fence via the normal
8
- * webserver route registration.
2
+ * The mobile surface's page routes: /m canonicalizes to /m/, which serves the
3
+ * standalone phone UI. The page and worker live in the /m/ scope so the PWA
4
+ * can cache only its static shell; the paired-device data channel remains at
5
+ * /m/api and is never handled by the worker.
9
6
  */
10
7
  import { readFile } from 'node:fs/promises';
11
8
  import { existsSync } from 'node:fs';
12
9
  import { fileURLToPath } from 'node:url';
10
+ const MOBILE_ROOT = '/m/';
11
+ const MOBILE_BUNDLE_URL = '/m/mobile.js';
12
+ const MOBILE_MANIFEST_URL = '/m/manifest.webmanifest';
13
+ const MOBILE_WORKER_URL = '/m/service-worker.js';
14
+ const MOBILE_OFFLINE_URL = '/m/offline.html';
13
15
  /** The standalone mobile bundle (built artifact, next to this file's own lib output). */
14
16
  function mobileBundlePath() {
15
17
  return fileURLToPath(new URL('../lib/mobile.js', import.meta.url));
16
18
  }
17
- /** The apple-touch-icon shipped with the package (iOS home-screen icon, 180x180 PNG). */
18
- function appleTouchIconPath() {
19
- return fileURLToPath(new URL('../assets/apple-touch-icon.png', import.meta.url));
19
+ /** A package asset available to the host after a registry or git install. */
20
+ function mobileAssetPath(name) {
21
+ return fileURLToPath(new URL('../assets/' + name, import.meta.url));
20
22
  }
21
- /** The mobile page shell: minimal, offline-safe, no external assets. */
23
+ /** The mobile page shell: self-contained, with no document-level user data. */
22
24
  function pageHtml(bundleUrl) {
23
25
  return [
24
26
  '<!doctype html>',
@@ -28,29 +30,73 @@ function pageHtml(bundleUrl) {
28
30
  '<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">',
29
31
  '<meta name="theme-color" content="#f3f5f9">',
30
32
  '<meta name="referrer" content="no-referrer">',
31
- // iOS "Add to Home Screen" uses apple-touch-icon for the tile icon;
32
- // the PNG ships with the package (opaque background — iOS composites
33
- // transparency onto black, so the icon avoids transparent regions).
33
+ '<meta name="mobile-web-app-capable" content="yes">',
34
+ '<meta name="apple-mobile-web-app-capable" content="yes">',
35
+ '<meta name="apple-mobile-web-app-title" content="DSH Remote">',
36
+ '<link rel="manifest" href="/m/manifest.webmanifest">',
34
37
  '<link rel="apple-touch-icon" href="/m/apple-touch-icon.png">',
35
38
  '<title>移动端远程控制</title>',
36
39
  '</head>',
37
40
  '<body>',
38
41
  '<div id="root"></div>',
39
- `<script type="module" src="${bundleUrl}"></script>`,
42
+ '<script type="module" src="' + bundleUrl + '"></script>',
40
43
  '</body>',
41
44
  '</html>',
42
45
  ].join('');
43
46
  }
44
- /** Send a small static body with cache headers (the bundle is content-hashed by rebuild). */
47
+ /** The installable app identity and icon declarations for the /m scope. */
48
+ function manifestJson() {
49
+ return JSON.stringify({
50
+ id: MOBILE_ROOT,
51
+ name: 'DSH Remote',
52
+ short_name: 'DSH Remote',
53
+ start_url: MOBILE_ROOT,
54
+ scope: MOBILE_ROOT,
55
+ display: 'standalone',
56
+ background_color: '#151424',
57
+ theme_color: '#f3f5f9',
58
+ icons: [
59
+ { src: '/m/icon-192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },
60
+ { src: '/m/icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'any maskable' },
61
+ ],
62
+ }, null, 2);
63
+ }
64
+ /** A static fallback that contains no paired-device, session, or workspace data. */
65
+ function offlineHtml() {
66
+ return [
67
+ '<!doctype html>',
68
+ '<html lang="zh-CN">',
69
+ '<head>',
70
+ '<meta charset="utf-8">',
71
+ '<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">',
72
+ '<meta name="theme-color" content="#151424">',
73
+ '<title>DSH Remote</title>',
74
+ '<style>body{margin:0;background:#151424;color:#f3f5f9;font:16px system-ui,sans-serif}main{box-sizing:border-box;display:grid;min-height:100vh;place-content:center;padding:32px;text-align:center}h1{margin:0 0 12px;font-size:24px}p{margin:0;color:#c4c7d8;line-height:1.5}</style>',
75
+ '</head>',
76
+ '<body><main><h1>DSH Remote</h1><p>Cannot reach the running DSH host. Restore the connection and reopen the app.</p></main></body>',
77
+ '</html>',
78
+ ].join('');
79
+ }
80
+ /** Send a small static UTF-8 body with revalidation headers. */
45
81
  function writeStatic(res, status, type, body) {
46
82
  res.writeHead(status, {
47
- 'content-type': `${type}; charset=utf-8`,
83
+ 'content-type': type + '; charset=utf-8',
84
+ 'cache-control': 'no-cache',
85
+ 'referrer-policy': 'no-referrer',
86
+ });
87
+ res.end(body);
88
+ }
89
+ /** Send the worker with the same scope it registers for, without HTTP caching. */
90
+ function writeServiceWorker(res, body) {
91
+ res.writeHead(200, {
92
+ 'content-type': 'text/javascript; charset=utf-8',
48
93
  'cache-control': 'no-cache',
49
94
  'referrer-policy': 'no-referrer',
95
+ 'service-worker-allowed': MOBILE_ROOT,
50
96
  });
51
97
  res.end(body);
52
98
  }
53
- /** Send the PNG icon as a binary body (unlike text assets, the PNG must not be decoded to utf-8). */
99
+ /** Send a PNG body without decoding it to UTF-8. */
54
100
  function writePng(res, status, body) {
55
101
  res.writeHead(status, {
56
102
  'content-type': 'image/png',
@@ -59,45 +105,90 @@ function writePng(res, status, body) {
59
105
  });
60
106
  res.end(body);
61
107
  }
108
+ /** Canonicalize the old /m route while retaining pair and workspace query parameters. */
109
+ function redirectToMobileRoot(req, res) {
110
+ const url = new URL(req.url ?? '/m', 'http://x');
111
+ res.writeHead(308, {
112
+ location: MOBILE_ROOT + url.search,
113
+ 'cache-control': 'no-store',
114
+ 'referrer-policy': 'no-referrer',
115
+ });
116
+ res.end();
117
+ }
62
118
  /**
63
119
  * Build the mobile page routes.
64
- * @returns the two exact routes to register on webServer.
120
+ * @returns Exact routes for the canonical page, static shell, and PWA assets.
65
121
  */
66
122
  export function makeMobileRoutes() {
67
123
  const handlePage = (_req, res) => {
68
- writeStatic(res, 200, 'text/html', pageHtml('/m/mobile.js'));
124
+ writeStatic(res, 200, 'text/html', pageHtml(MOBILE_BUNDLE_URL));
125
+ };
126
+ const handleManifest = (_req, res) => {
127
+ writeStatic(res, 200, 'application/manifest+json', manifestJson());
128
+ };
129
+ const handleOffline = (_req, res) => {
130
+ writeStatic(res, 200, 'text/html', offlineHtml());
69
131
  };
132
+ // The bundle is immutable for the process lifetime (a rebuild requires a
133
+ // host restart), so the body is read from disk once, not per phone.
134
+ let bundleBody;
70
135
  const handleBundle = async (_req, res) => {
71
- const path = mobileBundlePath();
72
- if (!existsSync(path)) {
73
- writeStatic(res, 503, 'text/plain', 'mobile bundle not built: run pnpm --filter @linxin666/dsh-remote-web-ui build');
74
- return;
75
- }
76
- try {
77
- const body = await readFile(path, 'utf8');
78
- writeStatic(res, 200, 'text/javascript', body);
136
+ if (bundleBody === undefined) {
137
+ const path = mobileBundlePath();
138
+ if (!existsSync(path)) {
139
+ writeStatic(res, 503, 'text/plain', 'mobile bundle not built: run pnpm --filter @linxin666/dsh-remote-web-ui build');
140
+ return;
141
+ }
142
+ try {
143
+ bundleBody = await readFile(path, 'utf8');
144
+ }
145
+ catch {
146
+ writeStatic(res, 500, 'text/plain', 'failed to read the mobile bundle');
147
+ return;
148
+ }
79
149
  }
80
- catch {
81
- writeStatic(res, 500, 'text/plain', 'failed to read the mobile bundle');
150
+ writeStatic(res, 200, 'text/javascript', bundleBody);
151
+ };
152
+ let workerBody;
153
+ const handleWorker = async (_req, res) => {
154
+ if (workerBody === undefined) {
155
+ const path = mobileAssetPath('mobile-service-worker.js');
156
+ if (!existsSync(path)) {
157
+ writeStatic(res, 503, 'text/plain', 'mobile service worker not found');
158
+ return;
159
+ }
160
+ try {
161
+ workerBody = await readFile(path, 'utf8');
162
+ }
163
+ catch {
164
+ writeStatic(res, 500, 'text/plain', 'failed to read the mobile service worker');
165
+ return;
166
+ }
82
167
  }
168
+ writeServiceWorker(res, workerBody);
83
169
  };
84
- const handleIcon = async (_req, res) => {
85
- const path = appleTouchIconPath();
170
+ const makeIconHandler = (asset) => async (_req, res) => {
171
+ const path = mobileAssetPath(asset);
86
172
  if (!existsSync(path)) {
87
- writeStatic(res, 404, 'text/plain', 'apple-touch-icon not found');
173
+ writeStatic(res, 404, 'text/plain', asset + ' not found');
88
174
  return;
89
175
  }
90
176
  try {
91
- const body = await readFile(path);
92
- writePng(res, 200, body);
177
+ writePng(res, 200, await readFile(path));
93
178
  }
94
179
  catch {
95
- writeStatic(res, 500, 'text/plain', 'failed to read the apple-touch-icon');
180
+ writeStatic(res, 500, 'text/plain', 'failed to read ' + asset);
96
181
  }
97
182
  };
98
183
  return [
99
- { kind: 'exact', path: '/m', handler: handlePage },
100
- { kind: 'exact', path: '/m/mobile.js', handler: handleBundle },
101
- { kind: 'exact', path: '/m/apple-touch-icon.png', handler: handleIcon },
184
+ { kind: 'exact', path: '/m', handler: redirectToMobileRoot },
185
+ { kind: 'exact', path: MOBILE_ROOT, handler: handlePage },
186
+ { kind: 'exact', path: MOBILE_BUNDLE_URL, handler: handleBundle },
187
+ { kind: 'exact', path: MOBILE_MANIFEST_URL, handler: handleManifest },
188
+ { kind: 'exact', path: MOBILE_WORKER_URL, handler: handleWorker },
189
+ { kind: 'exact', path: MOBILE_OFFLINE_URL, handler: handleOffline },
190
+ { kind: 'exact', path: '/m/apple-touch-icon.png', handler: makeIconHandler('apple-touch-icon.png') },
191
+ { kind: 'exact', path: '/m/icon-192.png', handler: makeIconHandler('mobile-icon-192.png') },
192
+ { kind: 'exact', path: '/m/icon-512.png', handler: makeIconHandler('mobile-icon-512.png') },
102
193
  ];
103
194
  }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Host single-instance guard shared by the plugin family. The family bundle
3
+ * (dsh-web-ui-all / dsh-skins) namespaces every child row id (web-ui-*), so
4
+ * the loader accepts a standalone install of the same package side by side;
5
+ * without this guard the second instance would still re-register the same
6
+ * webserver routes, tools, settings namespaces, and system-prompt sections
7
+ * and fail the boot. mountOnce makes the second host apply a no-op for the
8
+ * lifetime of the first instance (the browser half is already deduped by
9
+ * package name in the client module host).
10
+ *
11
+ * The registry rides a global symbol so two module instances of the same
12
+ * package (npm copy vs repository link) still share one verdict. cordis
13
+ * `ctx.effect` runs its callback immediately and treats the callback's
14
+ * return value as the fiber disposer, so the unmarker is returned, not run.
15
+ */
16
+ /**
17
+ * Wrap a cordis plugin apply so the package runs at most once per process.
18
+ * The first mount registers normally and unmarks when its fiber disposes;
19
+ * any later mount of the same package name is a no-op.
20
+ * @param packageName - npm package identity shared by every install source.
21
+ * @param fn - the original plugin apply.
22
+ * @returns an apply of the same shape.
23
+ */
24
+ export declare function mountOnce<T extends (...args: any[]) => unknown>(packageName: string, fn: T): T;
25
+ //# sourceMappingURL=mount-once.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mount-once.d.ts","sourceRoot":"","sources":["../../src/mount-once.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;;;;GAcG;AAaH;;;;;;;GAOG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,GAAG,CAAC,CAW9F"}
@@ -0,0 +1,42 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/host/mount-once.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
+ /**
3
+ * Host single-instance guard shared by the plugin family. The family bundle
4
+ * (dsh-web-ui-all / dsh-skins) namespaces every child row id (web-ui-*), so
5
+ * the loader accepts a standalone install of the same package side by side;
6
+ * without this guard the second instance would still re-register the same
7
+ * webserver routes, tools, settings namespaces, and system-prompt sections
8
+ * and fail the boot. mountOnce makes the second host apply a no-op for the
9
+ * lifetime of the first instance (the browser half is already deduped by
10
+ * package name in the client module host).
11
+ *
12
+ * The registry rides a global symbol so two module instances of the same
13
+ * package (npm copy vs repository link) still share one verdict. cordis
14
+ * `ctx.effect` runs its callback immediately and treats the callback's
15
+ * return value as the fiber disposer, so the unmarker is returned, not run.
16
+ */
17
+ const MOUNTED = Symbol.for('dsh-web-ui.mounted-plugins');
18
+ function mountedSet() {
19
+ const registry = globalThis;
20
+ return (registry[MOUNTED] ??= new Set());
21
+ }
22
+ /**
23
+ * Wrap a cordis plugin apply so the package runs at most once per process.
24
+ * The first mount registers normally and unmarks when its fiber disposes;
25
+ * any later mount of the same package name is a no-op.
26
+ * @param packageName - npm package identity shared by every install source.
27
+ * @param fn - the original plugin apply.
28
+ * @returns an apply of the same shape.
29
+ */
30
+ export function mountOnce(packageName, fn) {
31
+ return ((...args) => {
32
+ const mounted = mountedSet();
33
+ if (mounted.has(packageName))
34
+ return;
35
+ mounted.add(packageName);
36
+ const ctx = args[0];
37
+ ctx?.effect?.(() => () => {
38
+ mounted.delete(packageName);
39
+ });
40
+ return fn(...args);
41
+ });
42
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Optional cordis service other host plugins can ctx.get without taking a
3
+ * package dependency: a live paired-device cookie is an allow path on
4
+ * routes that sit outside /api (and therefore outside api/gate).
5
+ */
6
+ import type { IncomingMessage } from 'node:http';
7
+ import { Service, type Context } from '@deepseek-ai/cordis';
8
+ /** Named lookup key sibling plugins pass to ctx.get. */
9
+ export declare const REMOTE_WEB_UI_PAIRING = "remoteWebUiPairing";
10
+ /**
11
+ * Pairing identity for one HTTP request. Structural: consumers must not
12
+ * import this class, only the method shape.
13
+ */
14
+ export declare class RemoteWebUiPairing extends Service {
15
+ private readonly check;
16
+ /**
17
+ * @param ctx - host plugin context.
18
+ * @param check - live cookie + session predicate (re-read per request).
19
+ */
20
+ constructor(ctx: Context, check: (request: IncomingMessage) => boolean);
21
+ /**
22
+ * Whether the request carries a live paired-device cookie.
23
+ * @param request - the incoming HTTP request.
24
+ * @returns true when the session is live and was refreshed.
25
+ */
26
+ isPairedDevice(request: IncomingMessage): boolean;
27
+ }
28
+ //# sourceMappingURL=pairing-access.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pairing-access.d.ts","sourceRoot":"","sources":["../../src/pairing-access.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,WAAW,CAAA;AAChD,OAAO,EAAE,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAE3D,wDAAwD;AACxD,eAAO,MAAM,qBAAqB,uBAAuB,CAAA;AAEzD;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,OAAO;IAO3C,OAAO,CAAC,QAAQ,CAAC,KAAK;IANxB;;;OAGG;IACH,YACE,GAAG,EAAE,OAAO,EACK,KAAK,EAAE,CAAC,OAAO,EAAE,eAAe,KAAK,OAAO,EAG9D;IAED;;;;OAIG;IACH,cAAc,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAEhD;CACF"}
@@ -0,0 +1,26 @@
1
+ import { Service } from '@deepseek-ai/cordis';
2
+ /** Named lookup key sibling plugins pass to ctx.get. */
3
+ export const REMOTE_WEB_UI_PAIRING = 'remoteWebUiPairing';
4
+ /**
5
+ * Pairing identity for one HTTP request. Structural: consumers must not
6
+ * import this class, only the method shape.
7
+ */
8
+ export class RemoteWebUiPairing extends Service {
9
+ check;
10
+ /**
11
+ * @param ctx - host plugin context.
12
+ * @param check - live cookie + session predicate (re-read per request).
13
+ */
14
+ constructor(ctx, check) {
15
+ super(ctx, REMOTE_WEB_UI_PAIRING);
16
+ this.check = check;
17
+ }
18
+ /**
19
+ * Whether the request carries a live paired-device cookie.
20
+ * @param request - the incoming HTTP request.
21
+ * @returns true when the session is live and was refreshed.
22
+ */
23
+ isPairedDevice(request) {
24
+ return this.check(request);
25
+ }
26
+ }
@@ -87,6 +87,13 @@ export interface PairingConfig {
87
87
  maxDevices: number;
88
88
  /** Cookie name carrying the device id. */
89
89
  cookieName: string;
90
+ /**
91
+ * Path to a JSON file where paired device sessions are persisted. When
92
+ * set, sessions survive process restarts (the phone keeps its 365-day
93
+ * cookie), so re-pairing after a dsh web restart is not required. When
94
+ * unset (default), sessions stay memory-only — the previous behavior.
95
+ */
96
+ devicesFile?: string;
90
97
  }
91
98
  /** Result of one accept() attempt. */
92
99
  export type AcceptResult = {
@@ -138,6 +145,26 @@ export declare class PairingService {
138
145
  * @param clock - clock/entropy source (injectable for tests).
139
146
  */
140
147
  constructor(config: PairingConfig, clock?: PairingClock);
148
+ /**
149
+ * Restore device sessions persisted by a previous process run. A corrupt
150
+ * or missing file is tolerated (an empty device table, never a throw) —
151
+ * persistence is an availability convenience, not a security boundary.
152
+ */
153
+ private loadPersisted;
154
+ /** FIFO-cap the device table (a persisted file may outlive a lowered cap). */
155
+ private clampToMaxDevices;
156
+ /**
157
+ * Write the current device table to the configured file. Called on the
158
+ * mutation boundaries that change the set of live sessions (accept and
159
+ * stop); `lastSeenAt` refreshes are deliberately not persisted here so a
160
+ * per-request write storm is avoided — after a restart the phone's first
161
+ * heartbeat re-warms its own session.
162
+ *
163
+ * Device ids are session credentials (the gate authorizes requests by the
164
+ * cookie's device id), so the file is written 0600 via a temp file and
165
+ * atomic rename; a crash mid-write can never leave a half-written store.
166
+ */
167
+ private persist;
141
168
  /** The default LAN base URL (the first interface; undefined when not LAN-reachable). */
142
169
  get lanBaseUrl(): string | undefined;
143
170
  /** The LAN base URL for one specific literal (undefined when not constructible). */
@@ -1 +1 @@
1
- {"version":3,"file":"pairing.d.ts","sourceRoot":"","sources":["../../src/pairing.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAIH,uDAAuD;AACvD,MAAM,MAAM,YAAY;AACtB,mEAAmE;AACjE,cAAc;AAChB,oEAAoE;GAClE,SAAS;AACX,4DAA4D;GAC1D,SAAS;AACX,sDAAsD;GACpD,WAAW;AACb,6EAA6E;GAC3E,cAAc,CAAA;AAElB,sDAAsD;AACtD,MAAM,WAAW,WAAW;IAC1B,gEAAgE;IAChE,QAAQ,EAAE,MAAM,CAAA;IAChB,iEAAiE;IACjE,SAAS,EAAE,MAAM,CAAA;IACjB,iDAAiD;IACjD,QAAQ,EAAE,OAAO,CAAA;IACjB,sFAAsF;IACtF,EAAE,EAAE,MAAM,CAAA;IACV,iEAAiE;IACjE,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,2EAA2E;IAC3E,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED,8EAA8E;AAC9E,MAAM,WAAW,aAAa;IAC5B,+BAA+B;IAC/B,SAAS,EAAE,MAAM,CAAA;IACjB,gEAAgE;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AAO,CAAC,WAAW;IASnB,OAAO,CAAC,UAAU;IAIlB,OAAO,CAAC,MAAM;CAaf"}
@@ -15,6 +15,8 @@
15
15
  * devices are cut off on their next gated request.
16
16
  */
17
17
  import { randomBytes } from 'node:crypto';
18
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
19
+ import { dirname } from 'node:path';
18
20
  /** Thrown by issue() for an address outside the sampled LAN literals. */
19
21
  export class UnknownLanAddressError extends Error {
20
22
  /**
@@ -60,6 +62,70 @@ export class PairingService {
60
62
  constructor(config, clock = defaultClock) {
61
63
  this.config = config;
62
64
  this.clock = clock;
65
+ this.loadPersisted();
66
+ }
67
+ /**
68
+ * Restore device sessions persisted by a previous process run. A corrupt
69
+ * or missing file is tolerated (an empty device table, never a throw) —
70
+ * persistence is an availability convenience, not a security boundary.
71
+ */
72
+ loadPersisted() {
73
+ const file = this.config.devicesFile;
74
+ if (file === undefined)
75
+ return;
76
+ try {
77
+ const saved = JSON.parse(readFileSync(file, 'utf8'));
78
+ if (typeof saved !== 'object' || saved === null)
79
+ return;
80
+ for (const [deviceId, session] of Object.entries(saved)) {
81
+ if (typeof deviceId !== 'string')
82
+ continue;
83
+ if (typeof session !== 'object' || session === null)
84
+ continue;
85
+ const { createdAt, lastSeenAt } = session;
86
+ if (typeof createdAt !== 'number' || typeof lastSeenAt !== 'number')
87
+ continue;
88
+ this.devices.set(deviceId, { createdAt, lastSeenAt });
89
+ }
90
+ this.clampToMaxDevices();
91
+ }
92
+ catch {
93
+ // Unreadable/corrupt: start empty rather than refusing to boot.
94
+ }
95
+ }
96
+ /** FIFO-cap the device table (a persisted file may outlive a lowered cap). */
97
+ clampToMaxDevices() {
98
+ if (this.devices.size <= this.config.maxDevices)
99
+ return;
100
+ const overflow = this.devices.size - this.config.maxDevices;
101
+ const ordered = [...this.devices.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt);
102
+ for (const [id] of ordered.slice(0, overflow))
103
+ this.devices.delete(id);
104
+ }
105
+ /**
106
+ * Write the current device table to the configured file. Called on the
107
+ * mutation boundaries that change the set of live sessions (accept and
108
+ * stop); `lastSeenAt` refreshes are deliberately not persisted here so a
109
+ * per-request write storm is avoided — after a restart the phone's first
110
+ * heartbeat re-warms its own session.
111
+ *
112
+ * Device ids are session credentials (the gate authorizes requests by the
113
+ * cookie's device id), so the file is written 0600 via a temp file and
114
+ * atomic rename; a crash mid-write can never leave a half-written store.
115
+ */
116
+ persist() {
117
+ const file = this.config.devicesFile;
118
+ if (file === undefined)
119
+ return;
120
+ try {
121
+ mkdirSync(dirname(file), { recursive: true });
122
+ const temp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
123
+ writeFileSync(temp, JSON.stringify(Object.fromEntries(this.devices)), { mode: 0o600 });
124
+ renameSync(temp, file);
125
+ }
126
+ catch (error) {
127
+ console.error('remote-web-ui: failed to persist paired devices', error);
128
+ }
63
129
  }
64
130
  /** The default LAN base URL (the first interface; undefined when not LAN-reachable). */
65
131
  get lanBaseUrl() {
@@ -153,6 +219,7 @@ export class PairingService {
153
219
  this.devices.delete(oldest.id);
154
220
  }
155
221
  this.devices.set(deviceId, { createdAt: now, lastSeenAt: now });
222
+ this.persist();
156
223
  this.notify();
157
224
  return { ok: true, deviceId };
158
225
  }
@@ -164,6 +231,7 @@ export class PairingService {
164
231
  stop() {
165
232
  this.tokens.clear();
166
233
  this.devices.clear();
234
+ this.persist();
167
235
  this.stopped = true;
168
236
  this.notify();
169
237
  }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=pairing.persist.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pairing.persist.test.d.ts","sourceRoot":"","sources":["../../src/pairing.persist.test.ts"],"names":[],"mappings":""}