@walkhi/code-relax 0.1.0-beta.30 → 0.1.0-beta.32

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 (187) hide show
  1. package/README.md +95 -89
  2. package/dist/bin/cleanup-accounts.mjs +63 -63
  3. package/dist/bin/codex-remote.mjs +374 -367
  4. package/dist/bin/manage-relay-admin.mjs +20 -20
  5. package/dist/bin/migrate-relay-db.mjs +109 -109
  6. package/dist/bin/publish-android-release.mjs +63 -58
  7. package/dist/bin/publish-harmony-release.mjs +46 -0
  8. package/dist/bin/release-upload-server.mjs +174 -0
  9. package/dist/bin/self-relay-admin.mjs +8 -8
  10. package/dist/bin/self-relay-demo.mjs +33 -33
  11. package/dist/bin/self-relay-server.mjs +66 -66
  12. package/dist/build-platform.json +1 -1
  13. package/dist/get-lan-networks.ps1 +40 -40
  14. package/dist/get-shared-service-url.ps1 +6 -6
  15. package/dist/shared/app-server-events.cjs +422 -412
  16. package/dist/shared/code-browser.cjs +159 -159
  17. package/dist/shared/file-changes.cjs +31 -31
  18. package/dist/shared/file-citations.cjs +117 -117
  19. package/dist/shared/file-mentions.cjs +92 -92
  20. package/dist/shared/message-delivery.cjs +54 -54
  21. package/dist/shared/p2p-data-channel.cjs +72 -72
  22. package/dist/shared/p2p-diagnostics.cjs +28 -28
  23. package/dist/shared/p2p-file-channel.cjs +78 -74
  24. package/dist/shared/plan-pricing.cjs +32 -32
  25. package/dist/shared/question-attention.cjs +69 -0
  26. package/dist/shared/server-requests.cjs +219 -219
  27. package/dist/shared/timeline-sync.cjs +173 -173
  28. package/dist/skills/code-relax/SKILL.md +22 -22
  29. package/dist/src/archived-threads.mjs +22 -0
  30. package/dist/src/background-process.mjs +18 -18
  31. package/dist/src/bounded-process-log.mjs +63 -63
  32. package/dist/src/celsius-client.mjs +107 -107
  33. package/dist/src/code-browser.mjs +100 -100
  34. package/dist/src/desktop-launcher.mjs +46 -46
  35. package/dist/src/dots-approval-timeline.mjs +99 -99
  36. package/dist/src/dots-avatar.mjs +42 -42
  37. package/dist/src/dots-chat-projection.mjs +50 -50
  38. package/dist/src/dots-chat-server.mjs +461 -461
  39. package/dist/src/dots-message-images.mjs +319 -319
  40. package/dist/src/dots-profile.mjs +77 -77
  41. package/dist/src/dots-room-activity.mjs +94 -94
  42. package/dist/src/dots-room-client.mjs +135 -135
  43. package/dist/src/dots-room-projection.mjs +94 -94
  44. package/dist/src/dots-schedules.mjs +66 -66
  45. package/dist/src/dots-summary-tasks.mjs +32 -32
  46. package/dist/src/dots-task-catalog.mjs +430 -430
  47. package/dist/src/dots-task-files.mjs +52 -52
  48. package/dist/src/execution-health.mjs +26 -26
  49. package/dist/src/file-transfer-range.mjs +22 -22
  50. package/dist/src/file-upload-session.mjs +130 -130
  51. package/dist/src/hosted-history-app-server.mjs +103 -103
  52. package/dist/src/hosted-history-cache.mjs +113 -113
  53. package/dist/src/lan-socket-server.mjs +265 -263
  54. package/dist/src/managed-app-server.mjs +244 -244
  55. package/dist/src/message-images.mjs +9 -9
  56. package/dist/src/message-upload-files.mjs +74 -74
  57. package/dist/src/onboarding.mjs +12 -12
  58. package/dist/src/plan-pricing.mjs +47 -47
  59. package/dist/src/platform/README.md +12 -12
  60. package/dist/src/platform/codex-protocol.mjs +46 -46
  61. package/dist/src/platform/codex-runtime.mjs +3 -3
  62. package/dist/src/platform/credential-store.mjs +3 -3
  63. package/dist/src/platform/desktop-host.mjs +3 -3
  64. package/dist/src/platform/desktop-project-registration.mjs +3 -3
  65. package/dist/src/platform/desktop-project-store.mjs +208 -149
  66. package/dist/src/platform/file-opener.mjs +9 -0
  67. package/dist/src/platform/linux/README.md +3 -3
  68. package/dist/src/platform/linux/codex-runtime.mjs +56 -0
  69. package/dist/src/platform/linux/credential-store.mjs +28 -0
  70. package/dist/src/platform/linux/desktop-host.mjs +83 -0
  71. package/dist/src/platform/linux/desktop-installation.mjs +36 -0
  72. package/dist/src/platform/linux/desktop-project-registration.mjs +11 -0
  73. package/dist/src/platform/linux/network-info.mjs +11 -0
  74. package/dist/src/platform/linux/process.mjs +42 -0
  75. package/dist/src/platform/linux/project-locations.mjs +17 -0
  76. package/dist/src/platform/linux/resident-startup.mjs +52 -0
  77. package/dist/src/platform/linux/retained-runtime.mjs +76 -0
  78. package/dist/src/platform/linux/service-host.mjs +18 -0
  79. package/dist/src/platform/linux/system.mjs +49 -0
  80. package/dist/src/platform/linux/user-environment.mjs +7 -0
  81. package/dist/src/platform/macos/README.md +3 -3
  82. package/dist/src/platform/macos/codex-runtime.mjs +125 -125
  83. package/dist/src/platform/macos/credential-store.mjs +10 -10
  84. package/dist/src/platform/macos/desktop-host.mjs +82 -82
  85. package/dist/src/platform/macos/desktop-project-registration.mjs +11 -10
  86. package/dist/src/platform/macos/network-info.mjs +8 -28
  87. package/dist/src/platform/macos/project-locations.mjs +8 -8
  88. package/dist/src/platform/macos/resident-startup.mjs +84 -84
  89. package/dist/src/platform/macos/retained-runtime.mjs +127 -127
  90. package/dist/src/platform/macos/service-host.mjs +18 -18
  91. package/dist/src/platform/macos/system.mjs +29 -29
  92. package/dist/src/platform/macos/user-environment.mjs +7 -7
  93. package/dist/src/platform/native-package.mjs +58 -46
  94. package/dist/src/platform/network-info.mjs +3 -3
  95. package/dist/src/platform/path-identity.mjs +5 -5
  96. package/dist/src/platform/posix/network-candidates.mjs +23 -0
  97. package/dist/src/platform/posix/runtime-paths.mjs +25 -25
  98. package/dist/src/platform/project-locations.mjs +3 -3
  99. package/dist/src/platform/runtime-paths.mjs +8 -8
  100. package/dist/src/platform/select.mjs +5 -5
  101. package/dist/src/platform/service-host.mjs +3 -3
  102. package/dist/src/platform/user-environment.mjs +3 -3
  103. package/dist/src/platform/windows/IsolatedProcess.cs +79 -79
  104. package/dist/src/platform/windows/activate-desktop.ps1 +48 -48
  105. package/dist/src/platform/windows/background-process.mjs +30 -30
  106. package/dist/src/platform/windows/codex-runtime.mjs +215 -215
  107. package/dist/src/platform/windows/credential-store.mjs +27 -27
  108. package/dist/src/platform/windows/credential-store.ps1 +49 -49
  109. package/dist/src/platform/windows/desktop-helper.mjs +179 -179
  110. package/dist/src/platform/windows/desktop-host.mjs +58 -58
  111. package/dist/src/platform/windows/desktop-info.ps1 +14 -14
  112. package/dist/src/platform/windows/desktop-project-registration.mjs +4 -4
  113. package/dist/src/platform/windows/desktop-runtime.ps1 +10 -10
  114. package/dist/src/platform/windows/desktop-shortcuts.ps1 +21 -21
  115. package/dist/src/platform/windows/dots-profile.mjs +49 -49
  116. package/dist/src/platform/windows/launch-worker.mjs +41 -41
  117. package/dist/src/platform/windows/network-info.mjs +34 -34
  118. package/dist/src/platform/windows/project-locations.mjs +16 -16
  119. package/dist/src/platform/windows/resident-start.js +20 -20
  120. package/dist/src/platform/windows/resident-start.ps1 +7 -7
  121. package/dist/src/platform/windows/resident-startup.ps1 +83 -83
  122. package/dist/src/platform/windows/resolve-state-root.ps1 +14 -14
  123. package/dist/src/platform/windows/runtime-paths.mjs +20 -20
  124. package/dist/src/platform/windows/rustdesk-video-probe.mjs +167 -167
  125. package/dist/src/platform/windows/service-host.mjs +31 -31
  126. package/dist/src/platform/windows/start-hidden-console.ps1 +49 -49
  127. package/dist/src/platform/windows/stop-desktop.ps1 +22 -22
  128. package/dist/src/platform/windows/user-environment.mjs +50 -50
  129. package/dist/src/platform/windows/user-environment.ps1 +41 -41
  130. package/dist/src/project-archive.mjs +30 -0
  131. package/dist/src/project-create.mjs +121 -119
  132. package/dist/src/project-management.mjs +59 -69
  133. package/dist/src/project-remove.mjs +55 -0
  134. package/dist/src/project-update.mjs +56 -0
  135. package/dist/src/runtime-discovery.mjs +47 -47
  136. package/dist/src/self-relay/account-cleanup.mjs +30 -30
  137. package/dist/src/self-relay/account-connections.mjs +52 -52
  138. package/dist/src/self-relay/admin-cloud.mjs +101 -101
  139. package/dist/src/self-relay/admin-page.mjs +80 -80
  140. package/dist/src/self-relay/admin-server.mjs +74 -74
  141. package/dist/src/self-relay/admin-state.mjs +127 -127
  142. package/dist/src/self-relay/admin-style.mjs +14 -14
  143. package/dist/src/self-relay/android-releases.mjs +61 -61
  144. package/dist/src/self-relay/client.mjs +61 -61
  145. package/dist/src/self-relay/connector.mjs +439 -438
  146. package/dist/src/self-relay/debug-allowlist.mjs +33 -33
  147. package/dist/src/self-relay/demo.mjs +37 -37
  148. package/dist/src/self-relay/device-info.mjs +27 -0
  149. package/dist/src/self-relay/device-store.mjs +92 -84
  150. package/dist/src/self-relay/diagnostics.mjs +54 -54
  151. package/dist/src/self-relay/email-accounts.mjs +183 -183
  152. package/dist/src/self-relay/file-wire.mjs +13 -13
  153. package/dist/src/self-relay/lan-authorizations.mjs +71 -42
  154. package/dist/src/self-relay/lifecycle.mjs +264 -250
  155. package/dist/src/self-relay/long-pairing.mjs +40 -40
  156. package/dist/src/self-relay/mysql-state.mjs +118 -105
  157. package/dist/src/self-relay/p2p-probe.mjs +159 -159
  158. package/dist/src/self-relay/privacy-page.mjs +26 -26
  159. package/dist/src/self-relay/public-releases.mjs +52 -0
  160. package/dist/src/self-relay/rtc-file-bridge.mjs +41 -41
  161. package/dist/src/self-relay/server.mjs +1006 -932
  162. package/dist/src/self-relay/usage-daily.mjs +55 -55
  163. package/dist/src/self-relay/usage-meter.mjs +141 -141
  164. package/dist/src/self-relay/windows-route-helper.mjs +75 -75
  165. package/dist/src/self-relay/wire.mjs +36 -36
  166. package/dist/src/server.mjs +1861 -1778
  167. package/dist/src/service-control.mjs +82 -82
  168. package/dist/src/service-doctor.mjs +110 -110
  169. package/dist/src/service-health.mjs +33 -33
  170. package/dist/src/service-install.mjs +91 -91
  171. package/dist/src/service-lifecycle.mjs +138 -138
  172. package/dist/src/service-restart.mjs +81 -81
  173. package/dist/src/shared-app-server.mjs +615 -611
  174. package/dist/src/shared-catalog.mjs +132 -132
  175. package/dist/src/shared-recovery.mjs +146 -146
  176. package/dist/src/shared-thread-stream.mjs +164 -164
  177. package/dist/src/skill-install.mjs +51 -51
  178. package/dist/src/thread-title-generation.mjs +150 -150
  179. package/dist/src/turn-model-history.mjs +47 -47
  180. package/dist/src/usage-reset.mjs +17 -17
  181. package/dist/src/workstation-downloads.mjs +120 -120
  182. package/dist/tools/rtc-route-helper.ps1 +99 -99
  183. package/dist/tools/start-rtc-route-helper.ps1 +15 -15
  184. package/dist/web/vendor/markdown-it.LICENSE.txt +22 -22
  185. package/dist/web/vendor/markdown-it.umd.min.js +13 -13
  186. package/package.json +7 -6
  187. package/tools/postinstall.mjs +127 -127
