@dsh-mobile/mobile-remote 3.4.1 → 3.5.0-beta.2

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 (42) hide show
  1. package/README.md +1 -1
  2. package/docs/PRIVACY-POLICY.en.md +10 -2
  3. package/docs/PRIVACY-POLICY.md +10 -2
  4. package/docs/TERMS-OF-SERVICE.en.md +3 -2
  5. package/docs/TERMS-OF-SERVICE.md +3 -2
  6. package/lib/backup.js +30 -0
  7. package/lib/config.js +10 -0
  8. package/lib/host-plugins.js +290 -0
  9. package/lib/host-schedule.js +273 -0
  10. package/lib/host-team.js +89 -0
  11. package/lib/index.js +208 -3292
  12. package/lib/live-activity.js +351 -0
  13. package/lib/memory/context.js +17 -3
  14. package/lib/memory/decay.js +68 -4
  15. package/lib/memory/promises.js +116 -0
  16. package/lib/memory/routes.js +113 -1
  17. package/lib/memory/store.js +212 -13
  18. package/lib/memory/turn-hook.js +109 -0
  19. package/lib/phone-actions.js +17 -5
  20. package/lib/phone-announce.js +6 -5
  21. package/lib/phone-push.js +310 -0
  22. package/lib/protocol.js +16 -0
  23. package/lib/relay/connector.js +13 -1
  24. package/lib/routes/agents.js +405 -0
  25. package/lib/routes/app-state.js +179 -0
  26. package/lib/routes/backup.js +144 -0
  27. package/lib/routes/diagnostics.js +227 -0
  28. package/lib/routes/files.js +326 -0
  29. package/lib/routes/git.js +53 -0
  30. package/lib/routes/history.js +313 -0
  31. package/lib/routes/host-services.js +51 -0
  32. package/lib/routes/models.js +462 -0
  33. package/lib/routes/notifications.js +183 -0
  34. package/lib/routes/pairing.js +170 -0
  35. package/lib/routes/route-groups.js +20 -0
  36. package/lib/routes/send.js +341 -0
  37. package/lib/routes/sessions.js +462 -0
  38. package/lib/routes/toolbox.js +14 -0
  39. package/lib/routes/usage.js +211 -0
  40. package/lib/timeline.js +5 -1
  41. package/lib/toolbox.js +355 -0
  42. package/package.json +1 -1
@@ -13,10 +13,10 @@ export const ANNOUNCE_HEADER = "x-dsh-phone-actions";
13
13
  export const GRACE_MS = 60_000;
14
14
 
15
15
 
