@tenonai/yew 0.0.0-stage → 1.4.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 (133) hide show
  1. package/CHANGELOG.md +296 -0
  2. package/LICENSE +21 -0
  3. package/README.md +55 -2
  4. package/THIRD-PARTY-NOTICES.md +122 -0
  5. package/bin/yew.js +9 -0
  6. package/dist/cli/app.js +198 -0
  7. package/dist/cli/export.js +57 -0
  8. package/dist/cli/io.js +65 -0
  9. package/dist/cli/key.js +113 -0
  10. package/dist/cli/main.js +44 -0
  11. package/dist/cli/mcp.js +76 -0
  12. package/dist/cli/remote.js +116 -0
  13. package/dist/cli/run.js +72 -0
  14. package/dist/cli/schedule.js +123 -0
  15. package/dist/cli/send.js +126 -0
  16. package/dist/cli/serve.js +301 -0
  17. package/dist/cli/service.js +241 -0
  18. package/dist/cli/system.js +44 -0
  19. package/dist/remote/access.js +107 -0
  20. package/dist/remote/connector.js +278 -0
  21. package/dist/remote/identity.js +71 -0
  22. package/dist/remote/noise.js +287 -0
  23. package/dist/remote/protocol.js +51 -0
  24. package/dist/remote/push.js +37 -0
  25. package/dist/server/agent/compaction.js +242 -0
  26. package/dist/server/agent/context.js +119 -0
  27. package/dist/server/agent/held.js +48 -0
  28. package/dist/server/agent/helper.js +122 -0
  29. package/dist/server/agent/mailroom.js +510 -0
  30. package/dist/server/agent/prompt.js +268 -0
  31. package/dist/server/agent/runner.js +1159 -0
  32. package/dist/server/artifacts.js +216 -0
  33. package/dist/server/budget.js +88 -0
  34. package/dist/server/data-export.js +105 -0
  35. package/dist/server/data-usage.js +143 -0
  36. package/dist/server/db/database.js +49 -0
  37. package/dist/server/db/migrations.js +347 -0
  38. package/dist/server/errors.js +16 -0
  39. package/dist/server/events.js +17 -0
  40. package/dist/server/export.js +378 -0
  41. package/dist/server/folder-picker.js +32 -0
  42. package/dist/server/from-jig.js +98 -0
  43. package/dist/server/http/agents.js +78 -0
  44. package/dist/server/http/api.js +468 -0
  45. package/dist/server/http/app.js +111 -0
  46. package/dist/server/http/artifacts.js +53 -0
  47. package/dist/server/http/data.js +54 -0
  48. package/dist/server/http/devices.js +47 -0
  49. package/dist/server/http/events.js +134 -0
  50. package/dist/server/http/idempotency.js +53 -0
  51. package/dist/server/http/input.js +106 -0
  52. package/dist/server/http/mail.js +52 -0
  53. package/dist/server/http/mcp.js +134 -0
  54. package/dist/server/http/notes.js +91 -0
  55. package/dist/server/http/problem.js +55 -0
  56. package/dist/server/http/providers.js +131 -0
  57. package/dist/server/http/schedules.js +58 -0
  58. package/dist/server/http/search.js +42 -0
  59. package/dist/server/http/security.js +168 -0
  60. package/dist/server/http/skills.js +53 -0
  61. package/dist/server/http/system.js +26 -0
  62. package/dist/server/ids.js +30 -0
  63. package/dist/server/keys.js +51 -0
  64. package/dist/server/mail/envelope.js +152 -0
  65. package/dist/server/mail/post.js +603 -0
  66. package/dist/server/mail/store.js +279 -0
  67. package/dist/server/manage.js +601 -0
  68. package/dist/server/mcp-builtin.js +179 -0
  69. package/dist/server/mcp-config.js +305 -0
  70. package/dist/server/mcp-oauth.js +448 -0
  71. package/dist/server/mcp.js +668 -0
  72. package/dist/server/model/gateway.js +410 -0
  73. package/dist/server/paths.js +34 -0
  74. package/dist/server/permissions/engine.js +249 -0
  75. package/dist/server/permissions/paths.js +93 -0
  76. package/dist/server/permissions/shell.js +635 -0
  77. package/dist/server/push.js +345 -0
  78. package/dist/server/reveal.js +36 -0
  79. package/dist/server/runtime.js +17 -0
  80. package/dist/server/schedules.js +356 -0
  81. package/dist/server/settings.js +80 -0
  82. package/dist/server/skills.js +262 -0
  83. package/dist/server/store.js +1077 -0
  84. package/dist/server/tools/files.js +318 -0
  85. package/dist/server/tools/html.js +221 -0
  86. package/dist/server/tools/jobs.js +38 -0
  87. package/dist/server/tools/mail.js +680 -0
  88. package/dist/server/tools/match.js +81 -0
  89. package/dist/server/tools/misc.js +253 -0
  90. package/dist/server/tools/process.js +128 -0
  91. package/dist/server/tools/read-state.js +40 -0
  92. package/dist/server/tools/registry.js +43 -0
  93. package/dist/server/tools/search.js +175 -0
  94. package/dist/server/tools/shell.js +124 -0
  95. package/dist/server/tools/types.js +43 -0
  96. package/dist/server/tools/web-search.js +198 -0
  97. package/dist/server/tools/web.js +240 -0
  98. package/dist/shared/cron.js +105 -0
  99. package/dist/shared/mcp-presets.js +170 -0
  100. package/dist/shared/messages.js +45 -0
  101. package/dist/shared/policy.js +42 -0
  102. package/dist/shared/types.js +34 -0
  103. package/dist/shared/version.js +8 -0
  104. package/mcp-builtin/package-lock.json +3398 -0
  105. package/mcp-builtin/package.json +14 -0
  106. package/mcp-builtin/presets/gitee/package-lock.json +105 -0
  107. package/mcp-builtin/presets/gitee/package.json +10 -0
  108. package/mcp-builtin/presets/notion/package-lock.json +2243 -0
  109. package/mcp-builtin/presets/notion/package.json +10 -0
  110. package/mcp-builtin/presets/sentry/package-lock.json +28 -0
  111. package/mcp-builtin/presets/sentry/package.json +10 -0
  112. package/package.json +75 -5
  113. package/web/dist/THIRD-PARTY-NOTICES.txt +1944 -0
  114. package/web/dist/assets/index-B9oWPSod.css +1 -0
  115. package/web/dist/assets/index-C5qBMzFX.js +68 -0
  116. package/web/dist/icons/app-icon.png +0 -0
  117. package/web/dist/icons/apple-touch-icon.png +0 -0
  118. package/web/dist/icons/favicon-16.png +0 -0
  119. package/web/dist/icons/favicon-32.png +0 -0
  120. package/web/dist/icons/favicon-64.png +0 -0
  121. package/web/dist/icons/tenon-mark.svg +1 -0
  122. package/web/dist/icons/yew-mark.svg +1 -0
  123. package/web/dist/index.html +18 -0
  124. package/web/dist/mascot/gift.webp +0 -0
  125. package/web/dist/mascot/greeting.webp +0 -0
  126. package/web/dist/mascot/happy.webp +0 -0
  127. package/web/dist/mascot/lost.webp +0 -0
  128. package/web/dist/mascot/shush.webp +0 -0
  129. package/web/dist/mascot/sleepy.webp +0 -0
  130. package/web/dist/mascot/sorry.webp +0 -0
  131. package/web/dist/mascot/thinking.webp +0 -0
  132. package/web/dist/mascot/waking.webp +0 -0
  133. package/web/dist/mascot/writing.webp +0 -0