@@ -1,33 +1,33 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { randomUUID } from 'node:crypto';
4
- import { validId } from './device-store.mjs';
5
-
6
- export function readDebugAllowlist(file) {
7
- if (!file || !fs.existsSync(file)) return { version: 1, devices: [] };
8
- const value = JSON.parse(fs.readFileSync(file, 'utf8'));
9
- if (value.version !== 1 || !Array.isArray(value.devices) || value.devices.some(entry => !validId(entry.deviceId))) {
10
- throw new Error('Invalid debug allowlist');
11
- }
12
- return value;
13
- }
14
-
15
- export function debugAllowed(allowlist, deviceId, client) {
16
- return Boolean(client && allowlist.devices.some(entry => entry.deviceId === deviceId));
17
- }
18
-
19
- // Administrator-only file; never invoked by the relay wire protocol or Desktop CLI.
20
- export function updateDebugAllowlist(file, deviceId, enabled) {
21
- if (!validId(deviceId)) throw new Error('Invalid debug device');
22
- const value = readDebugAllowlist(file);
23
- const previous = fs.existsSync(file) ? fs.statSync(file) : null;
24
- value.devices = value.devices.filter(entry => entry.deviceId !== deviceId);
25
- if (enabled) value.devices.push({ deviceId });
26
- fs.mkdirSync(path.dirname(file), { recursive: true });
27
- const temporary = `${file}.${randomUUID()}.tmp`;
28
- try {
29
- fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', { mode: 0o640, flag: 'wx' });
30
- if (previous && process.platform !== 'win32') fs.chownSync(temporary, previous.uid, previous.gid);
31
- fs.renameSync(temporary, file);
32
- } finally { fs.rmSync(temporary, { force: true }); }
33
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { validId } from './device-store.mjs';
5
+
6
+ export function readDebugAllowlist(file) {
7
+ if (!file || !fs.existsSync(file)) return { version: 1, devices: [] };
8
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
9
+ if (value.version !== 1 || !Array.isArray(value.devices) || value.devices.some(entry => !validId(entry.deviceId))) {
10
+ throw new Error('Invalid debug allowlist');
11
+ }
12
+ return value;
13
+ }
14
+
15
+ export function debugAllowed(allowlist, deviceId, client) {
16
+ return Boolean(client && allowlist.devices.some(entry => entry.deviceId === deviceId));
17
+ }
18
+
19
+ // Administrator-only file; never invoked by the relay wire protocol or Desktop CLI.
20
+ export function updateDebugAllowlist(file, deviceId, enabled) {
21
+ if (!validId(deviceId)) throw new Error('Invalid debug device');
22
+ const value = readDebugAllowlist(file);
23
+ const previous = fs.existsSync(file) ? fs.statSync(file) : null;
24
+ value.devices = value.devices.filter(entry => entry.deviceId !== deviceId);
25
+ if (enabled) value.devices.push({ deviceId });
26
+ fs.mkdirSync(path.dirname(file), { recursive: true });
27
+ const temporary = `${file}.${randomUUID()}.tmp`;
28
+ try {
29
+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', { mode: 0o640, flag: 'wx' });
30
+ if (previous && process.platform !== 'win32') fs.chownSync(temporary, previous.uid, previous.gid);
31
+ fs.renameSync(temporary, file);
32
+ } finally { fs.rmSync(temporary, { force: true }); }
33
+ }
@@ -1,37 +1,37 @@
1
- import http from 'node:http';
2
- import { randomUUID } from 'node:crypto';
3
- import { attachLanSocket } from '../lan-socket-server.mjs';
4
- import { startSelfRelay } from './server.mjs';
5
- import { connectBridgeRelay } from './connector.mjs';
6
- import { connectRelayClient } from './client.mjs';
7
- import { secret } from './wire.mjs';
8
-
9
- export async function startRelayDemo({ mode = 'lan-shared', pairingTtlMs, dispatch, remoteRelay, hostName = 'TEST-PC', lanCandidates = [], relayOptions = {} } = {}) {
10
- if (mode !== 'lan-shared') throw new Error('Invalid demo mode');
11
- const token = secret(), calls = [];
12
- const bridge = http.createServer((_request, response) => { response.writeHead(404); response.end(); });
13
- const lan = attachLanSocket(bridge, { token, dispatch: async (request, reply) => {
14
- calls.push(request);
15
- if (dispatch) return dispatch(request, reply);
16
- if (request.url === '/api/health') return reply.json(200, { ok: true, transportMode: mode, simulated: true });
17
- if (request.url.split('?')[0] === '/api/threads/demo/events') {
18
- reply.startEvents(); reply.event('update', { thread: { id: 'demo' }, simulated: true }); return;
19
- }
20
- if (request.url === '/api/demo/stop') return reply.json(200, { stopped: true, simulated: true });
21
- reply.json(404, { error: '模拟桌面服务不执行真实任务' });
22
- } });
23
- await new Promise(resolve => bridge.listen(0, '127.0.0.1', resolve));
24
- const relay = remoteRelay ? { ...remoteRelay, async close() {} } : await startSelfRelay({ pairingTtlMs, ...relayOptions });
25
- const bridgeUrl = `ws://127.0.0.1:${bridge.address().port}/api/socket`;
26
- const identity = remoteRelay ? { id: randomUUID(), secret: secret() } : undefined;
27
- const clientId = randomUUID(), credential = secret();
28
- const connector = connectBridgeRelay({ identity, relayUrl: relay.url, hostKey: relay.hostKey, bridgeUrl, bridgeToken: token, hostName, lanCandidates });
29
- let pairing;
30
- try { pairing = await connector.ready; }
31
- catch (error) { connector.close(); await relay.close(); lan.close(); await new Promise(resolve => bridge.close(resolve)); throw error; }
32
- return {
33
- relay, connector, pairing, bridgeUrl, calls,
34
- connect(options = {}) { return connectRelayClient({ relayUrl: relay.url, room: pairing.room, code: pairing.code, ...(remoteRelay ? { clientId, credential } : {}), ...options }); },
35
- async close() { if (remoteRelay) await connector.command('revoke'); connector.close(); await relay.close(); lan.close(); await new Promise(resolve => bridge.close(resolve)); },
36
- };
37
- }
1
+ import http from 'node:http';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { attachLanSocket } from '../lan-socket-server.mjs';
4
+ import { startSelfRelay } from './server.mjs';
5
+ import { connectBridgeRelay } from './connector.mjs';
6
+ import { connectRelayClient } from './client.mjs';
7
+ import { secret } from './wire.mjs';
8
+
9
+ export async function startRelayDemo({ mode = 'lan-shared', pairingTtlMs, dispatch, remoteRelay, hostName = 'TEST-PC', lanCandidates = [], relayOptions = {} } = {}) {
10
+ if (mode !== 'lan-shared') throw new Error('Invalid demo mode');
11
+ const token = secret(), calls = [];
12
+ const bridge = http.createServer((_request, response) => { response.writeHead(404); response.end(); });
13
+ const lan = attachLanSocket(bridge, { token, dispatch: async (request, reply) => {
14
+ calls.push(request);
15
+ if (dispatch) return dispatch(request, reply);
16
+ if (request.url === '/api/health') return reply.json(200, { ok: true, transportMode: mode, simulated: true });
17
+ if (request.url.split('?')[0] === '/api/threads/demo/events') {
18
+ reply.startEvents(); reply.event('update', { thread: { id: 'demo' }, simulated: true }); return;
19
+ }
20
+ if (request.url === '/api/demo/stop') return reply.json(200, { stopped: true, simulated: true });
21
+ reply.json(404, { error: '模拟桌面服务不执行真实任务' });
22
+ } });
23
+ await new Promise(resolve => bridge.listen(0, '127.0.0.1', resolve));
24
+ const relay = remoteRelay ? { ...remoteRelay, async close() {} } : await startSelfRelay({ pairingTtlMs, ...relayOptions });
25
+ const bridgeUrl = `ws://127.0.0.1:${bridge.address().port}/api/socket`;
26
+ const identity = remoteRelay ? { id: randomUUID(), secret: secret() } : undefined;
27
+ const clientId = randomUUID(), credential = secret();
28
+ const connector = connectBridgeRelay({ identity, relayUrl: relay.url, hostKey: relay.hostKey, bridgeUrl, bridgeToken: token, hostName, lanCandidates });
29
+ let pairing;
30
+ try { pairing = await connector.ready; }
31
+ catch (error) { connector.close(); await relay.close(); lan.close(); await new Promise(resolve => bridge.close(resolve)); throw error; }
32
+ return {
33
+ relay, connector, pairing, bridgeUrl, calls,
34
+ connect(options = {}) { return connectRelayClient({ relayUrl: relay.url, room: pairing.room, code: pairing.code, ...(remoteRelay ? { clientId, credential } : {}), ...options }); },
35
+ async close() { if (remoteRelay) await connector.command('revoke'); connector.close(); await relay.close(); lan.close(); await new Promise(resolve => bridge.close(resolve)); },
36
+ };
37
+ }
@@ -0,0 +1,27 @@
1
+ export function deviceInfo(value = {}) {
2
+ const info = {};
3
+ if (value.platform !== undefined && value.platform !== null) {
4
+ if (!['android', 'harmony'].includes(value.platform)) throw new Error('Invalid mobile platform');
5
+ info.platform = value.platform;
6
+ }
7
+ if (value.deviceName !== undefined && value.deviceName !== null) {
8
+ if (typeof value.deviceName !== 'string' || value.deviceName.length > 80 || /[\u0000-\u001f\u007f]/.test(value.deviceName)) throw new Error('Invalid mobile device name');
9
+ if (value.deviceName.trim()) info.deviceName = value.deviceName.trim();
10
+ }
11
+ return info;
12
+ }
13
+
14
+ export function connectionInfo(client, at, info = {}) {
15
+ const time = Date.parse(at);
16
+ if (!Number.isFinite(time)) throw new Error('Invalid mobile connection time');
17
+ const next = deviceInfo(info);
18
+ if (client.lastConnectedAt && Date.parse(client.lastConnectedAt) > time) return client;
19
+ return { ...client, ...next, lastConnectedAt: new Date(time).toISOString() };
20
+ }
21
+
22
+ export function validConnectionInfo(client) {
23
+ try {
24
+ deviceInfo(client);
25
+ return client.lastConnectedAt == null || Number.isFinite(Date.parse(client.lastConnectedAt));
26
+ } catch { return false; }
27
+ }
@@ -1,84 +1,92 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { randomUUID } from 'node:crypto';
4
-
5
- export const validId = value => typeof value === 'string' && /^[\w-]{16,128}$/.test(value);
6
- const hash = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
7
- export function deviceStore(file, { initialize = false } = {}) {
8
- let devices = new Map();
9
- function validate(record) {
10
- if (!validId(record.id) || !hash(record.hostHash) || !['active', 'revoked'].includes(record.status) ||
11
- !Number.isSafeInteger(record.revision) || record.revision < 0 ||
12
- !Array.isArray(record.clients) || record.clients.length > 16 ||
13
- record.clients.some(client => !validId(client.id) || !hash(client.hash) ||
14
- !Number.isFinite(Date.parse(client.createdAt)) || !Number.isFinite(Date.parse(client.updatedAt))) ||
15
- new Set(record.clients.map(client => client.id)).size !== record.clients.length ||
16
- !Number.isFinite(Date.parse(record.createdAt)) || !Number.isFinite(Date.parse(record.updatedAt)) ||
17
- !validOfficialComputer(record.officialComputer)) {
18
- throw new Error('Invalid relay device record');
19
- }
20
- }
21
- function write(next) {
22
- if (!file) return;
23
- const temporary = `${file}.${randomUUID()}.tmp`;
24
- let fd;
25
- try {
26
- fd = fs.openSync(temporary, 'wx', 0o600);
27
- fs.writeFileSync(fd, JSON.stringify({ version: 4, devices: [...next.values()] }));
28
- fs.fsyncSync(fd); fs.closeSync(fd); fd = undefined;
29
- fs.renameSync(temporary, file);
30
- if (process.platform !== 'win32') {
31
- const directory = fs.openSync(path.dirname(file), 'r');
32
- try { fs.fsyncSync(directory); } finally { fs.closeSync(directory); }
33
- }
34
- } finally {
35
- if (fd !== undefined) fs.closeSync(fd);
36
- fs.rmSync(temporary, { force: true });
37
- }
38
- }
39
- if (file) {
40
- if (!fs.existsSync(file)) {
41
- if (!initialize) throw new Error('Device store missing; explicit --init-state required for first installation');
42
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); write(devices);
43
- } else {
44
- if (initialize) throw new Error('Device store already exists; initialization refused');
45
- const saved = JSON.parse(fs.readFileSync(file, 'utf8'));
46
- if (![2, 3, 4].includes(saved.version) || !Array.isArray(saved.devices)) throw new Error('Invalid relay device store version');
47
- for (const source of saved.devices) {
48
- const record = saved.version === 2 ? {
49
- ...source,
50
- clients: source.clientHash == null ? [] : [{
51
- id: source.clientId,
52
- hash: source.clientHash,
53
- createdAt: source.updatedAt,
54
- updatedAt: source.updatedAt,
55
- }],
56
- } : source;
57
- delete record.clientHash; delete record.clientId;
58
- validate(record);
59
- if (devices.has(record.id)) throw new Error('Duplicate relay device identity');
60
- devices.set(record.id, record);
61
- }
62
- }
63
- }
64
- return {
65
- entries: () => [...devices.values()],
66
- // Synchronous single-writer commit: publish only after durable replacement.
67
- save(record) {
68
- validate(record);
69
- const next = new Map(devices); next.set(record.id, record); write(next); devices = next;
70
- },
71
- };
72
- }
73
-
74
- function validOfficialComputer(value) {
75
- if (value === undefined) return true;
76
- return value && typeof value === 'object' && plain(value.environmentId, 256, false) &&
77
- plain(value.name, 80, true) && plain(value.hostname, 80, true) &&
78
- Number.isFinite(Date.parse(value.updatedAt));
79
- }
80
-
81
- function plain(value, limit, empty) {
82
- return typeof value === 'string' && (empty || value.trim().length > 0) &&
83
- value.trim().length <= limit && !/[\u0000-\u001f\u007f]/.test(value);
84
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { connectionInfo, validConnectionInfo } from './device-info.mjs';
5
+
6
+ export const validId = value => typeof value === 'string' && /^[\w-]{16,128}$/.test(value);
7
+ const hash = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
8
+ export function deviceStore(file, { initialize = false } = {}) {
9
+ let devices = new Map();
10
+ function validate(record) {
11
+ if (!validId(record.id) || !hash(record.hostHash) || !['active', 'revoked'].includes(record.status) ||
12
+ !Number.isSafeInteger(record.revision) || record.revision < 0 ||
13
+ !Array.isArray(record.clients) ||
14
+ record.clients.some(client => !validId(client.id) || !hash(client.hash) || !validConnectionInfo(client) ||
15
+ !Number.isFinite(Date.parse(client.createdAt)) || !Number.isFinite(Date.parse(client.updatedAt))) ||
16
+ new Set(record.clients.map(client => client.id)).size !== record.clients.length ||
17
+ !Number.isFinite(Date.parse(record.createdAt)) || !Number.isFinite(Date.parse(record.updatedAt)) ||
18
+ !validOfficialComputer(record.officialComputer)) {
19
+ throw new Error('Invalid relay device record');
20
+ }
21
+ }
22
+ function write(next) {
23
+ if (!file) return;
24
+ const temporary = `${file}.${randomUUID()}.tmp`;
25
+ let fd;
26
+ try {
27
+ fd = fs.openSync(temporary, 'wx', 0o600);
28
+ fs.writeFileSync(fd, JSON.stringify({ version: 4, devices: [...next.values()] }));
29
+ fs.fsyncSync(fd); fs.closeSync(fd); fd = undefined;
30
+ fs.renameSync(temporary, file);
31
+ if (process.platform !== 'win32') {
32
+ const directory = fs.openSync(path.dirname(file), 'r');
33
+ try { fs.fsyncSync(directory); } finally { fs.closeSync(directory); }
34
+ }
35
+ } finally {
36
+ if (fd !== undefined) fs.closeSync(fd);
37
+ fs.rmSync(temporary, { force: true });
38
+ }
39
+ }
40
+ if (file) {
41
+ if (!fs.existsSync(file)) {
42
+ if (!initialize) throw new Error('Device store missing; explicit --init-state required for first installation');
43
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); write(devices);
44
+ } else {
45
+ if (initialize) throw new Error('Device store already exists; initialization refused');
46
+ const saved = JSON.parse(fs.readFileSync(file, 'utf8'));
47
+ if (![2, 3, 4].includes(saved.version) || !Array.isArray(saved.devices)) throw new Error('Invalid relay device store version');
48
+ for (const source of saved.devices) {
49
+ const record = saved.version === 2 ? {
50
+ ...source,
51
+ clients: source.clientHash == null ? [] : [{
52
+ id: source.clientId,
53
+ hash: source.clientHash,
54
+ createdAt: source.updatedAt,
55
+ updatedAt: source.updatedAt,
56
+ }],
57
+ } : source;
58
+ delete record.clientHash; delete record.clientId;
59
+ validate(record);
60
+ if (devices.has(record.id)) throw new Error('Duplicate relay device identity');
61
+ devices.set(record.id, record);
62
+ }
63
+ }
64
+ }
65
+ return {
66
+ entries: () => [...devices.values()],
67
+ recordConnection(id, clientId, at, info) {
68
+ const record = devices.get(id), client = record?.clients.find(item => item.id === clientId);
69
+ if (!client) return;
70
+ const updated = connectionInfo(client, at, info);
71
+ this.save({ ...record, clients: record.clients.map(item => item.id === clientId ? updated : item) });
72
+ return updated;
73
+ },
74
+ // Synchronous single-writer commit: publish only after durable replacement.
75
+ save(record) {
76
+ validate(record);
77
+ const next = new Map(devices); next.set(record.id, record); write(next); devices = next;
78
+ },
79
+ };
80
+ }
81
+
82
+ function validOfficialComputer(value) {
83
+ if (value === undefined) return true;
84
+ return value && typeof value === 'object' && plain(value.environmentId, 256, false) &&
85
+ plain(value.name, 80, true) && plain(value.hostname, 80, true) &&
86
+ Number.isFinite(Date.parse(value.updatedAt));
87
+ }
88
+
89
+ function plain(value, limit, empty) {
90
+ return typeof value === 'string' && (empty || value.trim().length > 0) &&
91
+ value.trim().length <= limit && !/[\u0000-\u001f\u007f]/.test(value);
92
+ }
@@ -1,54 +1,54 @@
1
- const MAX_BATCH = 200;
2
-
3
- export function relayDiagnostics(pool, onError = () => {}) {
4
- let tail = Promise.resolve();
5
- function validSource(source) {
6
- if (!/^[a-z-]{1,32}$/.test(source)) throw new Error('Invalid diagnostic source');
7
- return source;
8
- }
9
- function serialize(action) {
10
- const result = tail.then(action);
11
- tail = result.catch(error => { onError(error); });
12
- return result;
13
- }
14
- function record(source, event, detail) {
15
- validSource(source);
16
- if (!/^[a-z-]{1,32}$/.test(event) || !/^[a-z0-9=;.-]{1,64}$/.test(detail)) throw new Error('Invalid diagnostic event');
17
- return serialize(async () => {
18
- await pool.execute('INSERT INTO relay_diagnostics (created_at,source,event,detail) VALUES (UTC_TIMESTAMP(3),?,?,?)', [source, event, detail]);
19
- await pool.execute('DELETE FROM relay_diagnostics WHERE created_at < UTC_TIMESTAMP(3) - INTERVAL 1 DAY');
20
- }).catch(() => {});
21
- }
22
- async function read(source) {
23
- validSource(source);
24
- return serialize(async () => {
25
- const [rows] = await pool.execute(`SELECT id,created_at,source,event,detail FROM relay_diagnostics
26
- WHERE source=? ORDER BY id LIMIT ${MAX_BATCH + 1}`, [source]);
27
- return { rows: rows.slice(0, MAX_BATCH), hasMore: rows.length > MAX_BATCH };
28
- });
29
- }
30
- async function clear(source) {
31
- validSource(source);
32
- return serialize(async () => {
33
- const [result] = await pool.execute('DELETE FROM relay_diagnostics WHERE source=?', [source]);
34
- return { cleared: result.affectedRows };
35
- });
36
- }
37
- async function drain(source) {
38
- validSource(source);
39
- return serialize(async () => {
40
- const db = await pool.getConnection();
41
- try {
42
- await db.beginTransaction();
43
- const [rows] = await db.execute(`SELECT id,created_at,source,event,detail FROM relay_diagnostics
44
- WHERE source=? ORDER BY id LIMIT ${MAX_BATCH + 1} FOR UPDATE`, [source]);
45
- const selected = rows.slice(0, MAX_BATCH);
46
- if (selected.length) await db.execute('DELETE FROM relay_diagnostics WHERE source=? AND id <= ?', [source, selected.at(-1).id]);
47
- await db.commit();
48
- return { rows: selected, hasMore: rows.length > MAX_BATCH };
49
- } catch (error) { await db.rollback(); throw error; }
50
- finally { db.release(); }
51
- });
52
- }
53
- return { record, read, clear, drain };
54
- }
1
+ const MAX_BATCH = 200;
2
+
3
+ export function relayDiagnostics(pool, onError = () => {}) {
4
+ let tail = Promise.resolve();
5
+ function validSource(source) {
6
+ if (!/^[a-z-]{1,32}$/.test(source)) throw new Error('Invalid diagnostic source');
7
+ return source;
8
+ }
9
+ function serialize(action) {
10
+ const result = tail.then(action);
11
+ tail = result.catch(error => { onError(error); });
12
+ return result;
13
+ }
14
+ function record(source, event, detail) {
15
+ validSource(source);
16
+ if (!/^[a-z-]{1,32}$/.test(event) || !/^[a-z0-9=;.-]{1,64}$/.test(detail)) throw new Error('Invalid diagnostic event');
17
+ return serialize(async () => {
18
+ await pool.execute('INSERT INTO relay_diagnostics (created_at,source,event,detail) VALUES (UTC_TIMESTAMP(3),?,?,?)', [source, event, detail]);
19
+ await pool.execute('DELETE FROM relay_diagnostics WHERE created_at < UTC_TIMESTAMP(3) - INTERVAL 1 DAY');
20
+ }).catch(() => {});
21
+ }
22
+ async function read(source) {
23
+ validSource(source);
24
+ return serialize(async () => {
25
+ const [rows] = await pool.execute(`SELECT id,created_at,source,event,detail FROM relay_diagnostics
26
+ WHERE source=? ORDER BY id LIMIT ${MAX_BATCH + 1}`, [source]);
27
+ return { rows: rows.slice(0, MAX_BATCH), hasMore: rows.length > MAX_BATCH };
28
+ });
29
+ }
30
+ async function clear(source) {
31
+ validSource(source);
32
+ return serialize(async () => {
33
+ const [result] = await pool.execute('DELETE FROM relay_diagnostics WHERE source=?', [source]);
34
+ return { cleared: result.affectedRows };
35
+ });
36
+ }
37
+ async function drain(source) {
38
+ validSource(source);
39
+ return serialize(async () => {
40
+ const db = await pool.getConnection();
41
+ try {
42
+ await db.beginTransaction();
43
+ const [rows] = await db.execute(`SELECT id,created_at,source,event,detail FROM relay_diagnostics
44
+ WHERE source=? ORDER BY id LIMIT ${MAX_BATCH + 1} FOR UPDATE`, [source]);
45
+ const selected = rows.slice(0, MAX_BATCH);
46
+ if (selected.length) await db.execute('DELETE FROM relay_diagnostics WHERE source=? AND id <= ?', [source, selected.at(-1).id]);
47
+ await db.commit();
48
+ return { rows: selected, hasMore: rows.length > MAX_BATCH };
49
+ } catch (error) { await db.rollback(); throw error; }
50
+ finally { db.release(); }
51
+ });
52
+ }
53
+ return { record, read, clear, drain };
54
+ }