dsh-desktop-enhance 0.6.12 → 0.6.13

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/lib/remote.js CHANGED
@@ -5,7 +5,20 @@ import { createServer, request } from "node:http";
5
5
  import { request as request$1 } from "node:https";
6
6
  import { isIP } from "node:net";
7
7
  import { Transform, pipeline } from "node:stream";
8
+ //#region src/shared/remote.ts
9
+ const REMOTE_MANAGEMENT_ROUTE = "/api/desktop-enhance/remote";
10
+ const REMOTE_DEVICE_ISSUE_ROUTE = "/api/device/issue";
11
+ const REMOTE_DEVICE_ROUTE = "/_desktop-enhance/device";
12
+ const REMOTE_PROBE_ROUTE = "/remote/api/remote.mux";
13
+ const REMOTE_PROXY_HEADER = "x-desktop-enhance-remote";
14
+ const DEFAULT_REMOTE_PORT = 19388;
15
+ function deviceLabel(userAgent) {
16
+ return [/Edg\//.test(userAgent) ? "Edge" : /Firefox\//.test(userAgent) ? "Firefox" : /Chrome\//.test(userAgent) ? "Chrome" : /Safari/.test(userAgent) ? "Safari" : "", /iPhone|iPad/.test(userAgent) ? "iOS" : /Android/.test(userAgent) ? "Android" : /Macintosh/.test(userAgent) ? "macOS" : /Windows/.test(userAgent) ? "Windows" : ""].filter(Boolean).join(" · ");
17
+ }
18
+ //#endregion
8
19
  //#region src/remote/access.ts
20
+ const USER_AGENT_MAX = 512;
21
+ const NAME_MAX = 100;
9
22
  var RemoteAccessError = class extends Error {
10
23
  code;
11
24
  constructor(code) {
@@ -14,15 +27,8 @@ var RemoteAccessError = class extends Error {
14
27
  this.code = code;
15
28
  }
16
29
  };
17
- const SECRET = /^[A-Za-z0-9_-]{43}$/;
18
- const HASH = /^[a-f0-9]{64}$/;
19
- const ID = /^[a-f0-9]{32}$/;
20
- function digest(secret) {
21
- return createHash("sha256").update(secret).digest("hex");
22
- }
23
- function matches(secret, hash) {
24
- return typeof secret === "string" && SECRET.test(secret) && timingSafeEqual(Buffer.from(digest(secret), "hex"), Buffer.from(hash, "hex"));
25
- }
30
+ const TOKEN = /^[A-Za-z0-9_-]{43}$/u;
31
+ const ID = /^[a-f0-9]{32}$/u;
26
32
  function record(value) {
27
33
  return typeof value === "object" && value !== null && !Array.isArray(value);
28
34
  }
@@ -32,61 +38,42 @@ function exactKeys(value, keys) {
32
38
  function text(value, max, allowEmpty = false) {
33
39
  return typeof value === "string" && (allowEmpty || value.trim().length > 0) && value.length <= max && !/[\u0000-\u001f\u007f]/u.test(value);
34
40
  }
35
- function validAudience(value) {
36
- if (!text(value, 2048)) return false;
37
- try {
38
- const url = new URL(value);
39
- return (url.protocol === "http:" || url.protocol === "https:") && url.origin === value;
40
- } catch {
41
- return false;
42
- }
41
+ function sameKey(presented, stored) {
42
+ return timingSafeEqual(Buffer.from(presented, "utf8"), Buffer.from(stored, "utf8"));
43
43
  }
44
- function validateState(raw, time) {
45
- if (raw === void 0) return {
46
- version: 2,
47
- pairToken: null,
48
- devices: []
49
- };
50
- if (!record(raw)) throw new RemoteAccessError("INVALID_STATE");
51
- const legacy = raw.version === 1;
52
- if (!exactKeys(raw, legacy ? ["version", "devices"] : [
53
- "version",
54
- "pairToken",
55
- "devices"
56
- ]) || !legacy && raw.version !== 2 || !Array.isArray(raw.devices)) throw new RemoteAccessError("INVALID_STATE");
57
- const pairToken = legacy ? null : raw.pairToken;
58
- if (!(pairToken === null || typeof pairToken === "string" && SECRET.test(pairToken))) throw new RemoteAccessError("INVALID_STATE");
44
+ const EMPTY = {
45
+ version: 3,
46
+ devices: []
47
+ };
48
+ function validateV3(raw) {
49
+ if (!exactKeys(raw, ["version", "devices"]) || raw.version !== 3 || !Array.isArray(raw.devices)) throw new RemoteAccessError("INVALID_STATE");
59
50
  const ids = new Set();
60
- const hashes = new Set();
51
+ const tokens = new Set();
61
52
  return {
62
- version: 2,
63
- pairToken,
53
+ version: 3,
64
54
  devices: raw.devices.map((entry) => {
65
55
  if (!record(entry)) throw new RemoteAccessError("INVALID_STATE");
66
56
  const hasRevocation = Object.hasOwn(entry, "revokedAt");
57
+ const revokedAt = entry.revokedAt;
67
58
  if (!exactKeys(entry, [
68
59
  "id",
69
- "secretHash",
60
+ "token",
70
61
  "name",
71
62
  "userAgent",
72
- "audience",
73
63
  "createdAt",
74
- ...legacy ? ["expiresAt"] : [],
75
64
  ...hasRevocation ? ["revokedAt"] : []
76
- ]) || typeof entry.id !== "string" || !ID.test(entry.id) || typeof entry.secretHash !== "string" || !HASH.test(entry.secretHash) || !text(entry.name, 100) || !text(entry.userAgent, 512, true) || !validAudience(entry.audience) || typeof entry.createdAt !== "number" || !Number.isSafeInteger(entry.createdAt) || entry.createdAt < 0 || legacy && (typeof entry.expiresAt !== "number" || !Number.isSafeInteger(entry.expiresAt) || entry.expiresAt - entry.createdAt !== 2592e6) || hasRevocation && (typeof entry.revokedAt !== "number" || !Number.isSafeInteger(entry.revokedAt) || entry.revokedAt < entry.createdAt) || ids.has(entry.id) || hashes.has(entry.secretHash) || pairToken !== null && digest(pairToken) === entry.secretHash) throw new RemoteAccessError("INVALID_STATE");
65
+ ]) || typeof entry.id !== "string" || !ID.test(entry.id) || typeof entry.token !== "string" || !TOKEN.test(entry.token) || !text(entry.name, NAME_MAX, true) || !text(entry.userAgent, USER_AGENT_MAX, true) || typeof entry.createdAt !== "number" || !Number.isSafeInteger(entry.createdAt) || entry.createdAt < 0 || hasRevocation && (typeof revokedAt !== "number" || !Number.isSafeInteger(revokedAt) || revokedAt < entry.createdAt) || ids.has(entry.id) || tokens.has(entry.token)) throw new RemoteAccessError("INVALID_STATE");
77
66
  ids.add(entry.id);
78
- hashes.add(entry.secretHash);
67
+ tokens.add(entry.token);
79
68
  return {
80
69
  id: entry.id,
81
- secretHash: entry.secretHash,
70
+ token: entry.token,
82
71
  name: entry.name,
83
72
  userAgent: entry.userAgent,
84
- audience: entry.audience,
85
73
  createdAt: entry.createdAt,
86
- ...legacy ? { expiresAt: entry.expiresAt } : {},
87
- ...hasRevocation ? { revokedAt: entry.revokedAt } : {}
74
+ ...typeof revokedAt === "number" ? { revokedAt } : {}
88
75
  };
89
- }).filter((device) => !legacy || device.revokedAt !== void 0 || device.expiresAt > time).map(({ expiresAt: _expiry, ...device }) => device)
76
+ })
90
77
  };
91
78
  }
