dsh-lan-guard 0.1.1 → 0.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.
- package/CHANGELOG.md +49 -2
- package/README.md +18 -0
- package/README.zh.md +18 -0
- package/lib/client.js +209 -90
- package/lib/client.js.map +1 -1
- package/lib/index.d.ts +69 -9
- package/lib/index.js +295 -30
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -83,6 +83,7 @@ const Config = z.object({
|
|
|
83
83
|
adminProtection: z.boolean().default(true).volatile(),
|
|
84
84
|
allowLoopback: z.boolean().default(true).volatile(),
|
|
85
85
|
requirePairing: z.boolean().default(true).volatile(),
|
|
86
|
+
requireApproval: z.boolean().default(false).volatile(),
|
|
86
87
|
sessionMaxAgeMs: z.natural().default(2592e6),
|
|
87
88
|
adminSessionMaxAgeMs: z.natural().default(18e5),
|
|
88
89
|
maxFailedAttempts: z.natural().default(5),
|
|
@@ -133,7 +134,8 @@ function liveSwitches(rawConfig, resolved) {
|
|
|
133
134
|
adminPolicy: () => readField(root.auth === void 0 ? void 0 : auth.adminPolicy, resolved.auth.adminPolicy),
|
|
134
135
|
adminProtection: () => readField(root.auth === void 0 ? void 0 : auth.adminProtection, resolved.auth.adminProtection),
|
|
135
136
|
allowLoopback: () => readField(root.auth === void 0 ? void 0 : auth.allowLoopback, resolved.auth.allowLoopback),
|
|
136
|
-
requirePairing: () => readField(root.auth === void 0 ? void 0 : auth.requirePairing, resolved.auth.requirePairing)
|
|
137
|
+
requirePairing: () => readField(root.auth === void 0 ? void 0 : auth.requirePairing, resolved.auth.requirePairing),
|
|
138
|
+
requireApproval: () => readField(root.auth === void 0 ? void 0 : auth.requireApproval, resolved.auth.requireApproval)
|
|
137
139
|
};
|
|
138
140
|
}
|
|
139
141
|
/** Wrap plain values as live switches (used by tests and by callers without a raw config). */
|
|
@@ -146,7 +148,8 @@ function staticSwitches(config) {
|
|
|
146
148
|
adminPolicy: () => config.auth.adminPolicy,
|
|
147
149
|
adminProtection: () => config.auth.adminProtection,
|
|
148
150
|
allowLoopback: () => config.auth.allowLoopback,
|
|
149
|
-
requirePairing: () => config.auth.requirePairing
|
|
151
|
+
requirePairing: () => config.auth.requirePairing,
|
|
152
|
+
requireApproval: () => config.auth.requireApproval
|
|
150
153
|
};
|
|
151
154
|
}
|
|
152
155
|
/** Raised when a config value is syntactically valid but semantically unsafe. */
|
|
@@ -228,7 +231,8 @@ function unwrapVolatileInput(input) {
|
|
|
228
231
|
"adminPolicy",
|
|
229
232
|
"adminProtection",
|
|
230
233
|
"allowLoopback",
|
|
231
|
-
"requirePairing"
|
|
234
|
+
"requirePairing",
|
|
235
|
+
"requireApproval"
|
|
232
236
|
]) {
|
|
233
237
|
const value = auth[key];
|
|
234
238
|
if (isVolatileLike(value)) auth[key] = value.get();
|
|
@@ -261,6 +265,7 @@ function parseConfig(input) {
|
|
|
261
265
|
adminProtection: readField(rawAuth.adminProtection, true),
|
|
262
266
|
allowLoopback: readField(rawAuth.allowLoopback, true),
|
|
263
267
|
requirePairing: readField(rawAuth.requirePairing, true),
|
|
268
|
+
requireApproval: readField(rawAuth.requireApproval, false),
|
|
264
269
|
sessionMaxAgeMs: readField(rawAuth.sessionMaxAgeMs, 2592e6),
|
|
265
270
|
adminSessionMaxAgeMs: readField(rawAuth.adminSessionMaxAgeMs, 18e5),
|
|
266
271
|
maxFailedAttempts: readField(rawAuth.maxFailedAttempts, 5),
|
|
@@ -437,7 +442,11 @@ var SecretsStore = class {
|
|
|
437
442
|
async loadDevices() {
|
|
438
443
|
const parsed = await readJson(this.devicesPath, this.#logger);
|
|
439
444
|
if (parsed === void 0 || !Array.isArray(parsed.devices)) return [];
|
|
440
|
-
return parsed.devices.filter((entry) => typeof entry === "object" && entry !== null && typeof entry.id === "string" && typeof entry.label === "string" && typeof entry.tokenHash === "string")
|
|
445
|
+
return parsed.devices.filter((entry) => typeof entry === "object" && entry !== null && typeof entry.id === "string" && typeof entry.label === "string" && typeof entry.tokenHash === "string").map((entry) => ({
|
|
446
|
+
...entry,
|
|
447
|
+
status: entry.status === "pending" || entry.status === "blocked" ? entry.status : "approved",
|
|
448
|
+
decidedAtMs: entry.decidedAtMs ?? null
|
|
449
|
+
}));
|
|
441
450
|
}
|
|
442
451
|
/** Persist paired devices with mode 600. */
|
|
443
452
|
async saveDevices(devices) {
|
|
@@ -1010,6 +1019,8 @@ function notice(state, lockedUntilMs, now) {
|
|
|
1010
1019
|
return `<p class="notice error">尝试次数过多,该地址已被临时锁定${seconds > 0 ? `,请在约 ${String(seconds)} 秒后重试` : ",请稍后重试"}。</p>`;
|
|
1011
1020
|
}
|
|
1012
1021
|
if (state === "csrf") return "<p class=\"notice error\">请求来源校验未通过,请从本页重新登录。</p>";
|
|
1022
|
+
if (state === "link-inactive") return "<p class=\"notice error\">这条免密链接无效,或当前「仅密码」模式不使用免密链接。<br>请输入访问密码;若希望链接可用,请在运行本程序的电脑上把验证模式改为「令牌 + 密码」。</p>";
|
|
1023
|
+
if (state === "pending-approval") return "<p class=\"notice\">⏳ <strong>这台设备正在等待管理员批准。</strong><br>请在运行本程序的电脑上打开设置 → 局域网访问 → 已授权设备,点「批准」后刷新本页即可进入。</p>";
|
|
1013
1024
|
if (state === "device-removed") return "<p class=\"notice error\"><strong>此设备已被移除访问权限。</strong><br>请联系管理员在「已授权设备」中重新放行,或让管理员删除该记录后重新确认。</p>";
|
|
1014
1025
|
if (state === "token-only") return "<p class=\"notice warn\">当前验证模式为<strong>仅安全 Token</strong>,不接受密码登录。请使用管理员提供的免密链接或二维码。</p>";
|
|
1015
1026
|
if (state === "no-password") return "<p class=\"notice warn\"><strong>尚未设置访问密码。</strong><br>出于安全考虑,未设置密码时门禁不会放行任何设备。请在桌面 DSH 的「设置 → 局域网访问」中设置访问密码。</p>";
|
|
@@ -1023,7 +1034,7 @@ function notice(state, lockedUntilMs, now) {
|
|
|
1023
1034
|
*/
|
|
1024
1035
|
function renderLoginPage(options) {
|
|
1025
1036
|
const now = options.now ?? Date.now();
|
|
1026
|
-
const blocked = options.state === "locked" || options.state === "no-password" || options.state === "device-removed";
|
|
1037
|
+
const blocked = options.state === "locked" || options.state === "no-password" || options.state === "device-removed" || options.state === "pending-approval" || options.state === "link-inactive";
|
|
1027
1038
|
const next = options.next !== void 0 && options.next.startsWith("/") ? options.next : "/";
|
|
1028
1039
|
const modeHint = options.mode === "password" ? "本设备需要输入访问密码。" : options.mode === "token" ? "本设备使用免密链接访问;如已失效,请向管理员索取新的二维码。" : "输入访问密码,或使用管理员提供的免密链接。";
|
|
1029
1040
|
return `<!doctype html>
|
|
@@ -1094,11 +1105,13 @@ var VisitorGate = class {
|
|
|
1094
1105
|
#auth;
|
|
1095
1106
|
#devices;
|
|
1096
1107
|
#requirePairing;
|
|
1108
|
+
#requireApproval;
|
|
1097
1109
|
#logger;
|
|
1098
1110
|
constructor(options) {
|
|
1099
1111
|
this.#auth = options.auth;
|
|
1100
1112
|
this.#devices = options.devices;
|
|
1101
1113
|
this.#requirePairing = options.requirePairing ?? (() => false);
|
|
1114
|
+
this.#requireApproval = options.requireApproval ?? (() => false);
|
|
1102
1115
|
this.#logger = options.logger ?? noopLogger;
|
|
1103
1116
|
}
|
|
1104
1117
|
/**
|
|
@@ -1142,12 +1155,16 @@ var VisitorGate = class {
|
|
|
1142
1155
|
}
|
|
1143
1156
|
const deviceToken = readCookie(req, DEVICE_COOKIE);
|
|
1144
1157
|
if (deviceToken !== void 0) {
|
|
1145
|
-
const device = this.#devices?.
|
|
1146
|
-
if (device === void 0) {
|
|
1147
|
-
this.#logger.warn("refused a revoked or unknown device ip=%s", clientIp(req));
|
|
1158
|
+
const device = this.#devices?.lookup(deviceToken);
|
|
1159
|
+
if (device === void 0 || device.revokedAtMs !== null || device.status === "blocked") {
|
|
1160
|
+
this.#logger.warn("refused a revoked, blocked or unknown device ip=%s", clientIp(req));
|
|
1148
1161
|
this.#sendRemoved(req, res);
|
|
1149
1162
|
return "handled";
|
|
1150
1163
|
}
|
|
1164
|
+
if (device.status === "pending") {
|
|
1165
|
+
this.#sendPending(req, res);
|
|
1166
|
+
return "handled";
|
|
1167
|
+
}
|
|
1151
1168
|
await this.#devices?.touch(device.id, clientIp(req)).catch((error) => {
|
|
1152
1169
|
this.#logger.warn("device touch failed name=%s", error.name);
|
|
1153
1170
|
});
|
|
@@ -1156,17 +1173,26 @@ var VisitorGate = class {
|
|
|
1156
1173
|
const link = url.searchParams.get("auth");
|
|
1157
1174
|
if (link !== null) return await this.#handleAuthLink(req, res, url, link);
|
|
1158
1175
|
const verdict = await this.#auth.verifyRequest(req);
|
|
1159
|
-
if (verdict.ok)
|
|
1160
|
-
if (this.#requirePairing() && verdict.via === "session") {
|
|
1161
|
-
this.#sendPairingPage(req, res);
|
|
1162
|
-
return "handled";
|
|
1163
|
-
}
|
|
1164
|
-
return "allow";
|
|
1165
|
-
}
|
|
1176
|
+
if (verdict.ok) return this.#afterVerdict(req, res, verdict);
|
|
1166
1177
|
this.#sendUnauthorized(req, res, verdict);
|
|
1167
1178
|
return "handled";
|
|
1168
1179
|
}
|
|
1169
1180
|
/**
|
|
1181
|
+
* Apply the pairing requirement to an already-authenticated request.
|
|
1182
|
+
*
|
|
1183
|
+
* Pairing exists to name REMOTE devices; the machine's own operator (loopback)
|
|
1184
|
+
* and a disabled gate never see it. Every authenticated entry point must go
|
|
1185
|
+
* through here — skipping it once left the app half-loaded (HTML 200, bundles
|
|
1186
|
+
* 428) and the page blank.
|
|
1187
|
+
*/
|
|
1188
|
+
#afterVerdict(req, res, verdict) {
|
|
1189
|
+
if (this.#requirePairing() && verdict.via === "session") {
|
|
1190
|
+
this.#sendPairingPage(req, res);
|
|
1191
|
+
return "handled";
|
|
1192
|
+
}
|
|
1193
|
+
return "allow";
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1170
1196
|
* Decide whether an upgrade may proceed.
|
|
1171
1197
|
*
|
|
1172
1198
|
* The caller must have attached its socket error handler BEFORE awaiting
|
|
@@ -1178,14 +1204,18 @@ var VisitorGate = class {
|
|
|
1178
1204
|
async verifyUpgrade(req) {
|
|
1179
1205
|
const deviceToken = readCookie(req, DEVICE_COOKIE);
|
|
1180
1206
|
if (deviceToken !== void 0) {
|
|
1181
|
-
const device = this.#devices?.
|
|
1182
|
-
if (device === void 0) {
|
|
1183
|
-
this.#logger.warn("upgrade refused: revoked device ip=%s", clientIp(req));
|
|
1207
|
+
const device = this.#devices?.lookup(deviceToken);
|
|
1208
|
+
if (device === void 0 || device.revokedAtMs !== null || device.status === "blocked") {
|
|
1209
|
+
this.#logger.warn("upgrade refused: revoked or blocked device ip=%s", clientIp(req));
|
|
1184
1210
|
return {
|
|
1185
1211
|
status: 403,
|
|
1186
1212
|
reason: "device_revoked"
|
|
1187
1213
|
};
|
|
1188
1214
|
}
|
|
1215
|
+
if (device.status === "pending") return {
|
|
1216
|
+
status: 403,
|
|
1217
|
+
reason: "pending_approval"
|
|
1218
|
+
};
|
|
1189
1219
|
await this.#devices?.touch(device.id, clientIp(req)).catch(() => void 0);
|
|
1190
1220
|
return;
|
|
1191
1221
|
}
|
|
@@ -1226,7 +1256,7 @@ var VisitorGate = class {
|
|
|
1226
1256
|
this.#sendPairingPage(req, res, "invalid");
|
|
1227
1257
|
return;
|
|
1228
1258
|
}
|
|
1229
|
-
const { device, token } = await this.#devices.add(label);
|
|
1259
|
+
const { device, token } = await this.#devices.add(label, { pending: this.#requireApproval() });
|
|
1230
1260
|
await this.#devices.touch(device.id, clientIp(req)).catch(() => void 0);
|
|
1231
1261
|
const expiresAtMs = Date.now() + DEVICE_COOKIE_MAX_AGE_MS;
|
|
1232
1262
|
res.writeHead(302, {
|
|
@@ -1259,6 +1289,26 @@ var VisitorGate = class {
|
|
|
1259
1289
|
});
|
|
1260
1290
|
res.end(html);
|
|
1261
1291
|
}
|
|
1292
|
+
/** Serve the waiting page (HTML) or a JSON hint for API calls (F9). */
|
|
1293
|
+
#sendPending(req, res) {
|
|
1294
|
+
if (isApiPath(new URL(req.url ?? "/", "http://dsh-lan-guard.invalid").pathname) || !wantsHtml(req)) {
|
|
1295
|
+
this.#sendJson(res, 403, {
|
|
1296
|
+
ok: false,
|
|
1297
|
+
error: "pending_approval"
|
|
1298
|
+
});
|
|
1299
|
+
return;
|
|
1300
|
+
}
|
|
1301
|
+
const html = renderLoginPage({
|
|
1302
|
+
state: "pending-approval",
|
|
1303
|
+
mode: this.#auth.mode
|
|
1304
|
+
});
|
|
1305
|
+
res.writeHead(403, {
|
|
1306
|
+
"content-type": "text/html; charset=utf-8",
|
|
1307
|
+
"cache-control": "no-store",
|
|
1308
|
+
"referrer-policy": "no-referrer"
|
|
1309
|
+
});
|
|
1310
|
+
res.end(html);
|
|
1311
|
+
}
|
|
1262
1312
|
/** Tell a revoked device it no longer has access. */
|
|
1263
1313
|
#sendRemoved(req, res) {
|
|
1264
1314
|
if (isApiPath(new URL(req.url ?? "/", "http://dsh-lan-guard.invalid").pathname) || !wantsHtml(req)) {
|
|
@@ -1283,8 +1333,9 @@ var VisitorGate = class {
|
|
|
1283
1333
|
async #handleAuthLink(req, res, url, link) {
|
|
1284
1334
|
if (this.#auth.mode === "password") {
|
|
1285
1335
|
const verdict = await this.#auth.verifyRequest(req);
|
|
1286
|
-
if (verdict.ok) return
|
|
1287
|
-
this.#
|
|
1336
|
+
if (verdict.ok) return this.#afterVerdict(req, res, verdict);
|
|
1337
|
+
this.#logger.warn("passwordless link ignored: mode=password ip=%s", clientIp(req));
|
|
1338
|
+
this.#sendLoginPage(req, res, "link-inactive", 401);
|
|
1288
1339
|
return "handled";
|
|
1289
1340
|
}
|
|
1290
1341
|
const masterAccepted = await this.#auth.verifySecretToken(link);
|
|
@@ -1292,8 +1343,8 @@ var VisitorGate = class {
|
|
|
1292
1343
|
if (!(masterAccepted || device !== void 0)) {
|
|
1293
1344
|
this.#logger.warn("passwordless link rejected ip=%s", clientIp(req));
|
|
1294
1345
|
const verdict = await this.#auth.verifyRequest(req);
|
|
1295
|
-
if (verdict.ok) return
|
|
1296
|
-
this.#
|
|
1346
|
+
if (verdict.ok) return this.#afterVerdict(req, res, verdict);
|
|
1347
|
+
this.#sendLoginPage(req, res, "link-inactive", 401);
|
|
1297
1348
|
return "handled";
|
|
1298
1349
|
}
|
|
1299
1350
|
const session = await this.#auth.issueSession();
|
|
@@ -1500,6 +1551,130 @@ function startMdns(options) {
|
|
|
1500
1551
|
}
|
|
1501
1552
|
} };
|
|
1502
1553
|
}
|
|
1554
|
+
/** Registry document that carries the `latest` tag. */
|
|
1555
|
+
const REGISTRY_LATEST_URL = `https://registry.npmjs.org/dsh-lan-guard/latest`;
|
|
1556
|
+
/** Network timeout for the lookup. */
|
|
1557
|
+
const FETCH_TIMEOUT_MS = 5e3;
|
|
1558
|
+
/**
|
|
1559
|
+
* Parse a version string.
|
|
1560
|
+
*
|
|
1561
|
+
* @param value - e.g. `0.1.1`, `0.1.2-rc.1`.
|
|
1562
|
+
* @returns the parsed version, or `undefined` when it is not a version.
|
|
1563
|
+
*/
|
|
1564
|
+
function parseVersion(value) {
|
|
1565
|
+
const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value.trim());
|
|
1566
|
+
if (match === null) return void 0;
|
|
1567
|
+
return {
|
|
1568
|
+
major: Number(match[1]),
|
|
1569
|
+
minor: Number(match[2]),
|
|
1570
|
+
patch: Number(match[3]),
|
|
1571
|
+
prerelease: match[4] === void 0 ? [] : match[4].split(".")
|
|
1572
|
+
};
|
|
1573
|
+
}
|
|
1574
|
+
/** Compare two prerelease identifier lists per semver's precedence rules. */
|
|
1575
|
+
function comparePrerelease(left, right) {
|
|
1576
|
+
if (left.length === 0 && right.length === 0) return 0;
|
|
1577
|
+
if (left.length === 0) return 1;
|
|
1578
|
+
if (right.length === 0) return -1;
|
|
1579
|
+
const length = Math.max(left.length, right.length);
|
|
1580
|
+
for (let index = 0; index < length; index += 1) {
|
|
1581
|
+
const a = left[index];
|
|
1582
|
+
const b = right[index];
|
|
1583
|
+
if (a === void 0) return -1;
|
|
1584
|
+
if (b === void 0) return 1;
|
|
1585
|
+
const aNumber = /^\d+$/.test(a) ? Number(a) : void 0;
|
|
1586
|
+
const bNumber = /^\d+$/.test(b) ? Number(b) : void 0;
|
|
1587
|
+
if (aNumber !== void 0 && bNumber !== void 0) {
|
|
1588
|
+
if (aNumber !== bNumber) return aNumber < bNumber ? -1 : 1;
|
|
1589
|
+
continue;
|
|
1590
|
+
}
|
|
1591
|
+
if (aNumber !== void 0) return -1;
|
|
1592
|
+
if (bNumber !== void 0) return 1;
|
|
1593
|
+
if (a !== b) return a < b ? -1 : 1;
|
|
1594
|
+
}
|
|
1595
|
+
return 0;
|
|
1596
|
+
}
|
|
1597
|
+
/**
|
|
1598
|
+
* Compare two versions.
|
|
1599
|
+
*
|
|
1600
|
+
* @param left - first version.
|
|
1601
|
+
* @param right - second version.
|
|
1602
|
+
* @returns `-1`, `0` or `1`; an unparsable version compares as equal.
|
|
1603
|
+
*/
|
|
1604
|
+
function compareVersions(left, right) {
|
|
1605
|
+
const a = parseVersion(left);
|
|
1606
|
+
const b = parseVersion(right);
|
|
1607
|
+
if (a === void 0 || b === void 0) return 0;
|
|
1608
|
+
if (a.major !== b.major) return a.major < b.major ? -1 : 1;
|
|
1609
|
+
if (a.minor !== b.minor) return a.minor < b.minor ? -1 : 1;
|
|
1610
|
+
if (a.patch !== b.patch) return a.patch < b.patch ? -1 : 1;
|
|
1611
|
+
return comparePrerelease(a.prerelease, b.prerelease);
|
|
1612
|
+
}
|
|
1613
|
+
/** Whether `latest` is newer than `current`. */
|
|
1614
|
+
function isNewer(latest, current) {
|
|
1615
|
+
return compareVersions(latest, current) > 0;
|
|
1616
|
+
}
|
|
1617
|
+
/** Reads the npm registry with a cache; never throws. */
|
|
1618
|
+
var UpdateChecker = class {
|
|
1619
|
+
#currentVersion;
|
|
1620
|
+
#logger;
|
|
1621
|
+
#fetch;
|
|
1622
|
+
#now;
|
|
1623
|
+
#ttlMs;
|
|
1624
|
+
#cached;
|
|
1625
|
+
constructor(options) {
|
|
1626
|
+
this.#currentVersion = options.currentVersion;
|
|
1627
|
+
this.#logger = options.logger ?? noopLogger;
|
|
1628
|
+
this.#fetch = options.fetchImpl ?? fetch;
|
|
1629
|
+
this.#now = options.now ?? (() => Date.now());
|
|
1630
|
+
this.#ttlMs = options.ttlMs ?? 216e5;
|
|
1631
|
+
}
|
|
1632
|
+
/** The version this process is running. */
|
|
1633
|
+
get currentVersion() {
|
|
1634
|
+
return this.#currentVersion;
|
|
1635
|
+
}
|
|
1636
|
+
/**
|
|
1637
|
+
* Look up the latest published version.
|
|
1638
|
+
*
|
|
1639
|
+
* @param options - `force` bypasses the cache.
|
|
1640
|
+
* @returns the status; a failure is reported in `error`, never thrown.
|
|
1641
|
+
*/
|
|
1642
|
+
async check(options = {}) {
|
|
1643
|
+
if (options.force !== true && this.#cached !== void 0) {
|
|
1644
|
+
if (this.#now() - (this.#cached.checkedAtMs ?? 0) < this.#ttlMs) return this.#cached;
|
|
1645
|
+
}
|
|
1646
|
+
let status;
|
|
1647
|
+
try {
|
|
1648
|
+
const response = await this.#fetch(REGISTRY_LATEST_URL, {
|
|
1649
|
+
headers: { accept: "application/json" },
|
|
1650
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
|
|
1651
|
+
});
|
|
1652
|
+
if (!response.ok) throw new Error(`registry ${String(response.status)}`);
|
|
1653
|
+
const body = await response.json();
|
|
1654
|
+
const latest = typeof body.version === "string" ? body.version : null;
|
|
1655
|
+
if (latest === null) throw new Error("registry response had no version");
|
|
1656
|
+
status = {
|
|
1657
|
+
current: this.#currentVersion,
|
|
1658
|
+
latest,
|
|
1659
|
+
hasUpdate: isNewer(latest, this.#currentVersion),
|
|
1660
|
+
checkedAtMs: this.#now(),
|
|
1661
|
+
error: null
|
|
1662
|
+
};
|
|
1663
|
+
if (status.hasUpdate) this.#logger.info("update available current=%s latest=%s", status.current, latest);
|
|
1664
|
+
} catch (error) {
|
|
1665
|
+
this.#logger.warn("update check failed name=%s", error.name);
|
|
1666
|
+
status = {
|
|
1667
|
+
current: this.#currentVersion,
|
|
1668
|
+
latest: null,
|
|
1669
|
+
hasUpdate: false,
|
|
1670
|
+
checkedAtMs: this.#now(),
|
|
1671
|
+
error: "registry_unavailable"
|
|
1672
|
+
};
|
|
1673
|
+
}
|
|
1674
|
+
this.#cached = status;
|
|
1675
|
+
return status;
|
|
1676
|
+
}
|
|
1677
|
+
};
|
|
1503
1678
|
//#endregion
|
|
1504
1679
|
//#region src/network.ts
|
|
1505
1680
|
/**
|
|
@@ -2149,6 +2324,10 @@ function sanitizePreferencePatch(patch) {
|
|
|
2149
2324
|
if (value !== "" && !/^[A-Za-z0-9_.:-]{1,64}$/.test(value)) throw new PreferenceError("networkInterface must be an interface name or an address literal");
|
|
2150
2325
|
result.networkInterface = value;
|
|
2151
2326
|
}
|
|
2327
|
+
if (Object.hasOwn(source, "requireApproval")) {
|
|
2328
|
+
if (typeof source.requireApproval !== "boolean") throw new PreferenceError("requireApproval must be a boolean");
|
|
2329
|
+
result.requireApproval = source.requireApproval;
|
|
2330
|
+
}
|
|
2152
2331
|
if (Object.hasOwn(source, "requirePairing")) {
|
|
2153
2332
|
if (typeof source.requirePairing !== "boolean") throw new PreferenceError("requirePairing must be a boolean");
|
|
2154
2333
|
result.requirePairing = source.requirePairing;
|
|
@@ -2185,6 +2364,7 @@ function toSettingsPatch(values) {
|
|
|
2185
2364
|
if (values.listenPort !== void 0) patch.listenPort = values.listenPort;
|
|
2186
2365
|
if (values.networkInterface !== void 0) patch.networkInterface = values.networkInterface;
|
|
2187
2366
|
if (values.requirePairing !== void 0) auth.requirePairing = values.requirePairing;
|
|
2367
|
+
if (values.requireApproval !== void 0) auth.requireApproval = values.requireApproval;
|
|
2188
2368
|
if (values.mode !== void 0) auth.mode = values.mode;
|
|
2189
2369
|
if (values.adminPolicy !== void 0) auth.adminPolicy = values.adminPolicy;
|
|
2190
2370
|
if (values.adminProtection !== void 0) auth.adminProtection = values.adminProtection;
|
|
@@ -2203,6 +2383,8 @@ function deviceView(device) {
|
|
|
2203
2383
|
return {
|
|
2204
2384
|
id: device.id,
|
|
2205
2385
|
label: device.label,
|
|
2386
|
+
status: device.status,
|
|
2387
|
+
decidedAtMs: device.decidedAtMs,
|
|
2206
2388
|
createdAtMs: device.createdAtMs,
|
|
2207
2389
|
lastSeenAtMs: device.lastSeenAtMs,
|
|
2208
2390
|
lastIp: device.lastIp,
|
|
@@ -2316,7 +2498,8 @@ function registerManagementRoutes(options) {
|
|
|
2316
2498
|
adminPolicy: options.switches.adminPolicy(),
|
|
2317
2499
|
adminProtection: options.switches.adminProtection(),
|
|
2318
2500
|
allowLoopback: options.switches.allowLoopback(),
|
|
2319
|
-
requirePairing: options.switches.requirePairing()
|
|
2501
|
+
requirePairing: options.switches.requirePairing(),
|
|
2502
|
+
requireApproval: options.switches.requireApproval()
|
|
2320
2503
|
},
|
|
2321
2504
|
listener: {
|
|
2322
2505
|
listenHost: options.config.listenHost,
|
|
@@ -2327,7 +2510,8 @@ function registerManagementRoutes(options) {
|
|
|
2327
2510
|
},
|
|
2328
2511
|
authStatus: statusOf(req),
|
|
2329
2512
|
access: await options.access(token ?? null),
|
|
2330
|
-
devices: options.devices.list().map(deviceView)
|
|
2513
|
+
devices: options.devices.list().map(deviceView),
|
|
2514
|
+
pendingCount: options.devices.list().filter((device) => device.status === "pending").length
|
|
2331
2515
|
};
|
|
2332
2516
|
if (token !== void 0) snapshot.secretToken = token;
|
|
2333
2517
|
return snapshot;
|
|
@@ -2555,6 +2739,18 @@ function registerManagementRoutes(options) {
|
|
|
2555
2739
|
return;
|
|
2556
2740
|
}
|
|
2557
2741
|
try {
|
|
2742
|
+
if (body.action === "approve" || body.action === "block" || body.action === "unblock") {
|
|
2743
|
+
if (typeof body.id !== "string") throw new PreferenceError("id must be a string");
|
|
2744
|
+
const status = body.action === "approve" ? "approved" : body.action === "block" ? "blocked" : "pending";
|
|
2745
|
+
const changed = await options.devices.setStatus(body.id, status);
|
|
2746
|
+
sendJson(res, changed ? 200 : 404, {
|
|
2747
|
+
ok: changed,
|
|
2748
|
+
...changed ? {} : { error: "unknown_or_unchanged_device" },
|
|
2749
|
+
devices: options.devices.list().map(deviceView),
|
|
2750
|
+
pendingCount: options.devices.list().filter((device) => device.status === "pending").length
|
|
2751
|
+
});
|
|
2752
|
+
return;
|
|
2753
|
+
}
|
|
2558
2754
|
if (body.action === "delete") {
|
|
2559
2755
|
if (typeof body.id !== "string") throw new PreferenceError("id must be a string");
|
|
2560
2756
|
const removed = await options.devices.remove(body.id);
|
|
@@ -2596,6 +2792,23 @@ function registerManagementRoutes(options) {
|
|
|
2596
2792
|
path: `${MANAGEMENT_BASE}/devices`,
|
|
2597
2793
|
handler: handleDevices
|
|
2598
2794
|
}));
|
|
2795
|
+
/**
|
|
2796
|
+
* Update detection (SPEC F8). Read-only: it reports what npm has and the
|
|
2797
|
+
* settings page offers a copyable command — the host never installs anything.
|
|
2798
|
+
*/
|
|
2799
|
+
disposers.push(options.webServer.register({
|
|
2800
|
+
kind: "exact",
|
|
2801
|
+
path: `${MANAGEMENT_BASE}/update`,
|
|
2802
|
+
handler: async (req, res) => {
|
|
2803
|
+
if (refusedByFence(req, res)) return;
|
|
2804
|
+
const url = new URL(req.url ?? "/", "http://dsh-lan-guard.invalid");
|
|
2805
|
+
const status = await options.updates.check({ force: url.searchParams.get("force") === "1" });
|
|
2806
|
+
sendJson(res, 200, {
|
|
2807
|
+
ok: true,
|
|
2808
|
+
...status
|
|
2809
|
+
});
|
|
2810
|
+
}
|
|
2811
|
+
}));
|
|
2599
2812
|
disposers.push(options.webServer.register({
|
|
2600
2813
|
kind: "exact",
|
|
2601
2814
|
path: `${MANAGEMENT_BASE}/port-check`,
|
|
@@ -2664,6 +2877,16 @@ var DeviceRegistry = class {
|
|
|
2664
2877
|
async init() {
|
|
2665
2878
|
this.#devices = await this.#store.loadDevices();
|
|
2666
2879
|
}
|
|
2880
|
+
/** The device behind a cookie, whatever its state (used for the gate's pages). */
|
|
2881
|
+
lookup(token) {
|
|
2882
|
+
if (!isDeviceToken(token)) return void 0;
|
|
2883
|
+
const presented = Buffer.from(hashToken(token), "utf8");
|
|
2884
|
+
for (const device of this.#devices) {
|
|
2885
|
+
const stored = Buffer.from(device.tokenHash, "utf8");
|
|
2886
|
+
if (stored.byteLength !== presented.byteLength) continue;
|
|
2887
|
+
if (timingSafeEqual(stored, presented)) return device;
|
|
2888
|
+
}
|
|
2889
|
+
}
|
|
2667
2890
|
/** Active and revoked devices, newest first. */
|
|
2668
2891
|
list() {
|
|
2669
2892
|
return [...this.#devices].sort((left, right) => right.createdAtMs - left.createdAtMs);
|
|
@@ -2678,7 +2901,7 @@ var DeviceRegistry = class {
|
|
|
2678
2901
|
* @param label - operator-facing name.
|
|
2679
2902
|
* @returns the stored record plus the plaintext token.
|
|
2680
2903
|
*/
|
|
2681
|
-
async add(label) {
|
|
2904
|
+
async add(label, options = {}) {
|
|
2682
2905
|
const token = `${DEVICE_TOKEN_PREFIX}${randomBytes(18).toString("hex")}`;
|
|
2683
2906
|
const device = {
|
|
2684
2907
|
id: randomBytes(4).toString("hex"),
|
|
@@ -2687,7 +2910,9 @@ var DeviceRegistry = class {
|
|
|
2687
2910
|
createdAtMs: this.#now(),
|
|
2688
2911
|
lastSeenAtMs: null,
|
|
2689
2912
|
lastIp: null,
|
|
2690
|
-
revokedAtMs: null
|
|
2913
|
+
revokedAtMs: null,
|
|
2914
|
+
status: options.pending === true ? "pending" : "approved",
|
|
2915
|
+
decidedAtMs: options.pending === true ? null : this.#now()
|
|
2691
2916
|
};
|
|
2692
2917
|
this.#devices = [...this.#devices, device];
|
|
2693
2918
|
await this.#store.saveDevices(this.#devices);
|
|
@@ -2728,17 +2953,39 @@ var DeviceRegistry = class {
|
|
|
2728
2953
|
await this.#store.saveDevices(this.#devices);
|
|
2729
2954
|
return true;
|
|
2730
2955
|
}
|
|
2956
|
+
/** Set a device's F9 state (approve / block / unblock). */
|
|
2957
|
+
async setStatus(id, status) {
|
|
2958
|
+
const target = this.#devices.find((device) => device.id === id);
|
|
2959
|
+
if (target === void 0 || target.status === status) return false;
|
|
2960
|
+
this.#devices = this.#devices.map((device) => device.id === id ? {
|
|
2961
|
+
...device,
|
|
2962
|
+
status,
|
|
2963
|
+
decidedAtMs: this.#now(),
|
|
2964
|
+
revokedAtMs: null
|
|
2965
|
+
} : device);
|
|
2966
|
+
await this.#store.saveDevices(this.#devices);
|
|
2967
|
+
this.#logger.info("device status changed id=%s status=%s", id, status);
|
|
2968
|
+
return true;
|
|
2969
|
+
}
|
|
2970
|
+
/** How many devices are waiting for approval. */
|
|
2971
|
+
get pendingCount() {
|
|
2972
|
+
return this.#devices.filter((device) => device.status === "pending").length;
|
|
2973
|
+
}
|
|
2731
2974
|
/**
|
|
2732
2975
|
* Verify a presented device token.
|
|
2733
2976
|
*
|
|
2977
|
+
* Only `approved` devices authenticate: a `pending` one is not refused as an
|
|
2978
|
+
* intruder (the gate shows it the waiting page) and a `blocked` one never
|
|
2979
|
+
* gets in again, even after re-pairing with the password.
|
|
2980
|
+
*
|
|
2734
2981
|
* @param token - the `?auth=` value.
|
|
2735
|
-
* @returns the matching
|
|
2982
|
+
* @returns the matching approved device, or `undefined`.
|
|
2736
2983
|
*/
|
|
2737
2984
|
verify(token) {
|
|
2738
2985
|
if (!isDeviceToken(token)) return void 0;
|
|
2739
2986
|
const presented = Buffer.from(hashToken(token), "utf8");
|
|
2740
2987
|
for (const device of this.#devices) {
|
|
2741
|
-
if (device.revokedAtMs !== null) continue;
|
|
2988
|
+
if (device.revokedAtMs !== null || device.status !== "approved") continue;
|
|
2742
2989
|
const stored = Buffer.from(device.tokenHash, "utf8");
|
|
2743
2990
|
if (stored.byteLength !== presented.byteLength) continue;
|
|
2744
2991
|
if (timingSafeEqual(stored, presented)) return device;
|
|
@@ -3170,6 +3417,16 @@ const inject = ["webServer", "connection"];
|
|
|
3170
3417
|
* @param rawConfig - the Loader config for this entry.
|
|
3171
3418
|
* @returns the running runtime, or `undefined` when the plugin is switched off.
|
|
3172
3419
|
*/
|
|
3420
|
+
/** Read the plugin's own version (used by the update check). */
|
|
3421
|
+
async function readPackageVersion() {
|
|
3422
|
+
try {
|
|
3423
|
+
const raw = await readFile(new URL("../package.json", import.meta.url), "utf8");
|
|
3424
|
+
const parsed = JSON.parse(raw);
|
|
3425
|
+
return typeof parsed.version === "string" ? parsed.version : "0.0.0";
|
|
3426
|
+
} catch {
|
|
3427
|
+
return "0.0.0";
|
|
3428
|
+
}
|
|
3429
|
+
}
|
|
3173
3430
|
async function startLanGuard(host, rawConfig) {
|
|
3174
3431
|
const logger = host.logger ?? noopLogger;
|
|
3175
3432
|
const config = parseConfig(rawConfig);
|
|
@@ -3194,10 +3451,15 @@ async function startLanGuard(host, rawConfig) {
|
|
|
3194
3451
|
logger
|
|
3195
3452
|
});
|
|
3196
3453
|
await devices.init();
|
|
3454
|
+
const updates = new UpdateChecker({
|
|
3455
|
+
currentVersion: await readPackageVersion(),
|
|
3456
|
+
logger
|
|
3457
|
+
});
|
|
3197
3458
|
const gate = new VisitorGate({
|
|
3198
3459
|
auth,
|
|
3199
3460
|
devices,
|
|
3200
3461
|
requirePairing: () => switches.requirePairing(),
|
|
3462
|
+
requireApproval: () => switches.requireApproval(),
|
|
3201
3463
|
logger
|
|
3202
3464
|
});
|
|
3203
3465
|
const upstreamAuth = new UpstreamAuth({
|
|
@@ -3246,7 +3508,8 @@ async function startLanGuard(host, rawConfig) {
|
|
|
3246
3508
|
port: () => proxy.port,
|
|
3247
3509
|
portFallback: () => proxy.portFallback
|
|
3248
3510
|
},
|
|
3249
|
-
devices
|
|
3511
|
+
devices,
|
|
3512
|
+
updates
|
|
3250
3513
|
});
|
|
3251
3514
|
if (proxy.portFallback) logger.warn("configured port %d was taken; listening on %d instead", proxy.requestedPort, proxy.port);
|
|
3252
3515
|
logger.info("listening host=%s port=%d upstream=%s tls=%s gate=%s mode=%s", proxy.host, proxy.port, config.upstreamOrigin, config.tls.mode, switches.enabled() ? "on" : "off", switches.mode());
|
|
@@ -3254,6 +3517,7 @@ async function startLanGuard(host, rawConfig) {
|
|
|
3254
3517
|
proxy,
|
|
3255
3518
|
auth,
|
|
3256
3519
|
devices,
|
|
3520
|
+
updates,
|
|
3257
3521
|
async close() {
|
|
3258
3522
|
mdns?.stop();
|
|
3259
3523
|
disposeManagement?.();
|
|
@@ -3333,6 +3597,7 @@ async function apply(ctx, rawConfig) {
|
|
|
3333
3597
|
access: deps.access,
|
|
3334
3598
|
listener: deps.listener,
|
|
3335
3599
|
devices: deps.devices,
|
|
3600
|
+
updates: deps.updates,
|
|
3336
3601
|
logger: deps.logger
|
|
3337
3602
|
})
|
|
3338
3603
|
}, rawConfig);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-lan-guard",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "DSH web plugin: expose the official desktop Web UI to the local network through a gated reverse proxy, without touching DSH's own loopback binding.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|