16
- export const isAnnounced = (req) => {
17
- const header = req?.headers?.[ANNOUNCE_HEADER];
16
+ export const isAnnounced = (req, name = ANNOUNCE_HEADER) => {
17
+ const header = req?.headers?.[name];
18
18
  if ((Array.isArray(header) ? header[0] : header) === "1") return true;
19
- try { return new URL(String(req?.url ?? ""), "http://x").searchParams.get(ANNOUNCE_HEADER) === "1"; } catch { return false; }
19
+ try { return new URL(String(req?.url ?? ""), "http://x").searchParams.get(name) === "1"; } catch { return false; }
20
20
  };
21
21
 
22
22
 
@@ -24,7 +24,8 @@ export const isAnnounced = (req) => {
24
24
 
25
25
 
26
26
 
27
- export const createCapableTracker = ({ onActive, onIdle, graceMs = GRACE_MS, setTimer = setTimeout, clearTimer = clearTimeout } = {}) => {
27
+
28
+ export const createCapableTracker = ({ onActive, onIdle, header = ANNOUNCE_HEADER, graceMs = GRACE_MS, setTimer = setTimeout, clearTimer = clearTimeout } = {}) => {
28
29
  const streams = new Set();
29
30
  let timer = null;
30
31
  let disposed = false;
@@ -39,7 +40,7 @@ export const createCapableTracker = ({ onActive, onIdle, graceMs = GRACE_MS, set
39
40
  count: () => streams.size,
40
41
 
41
42
  attach(res, req) {
42
- if (disposed || streams.has(res) || !isAnnounced(req)) return false;
43
+ if (disposed || streams.has(res) || !isAnnounced(req, header)) return false;
43
44
  const wasActive = active();
44
45
  if (timer !== null) { clearTimer(timer); timer = null; }
45
46
  streams.add(res);
@@ -0,0 +1,310 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
23
+ import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
24
+ import { join } from "node:path";
25
+ import { readBody, sendError, sendJson } from "./http-util.js";
26
+
27
+ export const PUSH_AAD = "dsh-push-v1";
28
+ export const ANSWER_AAD = "dsh-push-answer-v1|";
29
+ export const MAX_REGISTRATIONS = 8;
30
+
31
+ export const ANSWER_MAX_AGE_MS = 10 * 60_000;
32
+
33
+ export const MAX_PLAINTEXT_BYTES = 2048;
34
+ const FILE = "push-registrations.json";
35
+
36
+ const KEY_ID_RE = /^[0-9a-f]{16}$/;
37
+ const APNS_TOKEN_RE = /^[0-9a-f]{64,200}$/;
38
+ const FCM_TOKEN_RE = /^[A-Za-z0-9_:-]{20,400}$/;
39
+ const KINDS = new Set(["needs-you", "done", "failed", "phone-action", "reminder"]);
40
+
41
+ export const PHONE_PUSH_KINDS = Object.freeze({ "needs-answer": "needs-you", completed: "done", failed: "failed", reminder: "reminder" });
42
+
43
+
44
+ const clean = (v, max) => (typeof v === "string" ? v.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, " ").trim().slice(0, max) : "");
45
+
46
+
47
+ const line = (v, max) => clean(typeof v === "string" ? v.replace(/[\u0000-\u001f\u007f]/g, " ") : v, max);
48
+ const b64u = {
49
+ enc: (buf) => Buffer.from(buf).toString("base64url"),
50
+ dec: (s) => Buffer.from(s, "base64url"),
51
+ };
52
+
53
+
54
+ export function seal(key, keyIdHex, plaintext, aad = PUSH_AAD, nonce = randomBytes(12)) {
55
+ const cipher = createCipheriv("aes-256-gcm", key, nonce);
56
+ cipher.setAAD(Buffer.from(aad, "utf8"));
57
+ const ct = Buffer.concat([cipher.update(typeof plaintext === "string" ? Buffer.from(plaintext, "utf8") : plaintext), cipher.final()]);
58
+ return b64u.enc(Buffer.concat([Buffer.from(keyIdHex, "hex"), nonce, ct, cipher.getAuthTag()]));
59
+ }
60
+
61
+
62
+ export function boxKeyId(box) {
63
+ if (typeof box !== "string" || !/^[A-Za-z0-9_-]{48,4000}$/.test(box)) return null;
64
+ const raw = b64u.dec(box);
65
+ return raw.length >= 36 ? raw.subarray(0, 8).toString("hex") : null;
66
+ }
67
+
68
+
69
+ export function open(key, box, aad = PUSH_AAD) {
70
+ try {
71
+ const raw = b64u.dec(box);
72
+ if (raw.length < 36) return null;
73
+ const decipher = createDecipheriv("aes-256-gcm", key, raw.subarray(8, 20));
74
+ decipher.setAAD(Buffer.from(aad, "utf8"));
75
+ decipher.setAuthTag(raw.subarray(raw.length - 16));
76
+ return Buffer.concat([decipher.update(raw.subarray(20, raw.length - 16)), decipher.final()]);
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
81
+
82
+
83
+ export function checkRegistration(body) {
84
+ if (!body || typeof body !== "object" || Array.isArray(body)) return { ok: false, error: "bad-request" };
85
+ if (typeof body.keyId !== "string" || !KEY_ID_RE.test(body.keyId)) return { ok: false, error: "invalid-key-id" };
86
+ if (body.token === null) return { ok: true, forget: body.keyId };
87
+ const platform = body.platform;
88
+ if (platform !== "apns" && platform !== "fcm") return { ok: false, error: "invalid-platform" };
89
+ const re = platform === "apns" ? APNS_TOKEN_RE : FCM_TOKEN_RE;
90
+ if (typeof body.token !== "string" || !re.test(body.token)) return { ok: false, error: "invalid-token" };
91
+ let key;
92
+ try {
93
+ key = typeof body.key === "string" ? Buffer.from(body.key, "base64") : null;
94
+ } catch {
95
+ key = null;
96
+ }
97
+ if (!key || key.length !== 32) return { ok: false, error: "invalid-key" };
98
+ const environment = platform === "apns" ? (body.environment === "sandbox" ? "sandbox" : "production") : null;
99
+ return { ok: true, reg: { keyId: body.keyId, key: key.toString("base64"), platform, token: body.token, environment } };
100
+ }
101
+
102
+
103
+
104
+
105
+
106
+ export function buildPlaintext({ kind, title, body, pc, sid, ask, reply, at }) {
107
+ const msg = { v: 1, kind: KINDS.has(kind) ? kind : "needs-you", title: line(title, 120), body: clean(body, 600), pc: line(pc, 60), at };
108
+ const s = clean(sid, 120);
109
+ if (s) msg.sid = s;
110
+ if (ask && (ask.type === "approval" || ask.type === "phone-action") && typeof ask.id === "string" && ask.id.length <= 200) {
111
+ msg.ask = { type: ask.type, id: ask.id };
112
+ }
113
+ if (reply && /^https:\/\/[^/\s]+$/.test(reply.url ?? "") && /^[0-9a-f]{32}$/.test(reply.room ?? "")) msg.reply = { url: reply.url, room: reply.room };
114
+ let text = JSON.stringify(msg);
115
+ while (Buffer.byteLength(text) > MAX_PLAINTEXT_BYTES && (msg.body.length > 0 || msg.title.length > 0)) {
116
+ if (msg.body.length > 0) msg.body = msg.body.slice(0, Math.floor(msg.body.length / 2));
117
+ else msg.title = msg.title.slice(0, Math.floor(msg.title.length / 2));
118
+ text = JSON.stringify(msg);
119
+ }
120
+ return text;
121
+ }
122
+
123
+
124
+ export function workerEndpoint(config) {
125
+ const raw = config?.phonePush?.endpoint || config?.liveActivityPush?.endpoint || "";
126
+ return typeof raw === "string" && /^https:\/\/[^/\s]+/.test(raw) ? raw.replace(/\/+$/, "") : null;
127
+ }
128
+
129
+
130
+
131
+
132
+
133
+
134
+
135
+
136
+ export function createPhonePush({ dir, endpoint, pcName = () => "", reply = () => null, fetchImpl = globalThis.fetch, now = Date.now, logger = {}, timeoutMs = 10_000 } = {}) {
137
+
138
+ const regs = new Map();
139
+ const seenAnswers = new Set();
140
+ const file = dir ? join(dir, FILE) : null;
141
+ const log = (m) => logger.info?.(`mobile-remote: [push] ${m}`);
142
+
143
+ const load = () => {
144
+ if (!file) return;
145
+ try {
146
+ const data = JSON.parse(readFileSync(file, "utf8"));
147
+ for (const r of Array.isArray(data?.regs) ? data.regs : []) {
148
+ const c = checkRegistration(r);
149
+ if (c.ok && c.reg) regs.set(c.reg.keyId, { ...c.reg, at: Number(r.at) || 0 });
150
+ }
151
+ } catch {
152
+
153
+ }
154
+ };
155
+ const save = () => {
156
+ if (!file) return;
157
+ try {
158
+ mkdirSync(dir, { recursive: true });
159
+ const tmp = `${file}.${process.pid}.tmp`;
160
+ writeFileSync(tmp, JSON.stringify({ v: 1, regs: [...regs.values()] }), { mode: 0o600 });
161
+ renameSync(tmp, file);
162
+ try { chmodSync(file, 0o600); } catch { }
163
+ } catch (err) {
164
+ log(`could not save registrations (${err?.code ?? "error"})`);
165
+ }
166
+ };
167
+ load();
168
+
169
+ const register = (reg) => {
170
+
171
+ for (const [id, r] of regs) if (r.token === reg.token && id !== reg.keyId) regs.delete(id);
172
+ regs.delete(reg.keyId);
173
+ if (regs.size >= MAX_REGISTRATIONS) regs.delete([...regs.values()].sort((a, b) => a.at - b.at)[0].keyId);
174
+ regs.set(reg.keyId, { ...reg, at: now() });
175
+ save();
176
+ };
177
+
178
+ const sendOne = async (reg, text) => {
179
+ const key = Buffer.from(reg.key, "base64");
180
+ const body = { platform: reg.platform, token: reg.token, e: seal(key, reg.keyId, text) };
181
+ if (reg.environment) body.environment = reg.environment;
182
+ const res = await fetchImpl(`${endpoint}/api/push/notify`, {
183
+ method: "POST",
184
+ headers: { "content-type": "application/json", "user-agent": "dsh-mobile-remote" },
185
+ body: JSON.stringify(body),
186
+ signal: AbortSignal.timeout(timeoutMs),
187
+ });
188
+ return res.status;
189
+ };
190
+
191
+ return {
192
+
193
+ get active() {
194
+ return endpoint !== null && regs.size > 0;
195
+ },
196
+ get size() {
197
+ return regs.size;
198
+ },
199
+
200
+ registration: (keyId) => regs.get(keyId),
201
+
202
+
203
+
204
+
205
+
206
+
207
+ openAnswer(box, room) {
208
+ const keyId = boxKeyId(box);
209
+ const reg = keyId ? regs.get(keyId) : undefined;
210
+ if (!reg || typeof room !== "string") return null;
211
+ const raw = open(Buffer.from(reg.key, "base64"), box, ANSWER_AAD + room);
212
+ if (!raw) return null;
213
+ let a;
214
+ try {
215
+ a = JSON.parse(raw.toString("utf8"));
216
+ } catch {
217
+ return null;
218
+ }
219
+ const ok = a?.v === 1 && typeof a.id === "string" && a.id.length <= 200 && Number.isFinite(a.at)
220
+ && ((a.type === "approval" && (a.decision === "approve" || a.decision === "decline")) || (a.type === "phone-action" && a.decision === "cancel"));
221
+ if (!ok || a.at < now() - ANSWER_MAX_AGE_MS || a.at > now() + 120_000) return null;
222
+ const seenKey = `${keyId}:${a.type}:${a.id}`;
223
+ if (seenAnswers.has(seenKey)) return null;
224
+ seenAnswers.add(seenKey);
225
+ if (seenAnswers.size > 256) seenAnswers.delete(seenAnswers.values().next().value);
226
+ return { type: a.type, id: a.id, decision: a.decision };
227
+ },
228
+
229
+
230
+
231
+
232
+
233
+ async notify(n) {
234
+ if (endpoint === null || regs.size === 0) return 0;
235
+ const text = buildPlaintext({ ...n, pc: pcName(), reply: n.ask ? reply() : null, at: now() });
236
+ let delivered = 0;
237
+ let dropped = false;
238
+ await Promise.all([...regs.values()].map(async (reg) => {
239
+ try {
240
+ const status = await sendOne(reg, text);
241
+ if (status === 200) delivered++;
242
+ else if (status === 410) {
243
+ regs.delete(reg.keyId);
244
+ dropped = true;
245
+ } else log(`${reg.platform} push refused (${status})`);
246
+ } catch (err) {
247
+ log(`${reg.platform} push failed (${err?.name ?? "error"})`);
248
+ }
249
+ }));
250
+ if (dropped) save();
251
+ return delivered;
252
+ },
253
+
254
+
255
+ async handle(req, res, method) {
256
+ if (method !== "POST") return sendError(res, 405, "method-not-allowed"), true;
257
+ let body;
258
+ try {
259
+ body = JSON.parse(await readBody(req, 8 * 1024));
260
+ } catch (err) {
261
+ return sendError(res, err?.status === 413 ? 413 : 400, err?.status === 413 ? "payload-too-large" : "invalid-json"), true;
262
+ }
263
+ const c = checkRegistration(body);
264
+ if (!c.ok) return sendError(res, 400, c.error), true;
265
+ if (c.forget) {
266
+ if (regs.delete(c.forget)) save();
267
+ } else register(c.reg);
268
+ return sendJson(res, 200, { ok: true, configured: endpoint !== null, actions: reply() !== null }), true;
269
+ },
270
+ };
271
+ }
272
+
273
+
274
+
275
+
276
+
277
+ export function replyTarget(relay) {
278
+ if (!relay?.remote || !/^[0-9a-f]{32}$/.test(relay.identity?.roomId ?? "")) return null;
279
+ const m = /^wss:\/\/([^/\s?#]+)/.exec(relay.urls?.[0] ?? "");
280
+ return m ? { url: `https://${m[1]}`, room: relay.identity.roomId } : null;
281
+ }
282
+
283
+
284
+ export function phoneActionText(frame) {
285
+ const a = frame?.args ?? {};
286
+ const icon = { add_reminder: "⏰", add_event: "📅", set_alarm: "⏰", set_timer: "⏱", open_link: "🔗" }[frame?.action] ?? "📱";
287
+ const what =
288
+ frame?.action === "add_reminder" ? `${a.title ?? ""} · ${a.at ?? ""}`
289
+ : frame?.action === "add_event" ? `${a.title ?? ""} · ${a.start ?? ""}`
290
+ : frame?.action === "set_alarm" ? `${a.time ?? ""}${a.label ? ` · ${a.label}` : ""}`
291
+ : frame?.action === "set_timer" ? `${Math.round((a.seconds ?? 0) / 60)} min${a.label ? ` · ${a.label}` : ""}`
292
+ : frame?.action === "open_link" ? String(a.url ?? "")
293
+ : "";
294
+ const label = { add_reminder: "Add reminder", add_event: "Add event", set_alarm: "Set alarm", set_timer: "Set timer", open_link: "Open link" }[frame?.action] ?? "Phone action";
295
+ return { title: `${icon} ${label}`, body: `${what}?` };
296
+ }
297
+
298
+
299
+
300
+
301
+
302
+ export function attachPushAnswers({ connector, phonePush, room, approve, cancelPhoneAction, logger = {} }) {
303
+ if (typeof connector?.onAnswer !== "function") return () => {};
304
+ return connector.onAnswer((box) => {
305
+ const a = phonePush.openAnswer(box, room());
306
+ if (!a) return void logger.info?.("mobile-remote: [push] lock-screen answer dropped (not ours, old or replayed)");
307
+ const done = a.type === "approval" ? approve(a.id, a.decision === "approve" ? "allowed-once" : "rejected") : cancelPhoneAction(a.id);
308
+ logger.info?.(`mobile-remote: [push] lock-screen ${a.type} ${a.decision} → ${done ? "applied" : "no longer pending"}`);
309
+ });
310
+ }
package/lib/protocol.js CHANGED
@@ -36,6 +36,22 @@ export const FEATURES = Object.freeze([
36
36
 
37
37
 
38
38
  "standby",
39
+
40
+
41
+ "schedules",
42
+
43
+
44
+ "agent-team",
45
+
46
+
47
+ "host-plugins",
48
+
49
+
50
+
51
+ "toolbox-install",
52
+
53
+
54
+ "push",
39
55
  ]);
40
56
 
41
57
 
@@ -47,7 +47,8 @@ const fromHex = (h) => Uint8Array.from(h.match(/../g) ?? [], (x) => parseInt(x,
47
47
 
48
48
  export const AUTH_CONTEXT = "dsh-relay-host-v1";
49
49
 
50
- export const HOST_CAPS = Object.freeze(["signal"]);
50
+
51
+ export const HOST_CAPS = Object.freeze(["signal", "push"]);
51
52
 
52
53
  export class RelayConnector {
53
54
 
@@ -71,6 +72,13 @@ export class RelayConnector {
71
72
  this.unsubscribe = devices.onRevoke((id) => this.dropDevice(id));
72
73
 
73
74
  this.signalHandlers = new Set();
75
+
76
+ this.answerHandlers = new Set();
77
+ }
78
+
79
+ onAnswer(handler) {
80
+ this.answerHandlers.add(handler);
81
+ return () => this.answerHandlers.delete(handler);
74
82
  }
75
83
  static TIMING = Object.freeze({ handshakeMs: 15_000, pingMs: 20_000, pongMs: 10_000, firstFrameMs: 15_000, backoffMinMs: 1_000, backoffMaxMs: 30_000, maxSessionsPerLink: 16, kickAckMs: 2_000, maxDirect: 16, maxDirectPerIp: 4, directHelloMs: 3_000, directOpenMs: 5_000 });
76
84
 
@@ -280,6 +288,10 @@ class RelayLink {
280
288
  this.pendingKicks.delete(msg.c);
281
289
  if (this.closing !== null && this.pendingKicks.size === 0) this.#finishShutdown();
282
290
  return;
291
+ case "answer":
292
+
293
+ if (typeof msg.d === "string" && msg.d.length <= 1400) for (const h of this.o.answerHandlers) try { h(msg.d); } catch { }
294
+ return;
283
295
  case "pong":
284
296
  case "error":
285
297
  return;