@zhanguym/chatroom 1.0.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 (223) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +52 -0
  3. package/assets/chatroom.svg +15 -0
  4. package/chatroom.config.example.json +24 -0
  5. package/dist/app/application.d.ts +20 -0
  6. package/dist/app/application.js +75 -0
  7. package/dist/app/event-bus.d.ts +25 -0
  8. package/dist/app/event-bus.js +11 -0
  9. package/dist/app/external-access-registry.d.ts +17 -0
  10. package/dist/app/external-access-registry.js +41 -0
  11. package/dist/app/lifecycle.d.ts +14 -0
  12. package/dist/app/lifecycle.js +130 -0
  13. package/dist/auth/auth-service.d.ts +88 -0
  14. package/dist/auth/auth-service.js +221 -0
  15. package/dist/auth/ingress-policy.d.ts +23 -0
  16. package/dist/auth/ingress-policy.js +61 -0
  17. package/dist/auth/passkey-service.d.ts +39 -0
  18. package/dist/auth/passkey-service.js +145 -0
  19. package/dist/cli/index.d.ts +2 -0
  20. package/dist/cli/index.js +10 -0
  21. package/dist/cli/run-cli.d.ts +1 -0
  22. package/dist/cli/run-cli.js +41 -0
  23. package/dist/config/load-config.d.ts +7 -0
  24. package/dist/config/load-config.js +197 -0
  25. package/dist/config/platform-paths.d.ts +7 -0
  26. package/dist/config/platform-paths.js +34 -0
  27. package/dist/config/types.d.ts +24 -0
  28. package/dist/config/types.js +1 -0
  29. package/dist/core/auth/passkey-repository.d.ts +18 -0
  30. package/dist/core/auth/passkey-repository.js +1 -0
  31. package/dist/core/auth/repository.d.ts +36 -0
  32. package/dist/core/auth/repository.js +1 -0
  33. package/dist/core/auth/session-repository.d.ts +6 -0
  34. package/dist/core/auth/session-repository.js +1 -0
  35. package/dist/core/errors/chatroom-error.d.ts +9 -0
  36. package/dist/core/errors/chatroom-error.js +31 -0
  37. package/dist/core/logging/types.d.ts +31 -0
  38. package/dist/core/logging/types.js +1 -0
  39. package/dist/core/operations/bounded-value.d.ts +6 -0
  40. package/dist/core/operations/bounded-value.js +57 -0
  41. package/dist/core/operations/redactor.d.ts +4 -0
  42. package/dist/core/operations/redactor.js +69 -0
  43. package/dist/core/operations/repository.d.ts +18 -0
  44. package/dist/core/operations/repository.js +1 -0
  45. package/dist/core/operations/types.d.ts +28 -0
  46. package/dist/core/operations/types.js +8 -0
  47. package/dist/core/runtime/child-environment.d.ts +1 -0
  48. package/dist/core/runtime/child-environment.js +39 -0
  49. package/dist/core/runtime/command-runner.d.ts +16 -0
  50. package/dist/core/runtime/command-runner.js +48 -0
  51. package/dist/core/runtime/identity.d.ts +2 -0
  52. package/dist/core/runtime/identity.js +9 -0
  53. package/dist/infrastructure/database/app-database.d.ts +6 -0
  54. package/dist/infrastructure/database/app-database.js +22 -0
  55. package/dist/infrastructure/database/mcp-tool-settings-repository.d.ts +8 -0
  56. package/dist/infrastructure/database/mcp-tool-settings-repository.js +22 -0
  57. package/dist/infrastructure/database/oauth-repository.d.ts +20 -0
  58. package/dist/infrastructure/database/oauth-repository.js +140 -0
  59. package/dist/infrastructure/database/operation-repository.d.ts +16 -0
  60. package/dist/infrastructure/database/operation-repository.js +120 -0
  61. package/dist/infrastructure/database/passkey-repository.d.ts +11 -0
  62. package/dist/infrastructure/database/passkey-repository.js +57 -0
  63. package/dist/infrastructure/database/schema.d.ts +1 -0
  64. package/dist/infrastructure/database/schema.js +90 -0
  65. package/dist/infrastructure/database/web-session-repository.d.ts +10 -0
  66. package/dist/infrastructure/database/web-session-repository.js +26 -0
  67. package/dist/infrastructure/http/http-server.d.ts +28 -0
  68. package/dist/infrastructure/http/http-server.js +146 -0
  69. package/dist/infrastructure/http/ingress-middleware.d.ts +6 -0
  70. package/dist/infrastructure/http/ingress-middleware.js +58 -0
  71. package/dist/infrastructure/logging/file-log-store.d.ts +9 -0
  72. package/dist/infrastructure/logging/file-log-store.js +173 -0
  73. package/dist/infrastructure/logging/system-log.d.ts +22 -0
  74. package/dist/infrastructure/logging/system-log.js +117 -0
  75. package/dist/mcp/server/create-mcp-server.d.ts +3 -0
  76. package/dist/mcp/server/create-mcp-server.js +16 -0
  77. package/dist/mcp/server/plugin-mcp-registrar.d.ts +31 -0
  78. package/dist/mcp/server/plugin-mcp-registrar.js +70 -0
  79. package/dist/mcp/server/request-context.d.ts +3 -0
  80. package/dist/mcp/server/request-context.js +8 -0
  81. package/dist/mcp/server/tool-control.d.ts +31 -0
  82. package/dist/mcp/server/tool-control.js +76 -0
  83. package/dist/mcp/server/tool-support.d.ts +44 -0
  84. package/dist/mcp/server/tool-support.js +72 -0
  85. package/dist/native/linux/chatroom-computer-helper +0 -0
  86. package/dist/native/macos/ChatRoomComputerHelper.app/Contents/Info.plist +14 -0
  87. package/dist/native/macos/ChatRoomComputerHelper.app/Contents/MacOS/chatroom-computer-helper +0 -0
  88. package/dist/native/macos/ChatRoomComputerHelper.app/Contents/_CodeSignature/CodeResources +115 -0
  89. package/dist/native/windows/chatroom-computer-helper.exe +0 -0
  90. package/dist/operations/operation-log.d.ts +24 -0
  91. package/dist/operations/operation-log.js +98 -0
  92. package/dist/plugins/cloud/api-client.d.ts +50 -0
  93. package/dist/plugins/cloud/api-client.js +112 -0
  94. package/dist/plugins/cloud/controller.d.ts +58 -0
  95. package/dist/plugins/cloud/controller.js +425 -0
  96. package/dist/plugins/cloud/device-proof.d.ts +9 -0
  97. package/dist/plugins/cloud/device-proof.js +17 -0
  98. package/dist/plugins/cloud/plugin.d.ts +4 -0
  99. package/dist/plugins/cloud/plugin.js +17 -0
  100. package/dist/plugins/cloud/state-store.d.ts +7 -0
  101. package/dist/plugins/cloud/state-store.js +79 -0
  102. package/dist/plugins/cloud/tunnel-client.d.ts +84 -0
  103. package/dist/plugins/cloud/tunnel-client.js +427 -0
  104. package/dist/plugins/cloud/types.d.ts +72 -0
  105. package/dist/plugins/cloud/types.js +60 -0
  106. package/dist/plugins/computer/audit.d.ts +34 -0
  107. package/dist/plugins/computer/audit.js +42 -0
  108. package/dist/plugins/computer/computer-native-backend.d.ts +11 -0
  109. package/dist/plugins/computer/computer-native-backend.js +58 -0
  110. package/dist/plugins/computer/computer-native-host.d.ts +30 -0
  111. package/dist/plugins/computer/computer-native-host.js +411 -0
  112. package/dist/plugins/computer/computer-protocol.d.ts +22 -0
  113. package/dist/plugins/computer/computer-protocol.js +74 -0
  114. package/dist/plugins/computer/computer-schemas.d.ts +285 -0
  115. package/dist/plugins/computer/computer-schemas.js +152 -0
  116. package/dist/plugins/computer/computer-service.d.ts +29 -0
  117. package/dist/plugins/computer/computer-service.js +117 -0
  118. package/dist/plugins/computer/computer-settings-repository.d.ts +8 -0
  119. package/dist/plugins/computer/computer-settings-repository.js +41 -0
  120. package/dist/plugins/computer/mcp.d.ts +3 -0
  121. package/dist/plugins/computer/mcp.js +126 -0
  122. package/dist/plugins/computer/plugin.d.ts +4 -0
  123. package/dist/plugins/computer/plugin.js +29 -0
  124. package/dist/plugins/computer/types.d.ts +174 -0
  125. package/dist/plugins/computer/types.js +1 -0
  126. package/dist/plugins/git/git-service.d.ts +30 -0
  127. package/dist/plugins/git/git-service.js +428 -0
  128. package/dist/plugins/git/plugin.d.ts +4 -0
  129. package/dist/plugins/git/plugin.js +12 -0
  130. package/dist/plugins/git/types.d.ts +32 -0
  131. package/dist/plugins/git/types.js +1 -0
  132. package/dist/plugins/plugin-manager.d.ts +11 -0
  133. package/dist/plugins/plugin-manager.js +63 -0
  134. package/dist/plugins/process/backend.d.ts +18 -0
  135. package/dist/plugins/process/backend.js +1 -0
  136. package/dist/plugins/process/head-tail-buffer.d.ts +17 -0
  137. package/dist/plugins/process/head-tail-buffer.js +49 -0
  138. package/dist/plugins/process/infrastructure/pipe-process-backend.d.ts +8 -0
  139. package/dist/plugins/process/infrastructure/pipe-process-backend.js +71 -0
  140. package/dist/plugins/process/infrastructure/pty-process-backend.d.ts +8 -0
  141. package/dist/plugins/process/infrastructure/pty-process-backend.js +51 -0
  142. package/dist/plugins/process/mcp.d.ts +3 -0
  143. package/dist/plugins/process/mcp.js +58 -0
  144. package/dist/plugins/process/plugin.d.ts +4 -0
  145. package/dist/plugins/process/plugin.js +25 -0
  146. package/dist/plugins/process/process-supervisor.d.ts +39 -0
  147. package/dist/plugins/process/process-supervisor.js +244 -0
  148. package/dist/plugins/process/types.d.ts +30 -0
  149. package/dist/plugins/process/types.js +1 -0
  150. package/dist/plugins/types.d.ts +35 -0
  151. package/dist/plugins/types.js +17 -0
  152. package/dist/plugins/web/api-types.d.ts +56 -0
  153. package/dist/plugins/web/api-types.js +1 -0
  154. package/dist/plugins/web/http/api-router.d.ts +13 -0
  155. package/dist/plugins/web/http/api-router.js +47 -0
  156. package/dist/plugins/web/http/auth-api-router.d.ts +8 -0
  157. package/dist/plugins/web/http/auth-api-router.js +123 -0
  158. package/dist/plugins/web/http/cloud-api-router.d.ts +4 -0
  159. package/dist/plugins/web/http/cloud-api-router.js +29 -0
  160. package/dist/plugins/web/http/computer-api-router.d.ts +5 -0
  161. package/dist/plugins/web/http/computer-api-router.js +69 -0
  162. package/dist/plugins/web/http/git-api-router.d.ts +3 -0
  163. package/dist/plugins/web/http/git-api-router.js +85 -0
  164. package/dist/plugins/web/http/logs-api-router.d.ts +3 -0
  165. package/dist/plugins/web/http/logs-api-router.js +49 -0
  166. package/dist/plugins/web/http/process-api-router.d.ts +3 -0
  167. package/dist/plugins/web/http/process-api-router.js +16 -0
  168. package/dist/plugins/web/http/runtime-api-router.d.ts +10 -0
  169. package/dist/plugins/web/http/runtime-api-router.js +34 -0
  170. package/dist/plugins/web/http/workspace-api-router.d.ts +3 -0
  171. package/dist/plugins/web/http/workspace-api-router.js +91 -0
  172. package/dist/plugins/web/plugin.d.ts +8 -0
  173. package/dist/plugins/web/plugin.js +17 -0
  174. package/dist/plugins/web/runtime.d.ts +18 -0
  175. package/dist/plugins/web/runtime.js +31 -0
  176. package/dist/plugins/workspace/mcp.d.ts +3 -0
  177. package/dist/plugins/workspace/mcp.js +24 -0
  178. package/dist/plugins/workspace/metadata.d.ts +6 -0
  179. package/dist/plugins/workspace/metadata.js +111 -0
  180. package/dist/plugins/workspace/plugin.d.ts +4 -0
  181. package/dist/plugins/workspace/plugin.js +22 -0
  182. package/dist/plugins/workspace/types.d.ts +23 -0
  183. package/dist/plugins/workspace/types.js +1 -0
  184. package/dist/plugins/workspace/workspace-fs.d.ts +28 -0
  185. package/dist/plugins/workspace/workspace-fs.js +200 -0
  186. package/dist/plugins/workspace/workspace-service.d.ts +15 -0
  187. package/dist/plugins/workspace/workspace-service.js +140 -0
  188. package/dist/presentation/http/http-utils.d.ts +9 -0
  189. package/dist/presentation/http/http-utils.js +89 -0
  190. package/dist/presentation/http/oauth-router.d.ts +5 -0
  191. package/dist/presentation/http/oauth-router.js +172 -0
  192. package/dist/web/assets/CloudView-CHjVbp-5.css +1 -0
  193. package/dist/web/assets/CloudView-CvX0dkgu.js +1 -0
  194. package/dist/web/assets/CodeViewer-CH1DEJge.css +1 -0
  195. package/dist/web/assets/CodeViewer.vue_vue_type_script_setup_true_lang-B5TxGkUW.js +3 -0
  196. package/dist/web/assets/ComputerView-91Z9Cefw.css +1 -0
  197. package/dist/web/assets/ComputerView-OOyEqWml.js +1 -0
  198. package/dist/web/assets/McpToolsView-BTnolyS6.css +1 -0
  199. package/dist/web/assets/McpToolsView-DjXWTKrZ.js +1 -0
  200. package/dist/web/assets/OperationsView-DqTY51Cr.js +4 -0
  201. package/dist/web/assets/ProcessesView-C13BykIa.js +4 -0
  202. package/dist/web/assets/StateChip.vue_vue_type_script_setup_true_lang-DyOhJmR6.js +1 -0
  203. package/dist/web/assets/SystemLogsView-Ci0u4BTb.js +1 -0
  204. package/dist/web/assets/VSelect-CAxEESw-.css +1 -0
  205. package/dist/web/assets/VSelect-DrRpKyYI.js +1 -0
  206. package/dist/web/assets/VSpacer-C3wAY3F0.js +1 -0
  207. package/dist/web/assets/VSpacer-DfbUir7X.css +1 -0
  208. package/dist/web/assets/VSwitch-Cos8PNSP.css +1 -0
  209. package/dist/web/assets/VSwitch-CxusR4iO.js +1 -0
  210. package/dist/web/assets/VTabs-DSWgbwhc.css +1 -0
  211. package/dist/web/assets/VTabs-qBcuuXh3.js +1 -0
  212. package/dist/web/assets/WorkspacesView-BzQ0aH74.css +1 -0
  213. package/dist/web/assets/WorkspacesView-CijIvfsp.js +2 -0
  214. package/dist/web/assets/_plugin-vue_export-helper-DlAUqK2U.js +1 -0
  215. package/dist/web/assets/chatroom-B5p-5n3y.svg +15 -0
  216. package/dist/web/assets/index-BDkarAkX.js +2 -0
  217. package/dist/web/assets/index-BegKQ3Yd.js +19 -0
  218. package/dist/web/assets/index-CkjqXRSj.css +1 -0
  219. package/dist/web/assets/syntax-highlight-B5ArnyrC.js +3 -0
  220. package/dist/web/assets/useOperationLabels-BDjzGDkT.js +1 -0
  221. package/dist/web/assets/utils-rtPwWNel.js +1 -0
  222. package/dist/web/index.html +19 -0
  223. package/package.json +125 -0