92
79
  async function createRemoteAccess(options) {
@@ -99,8 +86,15 @@ async function createRemoteAccess(options) {
99
86
  } catch {
100
87
  throw new RemoteAccessError("STORE_FAILED");
101
88
  }
102
- let state = validateState(loaded, now());
103
- if (record(loaded) && loaded.version === 1) try {
89
+ let state;
90
+ let discardLegacy = false;
91
+ if (loaded === void 0) state = EMPTY;
92
+ else if (!record(loaded)) throw new RemoteAccessError("INVALID_STATE");
93
+ else if (loaded.version === 1 || loaded.version === 2) {
94
+ state = EMPTY;
95
+ discardLegacy = true;
96
+ } else state = validateV3(loaded);
97
+ if (discardLegacy) try {
104
98
  await store.save(structuredClone(state));
105
99
  } catch {
106
100
  throw new RemoteAccessError("STORE_FAILED");
@@ -118,15 +112,6 @@ async function createRemoteAccess(options) {
118
112
  tail = result.catch(() => void 0);
119
113
  return result;
120
114
  }
121
- function random(size) {
122
- try {
123
- const bytes = randomBytes$1(size);
124
- if (!(bytes instanceof Uint8Array) || bytes.byteLength !== size) throw new Error();
125
- return Buffer.from(bytes);
126
- } catch {
127
- throw new RemoteAccessError("ENTROPY_FAILED");
128
- }
129
- }
130
115
  async function commit(next) {
131
116
  try {
132
117
  await store.save(structuredClone(next));
@@ -136,87 +121,91 @@ async function createRemoteAccess(options) {
136
121
  }
137
122
  state = next;
138
123
  }
139
- function newPairToken() {
124
+ function random(size) {
125
+ try {
126
+ const bytes = randomBytes$1(size);
127
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength !== size) throw new Error();
128
+ return Buffer.from(bytes);
129
+ } catch {
130
+ throw new RemoteAccessError("ENTROPY_FAILED");
131
+ }
132
+ }
133
+ function newToken() {
140
134
  const token = random(32).toString("base64url");
141
- if (token === state.pairToken || state.devices.some((device) => device.secretHash === digest(token))) throw new RemoteAccessError("ENTROPY_FAILED");
135
+ if (state.devices.some((device) => device.token === token)) throw new RemoteAccessError("ENTROPY_FAILED");
142
136
  return token;
143
137
  }
138
+ function project(device) {
139
+ const { token: _token, ...view } = device;
140
+ return view;
141
+ }
144
142
  return {
145
143
  close() {
146
144
  closing ??= tail.then(() => void 0);
147
145
  return closing;
148
146
  },
149
- snapshot() {
147
+ status() {
148
+ const ready = !closing && !failed;
150
149
  const time = now();
151
150
  return {
152
- pairing: !closing && !failed && state.pairToken !== null,
153
- devices: closing || failed ? [] : state.devices.filter((device) => device.createdAt <= time).map(({ secretHash: _hash, ...device }) => device)
151
+ ready,
152
+ devices: ready ? state.devices.filter((device) => device.createdAt <= time).map(project) : []
154
153
  };
155
154
  },
156
- startPairing() {
157
- return serialize(async () => {
158
- if (state.pairToken !== null) return;
159
- await commit({
160
- ...state,
161
- pairToken: newPairToken()
162
- });
163
- });
164
- },
165
- copyPairToken() {
166
- return serialize(() => {
167
- if (state.pairToken === null) throw new RemoteAccessError("PAIRING_CLOSED");
168
- return state.pairToken;
169
- });
170
- },
171
- resetPairing() {
155
+ add(input) {
172
156
  return serialize(async () => {
173
- if (state.pairToken === null) throw new RemoteAccessError("PAIRING_CLOSED");
157
+ if (!record(input) || typeof input.userAgent !== "string") throw new RemoteAccessError("INVALID_METADATA");
158
+ const userAgent = input.userAgent.slice(0, USER_AGENT_MAX);
159
+ if (!text(userAgent, USER_AGENT_MAX, true)) throw new RemoteAccessError("INVALID_METADATA");
160
+ const device = {
161
+ id: random(16).toString("hex"),
162
+ token: newToken(),
163
+ name: deviceLabel(userAgent),
164
+ userAgent,
165
+ createdAt: now()
166
+ };
174
167
  await commit({
175
168
  ...state,
176
- pairToken: newPairToken()
169
+ devices: [...state.devices, device]
177
170
  });
171
+ return {
172
+ device: project(device),
173
+ deviceId: device.id,
174
+ token: device.token
175
+ };
178
176
  });
179
177
  },
180
- endPairing() {
181
- return serialize(async () => {
182
- if (state.pairToken === null) return;
183
- await commit({
184
- ...state,
185
- pairToken: null
186
- });
187
- });
178
+ token(id) {
179
+ if (closing || failed) return null;
180
+ const time = now();
181
+ return state.devices.find((entry) => entry.id === id && entry.revokedAt === void 0 && entry.createdAt <= time)?.token ?? null;
188
182
  },
189
- exchange(pairToken, metadata) {
183
+ reissue(id) {
190
184
  return serialize(async () => {
191
185
  const time = now();
192
- if (state.pairToken === null || !matches(pairToken, digest(state.pairToken))) throw new RemoteAccessError("INVALID_PAIRING");
193
- if (!metadata || !text(metadata.name, 100) || !text(metadata.userAgent, 512, true) || !validAudience(metadata.audience)) throw new RemoteAccessError("INVALID_METADATA");
194
- const deviceCookie = random(32).toString("base64url");
195
- const id = random(16).toString("hex");
196
- const secretHash = digest(deviceCookie);
197
- if (deviceCookie === state.pairToken || state.devices.some((device) => device.id === id || device.secretHash === secretHash)) throw new RemoteAccessError("ENTROPY_FAILED");
198
- const device = {
199
- id,
200
- secretHash,
201
- name: metadata.name,
202
- userAgent: metadata.userAgent,
203
- audience: metadata.audience,
204
- createdAt: time
205
- };
186
+ if (!state.devices.find((entry) => entry.id === id && entry.revokedAt === void 0 && entry.createdAt <= time)) throw new RemoteAccessError("UNKNOWN_DEVICE");
187
+ const token = newToken();
206
188
  await commit({
207
189
  ...state,
208
- devices: [...state.devices, device]
190
+ devices: state.devices.map((entry) => entry.id === id ? {
191
+ ...entry,
192
+ token
193
+ } : entry)
209
194
  });
210
195
  return {
211
196
  deviceId: id,
212
- deviceCookie
197
+ token
213
198
  };
214
199
  });
215
200
  },
216
- authenticate(deviceCookie, audience) {
217
- if (closing || failed || typeof deviceCookie !== "string" || !SECRET.test(deviceCookie)) return null;
201
+ authenticate(presented) {
202
+ if (closing || failed || typeof presented !== "string" || !TOKEN.test(presented)) return null;
218
203
  const time = now();
219
- return state.devices.find((item) => item.revokedAt === void 0 && item.audience === audience && item.createdAt <= time && matches(deviceCookie, item.secretHash))?.id ?? null;
204
+ const device = state.devices.find((entry) => entry.revokedAt === void 0 && entry.createdAt <= time && sameKey(presented, entry.token));
205
+ return device ? {
206
+ deviceId: device.id,
207
+ token: device.token
208
+ } : null;
220
209
  },
221
210
  revoke(id) {
222
211
  return serialize(async () => {
@@ -312,23 +301,43 @@ function proxyStaticResponse(req, incoming, res, headers) {
312
301
  return true;
313
302
  }
314
303
  //#endregion
315
- //#region src/shared/remote.ts
316
- const REMOTE_MANAGEMENT_ROUTE = "/api/desktop-enhance/remote";
317
- const REMOTE_PAIR_ISSUE_ROUTE = "/api/pair/issue";
318
- const REMOTE_PAIR_ROUTE = "/_desktop-enhance/pair";
319
- const REMOTE_PROBE_ROUTE = "/remote/api/remote.mux";
320
- const REMOTE_PROXY_HEADER = "x-desktop-enhance-remote";
321
- const DEFAULT_REMOTE_PORT = 19388;
322
- //#endregion
323
304
  //#region src/remote/gateway.ts
324
305
  function isLoopback(host) {
325
306
  return host === "[::1]" || host === "::1" || isIP(host) === 4 && host.startsWith("127.");
326
307
  }
327
- function cookieName(origin) {
328
- return `dsh-enhance-device-${createHash("sha256").update(origin).digest("hex").slice(0, 16)}`;
308
+ const DEVICE_COOKIE_PREFIX = "dsh-enhance-device";
309
+ const LEGACY_DEVICE_COOKIE = DEVICE_COOKIE_PREFIX;
310
+ const DEVICE_COOKIE_PATTERN = /^dsh-enhance-device-[a-f0-9]{32}$/u;
311
+ function deviceCookieName(deviceId) {
312
+ return `${DEVICE_COOKIE_PREFIX}-${deviceId}`;
313
+ }
314
+ function deviceCookieHeader(deviceId, token) {
315
+ return `${deviceCookieName(deviceId)}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=34560000`;
316
+ }
317
+ function clearLegacyCookieHeader() {
318
+ return `${LEGACY_DEVICE_COOKIE}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0`;
319
+ }
320
+ function cookieValues(req, name) {
321
+ return (req.headers.cookie ?? "").split(";").map((item) => item.trim()).filter((item) => item.startsWith(`${name}=`)).map((item) => item.slice(name.length + 1));
329
322
  }
330
- function deviceCookieHeader(origin, cookie) {
331
- return `${cookieName(origin)}=${cookie}; Path=/; HttpOnly; SameSite=Strict; Max-Age=34560000`;
323
+ function presentedTokens(req) {
324
+ const values = (req.headers.cookie ?? "").split(";").map((item) => item.trim());
325
+ const names = new Set(values.flatMap((item) => {
326
+ const eq = item.indexOf("=");
327
+ if (eq <= 0) return [];
328
+ const name = item.slice(0, eq);
329
+ return DEVICE_COOKIE_PATTERN.test(name) || name === LEGACY_DEVICE_COOKIE ? [name] : [];
330
+ }));
331
+ const scoped = [];
332
+ const legacy = [];
333
+ for (const name of names) {
334
+ const held = cookieValues(req, name);
335
+ const first = held[0];
336
+ if (held.length !== 1 || first === void 0) return null;
337
+ if (name === LEGACY_DEVICE_COOKIE) legacy.push(first);
338
+ else scoped.push(first);
339
+ }
340
+ return [...scoped, ...legacy];
332
341
  }
333
342
  function nativeCookieExpiry(header, requestedAt) {
334
343
  const attributes = header.split(";").slice(1).map((value) => value.trim());
@@ -341,15 +350,10 @@ function nativeCookieExpiry(header, requestedAt) {
341
350
  const expiresAt = expires === void 0 ? NaN : Date.parse(expires);
342
351
  return Number.isFinite(expiresAt) ? expiresAt : 0;
343
352
  }
344
- function cookieOf(req, origin) {
345
- const name = cookieName(origin);
346
- const matches = (req.headers.cookie ?? "").split(";").map((item) => item.trim()).filter((item) => item.startsWith(`${name}=`));
347
- return matches.length === 1 ? matches[0].slice(name.length + 1) : "";
348
- }
349
353
  function blockedPath(path) {
350
354
  return [
351
355
  REMOTE_MANAGEMENT_ROUTE,
352
- REMOTE_PAIR_ISSUE_ROUTE,
356
+ REMOTE_DEVICE_ISSUE_ROUTE,
353
357
  "/connect"
354
358
  ].some((prefix) => path === prefix || path.startsWith(`${prefix}/`));
355
359
  }
@@ -396,13 +400,13 @@ async function startRemoteGateway(options) {
396
400
  let nativeCookie;
397
401
  let login;
398
402
  let port = 0;
399
- function externalOrigin(req, allowPairNavigation = false) {
403
+ function externalOrigin(req, allowDeviceNavigation = false) {
400
404
  const host = req.headers.host;
401
405
  if (!host || Array.isArray(host) || /[@/\\?#\s]/u.test(host)) throw new Error("UNTRUSTED_HOST");
402
406
  const url = new URL(`http://${host}`);
403
407
  if (!(url.hostname === "localhost" || isLoopback(url.hostname) || Object.values(networkInterfaces()).flat().some((item) => item?.family === "IPv4" && !item.internal && item.address === url.hostname)) || Number(url.port || "80") !== port) throw new Error("UNTRUSTED_HOST");
404
408
  if (req.headers.origin !== void 0 && req.headers.origin !== url.origin) throw new Error("UNTRUSTED_ORIGIN");
405
- if (req.headers["sec-fetch-site"] === "cross-site" && !allowPairNavigation) throw new Error("UNTRUSTED_ORIGIN");
409
+ if (req.headers["sec-fetch-site"] === "cross-site" && !allowDeviceNavigation) throw new Error("UNTRUSTED_ORIGIN");
406
410
  return url.origin;
407
411
  }
408
412
  function track(id, destroy) {
@@ -454,13 +458,14 @@ async function startRemoteGateway(options) {
454
458
  }
455
459
  }, (response) => {
456
460
  response.resume();
457
- const auth = (response.headers["set-cookie"] ?? []).filter((value) => /^dsh-auth-[^=]+=.+$/u.test(value.split(";")[0]));
458
- if (stopped || response.statusCode !== 303 || auth.length !== 1) {
461
+ const auth = (response.headers["set-cookie"] ?? []).filter((value) => /^dsh-auth-[^=]+=.+$/u.test(value.split(";")[0] ?? ""));
462
+ const firstAuth = auth[0];
463
+ if (stopped || response.statusCode !== 303 || auth.length !== 1 || firstAuth === void 0) {
459
464
  reject(new Error("UPSTREAM_AUTH_FAILED"));
460
465
  return;
461
466
  }
462
- const value = auth[0].split(";")[0];
463
- const expiresAt = nativeCookieExpiry(auth[0], requestedAt);
467
+ const value = firstAuth.split(";")[0] ?? "";
468
+ const expiresAt = nativeCookieExpiry(firstAuth, requestedAt);
464
469
  if (expiresAt > Date.now()) nativeCookie = {
465
470
  value,
466
471
  expiresAt
@@ -504,57 +509,71 @@ async function startRemoteGateway(options) {
504
509
  });
505
510
  res.end(status === 401 ? "unauthorized" : status === 403 ? "forbidden" : "gateway unavailable");
506
511
  }
512
+ function grantOf(req) {
513
+ const tokens = presentedTokens(req);
514
+ if (tokens === null) return null;
515
+ for (const token of tokens) {
516
+ const grant = options.access.authenticate(token);
517
+ if (grant) return grant;
518
+ }
519
+ return null;
520
+ }
521
+ function authStatus(untrusted) {
522
+ return untrusted instanceof Error && [
523
+ "UNTRUSTED_ORIGIN",
524
+ "UNTRUSTED_HOST",
525
+ "INVALID_PATH",
526
+ "FORBIDDEN_PATH"
527
+ ].includes(untrusted.message) ? 403 : 401;
528
+ }
507
529
  async function handle(req, res) {
530
+ const rawUrl = req.url ?? "/";
508
531
  let origin;
509
532
  let path;
510
533
  try {
511
- path = safePath(req.url ?? "/");
512
- origin = externalOrigin(req, path === "/_desktop-enhance/pair" && req.method === "GET" && req.headers.origin === void 0 && req.headers["sec-fetch-mode"] === "navigate");
513
- } catch {
514
- reply(res, 403);
534
+ path = safePath(rawUrl);
535
+ origin = externalOrigin(req, path === "/_desktop-enhance/device" && req.method === "GET" && req.headers.origin === void 0 && req.headers["sec-fetch-mode"] === "navigate");
536
+ } catch (caught) {
537
+ reply(res, authStatus(caught));
515
538
  return;
516
539
  }
517
- const url = new URL(req.url ?? "/", origin);
540
+ const url = new URL(rawUrl, origin);
518
541
  if (path === "/remote/api/remote.mux") {
519
542
  reply(res, 403);
520
543
  return;
521
544
  }
522
- if (path === "/_desktop-enhance/pair") {
523
- if (req.method !== "GET" || url.searchParams.getAll("token").length !== 1) {
545
+ if (path === "/_desktop-enhance/device") {
546
+ const tokens = url.searchParams.getAll("token");
547
+ const token = tokens[0];
548
+ if (req.method !== "GET" || tokens.length !== 1 || token === void 0) {
524
549
  reply(res, 401);
525
550
  return;
526
551
  }
527
- try {
528
- const device = await options.access.exchange(url.searchParams.get("token"), {
529
- name: "远程浏览器",
530
- userAgent: (req.headers["user-agent"] ?? "").slice(0, 512),
531
- audience: origin
532
- });
533
- if (stopped || res.destroyed) return;
534
- res.writeHead(303, {
535
- "set-cookie": deviceCookieHeader(origin, device.deviceCookie),
536
- location: "/",
537
- "cache-control": "no-store",
538
- "referrer-policy": "no-referrer"
539
- });
540
- res.end();
541
- } catch (error) {
542
- if (error instanceof Error && "code" in error && error.code === "STORE_FAILED") fatal();
543
- else reply(res, 401);
552
+ const claimed = options.access.authenticate(token);
553
+ if (!claimed || stopped || res.destroyed) {
554
+ reply(res, 401);
555
+ return;
544
556
  }
557
+ res.writeHead(303, {
558
+ "set-cookie": [deviceCookieHeader(claimed.deviceId, claimed.token), clearLegacyCookieHeader()],
559
+ location: "/",
560
+ "cache-control": "no-store",
561
+ "referrer-policy": "no-referrer"
562
+ });
563
+ res.end();
545
564
  return;
546
565
  }
547
566
  if (url.searchParams.has("token")) {
548
567
  reply(res, 403);
549
568
  return;
550
569
  }
551
- const cookie = cookieOf(req, origin);
552
- const id = options.access.authenticate(cookie, origin);
553
- if (!id) {
570
+ const grant = grantOf(req);
571
+ if (!grant) {
554
572
  reply(res, 401);
555
573
  return;
556
574
  }
557
- res.setHeader("set-cookie", deviceCookieHeader(origin, cookie));
575
+ const id = grant.deviceId;
576
+ res.setHeader("set-cookie", [deviceCookieHeader(id, grant.token), clearLegacyCookieHeader()]);
558
577
  if (path === "/api/desktop-enhance/remote") {
559
578
  if (!options.manage) {
560
579
  reply(res, 403);
@@ -578,7 +597,7 @@ async function startRemoteGateway(options) {
578
597
  res.once("finish", untrack);
579
598
  const native = await getNativeCookie();
580
599
  if (stopped || res.destroyed) return;
581
- if (options.access.authenticate(cookie, origin) !== id) {
600
+ if (!options.access.authenticate(grant.token)) {
582
601
  reply(res, 401);
583
602
  return;
584
603
  }
@@ -588,7 +607,7 @@ async function startRemoteGateway(options) {
588
607
  delete forwarded["if-none-match"];
589
608
  delete forwarded["if-modified-since"];
590
609
  }
591
- const outgoing = request$2(new URL(req.url, upstream.origin), {
610
+ const outgoing = request$2(new URL(rawUrl, upstream.origin), {
592
611
  method: req.method,
593
612
  headers: forwarded
594
613
  }, (incoming) => {
@@ -618,25 +637,26 @@ async function startRemoteGateway(options) {
618
637
  socket.end(`HTTP/1.1 ${status} ${status === 401 ? "Unauthorized" : status === 403 ? "Forbidden" : "Bad Gateway"}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
619
638
  }
620
639
  async function handleUpgrade(req, socket, head) {
640
+ const rawUrl = req.url ?? "/";
621
641
  let origin;
622
642
  let path;
623
643
  try {
624
644
  origin = externalOrigin(req);
625
- path = safePath(req.url ?? "/");
626
- } catch {
627
- rejectUpgrade(socket, 403);
645
+ path = safePath(rawUrl);
646
+ } catch (caught) {
647
+ rejectUpgrade(socket, authStatus(caught));
628
648
  return;
629
649
  }
630
- if (path === "/api/desktop-enhance/remote" || path === "/remote/api/remote.mux" || path === "/_desktop-enhance/pair" || new URL(req.url, origin).searchParams.has("token")) {
650
+ if (path === "/api/desktop-enhance/remote" || path === "/remote/api/remote.mux" || path === "/_desktop-enhance/device" || new URL(rawUrl, origin).searchParams.has("token")) {
631
651
  rejectUpgrade(socket, 403);
632
652
  return;
633
653
  }
634
- const cookie = cookieOf(req, origin);
635
- const id = options.access.authenticate(cookie, origin);
636
- if (!id) {
654
+ const grant = grantOf(req);
655
+ if (!grant) {
637
656
  rejectUpgrade(socket, 401);
638
657
  return;
639
658
  }
659
+ const id = grant.deviceId;
640
660
  if (req.headers.upgrade?.toLowerCase() !== "websocket") {
641
661
  rejectUpgrade(socket, 403);
642
662
  return;
@@ -656,20 +676,20 @@ async function startRemoteGateway(options) {
656
676
  });
657
677
  const native = await getNativeCookie();
658
678
  if (stopped || socket.destroyed) return;
659
- if (options.access.authenticate(cookie, origin) !== id) {
679
+ if (!options.access.authenticate(grant.token)) {
660
680
  rejectUpgrade(socket, 401);
661
681
  return;
662
682
  }
663
683
  const headers = forwardedHeaders(req, native);
664
684
  headers.connection = "Upgrade";
665
685
  headers.upgrade = "websocket";
666
- const outgoing = request$2(new URL(req.url, upstream.origin), {
686
+ const outgoing = request$2(new URL(rawUrl, upstream.origin), {
667
687
  method: "GET",
668
688
  headers
669
689
  });
670
690
  cancelUpstream = () => outgoing.destroy();
671
691
  outgoing.once("upgrade", (response, remote, upstreamHead) => {
672
- if (stopped || socket.destroyed || options.access.authenticate(cookie, origin) !== id) {
692
+ if (stopped || socket.destroyed || !options.access.authenticate(grant.token)) {
673
693
  remote.destroy();
674
694
  socket.destroy();
675
695
  return;
@@ -686,7 +706,7 @@ async function startRemoteGateway(options) {
686
706
  rejectUpgrade(socket, 502);
687
707
  return;
688
708
  }
689
- headers["set-cookie"] = [deviceCookieHeader(origin, cookie)];
709
+ headers["set-cookie"] = [deviceCookieHeader(id, grant.token), clearLegacyCookieHeader()];
690
710
  headers.connection = "Upgrade";
691
711
  headers.upgrade = "websocket";
692
712
  const lines = Object.entries(headers).flatMap(([name, value]) => value === void 0 ? [] : (Array.isArray(value) ? value : [value]).map((item) => `${name}: ${item}`));
@@ -723,11 +743,16 @@ async function startRemoteGateway(options) {
723
743
  socket.on("error", () => socket.destroy());
724
744
  socket.once("close", () => sockets.delete(socket));
725
745
  });
746
+ function dropDevice(id) {
747
+ for (const destroy of active.get(id) ?? []) destroy();
748
+ active.delete(id);
749
+ }
726
750
  await new Promise((resolve, reject) => {
727
751
  server.once("error", reject);
728
752
  server.listen(options.port, options.host ?? "0.0.0.0", () => {
729
753
  server.off("error", reject);
730
- port = server.address().port;
754
+ const address = server.address();
755
+ port = typeof address === "object" && address !== null ? address.port : options.port;
731
756
  resolve();
732
757
  });
733
758
  });
@@ -735,6 +760,7 @@ async function startRemoteGateway(options) {
735
760
  port,
736
761
  close,
737
762
  onlineDeviceIds: () => [...active.keys()],
763
+ dropDevice,
738
764
  async revoke(id) {
739
765
  try {
740
766
  await options.access.revoke(id);
@@ -742,8 +768,7 @@ async function startRemoteGateway(options) {
742
768
  if (error instanceof Error && "code" in error && error.code === "STORE_FAILED") fatal();
743
769
  throw error;
744
770
  }
745
- for (const destroy of active.get(id) ?? []) destroy();
746
- active.delete(id);
771
+ dropDevice(id);
747
772
  }
748
773
  };
749
774
  }
@@ -778,6 +803,9 @@ function json(res, status, value) {
778
803
  });
779
804
  res.end(JSON.stringify(value));
780
805
  }
806
+ function plainRecord(value) {
807
+ return typeof value === "object" && value !== null && !Array.isArray(value);
808
+ }
781
809
  async function body(req) {
782
810
  let text = "";
783
811
  for await (const chunk of req) {
@@ -785,14 +813,12 @@ async function body(req) {
785
813
  if (Buffer.byteLength(text) > 4096) throw new Error("BODY_TOO_LARGE");
786
814
  }
787
815
  const value = JSON.parse(text || "{}");
788
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("INVALID_BODY");
816
+ if (!plainRecord(value)) throw new Error("INVALID_BODY");
789
817
  return value;
790
818
  }
791
819
  const publicErrors = new Set([
792
820
  "INVALID_STATE",
793
821
  "STORE_FAILED",
794
- "INVALID_PAIRING",
795
- "PAIRING_CLOSED",
796
822
  "INVALID_METADATA",
797
823
  "ENTROPY_FAILED",
798
824
  "ACCESS_CLOSED",
@@ -804,6 +830,7 @@ const publicErrors = new Set([
804
830
  "CONFIGURE_IN_PROGRESS",
805
831
  "INVALID_ACTION",
806
832
  "INVALID_DEVICE",
833
+ "UNKNOWN_DEVICE",
807
834
  "INVALID_BODY",
808
835
  "BODY_TOO_LARGE",
809
836
  "UPSTREAM_NOT_LOOPBACK"
@@ -812,11 +839,15 @@ function errorCode(caught, fallback) {
812
839
  return caught instanceof Error && publicErrors.has(caught.message) ? caught.message : fallback;
813
840
  }
814
841
  async function installRemoteHost(ctx, config, profile = process.env.DSH_PROFILE ?? "default") {
815
- const ws = ctx.get("webServer");
816
- const connection = ctx.get("connection");
817
- const credentials = ctx.get("credentials");
818
- const editor = ctx.get("configEditor");
819
- if (!ws || !connection || !credentials || !editor) throw new Error("REMOTE_DEPENDENCY_UNAVAILABLE");
842
+ const wsCandidate = ctx.get("webServer");
843
+ const connectionCandidate = ctx.get("connection");
844
+ const credentialsCandidate = ctx.get("credentials");
845
+ const editorCandidate = ctx.get("configEditor");
846
+ if (!wsCandidate || !connectionCandidate || !credentialsCandidate || !editorCandidate) throw new Error("REMOTE_DEPENDENCY_UNAVAILABLE");
847
+ const ws = wsCandidate;
848
+ const connection = connectionCandidate;
849
+ const credentials = credentialsCandidate;
850
+ const editor = editorCandidate;
820
851
  const recordKey = `desktop-enhance/remote-${createHash("sha256").update(profile).digest("hex").slice(0, 24)}`;
821
852
  let disposed = false;
822
853
  let configuring = false;
@@ -827,14 +858,13 @@ async function installRemoteHost(ctx, config, profile = process.env.DSH_PROFILE
827
858
  let nativeLoopback = false;
828
859
  const disposers = [];
829
860
  function status(identity) {
830
- const snapshot = access?.snapshot();
861
+ const snapshot = access?.status();
831
862
  const online = new Set(gateway?.onlineDeviceIds() ?? []);
832
863
  return {
833
864
  enabled: config.enabled,
834
865
  running: !!gateway && !error && !disposed,
835
866
  port: gateway?.port ?? config.port,
836
867
  nativeLoopback,
837
- pairing: snapshot?.pairing ?? false,
838
868
  devices: (snapshot?.devices ?? []).map((device) => ({
839
869
  ...device,
840
870
  online: online.has(device.id)
@@ -848,21 +878,28 @@ async function installRemoteHost(ctx, config, profile = process.env.DSH_PROFILE
848
878
  if (!access || !gateway || error || disposed) throw new Error("REMOTE_NOT_RUNNING");
849
879
  return access;
850
880
  }
851
- function pairOrigin(identity, requestedAddress) {
881
+ function deviceOrigin(identity, requestedAddress) {
852
882
  runningAccess();
883
+ if (!gateway) throw new Error("REMOTE_NOT_RUNNING");
853
884
  if (identity) return identity.origin;
854
885
  const choices = addresses();
855
886
  const address = requestedAddress ?? choices[0];
856
887
  if (typeof address !== "string" || !choices.includes(address)) throw new Error("INVALID_ADDRESS");
857
888
  return `http://${address}:${gateway.port}`;
858
889
  }
859
- async function pairLink(origin) {
860
- const token = await runningAccess().copyPairToken();
861
- const url = new URL(REMOTE_PAIR_ROUTE, origin);
890
+ function deviceIdOf(input) {
891
+ if (typeof input.id !== "string" || !input.id) throw new Error("INVALID_DEVICE");
892
+ return input.id;
893
+ }
894
+ function newDevice(req) {
895
+ return { userAgent: String(req.headers["user-agent"] ?? "") };
896
+ }
897
+ function deviceLink(origin, token) {
898
+ const url = new URL(REMOTE_DEVICE_ROUTE, origin);
862
899
  url.searchParams.set("token", token);
863
900
  return { url: url.href };
864
901
  }
865
- async function handle(req, res, pairOnly = false, identity) {
902
+ async function handle(req, res, issueOnly = false, identity) {
866
903
  if (disposed) {
867
904
  json(res, 503, { error: "ACCESS_CLOSED" });
868
905
  return;
@@ -878,7 +915,7 @@ async function installRemoteHost(ctx, config, profile = process.env.DSH_PROFILE
878
915
  return;
879
916
  }
880
917
  }
881
- if (req.method === "GET" && !pairOnly) {
918
+ if (req.method === "GET" && !issueOnly) {
882
919
  json(res, 200, status(identity));
883
920
  return;
884
921
  }
@@ -892,12 +929,10 @@ async function installRemoteHost(ctx, config, profile = process.env.DSH_PROFILE
892
929
  }
893
930
  try {
894
931
  const input = await body(req);
895
- if (pairOnly) {
896
- const origin = pairOrigin(void 0, input.address);
897
- await runningAccess().startPairing();
932
+ if (issueOnly) {
898
933
  json(res, 200, {
899
934
  ok: true,
900
- ...await pairLink(origin),
935
+ ...deviceLink(deviceOrigin(void 0, input.address), (await runningAccess().add(newDevice(req))).token),
901
936
  expiresAt: null,
902
937
  lanAddresses: addresses()
903
938
  });
@@ -952,19 +987,36 @@ async function installRemoteHost(ctx, config, profile = process.env.DSH_PROFILE
952
987
  } finally {
953
988
  configuring = false;
954
989
  }
955
- } else if (input.action === "startPairing") await runningAccess().startPairing();
956
- else if (input.action === "copyPairLink") {
957
- json(res, 200, await pairLink(pairOrigin(identity)));
990
+ } else if (input.action === "addDevice") {
991
+ const origin = deviceOrigin(identity);
992
+ const created = await runningAccess().add(newDevice(req));
993
+ json(res, 200, {
994
+ ...deviceLink(origin, created.token),
995
+ id: created.device.id
996
+ });
997
+ return;
998
+ } else if (input.action === "copyDeviceLink") {
999
+ const id = deviceIdOf(input);
1000
+ const origin = deviceOrigin(identity);
1001
+ const token = runningAccess().token(id);
1002
+ if (token === null) throw new Error("UNKNOWN_DEVICE");
1003
+ json(res, 200, deviceLink(origin, token));
1004
+ return;
1005
+ } else if (input.action === "reissue") {
1006
+ const id = deviceIdOf(input);
1007
+ const origin = deviceOrigin(identity);
1008
+ const { token } = await runningAccess().reissue(id);
1009
+ gateway?.dropDevice(id);
1010
+ json(res, 200, {
1011
+ ...deviceLink(origin, token),
1012
+ id
1013
+ });
958
1014
  return;
959
- } else if (input.action === "resetPairing") await runningAccess().resetPairing();
960
- else if (input.action === "endPairing") {
961
- if (!access) throw new Error("REMOTE_NOT_RUNNING");
962
- await access.endPairing();
963
1015
  } else if (input.action === "revoke") {
964
- if (typeof input.id !== "string" || !input.id) throw new Error("INVALID_DEVICE");
965
- if (!access) throw new Error("REMOTE_NOT_RUNNING");
966
- if (gateway) await gateway.revoke(input.id);
967
- else await access.revoke(input.id);
1016
+ const id = deviceIdOf(input);
1017
+ if (gateway && access) await gateway.revoke(id);
1018
+ else if (access) await access.revoke(id);
1019
+ else throw new Error("REMOTE_NOT_RUNNING");
968
1020
  } else throw new Error("INVALID_ACTION");
969
1021
  json(res, 200, { ok: true });
970
1022
  } catch (caught) {
@@ -1014,7 +1066,7 @@ async function installRemoteHost(ctx, config, profile = process.env.DSH_PROFILE
1014
1066
  }));
1015
1067
  disposers.push(ws.register({
1016
1068
  kind: "exact",
1017
- path: REMOTE_PAIR_ISSUE_ROUTE,
1069
+ path: REMOTE_DEVICE_ISSUE_ROUTE,
1018
1070
  handler: (req, res) => handle(req, res, true)
1019
1071
  }));
1020
1072
  disposers.push(ws.registerUpgrade({