@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
@@ -0,0 +1,55 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { readRecord, writeRecord } from './service-lifecycle.mjs';
4
+ import { withDesktopProjectRegistration } from './platform/desktop-project-registration.mjs';
5
+
6
+ const pending = new Map();
7
+ const uuid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
8
+
9
+ export async function removeWorkstationProject(server, stateRoot, codexDataRoot, projectId, body, dependencies = {}) {
10
+ if (!projectId || !uuid.test(body.idempotencyKey || '')) throw Object.assign(new Error('项目移除标识无效。'), { statusCode: 400 });
11
+ const record = path.join(stateRoot, 'project-remove-operations', `${body.idempotencyKey}.json`);
12
+ const running = pending.get(record);
13
+ if (running) {
14
+ if (running.projectId !== projectId) throw Object.assign(new Error('同一请求不能移除其他项目。'), { statusCode: 409 });
15
+ return running.promise;
16
+ }
17
+ const promise = perform().finally(() => pending.delete(record));
18
+ pending.set(record, { projectId, promise });
19
+ return promise;
20
+
21
+ async function perform() {
22
+ await fs.mkdir(path.dirname(record), { recursive: true });
23
+ const operation = readRecord(record) || { projectId };
24
+ if (operation.projectId !== projectId) throw Object.assign(new Error('移除标识已用于其他项目。'), { statusCode: 409 });
25
+ if (operation.result) return operation.result;
26
+ const save = () => writeRecord(record, operation);
27
+ const registration = dependencies.registration || withDesktopProjectRegistration;
28
+ return registration({ stateRoot, codexDataRoot, operationId: body.idempotencyKey, operation: 'remove',
29
+ confirmed: body.confirmDesktopRestart === true, serverUrl: server.url }, async desktop => {
30
+ if (!operation.project) {
31
+ operation.project = (await server.request('project/read', { projectId })).project;
32
+ if (operation.project.id !== projectId) throw new Error('项目身份不一致,未执行移除。');
33
+ save();
34
+ }
35
+ const removeNative = async () => {
36
+ if (operation.nativeDeleted) return;
37
+ if (operation.deleteAttempted) {
38
+ // An explicit retry first resolves an earlier unknown response.
39
+ try { await server.request('project/read', { projectId }); }
40
+ catch (error) {
41
+ if (error.message !== `project not found: ${projectId}`) throw error;
42
+ operation.nativeDeleted = true; save(); return;
43
+ }
44
+ }
45
+ operation.deleteAttempted = true; save();
46
+ await server.request('project/delete', { projectId });
47
+ operation.nativeDeleted = true; save();
48
+ };
49
+ const desktopRemoval = await desktop.remove(operation.project, operation, save, removeNative);
50
+ operation.result = { projectId, desktopRemoval };
51
+ save();
52
+ return operation.result;
53
+ });
54
+ }
55
+ }
@@ -0,0 +1,56 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { readRecord, writeRecord } from './service-lifecycle.mjs';
5
+ import { projectRoots, projectSummary } from './project-management.mjs';
6
+ import { withDesktopProjectRegistration } from './platform/desktop-project-registration.mjs';
7
+
8
+ const pending = new Map();
9
+ const fail = message => { throw Object.assign(new Error(message), { statusCode: 409 }); };
10
+ const rootKey = roots => JSON.stringify(roots.map(root => process.platform === 'win32' ? path.normalize(root.path).toLowerCase() : path.normalize(root.path)));
11
+ const same = (a, b) => a.name === b.name && rootKey(a.roots) === rootKey(b.roots);
12
+
13
+ export async function updateWorkstationProject(server, stateRoot, codexDataRoot, projectId, body, dependencies = {}) {
14
+ const name = typeof body.name === 'string' ? body.name.trim() : '';
15
+ if (!name || !Array.isArray(body.roots) || body.roots.some(root => typeof root?.path !== 'string' || !path.isAbsolute(root.path.trim()))
16
+ || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(body.idempotencyKey || '')) fail('项目名称、文件夹或操作标识无效。');
17
+ const target = { name, roots: body.roots.map(root => ({ path: path.normalize(root.path.trim()) })) };
18
+ const signature = createHash('sha256').update(JSON.stringify({ projectId, ...target })).digest('hex');
19
+ const record = path.join(stateRoot, 'project-update-operations', `${body.idempotencyKey}.json`);
20
+ const active = pending.get(record);
21
+ if (active) { if (active.signature !== signature) fail('同一请求不能修改其他项目内容。'); return active.promise; }
22
+ const promise = perform().finally(() => pending.delete(record));
23
+ pending.set(record, { signature, promise }); return promise;
24
+
25
+ async function perform() {
26
+ await fs.mkdir(path.dirname(record), { recursive: true });
27
+ const operation = readRecord(record) || { signature };
28
+ if (operation.signature !== signature) fail('项目编辑标识已用于其他内容。');
29
+ if (operation.result) return operation.result;
30
+ const save = () => writeRecord(record, operation);
31
+ const rpc = (method, params) => server.request(method, params);
32
+ try {
33
+ return await (dependencies.registration || withDesktopProjectRegistration)({ stateRoot, codexDataRoot,
34
+ operationId: body.idempotencyKey, operation: 'update', confirmed: body.confirmDesktopRestart === true, serverUrl: server.url }, async desktop => {
35
+ const current = (await rpc('project/read', { projectId })).project;
36
+ if (current.id !== projectId) fail('项目身份不一致。');
37
+ operation.previousProject ||= current;
38
+ if (!same(current, operation.previousProject) && !same(current, target)) fail('项目已被其他操作修改,请刷新后重新编辑。');
39
+ let project = current;
40
+ if (!same(current, target)) {
41
+ const rootsChanged = rootKey(current.roots) !== rootKey(target.roots);
42
+ const roots = rootsChanged ? await projectRoots(rpc, target.roots) : current.roots;
43
+ operation.updateAttempted = true; save();
44
+ project = (await rpc('project/update', { projectId, name, roots })).project;
45
+ }
46
+ save();
47
+ const desktopRegistration = await desktop.register(project, operation, save);
48
+ operation.result = { project: projectSummary(project), desktopRegistration }; save(); return operation.result;
49
+ });
50
+ } catch (error) {
51
+ error.details = { ...error.details, projectUpdatePending: operation.updateAttempted === true };
52
+ if (operation.updateAttempted) error.message += ' 请继续完成本次同步,会先核对已有修改。';
53
+ throw error;
54
+ }
55
+ }
56
+ }
@@ -1,47 +1,47 @@
1
- import { discoverCodex, resolveCodexRuntime, runtimeFingerprint } from './platform/codex-runtime.mjs';
2
-
3
- // Advisory discovery is independent of execution health. Failure here must never
4
- // disable an already running app-server or cause an automatic process restart.
5
- export class RuntimeDiscovery {
6
- constructor({ stateRoot, host, url, interval = 60000 }) {
7
- Object.assign(this, { stateRoot, host, url, interval });
8
- this.state = {};
9
- }
10
- start() { this.stopped = false; void this.tick(); }
11
- stop() { this.stopped = true; clearTimeout(this.timer); }
12
- async sample() {
13
- const errors = [];
14
- try {
15
- const candidates = discoverCodex();
16
- const signature = JSON.stringify(candidates.map(candidate => {
17
- try { return [candidate.executable, runtimeFingerprint(candidate.executable)]; }
18
- catch (error) { return [candidate.executable, error.message]; }
19
- }));
20
- if (signature !== this.signature) {
21
- await resolveCodexRuntime(this.stateRoot, { refresh: true });
22
- this.signature = signature;
23
- }
24
- } catch (error) { errors.push(error.message); }
25
- try {
26
- if (this.host.desktopIntegration === false) {
27
- this.state = { desktop: { state: 'unsupported', integrationSupported: false }, checkedAt: new Date().toISOString() };
28
- if (errors.length) this.state.discoveryError = errors.join('\n');
29
- return this.state;
30
- }
31
- const desktop = await this.host.inspect();
32
- const attached = desktop.running && await this.host.sharedServiceUrl() === this.url;
33
- this.state = { desktop: { state: !desktop.running ? 'stopped' : attached ? 'managed' : 'ordinary',
34
- installed: Boolean(desktop.desktop), attachedToManagedServer: Boolean(attached) },
35
- desktopRestartRecommended: Boolean(desktop.running && !attached), checkedAt: new Date().toISOString() };
36
- } catch (error) {
37
- errors.push(error.message);
38
- this.state = { checkedAt: new Date().toISOString() };
39
- }
40
- if (errors.length) this.state.discoveryError = errors.join('\n');
41
- return this.state;
42
- }
43
- async tick() {
44
- await this.sample();
45
- if (!this.stopped) { this.timer = setTimeout(() => this.tick(), this.interval); this.timer.unref?.(); }
46
- }
47
- }
1
+ import { discoverCodex, resolveCodexRuntime, runtimeFingerprint } from './platform/codex-runtime.mjs';
2
+
3
+ // Advisory discovery is independent of execution health. Failure here must never
4
+ // disable an already running app-server or cause an automatic process restart.
5
+ export class RuntimeDiscovery {
6
+ constructor({ stateRoot, host, url, interval = 60000 }) {
7
+ Object.assign(this, { stateRoot, host, url, interval });
8
+ this.state = {};
9
+ }
10
+ start() { this.stopped = false; void this.tick(); }
11
+ stop() { this.stopped = true; clearTimeout(this.timer); }
12
+ async sample() {
13
+ const errors = [];
14
+ try {
15
+ const candidates = discoverCodex();
16
+ const signature = JSON.stringify(candidates.map(candidate => {
17
+ try { return [candidate.executable, runtimeFingerprint(candidate.executable)]; }
18
+ catch (error) { return [candidate.executable, error.message]; }
19
+ }));
20
+ if (signature !== this.signature) {
21
+ await resolveCodexRuntime(this.stateRoot, { refresh: true });
22
+ this.signature = signature;
23
+ }
24
+ } catch (error) { errors.push(error.message); }
25
+ try {
26
+ if (this.host.desktopIntegration === false) {
27
+ this.state = { desktop: { state: 'unsupported', integrationSupported: false }, checkedAt: new Date().toISOString() };
28
+ if (errors.length) this.state.discoveryError = errors.join('\n');
29
+ return this.state;
30
+ }
31
+ const desktop = await this.host.inspect();
32
+ const attached = desktop.running && await this.host.sharedServiceUrl() === this.url;
33
+ this.state = { desktop: { state: !desktop.running ? 'stopped' : attached ? 'managed' : 'ordinary',
34
+ installed: Boolean(desktop.desktop), attachedToManagedServer: Boolean(attached) },
35
+ desktopRestartRecommended: Boolean(desktop.running && !attached), checkedAt: new Date().toISOString() };
36
+ } catch (error) {
37
+ errors.push(error.message);
38
+ this.state = { checkedAt: new Date().toISOString() };
39
+ }
40
+ if (errors.length) this.state.discoveryError = errors.join('\n');
41
+ return this.state;
42
+ }
43
+ async tick() {
44
+ await this.sample();
45
+ if (!this.stopped) { this.timer = setTimeout(() => this.tick(), this.interval); this.timer.unref?.(); }
46
+ }
47
+ }
@@ -1,30 +1,30 @@
1
- // Process one account per transaction; foreign keys keep incomplete deletion atomic.
2
- export async function purgeCancelledAccounts(pool, scopeHash) {
3
- let purged = 0;
4
- for (;;) {
5
- const db = await pool.getConnection();
6
- try {
7
- await db.beginTransaction();
8
- const [rows] = await db.query(`SELECT id FROM users WHERE status='cancelled'
9
- AND cancelled_at <= UTC_TIMESTAMP(3) - INTERVAL 1 DAY
10
- ORDER BY cancelled_at LIMIT 1 FOR UPDATE`);
11
- if (!rows.length) { await db.commit(); return purged; }
12
- const id = rows[0].id;
13
- const [identities] = await db.execute("SELECT normalized_value FROM user_login_identities WHERE user_id=? AND kind='email'", [id]);
14
- for (const { normalized_value: email } of identities) {
15
- await db.execute('DELETE FROM email_login_challenges WHERE email=?', [email]);
16
- await db.execute('DELETE FROM email_send_limits WHERE scope_hash=?', [scopeHash(`email:${email}`)]);
17
- await db.execute('DELETE FROM relay_admin_emails WHERE email=?', [email]);
18
- }
19
- for (const table of ['user_sessions', 'relay_usage_actions', 'relay_usage_sessions',
20
- 'relay_usage_user_days', 'relay_usage_budgets', 'relay_usage_entitlements',
21
- 'relay_usage_totals', 'user_login_identities']) {
22
- await db.execute(`DELETE FROM ${table} WHERE user_id=?`, [id]);
23
- }
24
- await db.execute('UPDATE computers SET owner_user_id=NULL WHERE owner_user_id=?', [id]);
25
- await db.execute('DELETE FROM users WHERE id=?', [id]);
26
- await db.commit(); purged++;
27
- } catch (error) { await db.rollback(); throw error; }
28
- finally { db.release(); }
29
- }
30
- }
1
+ // Process one account per transaction; foreign keys keep incomplete deletion atomic.
2
+ export async function purgeCancelledAccounts(pool, scopeHash) {
3
+ let purged = 0;
4
+ for (;;) {
5
+ const db = await pool.getConnection();
6
+ try {
7
+ await db.beginTransaction();
8
+ const [rows] = await db.query(`SELECT id FROM users WHERE status='cancelled'
9
+ AND cancelled_at <= UTC_TIMESTAMP(3) - INTERVAL 1 DAY
10
+ ORDER BY cancelled_at LIMIT 1 FOR UPDATE`);
11
+ if (!rows.length) { await db.commit(); return purged; }
12
+ const id = rows[0].id;
13
+ const [identities] = await db.execute("SELECT normalized_value FROM user_login_identities WHERE user_id=? AND kind='email'", [id]);
14
+ for (const { normalized_value: email } of identities) {
15
+ await db.execute('DELETE FROM email_login_challenges WHERE email=?', [email]);
16
+ await db.execute('DELETE FROM email_send_limits WHERE scope_hash=?', [scopeHash(`email:${email}`)]);
17
+ await db.execute('DELETE FROM relay_admin_emails WHERE email=?', [email]);
18
+ }
19
+ for (const table of ['user_sessions', 'relay_usage_actions', 'relay_usage_sessions',
20
+ 'relay_usage_user_days', 'relay_usage_budgets', 'relay_usage_entitlements',
21
+ 'relay_usage_totals', 'user_login_identities']) {
22
+ await db.execute(`DELETE FROM ${table} WHERE user_id=?`, [id]);
23
+ }
24
+ await db.execute('UPDATE computers SET owner_user_id=NULL WHERE owner_user_id=?', [id]);
25
+ await db.execute('DELETE FROM users WHERE id=?', [id]);
26
+ await db.commit(); purged++;
27
+ } catch (error) { await db.rollback(); throw error; }
28
+ finally { db.release(); }
29
+ }
30
+ }
@@ -1,52 +1,52 @@
1
- import { digest } from './wire.mjs';
2
-
3
- // Register before the asynchronous database check so logout also invalidates
4
- // handshakes whose successful authentication response has not arrived yet.
5
- export function accountConnections() {
6
- const sessions = new Map();
7
- return {
8
- track(token, onInvalid) {
9
- const key = digest(token);
10
- const entries = sessions.get(key) || new Set();
11
- sessions.set(key, entries);
12
- let active = true, expires = Infinity, timer;
13
- function dispose() {
14
- active = false;
15
- clearTimeout(timer);
16
- entries.delete(entry);
17
- if (!entries.size && sessions.get(key) === entries) sessions.delete(key);
18
- }
19
- function invalidate() {
20
- if (!active) return;
21
- dispose();
22
- onInvalid();
23
- }
24
- function valid() {
25
- if (active && Date.now() >= expires) invalidate();
26
- return active;
27
- }
28
- function schedule() {
29
- if (!valid()) return;
30
- // Login lasts 30 days, longer than Node's maximum timer delay.
31
- timer = setTimeout(schedule, Math.min(expires - Date.now(), 0x7fffffff));
32
- timer.unref();
33
- }
34
- const entry = {
35
- activate(expiresAt) {
36
- if (!active) return false;
37
- expires = Date.parse(expiresAt);
38
- if (!Number.isFinite(expires)) { invalidate(); return false; }
39
- schedule();
40
- return active;
41
- },
42
- valid, dispose, invalidate,
43
- };
44
- entries.add(entry);
45
- return entry;
46
- },
47
- revoke(token) {
48
- const entries = sessions.get(digest(token));
49
- if (entries) for (const entry of [...entries]) entry.invalidate();
50
- },
51
- };
52
- }
1
+ import { digest } from './wire.mjs';
2
+
3
+ // Register before the asynchronous database check so logout also invalidates
4
+ // handshakes whose successful authentication response has not arrived yet.
5
+ export function accountConnections() {
6
+ const sessions = new Map();
7
+ return {
8
+ track(token, onInvalid) {
9
+ const key = digest(token);
10
+ const entries = sessions.get(key) || new Set();
11
+ sessions.set(key, entries);
12
+ let active = true, expires = Infinity, timer;
13
+ function dispose() {
14
+ active = false;
15
+ clearTimeout(timer);
16
+ entries.delete(entry);
17
+ if (!entries.size && sessions.get(key) === entries) sessions.delete(key);
18
+ }
19
+ function invalidate() {
20
+ if (!active) return;
21
+ dispose();
22
+ onInvalid();
23
+ }
24
+ function valid() {
25
+ if (active && Date.now() >= expires) invalidate();
26
+ return active;
27
+ }
28
+ function schedule() {
29
+ if (!valid()) return;
30
+ // Login lasts 30 days, longer than Node's maximum timer delay.
31
+ timer = setTimeout(schedule, Math.min(expires - Date.now(), 0x7fffffff));
32
+ timer.unref();
33
+ }
34
+ const entry = {
35
+ activate(expiresAt) {
36
+ if (!active) return false;
37
+ expires = Date.parse(expiresAt);
38
+ if (!Number.isFinite(expires)) { invalidate(); return false; }
39
+ schedule();
40
+ return active;
41
+ },
42
+ valid, dispose, invalidate,
43
+ };
44
+ entries.add(entry);
45
+ return entry;
46
+ },
47
+ revoke(token) {
48
+ const entries = sessions.get(digest(token));
49
+ if (entries) for (const entry of [...entries]) entry.invalidate();
50
+ },
51
+ };
52
+ }
@@ -1,101 +1,101 @@
1
- import fs from 'node:fs';
2
- import tencentcloud from 'tencentcloud-sdk-nodejs-common';
3
-
4
- const INSTANCE_ID = 'lhins-byrs7n8o';
5
- const REGION = 'ap-beijing';
6
- const { CommonClient } = tencentcloud;
7
- const METRICS = [
8
- ['LighthouseOutratio', 'outRatioPercent', 10],
9
- ['LighthouseOuttraffic', 'outMbps', 10],
10
- ['LighthouseIntraffic', 'inMbps', 10],
11
- ['CpuUsage', 'cpuPercent', 10],
12
- ['MemUsage', 'memoryPercent', 10],
13
- ['DiskUsage', 'diskPercent', 60],
14
- ['CpuLoad1', 'cpuLoad1', 10],
15
- ];
16
-
17
- function latestPoint(result) {
18
- const point = result?.DataPoints?.[0];
19
- if (!point?.Values?.length || !point?.Timestamps?.length) return null;
20
- const index = point.Values.length - 1;
21
- const value = Number(point.Values[index]);
22
- const timestamp = Number(point.Timestamps[index]);
23
- return Number.isFinite(value) && Number.isFinite(timestamp)
24
- ? { value, sampledAt: new Date(timestamp * 1000).toISOString() } : null;
25
- }
26
-
27
- export function startAdminCloud({ credentialFile = process.env.CREDENTIALS_DIRECTORY
28
- ? `${process.env.CREDENTIALS_DIRECTORY}/tencent-monitor.json` : null,
29
- metricIntervalMs = 60000, trafficIntervalMs = 300000 } = {}) {
30
- if (!credentialFile) return { read: () => ({ configured: false }), close() {} };
31
- const { secretId, secretKey } = JSON.parse(fs.readFileSync(credentialFile, 'utf8'));
32
- if (!secretId || !secretKey) throw new Error('Tencent monitor credentials are incomplete');
33
- const credential = { secretId, secretKey };
34
- const profile = { httpProfile: { reqTimeout: 8 } };
35
- const monitor = new CommonClient('monitor.tencentcloudapi.com', '2018-07-24',
36
- { credential, region: REGION, profile });
37
- const lighthouse = new CommonClient('lighthouse.tencentcloudapi.com', '2020-03-24',
38
- { credential, region: REGION, profile });
39
- let closed = false;
40
- let metricBusy = false;
41
- let trafficBusy = false;
42
- const current = { configured: true, metricAvailable: false, trafficAvailable: false,
43
- outRatioPercent: null, outMbps: null, inMbps: null, metricSampledAt: null,
44
- cpuPercent: null, memoryPercent: null, diskPercent: null, cpuLoad1: null,
45
- trafficUsedBytes: null, trafficTotalBytes: null, trafficRemainingBytes: null,
46
- trafficStartAt: null, trafficEndAt: null, trafficSampledAt: null };
47
-
48
- async function sampleMetrics() {
49
- if (metricBusy || closed) return;
50
- metricBusy = true;
51
- const end = new Date();
52
- const base = { Namespace: 'QCE/LIGHTHOUSE',
53
- StartTime: new Date(end.getTime() - 180000).toISOString(), EndTime: end.toISOString(),
54
- Instances: [{ Dimensions: [{ Name: 'InstanceId', Value: INSTANCE_ID }] }] };
55
- try {
56
- const values = await Promise.allSettled(METRICS.map(([MetricName, , Period]) =>
57
- monitor.request('GetMonitorData', { ...base, MetricName, Period })));
58
- if (closed) return;
59
- const samples = values.map(result => result.status === 'fulfilled' ? latestPoint(result.value) : null);
60
- for (let index = 0; index < METRICS.length; index++) {
61
- const [, field] = METRICS[index];
62
- const value = samples[index]?.value ?? null;
63
- current[field] = value !== null && (field === 'outMbps' || field === 'inMbps') ? value * 8 : value;
64
- }
65
- current.metricSampledAt = samples.reduce((latest, sample) => sample?.sampledAt > latest
66
- ? sample.sampledAt : latest, '') || null;
67
- current.metricAvailable = Boolean(current.metricSampledAt);
68
- } catch {
69
- current.metricAvailable = false;
70
- } finally { metricBusy = false; }
71
- }
72
-
73
- async function sampleTraffic() {
74
- if (trafficBusy || closed) return;
75
- trafficBusy = true;
76
- try {
77
- const data = await lighthouse.request('DescribeInstancesTrafficPackages', { InstanceIds: [INSTANCE_ID] });
78
- if (closed) return;
79
- const packages = data?.InstanceTrafficPackageSet?.find(item => item.InstanceId === INSTANCE_ID)?.TrafficPackageSet || [];
80
- const active = packages.find(item => Date.parse(item.StartTime) <= Date.now()
81
- && Date.parse(item.EndTime) >= Date.now()) || packages[0];
82
- current.trafficUsedBytes = active?.TrafficUsed ?? null;
83
- current.trafficTotalBytes = active?.TrafficPackageTotal ?? null;
84
- current.trafficRemainingBytes = active?.TrafficPackageRemaining ?? null;
85
- current.trafficStartAt = active?.StartTime ?? null;
86
- current.trafficEndAt = active?.EndTime ?? null;
87
- current.trafficSampledAt = active ? new Date().toISOString() : null;
88
- current.trafficAvailable = Boolean(active);
89
- } catch {
90
- current.trafficAvailable = false;
91
- } finally { trafficBusy = false; }
92
- }
93
-
94
- void sampleMetrics();
95
- void sampleTraffic();
96
- const metricTimer = setInterval(sampleMetrics, metricIntervalMs);
97
- const trafficTimer = setInterval(sampleTraffic, trafficIntervalMs);
98
- metricTimer.unref();
99
- trafficTimer.unref();
100
- return { read: () => ({ ...current }), close() { closed = true; clearInterval(metricTimer); clearInterval(trafficTimer); } };
101
- }
1
+ import fs from 'node:fs';
2
+ import tencentcloud from 'tencentcloud-sdk-nodejs-common';
3
+
4
+ const INSTANCE_ID = 'lhins-byrs7n8o';
5
+ const REGION = 'ap-beijing';
6
+ const { CommonClient } = tencentcloud;
7
+ const METRICS = [
8
+ ['LighthouseOutratio', 'outRatioPercent', 10],
9
+ ['LighthouseOuttraffic', 'outMbps', 10],
10
+ ['LighthouseIntraffic', 'inMbps', 10],
11
+ ['CpuUsage', 'cpuPercent', 10],
12
+ ['MemUsage', 'memoryPercent', 10],
13
+ ['DiskUsage', 'diskPercent', 60],
14
+ ['CpuLoad1', 'cpuLoad1', 10],
15
+ ];
16
+
17
+ function latestPoint(result) {
18
+ const point = result?.DataPoints?.[0];
19
+ if (!point?.Values?.length || !point?.Timestamps?.length) return null;
20
+ const index = point.Values.length - 1;
21
+ const value = Number(point.Values[index]);
22
+ const timestamp = Number(point.Timestamps[index]);
23
+ return Number.isFinite(value) && Number.isFinite(timestamp)
24
+ ? { value, sampledAt: new Date(timestamp * 1000).toISOString() } : null;
25
+ }
26
+
27
+ export function startAdminCloud({ credentialFile = process.env.CREDENTIALS_DIRECTORY
28
+ ? `${process.env.CREDENTIALS_DIRECTORY}/tencent-monitor.json` : null,
29
+ metricIntervalMs = 60000, trafficIntervalMs = 300000 } = {}) {
30
+ if (!credentialFile) return { read: () => ({ configured: false }), close() {} };
31
+ const { secretId, secretKey } = JSON.parse(fs.readFileSync(credentialFile, 'utf8'));
32
+ if (!secretId || !secretKey) throw new Error('Tencent monitor credentials are incomplete');
33
+ const credential = { secretId, secretKey };
34
+ const profile = { httpProfile: { reqTimeout: 8 } };
35
+ const monitor = new CommonClient('monitor.tencentcloudapi.com', '2018-07-24',
36
+ { credential, region: REGION, profile });
37
+ const lighthouse = new CommonClient('lighthouse.tencentcloudapi.com', '2020-03-24',
38
+ { credential, region: REGION, profile });
39
+ let closed = false;
40
+ let metricBusy = false;
41
+ let trafficBusy = false;
42
+ const current = { configured: true, metricAvailable: false, trafficAvailable: false,
43
+ outRatioPercent: null, outMbps: null, inMbps: null, metricSampledAt: null,
44
+ cpuPercent: null, memoryPercent: null, diskPercent: null, cpuLoad1: null,
45
+ trafficUsedBytes: null, trafficTotalBytes: null, trafficRemainingBytes: null,
46
+ trafficStartAt: null, trafficEndAt: null, trafficSampledAt: null };
47
+
48
+ async function sampleMetrics() {
49
+ if (metricBusy || closed) return;
50
+ metricBusy = true;
51
+ const end = new Date();
52
+ const base = { Namespace: 'QCE/LIGHTHOUSE',
53
+ StartTime: new Date(end.getTime() - 180000).toISOString(), EndTime: end.toISOString(),
54
+ Instances: [{ Dimensions: [{ Name: 'InstanceId', Value: INSTANCE_ID }] }] };
55
+ try {
56
+ const values = await Promise.allSettled(METRICS.map(([MetricName, , Period]) =>
57
+ monitor.request('GetMonitorData', { ...base, MetricName, Period })));
58
+ if (closed) return;
59
+ const samples = values.map(result => result.status === 'fulfilled' ? latestPoint(result.value) : null);
60
+ for (let index = 0; index < METRICS.length; index++) {
61
+ const [, field] = METRICS[index];
62
+ const value = samples[index]?.value ?? null;
63
+ current[field] = value !== null && (field === 'outMbps' || field === 'inMbps') ? value * 8 : value;
64
+ }
65
+ current.metricSampledAt = samples.reduce((latest, sample) => sample?.sampledAt > latest
66
+ ? sample.sampledAt : latest, '') || null;
67
+ current.metricAvailable = Boolean(current.metricSampledAt);
68
+ } catch {
69
+ current.metricAvailable = false;
70
+ } finally { metricBusy = false; }
71
+ }
72
+
73
+ async function sampleTraffic() {
74
+ if (trafficBusy || closed) return;
75
+ trafficBusy = true;
76
+ try {
77
+ const data = await lighthouse.request('DescribeInstancesTrafficPackages', { InstanceIds: [INSTANCE_ID] });
78
+ if (closed) return;
79
+ const packages = data?.InstanceTrafficPackageSet?.find(item => item.InstanceId === INSTANCE_ID)?.TrafficPackageSet || [];
80
+ const active = packages.find(item => Date.parse(item.StartTime) <= Date.now()
81
+ && Date.parse(item.EndTime) >= Date.now()) || packages[0];
82
+ current.trafficUsedBytes = active?.TrafficUsed ?? null;
83
+ current.trafficTotalBytes = active?.TrafficPackageTotal ?? null;
84
+ current.trafficRemainingBytes = active?.TrafficPackageRemaining ?? null;
85
+ current.trafficStartAt = active?.StartTime ?? null;
86
+ current.trafficEndAt = active?.EndTime ?? null;
87
+ current.trafficSampledAt = active ? new Date().toISOString() : null;
88
+ current.trafficAvailable = Boolean(active);
89
+ } catch {
90
+ current.trafficAvailable = false;
91
+ } finally { trafficBusy = false; }
92
+ }
93
+
94
+ void sampleMetrics();
95
+ void sampleTraffic();
96
+ const metricTimer = setInterval(sampleMetrics, metricIntervalMs);
97
+ const trafficTimer = setInterval(sampleTraffic, trafficIntervalMs);
98
+ metricTimer.unref();
99
+ trafficTimer.unref();
100
+ return { read: () => ({ ...current }), close() { closed = true; clearInterval(metricTimer); clearInterval(trafficTimer); } };
101
+ }