@@ -0,0 +1,241 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { homedir, userInfo } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { parseArgs } from "node:util";
7
+ import { EXIT_ERROR, EXIT_OK, UsageError } from "./io.js";
8
+ import { serviceRunning } from "./serve.js";
9
+ const HELP = `Usage: yew service <install|uninstall|status> [options]
10
+
11
+ Start Yew when you log in, so your phone and scheduled tasks can reach it
12
+ without a terminal open. On macOS this is a LaunchAgent for your user, on
13
+ Linux a systemd user unit. Yew is restarted if it exits with an error, and
14
+ its log goes to the logs folder in Yew's data directory. Nothing is changed
15
+ on your system until you run install.
16
+
17
+ Commands:
18
+ install Start Yew at login, and start it now
19
+ uninstall Stop starting Yew at login, and stop it now
20
+ status Show whether it is installed and running
21
+
22
+ Options:
23
+ --json Print as JSON
24
+ -h, --help Show this help
25
+ `;
26
+ export const SERVICE_LABEL = "cn.tenonai.apps.yew";
27
+ const UNIT = "yew.service";
28
+ export function realServiceHost() {
29
+ return {
30
+ platform: process.platform,
31
+ homeDir: homedir(),
32
+ uid: userInfo().uid,
33
+ node: process.execPath,
34
+ // The sources in a checkout, the compiled file in the published package.
35
+ entry: fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./main.ts" : "./main.js", import.meta.url)),
36
+ run: (command, args) => spawnSync(command, args, { stdio: "ignore" }).status,
37
+ };
38
+ }
39
+ const xml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
40
+ /** The LaunchAgent: starts `yew serve` at login and again after an exit with an error. */
41
+ export function launchAgent(host, env, log) {
42
+ const strings = (values) => values.map((value) => `\t\t<string>${xml(value)}</string>`).join("\n");
43
+ const vars = Object.entries(env)
44
+ .map(([key, value]) => `\t\t<key>${xml(key)}</key>\n\t\t<string>${xml(value)}</string>`)
45
+ .join("\n");
46
+ return `<?xml version="1.0" encoding="UTF-8"?>
47
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
48
+ <plist version="1.0">
49
+ <dict>
50
+ <key>Label</key>
51
+ <string>${SERVICE_LABEL}</string>
52
+ <key>ProgramArguments</key>
53
+ <array>
54
+ ${strings([host.node, host.entry, "serve"])}
55
+ </array>
56
+ <key>EnvironmentVariables</key>
57
+ <dict>
58
+ ${vars}
59
+ </dict>
60
+ <key>RunAtLoad</key>
61
+ <true/>
62
+ <key>KeepAlive</key>
63
+ <dict>
64
+ <key>SuccessfulExit</key>
65
+ <false/>
66
+ </dict>
67
+ <key>ThrottleInterval</key>
68
+ <integer>10</integer>
69
+ <key>ProcessType</key>
70
+ <string>Background</string>
71
+ <key>StandardOutPath</key>
72
+ <string>${xml(log)}</string>
73
+ <key>StandardErrorPath</key>
74
+ <string>${xml(log)}</string>
75
+ </dict>
76
+ </plist>
77
+ `;
78
+ }
79
+ const quoted = (value) => `"${value.replace(/(["\\$`])/g, "\\$1").replace(/%/g, "%%")}"`;
80
+ /** The systemd user unit, with the same behavior as the LaunchAgent. */
81
+ export function systemdUnit(host, env, log) {
82
+ const vars = Object.entries(env)
83
+ .map(([key, value]) => `Environment=${quoted(`${key}=${value}`)}`)
84
+ .join("\n");
85
+ return `[Unit]
86
+ Description=Yew, an AI-native multi-agent workbench
87
+
88
+ [Service]
89
+ ExecStart=${quoted(host.node)} ${quoted(host.entry)} serve
90
+ ${vars}
91
+ Restart=on-failure
92
+ RestartSec=10
93
+ StandardOutput=append:${log}
94
+ StandardError=append:${log}
95
+
96
+ [Install]
97
+ WantedBy=default.target
98
+ `;
99
+ }
100
+ /** Starting at login is done with launchd on macOS and systemd on Linux. */
101
+ export const serviceSupported = (host) => host.platform === "darwin" || host.platform === "linux";
102
+ export function serviceFile(host) {
103
+ if (host.platform === "darwin") {
104
+ return join(host.homeDir, "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
105
+ }
106
+ if (host.platform === "linux")
107
+ return join(host.homeDir, ".config", "systemd", "user", UNIT);
108
+ throw new Error("yew service works on macOS and Linux.");
109
+ }
110
+ const target = (host) => `gui/${host.uid}/${SERVICE_LABEL}`;
111
+ /** The service file is there and the system has it loaded (macOS) or enabled (Linux). */
112
+ export function serviceLoaded(host) {
113
+ return (existsSync(serviceFile(host)) &&
114
+ (host.platform === "darwin"
115
+ ? host.run("launchctl", ["print", target(host)]) === 0
116
+ : host.run("systemctl", ["--user", "is-enabled", "--quiet", UNIT]) === 0));
117
+ }
118
+ /**
119
+ * Whether Yew will be started at the next login. On macOS the file is enough: launchd loads what is
120
+ * in LaunchAgents when the person logs in. On Linux the unit has to be enabled.
121
+ */
122
+ export function serviceAtLogin(host) {
123
+ if (!existsSync(serviceFile(host)))
124
+ return false;
125
+ return (host.platform === "darwin" ||
126
+ host.run("systemctl", ["--user", "is-enabled", "--quiet", UNIT]) === 0);
127
+ }
128
+ /**
129
+ * Writes the service file and registers it. With `start` (what `yew service install` does) the
130
+ * service is also started now; without it Yew starts at the next login and what runs now is left
131
+ * alone, which is what the settings need: they are served by the Yew that is running.
132
+ */
133
+ export function installService(host, home, env, options) {
134
+ const file = serviceFile(host);
135
+ const mac = host.platform === "darwin";
136
+ const log = join(home, "logs", "serve.log");
137
+ mkdirSync(join(home, "logs"), { recursive: true, mode: 0o700 });
138
+ // Shell commands the sessions run need your PATH; launchd and systemd start with a bare one.
139
+ const vars = { PATH: env.PATH ?? "/usr/bin:/bin" };
140
+ if (env.YEW_HOME)
141
+ vars.YEW_HOME = home;
142
+ mkdirSync(dirname(file), { recursive: true });
143
+ writeFileSync(file, mac ? launchAgent(host, vars, log) : systemdUnit(host, vars, log), {
144
+ mode: 0o644,
145
+ });
146
+ let code = 0;
147
+ if (mac) {
148
+ if (options.start) {
149
+ // Loading it again picks up a new Node.js or Yew path after an update.
150
+ host.run("launchctl", ["bootout", target(host)]);
151
+ code = host.run("launchctl", ["bootstrap", `gui/${host.uid}`, file]);
152
+ }
153
+ }
154
+ else {
155
+ host.run("systemctl", ["--user", "daemon-reload"]);
156
+ code = host.run("systemctl", ["--user", "enable", ...(options.start ? ["--now"] : []), UNIT]);
157
+ }
158
+ return { code, file, log };
159
+ }
160
+ /**
161
+ * Removes the service file and its registration; returns whether the file was there. With `stop`
162
+ * (what `yew service uninstall` does) the running service is stopped too; without it the Yew that
163
+ * is running keeps running and is only not started at the next login.
164
+ */
165
+ export function uninstallService(host, options) {
166
+ const file = serviceFile(host);
167
+ const mac = host.platform === "darwin";
168
+ const had = existsSync(file);
169
+ if (mac) {
170
+ if (options.stop)
171
+ host.run("launchctl", ["bootout", target(host)]);
172
+ }
173
+ else if (had) {
174
+ host.run("systemctl", ["--user", "disable", ...(options.stop ? ["--now"] : []), UNIT]);
175
+ }
176
+ rmSync(file, { force: true });
177
+ if (!mac && had)
178
+ host.run("systemctl", ["--user", "daemon-reload"]);
179
+ return had;
180
+ }
181
+ export function serviceCommand(host = realServiceHost()) {
182
+ return {
183
+ name: "service",
184
+ summary: "Start Yew when you log in",
185
+ async run(args, io) {
186
+ const { values, positionals } = parseArgs({
187
+ args,
188
+ options: { json: { type: "boolean" }, help: { type: "boolean", short: "h" } },
189
+ allowPositionals: true,
190
+ strict: true,
191
+ });
192
+ if (values.help) {
193
+ io.stdout.write(HELP);
194
+ return EXIT_OK;
195
+ }
196
+ const action = positionals[0];
197
+ if (positionals.length !== 1 || !["install", "uninstall", "status"].includes(action ?? "")) {
198
+ throw new UsageError("yew service needs one of install, uninstall or status");
199
+ }
200
+ const { yewHome } = await import("../server/paths.js");
201
+ const home = yewHome(io.env);
202
+ const file = serviceFile(host);
203
+ const mac = host.platform === "darwin";
204
+ if (action === "status") {
205
+ const state = { installed: serviceLoaded(host), running: serviceRunning(home), file };
206
+ if (values.json)
207
+ io.stdout.write(`${JSON.stringify(state)}\n`);
208
+ else {
209
+ io.stdout.write(`Start at login: ${state.installed ? `on (${file})` : "off"}\nYew service: ${state.running ? "running" : "not running"}\n`);
210
+ }
211
+ return EXIT_OK;
212
+ }
213
+ if (action === "uninstall") {
214
+ const had = uninstallService(host, { stop: true });
215
+ if (values.json)
216
+ io.stdout.write(`${JSON.stringify({ installed: false, file })}\n`);
217
+ else {
218
+ io.stdout.write(had
219
+ ? "Yew no longer starts at login, and was stopped.\n"
220
+ : "Yew was not set to start at login.\n");
221
+ }
222
+ return EXIT_OK;
223
+ }
224
+ if (!serviceLoaded(host) && serviceRunning(home)) {
225
+ io.stderr.write("yew: Yew is already running, started by hand. Stop that 'yew serve' first, then run this again.\n");
226
+ return EXIT_ERROR;
227
+ }
228
+ const { code, log } = installService(host, home, io.env, { start: true });
229
+ if (code !== 0) {
230
+ io.stderr.write(`yew: ${mac ? "launchctl" : "systemctl"} could not start the service (exit ${code ?? "none"}). The file is at ${file}.\n`);
231
+ return EXIT_ERROR;
232
+ }
233
+ if (values.json)
234
+ io.stdout.write(`${JSON.stringify({ installed: true, file, log })}\n`);
235
+ else {
236
+ io.stdout.write(`Yew now starts when you log in, and was started.\nLog: ${log}\nOpen the web interface with 'yew open'.\n`);
237
+ }
238
+ return EXIT_OK;
239
+ },
240
+ };
241
+ }
@@ -0,0 +1,44 @@
1
+ import { conflict } from "../server/errors.js";
2
+ import { appInstalled, appPath, installApp, realAppHost, uninstallApp, } from "./app.js";
3
+ import { installService, realServiceHost, serviceAtLogin, serviceFile, serviceSupported, uninstallService, } from "./service.js";
4
+ /**
5
+ * The settings' two switches, on the functions behind `yew service` and `yew app`. Unlike the
6
+ * commands, the start-at-login switch does not start or stop Yew now: the Yew that serves the
7
+ * settings keeps running as it was started, and only the next login changes.
8
+ */
9
+ export function systemControl(options) {
10
+ const service = options.service ?? realServiceHost();
11
+ const app = options.app ?? realAppHost();
12
+ const canStart = serviceSupported(service);
13
+ const canLaunch = app.platform === "darwin";
14
+ return {
15
+ status: () => ({
16
+ startAtLogin: {
17
+ supported: canStart,
18
+ on: canStart && serviceAtLogin(service),
19
+ file: canStart ? serviceFile(service) : null,
20
+ },
21
+ launcher: {
22
+ supported: canLaunch,
23
+ on: canLaunch && appInstalled(app),
24
+ path: canLaunch ? appPath(app) : null,
25
+ },
26
+ }),
27
+ setStartAtLogin(on) {
28
+ if (!on) {
29
+ uninstallService(service, { stop: false });
30
+ return;
31
+ }
32
+ const { code, file } = installService(service, options.home, options.env, { start: false });
33
+ if (code !== 0) {
34
+ throw conflict(`The system did not accept the service (exit ${code ?? "none"}). The file is at ${file}.`, undefined, "service-failed");
35
+ }
36
+ },
37
+ setLauncher(on) {
38
+ if (on)
39
+ installApp(app, options.home, options.env);
40
+ else
41
+ uninstallApp(app);
42
+ },
43
+ };
44
+ }
@@ -0,0 +1,107 @@
1
+ import { hostname } from "node:os";
2
+ import { readSettings } from "../server/settings.js";
3
+ import { Connector } from "./connector.js";
4
+ import { createPairing, loadIdentity } from "./identity.js";
5
+ import { MAX_PUSH_DATA, pushKey, sealPush } from "./push.js";
6
+ /** The name phones see for this Mac: the host name without `.local`. */
7
+ export const desktopName = () => hostname().replace(/\.local$/, "") || "Mac";
8
+ /**
9
+ * Starts and stops the relay connection to match the settings, which the interface, `manage_yew` and
10
+ * `yew remote` change; `sync` runs every few seconds, so changes made from the command line take hold.
11
+ */
12
+ export class RemoteAccess {
13
+ #store;
14
+ #keys;
15
+ #options;
16
+ #identity = null;
17
+ #connector = null;
18
+ /** Each phone's notification key, by its public key. */
19
+ #pushKeys = new Map();
20
+ constructor(store, keys, options) {
21
+ this.#store = store;
22
+ this.#keys = keys;
23
+ this.#options = options;
24
+ }
25
+ async identity() {
26
+ this.#identity ??= await loadIdentity(this.#keys);
27
+ return this.#identity;
28
+ }
29
+ async sync() {
30
+ const { enabled, relayUrl } = readSettings(this.#store).remote;
31
+ const current = this.#connector;
32
+ if (current && (!enabled || current.relayUrl !== relayUrl)) {
33
+ current.stop();
34
+ this.#connector = null;
35
+ }
36
+ if (!enabled || this.#connector)
37
+ return;
38
+ this.#connector = new Connector({
39
+ store: this.#store,
40
+ identity: await this.identity(),
41
+ relayUrl,
42
+ desktopName: desktopName(),
43
+ version: this.#options.version,
44
+ handle: this.#options.handle,
45
+ onPushResult: (result) => {
46
+ // Apple no longer knows the token (the app was removed, or restored elsewhere): forget it.
47
+ if (result.gone)
48
+ this.#store.dropPushToken(result.token);
49
+ else if (!result.ok)
50
+ this.#options.log?.(`notifications: ${result.reason ?? "not sent"}`);
51
+ },
52
+ ...(this.#options.log ? { log: this.#options.log } : {}),
53
+ ...(this.#options.WebSocketImpl ? { WebSocketImpl: this.#options.WebSocketImpl } : {}),
54
+ });
55
+ this.#connector.start();
56
+ }
57
+ status() {
58
+ const { enabled, relayUrl } = readSettings(this.#store).remote;
59
+ return {
60
+ enabled,
61
+ connected: this.#connector?.connected ?? false,
62
+ relayUrl,
63
+ desktopId: this.#identity?.desktopId ?? null,
64
+ };
65
+ }
66
+ /** A pairing QR code's content, valid five minutes and once. */
67
+ async pairing() {
68
+ const { relayUrl } = readSettings(this.#store).remote;
69
+ return createPairing(this.#store, await this.identity(), {
70
+ relay: relayUrl,
71
+ name: desktopName(),
72
+ });
73
+ }
74
+ /**
75
+ * Sends one notification to every paired phone that takes them, each sealed with that phone's key.
76
+ * Returns how many the relay was asked to deliver.
77
+ */
78
+ push(note, mode, id) {
79
+ const connector = this.#connector;
80
+ const identity = this.#identity;
81
+ if (!connector?.connected || !identity)
82
+ return 0;
83
+ const plaintext = Buffer.from(JSON.stringify(note));
84
+ let sent = 0;
85
+ for (const target of this.#store.pushTargets()) {
86
+ let key = this.#pushKeys.get(target.publicKey);
87
+ if (!key) {
88
+ key = pushKey(identity.noise, Buffer.from(target.publicKey, "base64url"));
89
+ this.#pushKeys.set(target.publicKey, key);
90
+ }
91
+ const data = sealPush(key, plaintext).toString("base64");
92
+ if (data.length > MAX_PUSH_DATA)
93
+ continue;
94
+ if (connector.push({ token: target.token, data, mode, ...(id ? { id } : {}) }))
95
+ sent += 1;
96
+ }
97
+ return sent;
98
+ }
99
+ /** A revoked device loses its open connections at once. */
100
+ disconnect(deviceId) {
101
+ this.#connector?.disconnect(deviceId);
102
+ }
103
+ stop() {
104
+ this.#connector?.stop();
105
+ this.#connector = null;
106
+ }
107
+ }
@@ -0,0 +1,278 @@
1
+ import { deflateRawSync } from "node:zlib";
2
+ import { consumePairing, signChallenge } from "./identity.js";
3
+ import { Opener, Responder, seal } from "./noise.js";
4
+ import { COMPRESS_FROM, prologueFor, } from "./protocol.js";
5
+ const FIRST_RETRY_MS = 1000;
6
+ export class Connector {
7
+ #options;
8
+ #log;
9
+ #channels = new Map();
10
+ #socket = null;
11
+ #stopped = true;
12
+ #retryMs = FIRST_RETRY_MS;
13
+ #timer = null;
14
+ connected = false;
15
+ constructor(options) {
16
+ this.#options = options;
17
+ this.#log = options.log ?? ((line) => process.stderr.write(`${line}\n`));
18
+ }
19
+ get relayUrl() {
20
+ return this.#options.relayUrl;
21
+ }
22
+ start() {
23
+ if (!this.#stopped)
24
+ return;
25
+ this.#stopped = false;
26
+ this.#connect();
27
+ }
28
+ stop() {
29
+ this.#stopped = true;
30
+ if (this.#timer)
31
+ clearTimeout(this.#timer);
32
+ this.#timer = null;
33
+ this.#socket?.close(1000);
34
+ this.#socket = null;
35
+ this.#dropChannels();
36
+ this.connected = false;
37
+ }
38
+ /** Closes the channels of a device that was just revoked. */
39
+ disconnect(deviceId) {
40
+ for (const [number, channel] of this.#channels) {
41
+ if (channel.device?.id === deviceId)
42
+ this.closeChannel(number);
43
+ }
44
+ }
45
+ #connect() {
46
+ const Impl = this.#options.WebSocketImpl ?? WebSocket;
47
+ const socket = new Impl(`${this.#options.relayUrl.replace(/\/$/, "")}/desktop`);
48
+ socket.binaryType = "arraybuffer";
49
+ this.#socket = socket;
50
+ socket.onmessage = (event) => {
51
+ if (typeof event.data === "string")
52
+ this.#control(event.data);
53
+ else
54
+ this.#frame(Buffer.from(event.data));
55
+ };
56
+ socket.onclose = () => {
57
+ if (this.#socket !== socket)
58
+ return;
59
+ this.#socket = null;
60
+ this.connected = false;
61
+ this.#dropChannels();
62
+ if (this.#stopped)
63
+ return;
64
+ // Back off up to the limit; a relay that is down is not asked again every second.
65
+ this.#timer = setTimeout(() => this.#connect(), this.#retryMs);
66
+ this.#retryMs = Math.min(this.#retryMs * 2, this.#options.maxRetryMs ?? 30_000);
67
+ };
68
+ socket.onerror = () => { };
69
+ }
70
+ #control(text) {
71
+ let message;
72
+ try {
73
+ message = JSON.parse(text);
74
+ }
75
+ catch {
76
+ return;
77
+ }
78
+ if (message.type === "challenge" && typeof message.nonce === "string") {
79
+ const { identity } = this.#options;
80
+ this.#socket?.send(JSON.stringify({
81
+ type: "hello",
82
+ key: identity.signingPublic.toString("base64url"),
83
+ sig: signChallenge(identity, message.nonce),
84
+ }));
85
+ }
86
+ else if (message.type === "ready") {
87
+ this.connected = true;
88
+ this.#retryMs = FIRST_RETRY_MS;
89
+ this.#log("remote access: connected to the relay");
90
+ }
91
+ else if (message.type === "open" && typeof message.channel === "number") {
92
+ this.#channels.set(message.channel, new Channel(this, message.channel, this.#options));
93
+ }
94
+ else if (message.type === "close" && typeof message.channel === "number") {
95
+ this.#channels.get(message.channel)?.end();
96
+ this.#channels.delete(message.channel);
97
+ }
98
+ else if (message.type === "pushResult" && typeof message.token === "string") {
99
+ this.#options.onPushResult?.({
100
+ token: message.token,
101
+ ok: message.ok === true,
102
+ gone: message.gone === true,
103
+ ...(typeof message.reason === "string" ? { reason: message.reason } : {}),
104
+ });
105
+ }
106
+ }
107
+ /** Asks the relay to notify a phone; false when the relay is not connected. */
108
+ push(job) {
109
+ if (!this.connected || !this.#socket)
110
+ return false;
111
+ this.#socket.send(JSON.stringify({ type: "push", ...job }));
112
+ return true;
113
+ }
114
+ #frame(frame) {
115
+ if (frame.length < 4)
116
+ return;
117
+ const channel = this.#channels.get(frame.readUInt32BE(0));
118
+ channel?.receive(frame.subarray(4)).catch((error) => {
119
+ this.#log(`remote access: ${error.message}`);
120
+ this.closeChannel(frame.readUInt32BE(0));
121
+ });
122
+ }
123
+ send(channel, payload) {
124
+ const header = Buffer.alloc(4);
125
+ header.writeUInt32BE(channel, 0);
126
+ this.#socket?.send(Buffer.concat([header, payload]));
127
+ }
128
+ closeChannel(channel) {
129
+ this.#channels.get(channel)?.end();
130
+ this.#channels.delete(channel);
131
+ this.#socket?.send(JSON.stringify({ type: "close", channel }));
132
+ }
133
+ #dropChannels() {
134
+ for (const channel of this.#channels.values())
135
+ channel.end();
136
+ this.#channels.clear();
137
+ }
138
+ }
139
+ /** One phone's connection: the handshake, then its requests. */
140
+ class Channel {
141
+ #connector;
142
+ #number;
143
+ #options;
144
+ #responder;
145
+ #session = null;
146
+ #opener = null;
147
+ #requests = new Map();
148
+ #ended = false;
149
+ #handshakeTimer;
150
+ device = null;
151
+ constructor(connector, number, options) {
152
+ this.#connector = connector;
153
+ this.#number = number;
154
+ this.#options = options;
155
+ this.#responder = new Responder({
156
+ static: options.identity.noise,
157
+ prologue: prologueFor(options.identity.desktopId),
158
+ });
159
+ // A connection that does not finish the handshake soon is closed, so someone who only knows
160
+ // this Mac's id cannot hold the places of its phones.
161
+ this.#handshakeTimer = setTimeout(() => {
162
+ if (!this.#session && !this.#ended)
163
+ connector.closeChannel(number);
164
+ }, options.handshakeMs ?? 10_000);
165
+ this.#handshakeTimer.unref();
166
+ }
167
+ async receive(payload) {
168
+ if (this.#ended)
169
+ return;
170
+ if (!this.#session) {
171
+ this.#handshake(payload);
172
+ return;
173
+ }
174
+ const message = this.#opener?.open(payload);
175
+ if (message)
176
+ await this.#message(JSON.parse(message.toString("utf8")));
177
+ }
178
+ #handshake(first) {
179
+ const { store } = this.#options;
180
+ const hello = JSON.parse(this.#responder.readFirst(first).toString("utf8"));
181
+ const key = this.#responder.remoteStatic?.toString("base64url") ?? "";
182
+ let device = store.deviceByKey(key);
183
+ if (!device) {
184
+ // Not paired: only the secret from the QR code, used once, lets it in.
185
+ if (typeof hello.pair !== "string" || !consumePairing(store, hello.pair)) {
186
+ throw new Error("a phone that is not paired tried to connect");
187
+ }
188
+ const name = typeof hello.name === "string" && hello.name.trim() ? hello.name.trim() : "Phone";
189
+ device = store.addDevice(name.slice(0, 60), key);
190
+ }
191
+ store.touchDevice(device.id);
192
+ this.device = device;
193
+ const welcome = {
194
+ desktop: this.#options.desktopName,
195
+ version: this.#options.version,
196
+ device: device.id,
197
+ };
198
+ const { message, session } = this.#responder.writeSecond(Buffer.from(JSON.stringify(welcome)));
199
+ this.#session = session;
200
+ this.#opener = new Opener(session.receive);
201
+ this.#connector.send(this.#number, message);
202
+ }
203
+ async #message(message) {
204
+ if (message.t === "cancel") {
205
+ this.#requests.get(message.id)?.abort();
206
+ return;
207
+ }
208
+ if (message.t !== "req")
209
+ return;
210
+ const device = this.device;
211
+ // A device revoked since it connected gets nothing more.
212
+ if (!device || !this.#options.store.deviceByKey(device.publicKey)) {
213
+ this.#connector.closeChannel(this.#number);
214
+ return;
215
+ }
216
+ if (!message.path.startsWith("/api/")) {
217
+ this.#send({ t: "res", id: message.id, status: 404, type: "text/plain", body: "" });
218
+ return;
219
+ }
220
+ const controller = new AbortController();
221
+ this.#requests.set(message.id, controller);
222
+ try {
223
+ const request = new Request(`http://yew.internal${message.path}`, {
224
+ method: message.method,
225
+ headers: { "Content-Type": "application/json" },
226
+ ...(message.body !== undefined && message.method !== "GET" ? { body: message.body } : {}),
227
+ signal: controller.signal,
228
+ });
229
+ const response = await this.#options.handle(request, device);
230
+ const type = response.headers.get("Content-Type") ?? "";
231
+ if (!type.startsWith("text/event-stream") || !response.body) {
232
+ const body = await response.text();
233
+ const packed = message.z === 1 && body.length >= COMPRESS_FROM;
234
+ this.#send({
235
+ t: "res",
236
+ id: message.id,
237
+ status: response.status,
238
+ type,
239
+ body: packed ? deflateRawSync(body).toString("base64") : body,
240
+ ...(packed ? { z: 1 } : {}),
241
+ });
242
+ return;
243
+ }
244
+ this.#send({ t: "head", id: message.id, status: response.status, type });
245
+ const reader = response.body.getReader();
246
+ controller.signal.addEventListener("abort", () => void reader.cancel());
247
+ const decoder = new TextDecoder();
248
+ while (!this.#ended) {
249
+ const { done, value } = await reader.read();
250
+ if (done)
251
+ break;
252
+ this.#send({ t: "chunk", id: message.id, data: decoder.decode(value, { stream: true }) });
253
+ }
254
+ this.#send({ t: "end", id: message.id });
255
+ }
256
+ catch (error) {
257
+ if (!controller.signal.aborted)
258
+ throw error;
259
+ }
260
+ finally {
261
+ this.#requests.delete(message.id);
262
+ }
263
+ }
264
+ #send(message) {
265
+ if (!this.#session || this.#ended)
266
+ return;
267
+ for (const part of seal(this.#session.send, Buffer.from(JSON.stringify(message)))) {
268
+ this.#connector.send(this.#number, part);
269
+ }
270
+ }
271
+ end() {
272
+ this.#ended = true;
273
+ clearTimeout(this.#handshakeTimer);
274
+ for (const controller of this.#requests.values())
275
+ controller.abort();
276
+ this.#requests.clear();
277
+ }
278
+ }