@tenonai/yew 0.0.0-stage → 1.3.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 +273 -0
  2. package/LICENSE +21 -0
  3. package/README.md +64 -2
  4. package/THIRD-PARTY-NOTICES.md +122 -0
  5. package/bin/yew.js +9 -0
  6. package/dist/cli/app.js +211 -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 +58 -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 +127 -0
  16. package/dist/cli/serve.js +301 -0
  17. package/dist/cli/service.js +268 -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 +120 -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 +144 -0
  36. package/dist/server/db/database.js +49 -0
  37. package/dist/server/db/migrations.js +343 -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 +465 -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 +70 -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 +180 -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 +43 -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 +77 -0
  82. package/dist/server/skills.js +263 -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-BtK_SzpF.css +1 -0
  115. package/web/dist/assets/index-C0rnUFI-.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,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
+ }
@@ -0,0 +1,71 @@
1
+ import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, sign, timingSafeEqual, } from "node:crypto";
2
+ import { publicKeyOf } from "./noise.js";
3
+ import { CHALLENGE_PREFIX, desktopIdOf, pairingLink } from "./protocol.js";
4
+ const ED25519_PKCS8 = Buffer.from("302e020100300506032b657004220420", "hex");
5
+ const ED25519_SPKI_LENGTH = 12;
6
+ export async function loadIdentity(keys) {
7
+ let noise = await keys.get("noise");
8
+ if (!noise) {
9
+ const { privateKey } = generateKeyPairSync("x25519");
10
+ noise = privateKey.export({ format: "der", type: "pkcs8" }).subarray(16).toString("base64url");
11
+ await keys.set("noise", noise);
12
+ }
13
+ let signingRaw = await keys.get("signing");
14
+ if (!signingRaw) {
15
+ const { privateKey } = generateKeyPairSync("ed25519");
16
+ signingRaw = privateKey
17
+ .export({ format: "der", type: "pkcs8" })
18
+ .subarray(ED25519_PKCS8.length)
19
+ .toString("base64url");
20
+ await keys.set("signing", signingRaw);
21
+ }
22
+ const noisePrivate = Buffer.from(noise, "base64url");
23
+ const signing = createPrivateKey({
24
+ key: Buffer.concat([ED25519_PKCS8, Buffer.from(signingRaw, "base64url")]),
25
+ format: "der",
26
+ type: "pkcs8",
27
+ });
28
+ const signingPublic = createPublicKey(signing)
29
+ .export({ format: "der", type: "spki" })
30
+ .subarray(ED25519_SPKI_LENGTH);
31
+ return {
32
+ noise: { privateKey: noisePrivate, publicKey: publicKeyOf(noisePrivate) },
33
+ signing,
34
+ signingPublic,
35
+ desktopId: desktopIdOf(signingPublic),
36
+ };
37
+ }
38
+ export function signChallenge(identity, nonce) {
39
+ return sign(null, Buffer.from(CHALLENGE_PREFIX + nonce), identity.signing).toString("base64url");
40
+ }
41
+ const PAIRING_MS = 5 * 60 * 1000;
42
+ const sha256 = (value) => createHash("sha256").update(value).digest();
43
+ /**
44
+ * A new pairing: the QR code's content, valid five minutes and once. Only the secret's hash is kept,
45
+ * in the database, so `yew remote pair` and the running service share it.
46
+ */
47
+ export function createPairing(store, identity, options) {
48
+ const secret = randomBytes(18).toString("base64url");
49
+ const expiresAt = Date.now() + PAIRING_MS;
50
+ store.setSetting("pairing", { hash: sha256(secret).toString("hex"), expiresAt });
51
+ return {
52
+ link: pairingLink({
53
+ relay: options.relay,
54
+ desktop: identity.desktopId,
55
+ key: identity.noise.publicKey.toString("base64url"),
56
+ secret,
57
+ name: options.name,
58
+ }),
59
+ expiresAt,
60
+ };
61
+ }
62
+ /** Checks a phone's pairing secret and uses it up; a wrong one also ends the pairing. */
63
+ export function consumePairing(store, secret) {
64
+ const pending = store.getSetting("pairing", null);
65
+ store.setSetting("pairing", null);
66
+ if (!pending || pending.expiresAt < Date.now())
67
+ return false;
68
+ const expected = Buffer.from(pending.hash, "hex");
69
+ const given = sha256(secret);
70
+ return expected.length === given.length && timingSafeEqual(expected, given);
71
+ }