@@ -0,0 +1,79 @@
1
+ import { generateKeyPairSync, randomUUID } from "node:crypto";
2
+ import { chmod, mkdir, readFile, rename, rm, writeFile, } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { z } from "zod";
5
+ import { CLOUD_DESIRED_SERVICES_SCHEMA, CLOUD_ENTITLEMENT_SCHEMA, CLOUD_HTTP_URL_SCHEMA, CLOUD_LEASE_SCHEMA, } from "./types.js";
6
+ const stateSchema = z
7
+ .object({
8
+ schemaVersion: z.literal(1),
9
+ installationId: z.string().uuid(),
10
+ devicePublicKey: z.string().min(20),
11
+ devicePrivateKey: z.string().min(20),
12
+ customerId: z.string().min(1).nullable(),
13
+ publicPrefix: z.string().min(1).nullable(),
14
+ desiredServices: CLOUD_DESIRED_SERVICES_SCHEMA,
15
+ entitlements: z.array(CLOUD_ENTITLEMENT_SCHEMA),
16
+ managementSession: z
17
+ .object({
18
+ purchaseToken: z.string().min(24),
19
+ managementUrl: CLOUD_HTTP_URL_SCHEMA,
20
+ expiresAt: z.string().datetime(),
21
+ })
22
+ .strict()
23
+ .nullable(),
24
+ lease: CLOUD_LEASE_SCHEMA.nullable(),
25
+ })
26
+ .strict();
27
+ export class CloudStateStore {
28
+ filePath;
29
+ constructor(dataDir) {
30
+ this.filePath = path.join(dataDir, "cloud.json");
31
+ }
32
+ async loadOrCreate() {
33
+ try {
34
+ return stateSchema.parse(JSON.parse(await readFile(this.filePath, "utf8")));
35
+ }
36
+ catch (error) {
37
+ if (error.code !== "ENOENT")
38
+ throw error;
39
+ }
40
+ const state = createInitialState();
41
+ await this.save(state);
42
+ return state;
43
+ }
44
+ async save(state) {
45
+ const validated = stateSchema.parse(state);
46
+ await mkdir(path.dirname(this.filePath), { recursive: true, mode: 0o700 });
47
+ const temporary = `${this.filePath}.${process.pid}.${randomUUID()}.tmp`;
48
+ try {
49
+ await writeFile(temporary, `${JSON.stringify(validated, null, 2)}\n`, {
50
+ mode: 0o600,
51
+ });
52
+ await chmod(temporary, 0o600).catch(() => undefined);
53
+ await rename(temporary, this.filePath);
54
+ await chmod(this.filePath, 0o600).catch(() => undefined);
55
+ }
56
+ finally {
57
+ await rm(temporary, { force: true }).catch(() => undefined);
58
+ }
59
+ }
60
+ }
61
+ function createInitialState() {
62
+ const { publicKey, privateKey } = generateKeyPairSync("ed25519");
63
+ return {
64
+ schemaVersion: 1,
65
+ installationId: randomUUID(),
66
+ devicePublicKey: publicKey
67
+ .export({ format: "der", type: "spki" })
68
+ .toString("base64url"),
69
+ devicePrivateKey: privateKey
70
+ .export({ format: "der", type: "pkcs8" })
71
+ .toString("base64url"),
72
+ customerId: null,
73
+ publicPrefix: null,
74
+ desiredServices: { remote_mcp: true, remote_web: true },
75
+ entitlements: [],
76
+ managementSession: null,
77
+ lease: null,
78
+ };
79
+ }
@@ -0,0 +1,84 @@
1
+ import { z } from "zod";
2
+ import { type CloudLeaseState } from "./types.js";
3
+ interface TunnelTimings {
4
+ readyTimeoutMs: number;
5
+ heartbeatIntervalMs: number;
6
+ }
7
+ declare const controlMessageSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
8
+ type: z.ZodLiteral<"challenge">;
9
+ nonce: z.ZodString;
10
+ }, z.core.$strict>, z.ZodObject<{
11
+ type: z.ZodLiteral<"ready">;
12
+ }, z.core.$strict>, z.ZodObject<{
13
+ type: z.ZodLiteral<"open">;
14
+ streamId: z.ZodNumber;
15
+ service: z.ZodEnum<{
16
+ mcp: "mcp";
17
+ web: "web";
18
+ }>;
19
+ method: z.ZodString;
20
+ path: z.ZodString;
21
+ headers: z.ZodRecord<z.ZodString, z.ZodString>;
22
+ }, z.core.$strict>, z.ZodObject<{
23
+ type: z.ZodLiteral<"end">;
24
+ streamId: z.ZodNumber;
25
+ }, z.core.$strict>, z.ZodObject<{
26
+ type: z.ZodLiteral<"abort">;
27
+ streamId: z.ZodNumber;
28
+ }, z.core.$strict>, z.ZodObject<{
29
+ type: z.ZodLiteral<"pause">;
30
+ streamId: z.ZodNumber;
31
+ }, z.core.$strict>, z.ZodObject<{
32
+ type: z.ZodLiteral<"resume">;
33
+ streamId: z.ZodNumber;
34
+ }, z.core.$strict>], "type">;
35
+ type ControlMessage = z.infer<typeof controlMessageSchema>;
36
+ export declare function parseTunnelControlMessage(input: string): ControlMessage;
37
+ export declare class CloudTunnelClient {
38
+ private lease;
39
+ private readonly identity;
40
+ private readonly local;
41
+ private readonly callbacks;
42
+ private socket;
43
+ private reconnectTimer;
44
+ private readyTimer;
45
+ private heartbeatTimer;
46
+ private awaitingPong;
47
+ private stopped;
48
+ private attempts;
49
+ private closeWhenIdle;
50
+ private acceptingServices;
51
+ private readonly streams;
52
+ private readonly timings;
53
+ constructor(lease: CloudLeaseState, identity: {
54
+ devicePrivateKey: string;
55
+ }, local: {
56
+ host: string;
57
+ port: number;
58
+ }, callbacks: {
59
+ onConnected(): void;
60
+ onDisconnected(): void;
61
+ onLeaseRejected(): void;
62
+ onError(error: Error): void;
63
+ }, timings?: Partial<TunnelTimings>);
64
+ start(): void;
65
+ stop(): void;
66
+ drainAndStop(): void;
67
+ updateLease(lease: CloudLeaseState): void;
68
+ private connect;
69
+ private handleControl;
70
+ private openStream;
71
+ private finishStream;
72
+ private pauseForBackpressure;
73
+ private destroyAllStreams;
74
+ private handleBinary;
75
+ private send;
76
+ private sendBinary;
77
+ private startReadyTimeout;
78
+ private clearReadyTimeout;
79
+ private startHeartbeat;
80
+ private clearSocketTimers;
81
+ private failSocket;
82
+ private scheduleReconnect;
83
+ }
84
+ export {};
@@ -0,0 +1,427 @@
1
+ import { createPrivateKey, sign } from "node:crypto";
2
+ import http from "node:http";
3
+ import WebSocket from "ws";
4
+ import { z } from "zod";
5
+ import { cloudServiceForPublicService, } from "./types.js";
6
+ const PROTOCOL = "chatroom-tunnel-v1";
7
+ const HIGH_WATER = 8 * 1024 * 1024;
8
+ const LOW_WATER = 2 * 1024 * 1024;
9
+ const READY_TIMEOUT_MS = 10_000;
10
+ const HEARTBEAT_INTERVAL_MS = 20_000;
11
+ const streamIdSchema = z.number().int().min(0).max(0xffff_ffff);
12
+ const controlMessageSchema = z.discriminatedUnion("type", [
13
+ z
14
+ .object({
15
+ type: z.literal("challenge"),
16
+ nonce: z.string().min(1),
17
+ })
18
+ .strict(),
19
+ z.object({ type: z.literal("ready") }).strict(),
20
+ z
21
+ .object({
22
+ type: z.literal("open"),
23
+ streamId: streamIdSchema,
24
+ service: z.enum(["mcp", "web"]),
25
+ method: z.string().min(1),
26
+ path: z.string().startsWith("/"),
27
+ headers: z.record(z.string(), z.string()),
28
+ })
29
+ .strict(),
30
+ z.object({ type: z.literal("end"), streamId: streamIdSchema }).strict(),
31
+ z.object({ type: z.literal("abort"), streamId: streamIdSchema }).strict(),
32
+ z.object({ type: z.literal("pause"), streamId: streamIdSchema }).strict(),
33
+ z.object({ type: z.literal("resume"), streamId: streamIdSchema }).strict(),
34
+ ]);
35
+ export function parseTunnelControlMessage(input) {
36
+ return controlMessageSchema.parse(JSON.parse(input));
37
+ }
38
+ export class CloudTunnelClient {
39
+ lease;
40
+ identity;
41
+ local;
42
+ callbacks;
43
+ socket = null;
44
+ reconnectTimer = null;
45
+ readyTimer = null;
46
+ heartbeatTimer = null;
47
+ awaitingPong = false;
48
+ stopped = true;
49
+ attempts = 0;
50
+ closeWhenIdle = null;
51
+ acceptingServices;
52
+ streams = new Map();
53
+ timings;
54
+ constructor(lease, identity, local, callbacks, timings = {}) {
55
+ this.lease = lease;
56
+ this.identity = identity;
57
+ this.local = local;
58
+ this.callbacks = callbacks;
59
+ this.acceptingServices = new Set(lease.services);
60
+ this.timings = {
61
+ readyTimeoutMs: timings.readyTimeoutMs ?? READY_TIMEOUT_MS,
62
+ heartbeatIntervalMs: timings.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS,
63
+ };
64
+ }
65
+ start() {
66
+ if (!this.stopped)
67
+ return;
68
+ this.stopped = false;
69
+ this.closeWhenIdle = null;
70
+ this.acceptingServices = new Set(this.lease.services);
71
+ this.connect();
72
+ }
73
+ stop() {
74
+ this.stopped = true;
75
+ this.closeWhenIdle = null;
76
+ this.acceptingServices.clear();
77
+ if (this.reconnectTimer)
78
+ clearTimeout(this.reconnectTimer);
79
+ this.reconnectTimer = null;
80
+ this.clearSocketTimers();
81
+ this.socket?.close();
82
+ this.socket = null;
83
+ this.destroyAllStreams();
84
+ }
85
+ drainAndStop() {
86
+ this.stopped = true;
87
+ this.acceptingServices.clear();
88
+ if (this.reconnectTimer)
89
+ clearTimeout(this.reconnectTimer);
90
+ this.reconnectTimer = null;
91
+ this.clearSocketTimers();
92
+ if (this.streams.size === 0) {
93
+ this.closeWhenIdle = null;
94
+ this.socket?.close();
95
+ return;
96
+ }
97
+ this.closeWhenIdle = "stop";
98
+ }
99
+ updateLease(lease) {
100
+ const tunnelChanged = lease.tunnelUrl !== this.lease.tunnelUrl;
101
+ const removesService = this.lease.services.some((service) => !lease.services.includes(service));
102
+ this.lease = lease;
103
+ this.acceptingServices = new Set(lease.services);
104
+ if (this.stopped)
105
+ return;
106
+ if (!tunnelChanged) {
107
+ if (this.socket?.readyState === WebSocket.OPEN)
108
+ this.send({ type: "update-lease", lease: lease.token });
109
+ return;
110
+ }
111
+ if (!removesService || this.streams.size === 0) {
112
+ this.socket?.close();
113
+ return;
114
+ }
115
+ this.closeWhenIdle = "reconnect";
116
+ }
117
+ connect() {
118
+ if (this.stopped || this.socket)
119
+ return;
120
+ const socket = new WebSocket(this.lease.tunnelUrl, PROTOCOL);
121
+ this.socket = socket;
122
+ socket.binaryType = "nodebuffer";
123
+ this.startReadyTimeout(socket);
124
+ socket.on("message", (data, isBinary) => {
125
+ try {
126
+ if (isBinary)
127
+ this.handleBinary(Buffer.from(data));
128
+ else
129
+ this.handleControl(parseTunnelControlMessage(data.toString()));
130
+ }
131
+ catch (error) {
132
+ this.callbacks.onError(error instanceof Error ? error : new Error(String(error)));
133
+ socket.close();
134
+ }
135
+ });
136
+ socket.on("pong", () => {
137
+ if (this.socket === socket)
138
+ this.awaitingPong = false;
139
+ });
140
+ socket.on("close", (code) => {
141
+ if (this.socket === socket) {
142
+ this.clearSocketTimers();
143
+ this.socket = null;
144
+ }
145
+ this.closeWhenIdle = null;
146
+ this.destroyAllStreams();
147
+ this.callbacks.onDisconnected();
148
+ if (this.stopped)
149
+ return;
150
+ if (code === 4003) {
151
+ this.stopped = true;
152
+ this.callbacks.onLeaseRejected();
153
+ return;
154
+ }
155
+ this.scheduleReconnect();
156
+ });
157
+ socket.on("error", (error) => this.failSocket(socket, error));
158
+ }
159
+ handleControl(message) {
160
+ if (message.type === "challenge") {
161
+ this.send({
162
+ type: "authenticate",
163
+ lease: this.lease.token,
164
+ signature: signChallenge(message.nonce, this.lease.token, this.identity.devicePrivateKey),
165
+ });
166
+ return;
167
+ }
168
+ if (message.type === "ready") {
169
+ this.attempts = 0;
170
+ this.clearReadyTimeout();
171
+ if (this.socket)
172
+ this.startHeartbeat(this.socket);
173
+ this.callbacks.onConnected();
174
+ return;
175
+ }
176
+ if (message.type === "open") {
177
+ this.openStream(message);
178
+ return;
179
+ }
180
+ const stream = this.streams.get(message.streamId);
181
+ if (!stream)
182
+ return;
183
+ if (message.type === "end")
184
+ stream.request.end();
185
+ else if (message.type === "abort") {
186
+ stream.request.destroy();
187
+ stream.response?.destroy();
188
+ this.finishStream(message.streamId);
189
+ }
190
+ else if (message.type === "pause")
191
+ stream.response?.pause();
192
+ else if (message.type === "resume")
193
+ stream.response?.resume();
194
+ }
195
+ openStream(message) {
196
+ if (this.streams.has(message.streamId))
197
+ throw new Error(`Duplicate tunnel stream id: ${message.streamId}`);
198
+ const service = cloudServiceForPublicService(message.service);
199
+ if (!this.acceptingServices.has(service) ||
200
+ !allowedPath(message.service, message.path)) {
201
+ this.send({
202
+ type: "response",
203
+ streamId: message.streamId,
204
+ status: 404,
205
+ headers: { "content-type": "text/plain" },
206
+ });
207
+ this.send({ type: "response-end", streamId: message.streamId });
208
+ return;
209
+ }
210
+ const headers = sanitizeHeaders(message.headers);
211
+ headers.host = publicHost(this.lease, message.service);
212
+ const request = http.request({
213
+ host: this.local.host,
214
+ port: this.local.port,
215
+ method: message.method,
216
+ path: message.path,
217
+ headers,
218
+ }, (response) => {
219
+ const stream = this.streams.get(message.streamId);
220
+ if (stream)
221
+ stream.response = response;
222
+ this.send({
223
+ type: "response",
224
+ streamId: message.streamId,
225
+ status: response.statusCode ?? 502,
226
+ headers: responseHeaders(response.headers),
227
+ });
228
+ response.on("data", (chunk) => {
229
+ if (!this.sendBinary(message.streamId, Buffer.from(chunk)))
230
+ this.pauseForBackpressure(message.streamId, response);
231
+ });
232
+ response.on("end", () => {
233
+ this.send({ type: "response-end", streamId: message.streamId });
234
+ this.finishStream(message.streamId);
235
+ });
236
+ response.on("error", () => {
237
+ this.send({ type: "abort", streamId: message.streamId });
238
+ this.finishStream(message.streamId);
239
+ });
240
+ });
241
+ request.on("drain", () => this.send({ type: "resume", streamId: message.streamId }));
242
+ request.on("error", () => {
243
+ this.send({
244
+ type: "response",
245
+ streamId: message.streamId,
246
+ status: 502,
247
+ headers: {},
248
+ });
249
+ this.send({ type: "response-end", streamId: message.streamId });
250
+ this.finishStream(message.streamId);
251
+ });
252
+ this.streams.set(message.streamId, {
253
+ request,
254
+ response: null,
255
+ backpressureTimer: null,
256
+ });
257
+ }
258
+ finishStream(streamId) {
259
+ const stream = this.streams.get(streamId);
260
+ if (stream?.backpressureTimer)
261
+ clearInterval(stream.backpressureTimer);
262
+ this.streams.delete(streamId);
263
+ if (this.streams.size !== 0 || !this.closeWhenIdle)
264
+ return;
265
+ const action = this.closeWhenIdle;
266
+ this.closeWhenIdle = null;
267
+ if (action === "stop") {
268
+ this.socket?.close();
269
+ return;
270
+ }
271
+ this.socket?.close();
272
+ }
273
+ pauseForBackpressure(streamId, response) {
274
+ response.pause();
275
+ const stream = this.streams.get(streamId);
276
+ if (!stream || stream.backpressureTimer)
277
+ return;
278
+ stream.backpressureTimer = setInterval(() => {
279
+ if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
280
+ if (stream.backpressureTimer)
281
+ clearInterval(stream.backpressureTimer);
282
+ stream.backpressureTimer = null;
283
+ return;
284
+ }
285
+ if (this.socket.bufferedAmount <= LOW_WATER) {
286
+ if (stream.backpressureTimer)
287
+ clearInterval(stream.backpressureTimer);
288
+ stream.backpressureTimer = null;
289
+ response.resume();
290
+ }
291
+ }, 10);
292
+ stream.backpressureTimer.unref();
293
+ }
294
+ destroyAllStreams() {
295
+ for (const stream of this.streams.values()) {
296
+ if (stream.backpressureTimer)
297
+ clearInterval(stream.backpressureTimer);
298
+ stream.request.destroy();
299
+ stream.response?.destroy();
300
+ }
301
+ this.streams.clear();
302
+ }
303
+ handleBinary(frame) {
304
+ if (frame.length < 4)
305
+ throw new Error("Invalid tunnel data frame");
306
+ const streamId = frame.readUInt32BE(0);
307
+ const stream = this.streams.get(streamId);
308
+ if (!stream)
309
+ return;
310
+ if (!stream.request.write(frame.subarray(4)))
311
+ this.send({ type: "pause", streamId });
312
+ }
313
+ send(message) {
314
+ if (this.socket?.readyState === WebSocket.OPEN)
315
+ this.socket.send(JSON.stringify(message));
316
+ }
317
+ sendBinary(streamId, chunk) {
318
+ const socket = this.socket;
319
+ if (!socket || socket.readyState !== WebSocket.OPEN)
320
+ return false;
321
+ const frame = Buffer.allocUnsafe(4 + chunk.length);
322
+ frame.writeUInt32BE(streamId, 0);
323
+ chunk.copy(frame, 4);
324
+ socket.send(frame, { binary: true });
325
+ return socket.bufferedAmount < HIGH_WATER;
326
+ }
327
+ startReadyTimeout(socket) {
328
+ this.clearReadyTimeout();
329
+ this.readyTimer = setTimeout(() => {
330
+ this.readyTimer = null;
331
+ this.failSocket(socket, new Error("Tunnel connection timed out"));
332
+ }, this.timings.readyTimeoutMs);
333
+ this.readyTimer.unref();
334
+ }
335
+ clearReadyTimeout() {
336
+ if (this.readyTimer)
337
+ clearTimeout(this.readyTimer);
338
+ this.readyTimer = null;
339
+ }
340
+ startHeartbeat(socket) {
341
+ if (this.heartbeatTimer)
342
+ clearInterval(this.heartbeatTimer);
343
+ this.awaitingPong = false;
344
+ this.heartbeatTimer = setInterval(() => {
345
+ if (this.socket !== socket || socket.readyState !== WebSocket.OPEN)
346
+ return;
347
+ if (this.awaitingPong) {
348
+ this.failSocket(socket, new Error("Tunnel heartbeat timed out"));
349
+ return;
350
+ }
351
+ this.awaitingPong = true;
352
+ socket.ping();
353
+ }, this.timings.heartbeatIntervalMs);
354
+ this.heartbeatTimer.unref();
355
+ }
356
+ clearSocketTimers() {
357
+ this.clearReadyTimeout();
358
+ if (this.heartbeatTimer)
359
+ clearInterval(this.heartbeatTimer);
360
+ this.heartbeatTimer = null;
361
+ this.awaitingPong = false;
362
+ }
363
+ failSocket(socket, error) {
364
+ if (this.socket !== socket)
365
+ return;
366
+ this.callbacks.onError(error);
367
+ this.clearSocketTimers();
368
+ this.socket = null;
369
+ socket.terminate();
370
+ }
371
+ scheduleReconnect() {
372
+ if (this.reconnectTimer || this.stopped)
373
+ return;
374
+ const delay = Math.min(30_000, 500 * 2 ** Math.min(this.attempts++, 6)) *
375
+ (0.8 + Math.random() * 0.4);
376
+ this.reconnectTimer = setTimeout(() => {
377
+ this.reconnectTimer = null;
378
+ this.connect();
379
+ }, delay);
380
+ this.reconnectTimer.unref();
381
+ }
382
+ }
383
+ function signChallenge(nonce, lease, privateKey) {
384
+ const key = createPrivateKey({
385
+ key: Buffer.from(privateKey, "base64url"),
386
+ format: "der",
387
+ type: "pkcs8",
388
+ });
389
+ return sign(null, Buffer.from(`chatroom-tunnel-v1\n${nonce}\n${lease}`), key).toString("base64url");
390
+ }
391
+ function publicHost(lease, service) {
392
+ const baseUrl = service === "mcp" ? lease.mcpBaseUrl : lease.webBaseUrl;
393
+ if (!baseUrl)
394
+ throw new Error("Tunnel lease is missing " + service + " public base URL");
395
+ return new URL(baseUrl).host;
396
+ }
397
+ function allowedPath(service, value) {
398
+ const pathname = new URL(value, "http://localhost").pathname;
399
+ if (service === "mcp")
400
+ return (pathname === "/mcp" ||
401
+ pathname.startsWith("/.well-known/oauth-") ||
402
+ pathname.startsWith("/oauth/"));
403
+ return (pathname !== "/mcp" &&
404
+ !pathname.startsWith("/oauth/") &&
405
+ !pathname.startsWith("/.well-known/oauth-"));
406
+ }
407
+ function sanitizeHeaders(headers) {
408
+ const blocked = new Set([
409
+ "connection",
410
+ "host",
411
+ "proxy-connection",
412
+ "keep-alive",
413
+ "transfer-encoding",
414
+ "upgrade",
415
+ ]);
416
+ return Object.fromEntries(Object.entries(headers).filter(([key]) => !blocked.has(key.toLowerCase())));
417
+ }
418
+ function responseHeaders(headers) {
419
+ const result = {};
420
+ for (const [key, value] of Object.entries(headers)) {
421
+ if (value === undefined ||
422
+ ["connection", "keep-alive", "transfer-encoding", "upgrade"].includes(key.toLowerCase()))
423
+ continue;
424
+ result[key] = Array.isArray(value) ? value.join(", ") : value;
425
+ }
426
+ return result;
427
+ }
@@ -0,0 +1,72 @@
1
+ import { z } from "zod";
2
+ export declare const CLOUD_SERVICES: readonly ["remote_mcp", "remote_web"];
3
+ export declare const CLOUD_HTTP_URL_SCHEMA: z.ZodString;
4
+ export declare const CLOUD_WEBSOCKET_URL_SCHEMA: z.ZodString;
5
+ export declare const CLOUD_SERVICE_SCHEMA: z.ZodEnum<{
6
+ remote_mcp: "remote_mcp";
7
+ remote_web: "remote_web";
8
+ }>;
9
+ export type CloudServiceId = (typeof CLOUD_SERVICES)[number];
10
+ declare const PUBLIC_SERVICE_TO_CLOUD_SERVICE: {
11
+ readonly mcp: "remote_mcp";
12
+ readonly web: "remote_web";
13
+ };
14
+ export type PublicService = keyof typeof PUBLIC_SERVICE_TO_CLOUD_SERVICE;
15
+ export declare const CLOUD_DESIRED_SERVICES_SCHEMA: z.ZodObject<{
16
+ remote_mcp: z.ZodBoolean;
17
+ remote_web: z.ZodBoolean;
18
+ }, z.core.$strict>;
19
+ export declare function cloudServiceForPublicService(service: PublicService): CloudServiceId;
20
+ export declare const CLOUD_ENTITLEMENT_SCHEMA: z.ZodObject<{
21
+ service: z.ZodEnum<{
22
+ remote_mcp: "remote_mcp";
23
+ remote_web: "remote_web";
24
+ }>;
25
+ status: z.ZodLiteral<"active">;
26
+ sourceProvider: z.ZodString;
27
+ sourceId: z.ZodString;
28
+ validUntil: z.ZodNullable<z.ZodString>;
29
+ }, z.core.$strict>;
30
+ export type CloudEntitlement = z.infer<typeof CLOUD_ENTITLEMENT_SCHEMA>;
31
+ export declare const CLOUD_LEASE_SCHEMA: z.ZodObject<{
32
+ token: z.ZodString;
33
+ expiresAt: z.ZodString;
34
+ tunnelUrl: z.ZodString;
35
+ mcpBaseUrl: z.ZodNullable<z.ZodString>;
36
+ webBaseUrl: z.ZodNullable<z.ZodString>;
37
+ services: z.ZodArray<z.ZodEnum<{
38
+ remote_mcp: "remote_mcp";
39
+ remote_web: "remote_web";
40
+ }>>;
41
+ }, z.core.$strict>;
42
+ export type CloudLeaseState = z.infer<typeof CLOUD_LEASE_SCHEMA>;
43
+ interface ManagementSessionState {
44
+ purchaseToken: string;
45
+ managementUrl: string;
46
+ expiresAt: string;
47
+ }
48
+ export interface CloudPersistedState {
49
+ schemaVersion: 1;
50
+ installationId: string;
51
+ devicePublicKey: string;
52
+ devicePrivateKey: string;
53
+ customerId: string | null;
54
+ publicPrefix: string | null;
55
+ desiredServices: Record<CloudServiceId, boolean>;
56
+ entitlements: CloudEntitlement[];
57
+ managementSession: ManagementSessionState | null;
58
+ lease: CloudLeaseState | null;
59
+ }
60
+ export interface CloudStatus {
61
+ installationId: string | null;
62
+ customerId: string | null;
63
+ publicPrefix: string | null;
64
+ desiredServices: Record<CloudServiceId, boolean>;
65
+ entitlements: CloudEntitlement[];
66
+ managementSessionActive: boolean;
67
+ connection: "inactive" | "connecting" | "connected" | "disconnected" | "error";
68
+ mcpUrl: string | null;
69
+ webUrl: string | null;
70
+ lastError: string | null;
71
+ }
72
+ export {};