@dsh-mobile/mobile-remote 3.5.0-beta.1 → 3.5.0-beta.3
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.
- package/README.md +1 -1
- package/cordis.patch.yml +3 -1
- package/docs/PRIVACY-POLICY.en.md +10 -5
- package/docs/PRIVACY-POLICY.md +10 -5
- package/lib/client.js +318 -266
- package/lib/config.js +7 -1
- package/lib/file-digest.js +49 -0
- package/lib/host-schedule.js +67 -0
- package/lib/host-session-search.js +149 -0
- package/lib/index.js +15 -14
- package/lib/phone-actions.js +17 -5
- package/lib/phone-push.js +310 -0
- package/lib/protocol.js +12 -0
- package/lib/relay/connector.js +30 -5
- package/lib/relay/p2p.js +24 -5
- package/lib/relay/phone.js +2 -2
- package/lib/relay/signal.js +25 -0
- package/lib/routes/app-state.js +2 -1
- package/lib/routes/files.js +4 -0
- package/lib/routes/host-services.js +4 -0
- package/package.json +1 -1
|
@@ -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
|
@@ -38,6 +38,11 @@ export const FEATURES = Object.freeze([
|
|
|
38
38
|
"standby",
|
|
39
39
|
|
|
40
40
|
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
"bulk",
|
|
44
|
+
|
|
45
|
+
|
|
41
46
|
"schedules",
|
|
42
47
|
|
|
43
48
|
|
|
@@ -48,7 +53,14 @@ export const FEATURES = Object.freeze([
|
|
|
48
53
|
|
|
49
54
|
|
|
50
55
|
|
|
56
|
+
"session-search",
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
|
|
51
60
|
"toolbox-install",
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
"push",
|
|
52
64
|
]);
|
|
53
65
|
|
|
54
66
|
|
package/lib/relay/connector.js
CHANGED
|
@@ -28,6 +28,12 @@
|
|
|
28
28
|
|
|
29
29
|
|
|
30
30
|
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
31
37
|
|
|
32
38
|
|
|
33
39
|
|
|
@@ -47,7 +53,8 @@ const fromHex = (h) => Uint8Array.from(h.match(/../g) ?? [], (x) => parseInt(x,
|
|
|
47
53
|
|
|
48
54
|
export const AUTH_CONTEXT = "dsh-relay-host-v1";
|
|
49
55
|
|
|
50
|
-
|
|
56
|
+
|
|
57
|
+
export const HOST_CAPS = Object.freeze(["signal", "push"]);
|
|
51
58
|
|
|
52
59
|
export class RelayConnector {
|
|
53
60
|
|
|
@@ -71,6 +78,13 @@ export class RelayConnector {
|
|
|
71
78
|
this.unsubscribe = devices.onRevoke((id) => this.dropDevice(id));
|
|
72
79
|
|
|
73
80
|
this.signalHandlers = new Set();
|
|
81
|
+
|
|
82
|
+
this.answerHandlers = new Set();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
onAnswer(handler) {
|
|
86
|
+
this.answerHandlers.add(handler);
|
|
87
|
+
return () => this.answerHandlers.delete(handler);
|
|
74
88
|
}
|
|
75
89
|
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
90
|
|
|
@@ -110,7 +124,10 @@ export class RelayConnector {
|
|
|
110
124
|
return [...this.links, ...this.direct];
|
|
111
125
|
}
|
|
112
126
|
status() {
|
|
113
|
-
return this.links.map((l) =>
|
|
127
|
+
return this.links.map((l) => {
|
|
128
|
+
const all = [...l.sessions.values()];
|
|
129
|
+
return { url: l.url, state: l.state, since: l.since, lastError: l.lastError, phones: all.filter((s) => !s.standby && !s.bulk).length, standby: all.filter((s) => s.standby).length, bulk: all.filter((s) => s.bulk).length };
|
|
130
|
+
});
|
|
114
131
|
}
|
|
115
132
|
|
|
116
133
|
|
|
@@ -280,6 +297,10 @@ class RelayLink {
|
|
|
280
297
|
this.pendingKicks.delete(msg.c);
|
|
281
298
|
if (this.closing !== null && this.pendingKicks.size === 0) this.#finishShutdown();
|
|
282
299
|
return;
|
|
300
|
+
case "answer":
|
|
301
|
+
|
|
302
|
+
if (typeof msg.d === "string" && msg.d.length <= 1400) for (const h of this.o.answerHandlers) try { h(msg.d); } catch { }
|
|
303
|
+
return;
|
|
283
304
|
case "pong":
|
|
284
305
|
case "error":
|
|
285
306
|
return;
|
|
@@ -400,6 +421,8 @@ class GuestSession {
|
|
|
400
421
|
|
|
401
422
|
this.standby = false;
|
|
402
423
|
|
|
424
|
+
this.bulk = false;
|
|
425
|
+
|
|
403
426
|
this.framesOut = 0;
|
|
404
427
|
this.timer = link.after(link.o.timing.firstFrameMs, () => {
|
|
405
428
|
if (this.state !== "open") this.kick("handshake timeout");
|
|
@@ -447,8 +470,9 @@ class GuestSession {
|
|
|
447
470
|
}
|
|
448
471
|
this.signal = this.relaySignal || info.mode === "signal";
|
|
449
472
|
this.standby = !this.signal && info.mode === "standby";
|
|
473
|
+
this.bulk = !this.signal && info.mode === "bulk";
|
|
450
474
|
|
|
451
|
-
const result = devices.authorize(rs, this.signal || this.standby ? { ...info, otp: undefined } : info);
|
|
475
|
+
const result = devices.authorize(rs, this.signal || this.standby || this.bulk ? { ...info, otp: undefined } : info);
|
|
452
476
|
if (!result) return this.kick("unauthorized device");
|
|
453
477
|
|
|
454
478
|
if (result.refused === "full") return this.kick("设备已满:已配对的手机到了上限,配对码未作废", "full");
|
|
@@ -471,7 +495,7 @@ class GuestSession {
|
|
|
471
495
|
this.framesOut++;
|
|
472
496
|
this.link.control({ t: "verified", c: this.connId });
|
|
473
497
|
this.state = "await-first";
|
|
474
|
-
this.link.o.log(`relay: 设备「${this.device.name}」${this.signal ? "打开信令连接" : this.standby ? "打开待命连接" : result.newlyPaired ? "完成配对" : "已连接"}`);
|
|
498
|
+
this.link.o.log(`relay: 设备「${this.device.name}」${this.signal ? "打开信令连接" : this.standby ? "打开待命连接" : this.bulk ? "打开大文件连接" : result.newlyPaired ? "完成配对" : "已连接"}`);
|
|
475
499
|
}
|
|
476
500
|
#sendPlain(frame) {
|
|
477
501
|
if (this.state === "closed") return;
|
|
@@ -523,11 +547,12 @@ class GuestSession {
|
|
|
523
547
|
const id = this.device?.id;
|
|
524
548
|
if (!id) return;
|
|
525
549
|
|
|
550
|
+
|
|
526
551
|
const standby = this.standby;
|
|
527
552
|
for (const link of this.link.o.allLinks()) {
|
|
528
553
|
for (const other of [...link.sessions.values()]) {
|
|
529
554
|
|
|
530
|
-
if (other !== this && other.device?.id === id && other.signal === this.signal && other.standby === standby) other.kick("replaced by a newer connection from the same device", "replaced");
|
|
555
|
+
if (other !== this && other.device?.id === id && other.signal === this.signal && other.standby === standby && other.bulk === this.bulk) other.kick("replaced by a newer connection from the same device", "replaced");
|
|
531
556
|
}
|
|
532
557
|
}
|
|
533
558
|
}
|
package/lib/relay/p2p.js
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
|
|
18
18
|
|
|
19
19
|
|
|
20
|
+
|
|
20
21
|
|
|
21
22
|
|
|
22
23
|
import { registerFeature } from "../protocol.js";
|
|
@@ -30,6 +31,22 @@ export const P2P_TIMING = Object.freeze({ openMs: 15_000, maxPeers: 4, stunGathe
|
|
|
30
31
|
const loadWerift = () => import("werift");
|
|
31
32
|
|
|
32
33
|
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
export function turnTlsServername(iceServers) {
|
|
40
|
+
for (const s of iceServers) {
|
|
41
|
+
for (const u of typeof s?.urls === "string" ? [s.urls] : (s?.urls ?? [])) {
|
|
42
|
+
const m = /^turns:([^:?/\[\]]+)/i.exec(u);
|
|
43
|
+
if (m && !/^[\d.]+$/.test(m[1])) return m[1].toLowerCase();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
33
50
|
export class ChannelSocket {
|
|
34
51
|
constructor(channel, { onClose } = {}) {
|
|
35
52
|
this.channel = channel;
|
|
@@ -106,9 +123,11 @@ class Attempt {
|
|
|
106
123
|
|
|
107
124
|
}
|
|
108
125
|
}
|
|
109
|
-
async offer(sdp, werift) {
|
|
126
|
+
async offer(sdp, werift, extraIce = []) {
|
|
110
127
|
const { RTCPeerConnection } = werift;
|
|
111
|
-
const
|
|
128
|
+
const iceServers = [...this.host.iceServers, ...extraIce];
|
|
129
|
+
const servername = turnTlsServername(iceServers);
|
|
130
|
+
const pc = (this.pc = new RTCPeerConnection({ iceServers, stunGatherTimeout: this.host.timing.stunGatherSec, iceUseDefaultStunServer: false, ...(servername ? { turnTlsOptions: { servername } } : {}) }));
|
|
112
131
|
pc.onIceCandidate.subscribe((c) => this.#local(c));
|
|
113
132
|
pc.connectionStateChange.subscribe((s) => {
|
|
114
133
|
if (s === "failed" || s === "closed") this.dispose(`connection ${s}`);
|
|
@@ -219,13 +238,13 @@ export class P2pHost {
|
|
|
219
238
|
}
|
|
220
239
|
if (e.type !== "message") return;
|
|
221
240
|
const { msg, peer, deviceId } = e;
|
|
222
|
-
if (msg.k === "offer") return void this.#offer(deviceId, peer, msg.sdp);
|
|
241
|
+
if (msg.k === "offer") return void this.#offer(deviceId, peer, msg.sdp, msg.ice);
|
|
223
242
|
const a = this.attempts.get(deviceId);
|
|
224
243
|
if (!a) return;
|
|
225
244
|
if (msg.k === "ice") a.run(() => a.remoteCandidate(msg.cand));
|
|
226
245
|
else if (msg.k === "bye" && !a.opened) a.dispose("bye");
|
|
227
246
|
}
|
|
228
|
-
async #offer(deviceId, peer, sdp) {
|
|
247
|
+
async #offer(deviceId, peer, sdp, ice = []) {
|
|
229
248
|
this.attempts.get(deviceId)?.dispose("replaced by a new offer");
|
|
230
249
|
if (this.attempts.size >= this.timing.maxPeers) return void peer.send({ k: "bye" });
|
|
231
250
|
const a = new Attempt(this, { ...peer, deviceId });
|
|
@@ -234,6 +253,6 @@ export class P2pHost {
|
|
|
234
253
|
a.bye();
|
|
235
254
|
return a.dispose("werift unavailable");
|
|
236
255
|
}
|
|
237
|
-
a.run(() => a.offer(sdp, this.werift));
|
|
256
|
+
a.run(() => a.offer(sdp, this.werift, ice));
|
|
238
257
|
}
|
|
239
258
|
}
|
package/lib/relay/phone.js
CHANGED
|
@@ -110,7 +110,7 @@ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", ot
|
|
|
110
110
|
const phone = new PhoneSession();
|
|
111
111
|
|
|
112
112
|
const base = relayUrl.replace(/\/+$/, "");
|
|
113
|
-
const query = [resume || signal || mode === "standby" ? "v=2" : "", signal ? "mode=signal" : ""].filter(Boolean).join("&");
|
|
113
|
+
const query = [resume || signal || mode === "standby" || mode === "bulk" ? "v=2" : "", signal ? "mode=signal" : ""].filter(Boolean).join("&");
|
|
114
114
|
const ws = new WebSocketImpl(lan ? `${base}/v1/lan` : `${base}/v1/guest/${room}${query ? `?${query}` : ""}`);
|
|
115
115
|
ws.binaryType = "arraybuffer";
|
|
116
116
|
phone.ws = ws;
|
|
@@ -136,7 +136,7 @@ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", ot
|
|
|
136
136
|
noise = new NoiseInitiator({ s: device, rs: pcPub, prologue: enc.encode(`DSH-RELAY/1|${room}`) });
|
|
137
137
|
stage = "handshake";
|
|
138
138
|
phone._setState("handshake");
|
|
139
|
-
ws.send(noise.writeMessage1(enc.encode(JSON.stringify({ v: 1, name, ...(signal ? { mode: "signal" } : mode === "standby" ? { mode } : {}), ...(otp && !opened && !signal && mode
|
|
139
|
+
ws.send(noise.writeMessage1(enc.encode(JSON.stringify({ v: 1, name, ...(signal ? { mode: "signal" } : mode === "standby" || mode === "bulk" ? { mode } : {}), ...(otp && !opened && !signal && !mode ? { otp } : {}) }))));
|
|
140
140
|
if (opened) {
|
|
141
141
|
clearTimeout(phone._rehandshakeTimer);
|
|
142
142
|
phone._rehandshakeTimer = setTimeout(() => phone.close(4408, "re-handshake timeout"), timeoutMs);
|
package/lib/relay/signal.js
CHANGED
|
@@ -14,6 +14,10 @@
|
|
|
14
14
|
|
|
15
15
|
|
|
16
16
|
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
17
21
|
|
|
18
22
|
|
|
19
23
|
|
|
@@ -32,6 +36,26 @@ export const CLOSE_SIGNAL_BUDGET = 4431;
|
|
|
32
36
|
const enc = new TextEncoder();
|
|
33
37
|
const dec = new TextDecoder();
|
|
34
38
|
|
|
39
|
+
const ICE_URL_RE = /^(stun|turn|turns):[^\s]{1,250}$/;
|
|
40
|
+
const ICE_TEXT_MAX = 256;
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
export function normalizeIceServers(list) {
|
|
44
|
+
if (!Array.isArray(list) || list.length > 4) throw new MuxError("bad ice servers");
|
|
45
|
+
return list.map((s) => {
|
|
46
|
+
if (!s || typeof s !== "object" || Array.isArray(s)) throw new MuxError("bad ice server");
|
|
47
|
+
const urls = typeof s.urls === "string" ? [s.urls] : s.urls;
|
|
48
|
+
if (!Array.isArray(urls) || urls.length === 0 || urls.length > 6 || !urls.every((u) => typeof u === "string" && ICE_URL_RE.test(u))) throw new MuxError("bad ice server urls");
|
|
49
|
+
const out = { urls: [...urls] };
|
|
50
|
+
for (const k of ["username", "credential"]) {
|
|
51
|
+
if (s[k] === undefined) continue;
|
|
52
|
+
if (typeof s[k] !== "string" || s[k].length > ICE_TEXT_MAX) throw new MuxError("bad ice server credential");
|
|
53
|
+
out[k] = s[k];
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
35
59
|
|
|
36
60
|
export function normalizeSignal(msg) {
|
|
37
61
|
if (!msg || typeof msg !== "object" || msg.t !== "sig") throw new MuxError("bad signal message");
|
|
@@ -42,6 +66,7 @@ export function normalizeSignal(msg) {
|
|
|
42
66
|
if (typeof msg.sdp !== "string" || msg.sdp.length === 0) throw new MuxError("signal without sdp");
|
|
43
67
|
out.sdp = msg.sdp;
|
|
44
68
|
}
|
|
69
|
+
if (msg.k === "offer" && msg.ice !== undefined) out.ice = normalizeIceServers(msg.ice);
|
|
45
70
|
if (msg.k === "ice") {
|
|
46
71
|
if (msg.cand !== null && (typeof msg.cand !== "object" || Array.isArray(msg.cand))) throw new MuxError("bad ice candidate");
|
|
47
72
|
out.cand = msg.cand ?? null;
|
package/lib/routes/app-state.js
CHANGED
|
@@ -15,7 +15,7 @@ import { NOT_HANDLED } from "./route-groups.js";
|
|
|
15
15
|
export async function handleAppStateRoutes(deps, req, res, url, rest, method, miss) {
|
|
16
16
|
const {
|
|
17
17
|
agentSessionId, assistantPrefs, authEnabled, basePath, config, ctx, error, handleMemory, handlePersona,
|
|
18
|
-
handleReminders, ipv4Addresses, lanNoiseUrls, lanPort, liveActivity, noteUserActivity, phoneActions, pluginVersion,
|
|
18
|
+
handleReminders, ipv4Addresses, lanNoiseUrls, lanPort, liveActivity, noteUserActivity, phoneActions, phonePush, pluginVersion,
|
|
19
19
|
privateFirst, proactive, proactiveIdleMs, readJson, sessionTitleOf, shortSessionId,
|
|
20
20
|
} = deps;
|
|
21
21
|
if (rest === "/bootstrap") {
|
|
@@ -79,6 +79,7 @@ export async function handleAppStateRoutes(deps, req, res, url, rest, method, mi
|
|
|
79
79
|
|
|
80
80
|
if (rest === "/phone-action-result" && await phoneActions.handle(req, res, method)) return;
|
|
81
81
|
if (rest === "/live-activity/token" && await liveActivity.handle(req, res, method)) return;
|
|
82
|
+
if (rest === "/push/register" && await phonePush.handle(req, res, method)) return;
|
|
82
83
|
|
|
83
84
|
if (rest === "/persona" || rest.startsWith("/persona/")) {
|
|
84
85
|
if (await handlePersona(req, res, rest, method)) return;
|
package/lib/routes/files.js
CHANGED
|
@@ -12,6 +12,7 @@ import { fileMimeOf, ifNoneMatch, normalizeServerPath, parseByteRange, requestHe
|
|
|
12
12
|
import { guardRes, requireGet, sendJson } from "../http-util.js";
|
|
13
13
|
import { isProtectedFile, isProtectedPath, isStillAt, realPathOf, removeCreatedEntry } from "../protected-paths.js";
|
|
14
14
|
import { NOT_HANDLED } from "./route-groups.js";
|
|
15
|
+
import { DIGEST_HEADER, fileSha256 } from "../file-digest.js";
|
|
15
16
|
|
|
16
17
|
export async function handleFilesRoutes(deps, req, res, url, rest, method, miss) {
|
|
17
18
|
const {
|
|
@@ -196,6 +197,8 @@ export async function handleFilesRoutes(deps, req, res, url, rest, method, miss)
|
|
|
196
197
|
const start = range ? range.start : 0;
|
|
197
198
|
const end = range ? range.end : st.size - 1;
|
|
198
199
|
const length = st.size === 0 ? 0 : end - start + 1;
|
|
200
|
+
|
|
201
|
+
const digest = method === "HEAD" ? null : await fileSha256(fd, { path: target, size: st.size, mtimeMs: st.mtimeMs });
|
|
199
202
|
const headers = {
|
|
200
203
|
"content-type": fileMimeOf(name),
|
|
201
204
|
"content-length": String(length),
|
|
@@ -207,6 +210,7 @@ export async function handleFilesRoutes(deps, req, res, url, rest, method, miss)
|
|
|
207
210
|
|
|
208
211
|
connection: "close",
|
|
209
212
|
...(range ? { "content-range": `bytes ${start}-${end}/${st.size}` } : {}),
|
|
213
|
+
...(digest ? { [DIGEST_HEADER]: digest } : {}),
|
|
210
214
|
};
|
|
211
215
|
res.writeHead(range ? 206 : 200, headers);
|
|
212
216
|
if (method === "HEAD" || st.size === 0) {
|
|
@@ -7,8 +7,10 @@
|
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
|
|
10
|
+
|
|
10
11
|
import { createHostPluginRoutes } from "../host-plugins.js";
|
|
11
12
|
import { createScheduleRoutes } from "../host-schedule.js";
|
|
13
|
+
import { createSessionSearchRoutes } from "../host-session-search.js";
|
|
12
14
|
import { createTeamRoutes } from "../host-team.js";
|
|
13
15
|
import { NOT_HANDLED } from "./route-groups.js";
|
|
14
16
|
|
|
@@ -22,6 +24,7 @@ function handlersFor(deps) {
|
|
|
22
24
|
const logger = ctx?.logger;
|
|
23
25
|
h = {
|
|
24
26
|
schedules: createScheduleRoutes({ service: () => ctx.get("schedule"), logger }),
|
|
27
|
+
search: createSessionSearchRoutes({ service: () => ctx.get("sessionQuery"), logger }),
|
|
25
28
|
team: createTeamRoutes({ service: () => ctx.get("agentTeams"), agents: () => ctx.get("agents"), logger }),
|
|
26
29
|
plugins: createHostPluginRoutes({
|
|
27
30
|
manager: () => ctx.get("pluginManager"),
|
|
@@ -42,6 +45,7 @@ export async function handleHostServicesRoutes(deps, req, res, url, rest, method
|
|
|
42
45
|
if (owns(rest, "/schedules")) pick = "schedules";
|
|
43
46
|
else if (rest === "/team/tasks") pick = "team";
|
|
44
47
|
else if (owns(rest, "/host-plugins")) pick = "plugins";
|
|
48
|
+
else if (rest === "/session-search") pick = "search";
|
|
45
49
|
if (!pick) {
|
|
46
50
|
miss.now = true;
|
|
47
51
|
return NOT_HANDLED;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dsh-mobile/mobile-remote",
|
|
3
|
-
"version": "3.5.0-beta.
|
|
3
|
+
"version": "3.5.0-beta.3",
|
|
4
4
|
"description": "DSH Mobile:把 DeepSeek Harness 变成随身控制台——手机远程发消息派活、看进度、收通知、审批决策、管理会话;配套 Flutter App(Android、iPhone / iPad)",
|
|
5
5
|
"homepage": "https://dsh.claud.ing/",
|
|
6
6
|
"repository": {
|