printer-doctor 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +171 -2
- package/package.json +48 -4
- package/src/index.js +112 -0
- package/src/lib/cups.js +237 -0
- package/src/lib/diagnose.js +439 -0
- package/src/lib/gather.js +317 -0
- package/src/lib/ipp.js +283 -0
- package/src/lib/mdns.js +385 -0
- package/src/lib/net.js +236 -0
- package/src/lib/report.js +130 -0
- package/src/lib/run.js +52 -0
- package/src/lib/text.js +27 -0
- package/src/lib/windows.js +173 -0
package/src/lib/mdns.js
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
// Finds printers that announce themselves on the home network (the way AirPrint and most
|
|
2
|
+
// modern printers do), with mDNS / DNS-SD (RFC 6762 and 6763) in plain JavaScript.
|
|
3
|
+
//
|
|
4
|
+
// One short question is sent to the standard mDNS group address, which only reaches devices on
|
|
5
|
+
// the same home network, and the answers are collected for a couple of seconds. The question
|
|
6
|
+
// goes out two ways: once the standard way (printers answer to the whole group, which is what a
|
|
7
|
+
// real Brother printer was seen to do), and once from a temporary port asking for a direct reply
|
|
8
|
+
// (which gets through firewalls that drop group traffic).
|
|
9
|
+
import dgram from "node:dgram";
|
|
10
|
+
|
|
11
|
+
import { isPrivateAddress, isLoopback } from "./net.js";
|
|
12
|
+
import { cleanText, cleanOrNull } from "./text.js";
|
|
13
|
+
|
|
14
|
+
/** The standard mDNS group address. Not a host: every device on the local network listens on it. */
|
|
15
|
+
export const MDNS_GROUP = "224.0.0.251";
|
|
16
|
+
export const MDNS_PORT = 5353;
|
|
17
|
+
|
|
18
|
+
/** The ways a printer can announce itself, best first. */
|
|
19
|
+
export const SERVICES = [
|
|
20
|
+
{ type: "ipps", labels: ["_ipps", "_tcp", "local"] },
|
|
21
|
+
{ type: "ipp", labels: ["_ipp", "_tcp", "local"] },
|
|
22
|
+
{ type: "raw", labels: ["_pdl-datastream", "_tcp", "local"] },
|
|
23
|
+
{ type: "lpd", labels: ["_printer", "_tcp", "local"] },
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
const TYPE = { A: 1, PTR: 12, TXT: 16, AAAA: 28, SRV: 33 };
|
|
27
|
+
|
|
28
|
+
// ---------- wire format ------------------------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
function encodeName(labels) {
|
|
31
|
+
const parts = [];
|
|
32
|
+
for (const label of labels) {
|
|
33
|
+
const b = Buffer.from(label, "utf8");
|
|
34
|
+
if (!b.length || b.length > 63) throw new Error("bad label");
|
|
35
|
+
parts.push(Buffer.from([b.length]), b);
|
|
36
|
+
}
|
|
37
|
+
parts.push(Buffer.from([0]));
|
|
38
|
+
return Buffer.concat(parts);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A query for the given [{ labels, type }] questions. `direct` asks for the reply to come
|
|
43
|
+
* straight back to the sender instead of to the whole group.
|
|
44
|
+
*/
|
|
45
|
+
export function encodeQuery(questions, { direct = true } = {}) {
|
|
46
|
+
const head = Buffer.alloc(12);
|
|
47
|
+
head.writeUInt16BE(questions.length, 4);
|
|
48
|
+
const parts = [head];
|
|
49
|
+
for (const q of questions) {
|
|
50
|
+
const tail = Buffer.alloc(4);
|
|
51
|
+
tail.writeUInt16BE(TYPE[q.type], 0);
|
|
52
|
+
tail.writeUInt16BE(direct ? 0x8001 : 0x0001, 2); // class IN, with or without the "reply directly to me" bit
|
|
53
|
+
parts.push(encodeName(q.labels), tail);
|
|
54
|
+
}
|
|
55
|
+
return Buffer.concat(parts);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Reads a name at pos. Names can point back into the message to save space; the limits on jumps
|
|
60
|
+
* and on total length make sure a name that points at itself ends in an error, not a loop.
|
|
61
|
+
*/
|
|
62
|
+
function readName(buf, start) {
|
|
63
|
+
const labels = [];
|
|
64
|
+
let pos = start;
|
|
65
|
+
let end = null;
|
|
66
|
+
let jumps = 0;
|
|
67
|
+
let total = 0;
|
|
68
|
+
for (;;) {
|
|
69
|
+
if (pos >= buf.length) throw new Error("name runs past the end");
|
|
70
|
+
const len = buf[pos];
|
|
71
|
+
if (len === 0) {
|
|
72
|
+
pos += 1;
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
if ((len & 0xc0) === 0xc0) {
|
|
76
|
+
if (pos + 1 >= buf.length) throw new Error("pointer runs past the end");
|
|
77
|
+
const target = ((len & 0x3f) << 8) | buf[pos + 1];
|
|
78
|
+
if (end === null) end = pos + 2;
|
|
79
|
+
if (target >= pos || ++jumps > 32) throw new Error("bad name pointer");
|
|
80
|
+
pos = target;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (len & 0xc0) throw new Error("bad label");
|
|
84
|
+
if (pos + 1 + len > buf.length) throw new Error("label runs past the end");
|
|
85
|
+
total += len + 1;
|
|
86
|
+
if (total > 255) throw new Error("name too long");
|
|
87
|
+
labels.push(buf.toString("utf8", pos + 1, pos + 1 + len));
|
|
88
|
+
pos += 1 + len;
|
|
89
|
+
}
|
|
90
|
+
return [labels, end ?? pos];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function readTxt(raw) {
|
|
94
|
+
const out = Object.create(null);
|
|
95
|
+
let pos = 0;
|
|
96
|
+
while (pos < raw.length) {
|
|
97
|
+
const len = raw[pos];
|
|
98
|
+
if (pos + 1 + len > raw.length) break;
|
|
99
|
+
const s = raw.toString("utf8", pos + 1, pos + 1 + len);
|
|
100
|
+
pos += 1 + len;
|
|
101
|
+
const eq = s.indexOf("=");
|
|
102
|
+
if (eq > 0) out[s.slice(0, eq).toLowerCase()] = s.slice(eq + 1);
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const v6 = (raw) => {
|
|
108
|
+
const groups = [];
|
|
109
|
+
for (let i = 0; i < 16; i += 2) groups.push(raw.readUInt16BE(i).toString(16));
|
|
110
|
+
return groups.join(":");
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* One mDNS message -> { response, records: [{ name: [labels], type, ... }] }. Record types this
|
|
115
|
+
* tool has no use for are skipped. Throws on a message that is cut off or malformed.
|
|
116
|
+
*/
|
|
117
|
+
export function decodeMessage(buf) {
|
|
118
|
+
if (!Buffer.isBuffer(buf) || buf.length < 12) throw new Error("message too short");
|
|
119
|
+
const response = (buf[2] & 0x80) !== 0;
|
|
120
|
+
const questions = buf.readUInt16BE(4);
|
|
121
|
+
const total = buf.readUInt16BE(6) + buf.readUInt16BE(8) + buf.readUInt16BE(10);
|
|
122
|
+
if (questions > 64 || total > 512) throw new Error("too many records");
|
|
123
|
+
let pos = 12;
|
|
124
|
+
for (let i = 0; i < questions; i++) {
|
|
125
|
+
pos = readName(buf, pos)[1] + 4;
|
|
126
|
+
if (pos > buf.length) throw new Error("question runs past the end");
|
|
127
|
+
}
|
|
128
|
+
const records = [];
|
|
129
|
+
for (let i = 0; i < total; i++) {
|
|
130
|
+
const [name, after] = readName(buf, pos);
|
|
131
|
+
if (after + 10 > buf.length) throw new Error("record runs past the end");
|
|
132
|
+
const type = buf.readUInt16BE(after);
|
|
133
|
+
const len = buf.readUInt16BE(after + 8);
|
|
134
|
+
const start = after + 10;
|
|
135
|
+
const end = start + len;
|
|
136
|
+
if (end > buf.length) throw new Error("record data runs past the end");
|
|
137
|
+
pos = end;
|
|
138
|
+
if (type === TYPE.PTR) records.push({ name, type: "PTR", target: readName(buf, start)[0] });
|
|
139
|
+
else if (type === TYPE.SRV && len >= 7) records.push({ name, type: "SRV", port: buf.readUInt16BE(start + 4), target: readName(buf, start + 6)[0] });
|
|
140
|
+
else if (type === TYPE.TXT) records.push({ name, type: "TXT", txt: readTxt(buf.subarray(start, end)) });
|
|
141
|
+
else if (type === TYPE.A && len === 4) records.push({ name, type: "A", address: [...buf.subarray(start, end)].join(".") });
|
|
142
|
+
else if (type === TYPE.AAAA && len === 16) records.push({ name, type: "AAAA", address: v6(buf.subarray(start, end)) });
|
|
143
|
+
}
|
|
144
|
+
return { response, records };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// ---------- putting the answers together -------------------------------------------------------
|
|
148
|
+
|
|
149
|
+
/** The IPP path a printer announces ("ipp/print"), only if it is a plain path; otherwise null. */
|
|
150
|
+
const safePath = (rp) => {
|
|
151
|
+
const p = `/${String(rp || "").replace(/^\/+/, "")}`;
|
|
152
|
+
return p.length > 1 && /^[A-Za-z0-9._~/-]{2,64}$/.test(p) && !p.includes("..") ? p : null;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
const key = (labels) => labels.join("\u0000").toLowerCase();
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Collects records from many replies and turns them into a list of printers:
|
|
159
|
+
* [{ instance, host, addresses, services: [{ type, port, path }], model, uuid }]
|
|
160
|
+
*/
|
|
161
|
+
export class Announcements {
|
|
162
|
+
/**
|
|
163
|
+
* allowLoopback is for tests that run a pretend printer on this computer. Normally an
|
|
164
|
+
* announcement that claims a printer lives at this computer's own address is not believed:
|
|
165
|
+
* a device on the network must not be able to point this tool at the computer itself.
|
|
166
|
+
*/
|
|
167
|
+
constructor({ allowLoopback = false } = {}) {
|
|
168
|
+
this.allowLoopback = allowLoopback;
|
|
169
|
+
this.instances = new Map(); // key(instance labels) -> { labels, type, srv, txt }
|
|
170
|
+
this.hosts = new Map(); // key(host labels) -> Set(address)
|
|
171
|
+
this.sources = new Map(); // key(instance labels) -> address the reply came from
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
add(records, from = null) {
|
|
175
|
+
for (const r of records) {
|
|
176
|
+
if (r.type === "PTR") {
|
|
177
|
+
const service = SERVICES.find((s) => key(s.labels) === key(r.name));
|
|
178
|
+
if (!service || r.target.length !== service.labels.length + 1) continue;
|
|
179
|
+
this.#instance(r.target, service.type);
|
|
180
|
+
} else if (r.type === "SRV" || r.type === "TXT") {
|
|
181
|
+
const service = SERVICES.find((s) => key(s.labels) === key(r.name.slice(1)));
|
|
182
|
+
if (!service) continue;
|
|
183
|
+
const inst = this.#instance(r.name, service.type);
|
|
184
|
+
if (r.type === "SRV") {
|
|
185
|
+
inst.srv = { port: r.port, host: r.target };
|
|
186
|
+
if (from && (this.allowLoopback || !isLoopback(from))) this.sources.set(key(r.name), from);
|
|
187
|
+
} else inst.txt = r.txt;
|
|
188
|
+
} else if (r.type === "A" || r.type === "AAAA") {
|
|
189
|
+
// Only addresses inside a home network are kept; an fe80 address is useless without its interface.
|
|
190
|
+
if (!isPrivateAddress(r.address) || /^fe80/i.test(r.address)) continue;
|
|
191
|
+
if (isLoopback(r.address) && !this.allowLoopback) continue;
|
|
192
|
+
const k = key(r.name);
|
|
193
|
+
if (!this.hosts.has(k)) this.hosts.set(k, new Set());
|
|
194
|
+
this.hosts.get(k).add(r.address);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
#instance(labels, type) {
|
|
200
|
+
const k = key(labels);
|
|
201
|
+
if (!this.instances.has(k)) this.instances.set(k, { labels, type, srv: null, txt: null });
|
|
202
|
+
return this.instances.get(k);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Questions still worth asking: details of instances, and addresses of their hosts. */
|
|
206
|
+
missing() {
|
|
207
|
+
const out = [];
|
|
208
|
+
for (const inst of this.instances.values()) {
|
|
209
|
+
if (!inst.srv) out.push({ labels: inst.labels, type: "SRV" }, { labels: inst.labels, type: "TXT" });
|
|
210
|
+
else if (!this.hosts.has(key(inst.srv.host))) out.push({ labels: inst.srv.host, type: "A" });
|
|
211
|
+
}
|
|
212
|
+
return out;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
printers() {
|
|
216
|
+
const byName = new Map();
|
|
217
|
+
for (const [k, inst] of this.instances) {
|
|
218
|
+
const name = cleanText(inst.labels[0]);
|
|
219
|
+
if (!name) continue;
|
|
220
|
+
const id = name.toLowerCase();
|
|
221
|
+
if (!byName.has(id)) byName.set(id, { instance: name, host: null, addresses: [], services: [], model: null, uuid: null });
|
|
222
|
+
const p = byName.get(id);
|
|
223
|
+
const txt = inst.txt || {};
|
|
224
|
+
if (inst.srv) {
|
|
225
|
+
// Port 0 means "this service is listed but not offered" (RFC 6763, section 6.1).
|
|
226
|
+
if (inst.srv.port > 0) p.services.push({ type: inst.type, port: inst.srv.port, path: safePath(txt.rp) });
|
|
227
|
+
p.host = p.host || cleanText(inst.srv.host.join("."), 255);
|
|
228
|
+
const known = this.hosts.get(key(inst.srv.host));
|
|
229
|
+
const addrs = known ? [...known] : this.sources.has(k) ? [this.sources.get(k)] : [];
|
|
230
|
+
for (const a of addrs) if (!p.addresses.includes(a)) p.addresses.push(a);
|
|
231
|
+
}
|
|
232
|
+
const model = txt.ty || (txt.product ? String(txt.product).replace(/^\(|\)$/g, "") : null) || ([txt.usb_mfg, txt.usb_mdl].filter(Boolean).join(" ") || null);
|
|
233
|
+
p.model = p.model || cleanOrNull(model);
|
|
234
|
+
p.uuid = p.uuid || (/^[0-9a-f-]{8,64}$/i.test(String(txt.uuid || "")) ? String(txt.uuid).toLowerCase() : null);
|
|
235
|
+
}
|
|
236
|
+
const order = SERVICES.map((s) => s.type);
|
|
237
|
+
const list = [...byName.values()];
|
|
238
|
+
for (const p of list) {
|
|
239
|
+
p.addresses.sort((a, b) => Number(a.includes(":")) - Number(b.includes(":"))); // IPv4 first
|
|
240
|
+
p.services.sort((a, b) => order.indexOf(a.type) - order.indexOf(b.type));
|
|
241
|
+
}
|
|
242
|
+
return list.filter((p) => p.services.length).sort((a, b) => a.instance.localeCompare(b.instance));
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// ---------- asking the network -----------------------------------------------------------------
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Asks the local network which printers are there and waits a couple of seconds for answers.
|
|
250
|
+
* localAddresses this computer's addresses on the home network; the question goes out of each
|
|
251
|
+
* listen also listen on the mDNS port for answers sent to the whole group
|
|
252
|
+
* allowLoopback believe an announcement that points at this computer itself (tests only)
|
|
253
|
+
* Replies from addresses outside a home network are ignored. Never throws.
|
|
254
|
+
* Resolves with { printers, heard } where heard is the number of devices that answered anything.
|
|
255
|
+
*/
|
|
256
|
+
export function browse({ localAddresses = [], timeoutMs = 3000, group = MDNS_GROUP, port = MDNS_PORT, listen = true, allowLoopback = false } = {}) {
|
|
257
|
+
const found = new Announcements({ allowLoopback });
|
|
258
|
+
const asked = new Set();
|
|
259
|
+
const responders = new Set();
|
|
260
|
+
const sockets = [];
|
|
261
|
+
let messages = 0;
|
|
262
|
+
let closed = false;
|
|
263
|
+
const services = SERVICES.map((s) => ({ labels: s.labels, type: "PTR" }));
|
|
264
|
+
const locals = (localAddresses.length ? localAddresses : [null]).slice(0, 3);
|
|
265
|
+
|
|
266
|
+
// What to do with every packet that arrives. `followUp` sends further questions the same way
|
|
267
|
+
// the first one went: straight to the device, or to the group.
|
|
268
|
+
const onMessage = (followUp) => (buf, rinfo) => {
|
|
269
|
+
if (closed || !isPrivateAddress(rinfo.address) || buf.length > 9000 || ++messages > 3000) return;
|
|
270
|
+
let msg;
|
|
271
|
+
try {
|
|
272
|
+
msg = decodeMessage(buf);
|
|
273
|
+
} catch {
|
|
274
|
+
return; // not a readable mDNS message
|
|
275
|
+
}
|
|
276
|
+
if (!msg.response) return; // other devices' questions (and our own, echoed back)
|
|
277
|
+
responders.add(rinfo.address);
|
|
278
|
+
found.add(msg.records, rinfo.address);
|
|
279
|
+
// Ask for whatever the first answer left out (a printer's port and address often are).
|
|
280
|
+
const more = found.missing().filter((q) => {
|
|
281
|
+
const id = `${q.type}:${key(q.labels)}`;
|
|
282
|
+
if (asked.has(id) || asked.size > 200) return false;
|
|
283
|
+
asked.add(id);
|
|
284
|
+
return true;
|
|
285
|
+
});
|
|
286
|
+
for (let i = 0; i < more.length; i += 8) {
|
|
287
|
+
try {
|
|
288
|
+
followUp(more.slice(i, i + 8), rinfo);
|
|
289
|
+
} catch {
|
|
290
|
+
/* a name that can't be asked about is skipped */
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
const tune = (sock, local) => {
|
|
296
|
+
try {
|
|
297
|
+
if (local) sock.setMulticastInterface(local); // out of the home network's interface, not a VPN
|
|
298
|
+
sock.setMulticastTTL(1); // never past the local network
|
|
299
|
+
} catch {
|
|
300
|
+
/* the default interface will do */
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
const thrice = (send) => {
|
|
304
|
+
const go = () => {
|
|
305
|
+
if (closed) return;
|
|
306
|
+
try {
|
|
307
|
+
send();
|
|
308
|
+
} catch {
|
|
309
|
+
/* the socket went away */
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
go();
|
|
313
|
+
// Again, in case the first one was lost, and once more for a printer that is slow to wake up
|
|
314
|
+
// (on a real Mac a sleeping printer missed the first round and answered a later one).
|
|
315
|
+
setTimeout(go, 700).unref?.();
|
|
316
|
+
setTimeout(go, 1700).unref?.();
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
// A temporary port, asking each device to answer directly.
|
|
320
|
+
const direct = (local) =>
|
|
321
|
+
new Promise((resolve) => {
|
|
322
|
+
const sock = dgram.createSocket({ type: "udp4" });
|
|
323
|
+
sockets.push(sock);
|
|
324
|
+
sock.on("error", () => resolve());
|
|
325
|
+
sock.on(
|
|
326
|
+
"message",
|
|
327
|
+
onMessage((qs, rinfo) => sock.send(encodeQuery(qs), rinfo.port, rinfo.address, () => {})),
|
|
328
|
+
);
|
|
329
|
+
const ready = () => {
|
|
330
|
+
tune(sock, local);
|
|
331
|
+
thrice(() => sock.send(encodeQuery(services), port, group, () => {}));
|
|
332
|
+
resolve();
|
|
333
|
+
};
|
|
334
|
+
try {
|
|
335
|
+
if (local) sock.bind(0, local, ready);
|
|
336
|
+
else sock.bind(0, ready);
|
|
337
|
+
} catch {
|
|
338
|
+
resolve();
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
// The mDNS port itself, shared with the system's own mDNS service, to hear answers sent to the
|
|
343
|
+
// whole group. If the port can't be shared on this computer, the direct question still works.
|
|
344
|
+
const shared = (local) =>
|
|
345
|
+
new Promise((resolve) => {
|
|
346
|
+
const sock = dgram.createSocket({ type: "udp4", reuseAddr: true });
|
|
347
|
+
sockets.push(sock);
|
|
348
|
+
sock.on("error", () => resolve());
|
|
349
|
+
sock.on(
|
|
350
|
+
"message",
|
|
351
|
+
onMessage((qs) => sock.send(encodeQuery(qs, { direct: false }), port, group, () => {})),
|
|
352
|
+
);
|
|
353
|
+
try {
|
|
354
|
+
sock.bind(port, () => {
|
|
355
|
+
try {
|
|
356
|
+
if (local) sock.addMembership(group, local);
|
|
357
|
+
else sock.addMembership(group);
|
|
358
|
+
} catch {
|
|
359
|
+
return resolve(); // no group traffic on this interface
|
|
360
|
+
}
|
|
361
|
+
tune(sock, local);
|
|
362
|
+
thrice(() => sock.send(encodeQuery(services, { direct: false }), port, group, () => {}));
|
|
363
|
+
resolve();
|
|
364
|
+
});
|
|
365
|
+
} catch {
|
|
366
|
+
resolve();
|
|
367
|
+
}
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
return new Promise((resolve) => {
|
|
371
|
+
Promise.all(locals.flatMap((l) => (listen ? [direct(l), shared(l)] : [direct(l)]))).then(() => {
|
|
372
|
+
setTimeout(() => {
|
|
373
|
+
closed = true;
|
|
374
|
+
for (const s of sockets) {
|
|
375
|
+
try {
|
|
376
|
+
s.close();
|
|
377
|
+
} catch {
|
|
378
|
+
/* already closed or never opened */
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
resolve({ printers: found.printers(), heard: responders.size });
|
|
382
|
+
}, timeoutMs);
|
|
383
|
+
});
|
|
384
|
+
});
|
|
385
|
+
}
|
package/src/lib/net.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// Network facts about this computer: its addresses, whether a VPN carries its traffic, and
|
|
2
|
+
// which addresses belong to a home network. Also the one rule that keeps this tool at home:
|
|
3
|
+
// isPrivateAddress(). Nothing outside those ranges is ever contacted.
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import net from "node:net";
|
|
7
|
+
import dns from "node:dns";
|
|
8
|
+
|
|
9
|
+
import { run } from "./run.js";
|
|
10
|
+
|
|
11
|
+
const PLATFORM = process.platform;
|
|
12
|
+
const now = () => performance.now();
|
|
13
|
+
|
|
14
|
+
// ---------- which addresses are "at home" -----------------------------------------------------
|
|
15
|
+
|
|
16
|
+
const v4Parts = (ip) => (net.isIPv4(ip) ? ip.split(".").map(Number) : null);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* True for addresses that only exist inside a home or office network (or on this computer):
|
|
20
|
+
* 10.x, 172.16 to 172.31, 192.168.x, 169.254.x (self-assigned), 127.x, and the IPv6 equivalents
|
|
21
|
+
* (fc00::/7, fe80::/10, ::1). Everything else is on the internet and is never contacted.
|
|
22
|
+
*/
|
|
23
|
+
export function isPrivateAddress(ip) {
|
|
24
|
+
const s = String(ip || "").replace(/%.*$/, "");
|
|
25
|
+
const p = v4Parts(s);
|
|
26
|
+
if (p) {
|
|
27
|
+
const [a, b] = p;
|
|
28
|
+
return a === 10 || a === 127 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254);
|
|
29
|
+
}
|
|
30
|
+
if (!net.isIPv6(s)) return false;
|
|
31
|
+
const low = s.toLowerCase();
|
|
32
|
+
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(low);
|
|
33
|
+
if (mapped) return isPrivateAddress(mapped[1]);
|
|
34
|
+
if (low === "::1") return true;
|
|
35
|
+
const first = parseInt(low.split(":")[0] || "0", 16);
|
|
36
|
+
return (first & 0xfe00) === 0xfc00 || (first & 0xffc0) === 0xfe80;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const isLoopback = (ip) => /^127\./.test(String(ip)) || ip === "::1" || ip === "localhost";
|
|
40
|
+
|
|
41
|
+
const toInt = (ip) => {
|
|
42
|
+
const p = v4Parts(ip);
|
|
43
|
+
return p ? ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]) >>> 0 : null;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** Is this IPv4 address inside one of this computer's own networks? null when it can't be told. */
|
|
47
|
+
export function onSameNetwork(ip, interfaces) {
|
|
48
|
+
const target = toInt(ip);
|
|
49
|
+
if (target === null) return null;
|
|
50
|
+
const nets = (interfaces?.list || []).filter((a) => a.family === "IPv4" && a.netmask && !isVpnName(a.name));
|
|
51
|
+
if (!nets.length) return null;
|
|
52
|
+
return nets.some((a) => {
|
|
53
|
+
const mask = toInt(a.netmask);
|
|
54
|
+
const mine = toInt(a.address);
|
|
55
|
+
if (mask === null || mine === null) return false;
|
|
56
|
+
return ((target & mask) >>> 0) === ((mine & mask) >>> 0);
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ---------- interfaces and VPNs ---------------------------------------------------------------
|
|
61
|
+
|
|
62
|
+
const VPN_NAME =
|
|
63
|
+
/^(utun|tun|tap|wg|ppp|ipsec|tailscale|zt|nordlynx|proton|mullvad|cscotun|gpd)|vpn|wireguard|tailscale|openvpn|wintun|tap-windows|nordlynx|anyconnect|globalprotect|pangp|zerotier|forti|zscaler|warp/i;
|
|
64
|
+
|
|
65
|
+
export const isVpnName = (name) => VPN_NAME.test(String(name || ""));
|
|
66
|
+
|
|
67
|
+
const isGlobalV6 = (a) => !/^(fe80|fc|fd|::1|::$)/i.test(a);
|
|
68
|
+
|
|
69
|
+
/** Addresses this computer has, without the internal loopback ones. */
|
|
70
|
+
export function getInterfaces(ifaces = os.networkInterfaces()) {
|
|
71
|
+
const list = [];
|
|
72
|
+
for (const [name, addrs] of Object.entries(ifaces)) {
|
|
73
|
+
for (const a of addrs || []) {
|
|
74
|
+
if (a.internal) continue;
|
|
75
|
+
list.push({ name, family: a.family === 4 ? "IPv4" : a.family === 6 ? "IPv6" : a.family, address: a.address, netmask: a.netmask || null });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const v4 = list.filter((a) => a.family === "IPv4");
|
|
79
|
+
const usableV4 = v4.filter((a) => !a.address.startsWith("169.254."));
|
|
80
|
+
// Tunnels that carry a real address. macOS always has a few utun interfaces with only
|
|
81
|
+
// link-local addresses; those are system plumbing, not a VPN someone turned on.
|
|
82
|
+
const tunnels = [...new Set(list.filter((a) => isVpnName(a.name) && (a.family === "IPv4" || isGlobalV6(a.address))).map((a) => a.name))];
|
|
83
|
+
return {
|
|
84
|
+
list,
|
|
85
|
+
hasAny: usableV4.length > 0 || list.some((a) => a.family === "IPv6" && isGlobalV6(a.address)),
|
|
86
|
+
tunnels,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The addresses of this computer that face a home network: IPv4, private, not a VPN. The one on
|
|
92
|
+
* the interface that leads to the router comes first.
|
|
93
|
+
*/
|
|
94
|
+
export function homeAddresses(interfaces, routerIface = null) {
|
|
95
|
+
const list = (interfaces?.list || []).filter((a) => a.family === "IPv4" && isPrivateAddress(a.address) && !a.address.startsWith("127.") && !isVpnName(a.name));
|
|
96
|
+
return [...list.filter((a) => a.name === routerIface), ...list.filter((a) => a.name !== routerIface)].map((a) => a.address);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ---------- routes (readers) ------------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
const hexToIPv4 = (hex) => {
|
|
102
|
+
const n = parseInt(hex, 16);
|
|
103
|
+
return [n & 0xff, (n >>> 8) & 0xff, (n >>> 16) & 0xff, (n >>> 24) & 0xff].join(".");
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Linux /proc/net/route. Returns the default routes (and the two half-routes some VPNs use)
|
|
108
|
+
* lowest metric first: [{ iface, gateway (IPv4 or null), metric, split }].
|
|
109
|
+
*/
|
|
110
|
+
export function parseProcRoute(text) {
|
|
111
|
+
const out = [];
|
|
112
|
+
for (const line of String(text).split("\n").slice(1)) {
|
|
113
|
+
const f = line.trim().split(/\s+/);
|
|
114
|
+
if (f.length < 8) continue;
|
|
115
|
+
const [iface, dest, gw, flags, , , metric, mask] = f;
|
|
116
|
+
const up = (parseInt(flags, 16) & 0x1) !== 0;
|
|
117
|
+
if (!up) continue;
|
|
118
|
+
const isDefault = dest === "00000000" && mask === "00000000";
|
|
119
|
+
const isSplit = mask === "00000080" && (dest === "00000000" || dest === "00000080");
|
|
120
|
+
if (!isDefault && !isSplit) continue;
|
|
121
|
+
const gateway = gw === "00000000" ? null : hexToIPv4(gw);
|
|
122
|
+
out.push({ iface, gateway, metric: Number(metric) || 0, split: isSplit });
|
|
123
|
+
}
|
|
124
|
+
return out.sort((a, b) => a.metric - b.metric);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* macOS `netstat -rn -f inet`. Returns the default routes (and the 0/1 + 128.0/1 halves some VPNs
|
|
129
|
+
* use) in table order: [{ gateway (IPv4 or null for link#N), flags, iface, scoped, split }].
|
|
130
|
+
* A scoped line (flag I) is a per-interface default; an unscoped one is what traffic actually takes.
|
|
131
|
+
*/
|
|
132
|
+
export function parseNetstatDarwin(text) {
|
|
133
|
+
const out = [];
|
|
134
|
+
for (const line of String(text).split("\n")) {
|
|
135
|
+
const f = line.trim().split(/\s+/);
|
|
136
|
+
const split = f[0] === "0/1" || f[0] === "128.0/1";
|
|
137
|
+
if ((f[0] !== "default" && !split) || f.length < 4) continue;
|
|
138
|
+
const [, gw, flags, iface] = f;
|
|
139
|
+
out.push({ gateway: net.isIPv4(gw) ? gw : null, flags, iface, scoped: flags.includes("I"), split });
|
|
140
|
+
}
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Windows `route print -4`. Reads rows by shape, not by heading, so any display language works.
|
|
146
|
+
* Returns active routes for the default route and the VPN halves, lowest metric first:
|
|
147
|
+
* [{ gateway (IPv4 or null when "On-link"), ifaceIp, metric, split }].
|
|
148
|
+
*/
|
|
149
|
+
export function parseRoutePrintWin(text) {
|
|
150
|
+
const out = [];
|
|
151
|
+
for (const line of String(text).split(/\r?\n/)) {
|
|
152
|
+
// Active rows: destination, mask, gateway, interface address, metric. The gateway can be a
|
|
153
|
+
// translated word of more than one token ("On-link", "Auf Verbindung"). Persistent rows have
|
|
154
|
+
// no interface column, so they fail the five-column test.
|
|
155
|
+
const f = line.trim().split(/\s+/);
|
|
156
|
+
if (f.length < 5) continue;
|
|
157
|
+
const [dest, mask] = f;
|
|
158
|
+
const ifaceIp = f[f.length - 2];
|
|
159
|
+
const metric = f[f.length - 1];
|
|
160
|
+
const gw = f.slice(2, -2).join(" ");
|
|
161
|
+
if (!net.isIPv4(dest) || !net.isIPv4(mask) || !net.isIPv4(ifaceIp) || !/^\d+$/.test(metric)) continue;
|
|
162
|
+
const isDefault = dest === "0.0.0.0" && mask === "0.0.0.0";
|
|
163
|
+
const isSplit = mask === "128.0.0.0" && (dest === "0.0.0.0" || dest === "128.0.0.0");
|
|
164
|
+
if (!isDefault && !isSplit) continue;
|
|
165
|
+
out.push({ gateway: net.isIPv4(gw) ? gw : null, ifaceIp, metric: Number(metric), split: isSplit });
|
|
166
|
+
}
|
|
167
|
+
return out.sort((a, b) => a.metric - b.metric);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Where traffic leaves this computer: { primaryIface, viaVpn, routerIface, vpnIfaces }.
|
|
172
|
+
* Only used to tell whether a VPN carries the traffic and which interface faces the home router.
|
|
173
|
+
*/
|
|
174
|
+
export async function getRoutes(interfaces = getInterfaces()) {
|
|
175
|
+
const out = { primaryIface: null, viaVpn: false, routerIface: null, vpnIfaces: interfaces.tunnels };
|
|
176
|
+
try {
|
|
177
|
+
let rows = [];
|
|
178
|
+
if (PLATFORM === "linux") {
|
|
179
|
+
rows = parseProcRoute(fs.readFileSync("/proc/net/route", "utf8"));
|
|
180
|
+
} else if (PLATFORM === "darwin") {
|
|
181
|
+
const r = await run("netstat", ["-rn", "-f", "inet"], { timeoutMs: 8000 });
|
|
182
|
+
rows = parseNetstatDarwin(r.stdout);
|
|
183
|
+
// An unscoped default is what traffic actually takes; put those first.
|
|
184
|
+
rows = [...rows.filter((x) => x.split), ...rows.filter((x) => !x.split && !x.scoped), ...rows.filter((x) => !x.split && x.scoped)];
|
|
185
|
+
} else if (PLATFORM === "win32") {
|
|
186
|
+
const r = await run("route", ["print", "-4"], { timeoutMs: 8000 });
|
|
187
|
+
const byIp = new Map(interfaces.list.filter((a) => a.family === "IPv4").map((a) => [a.address, a.name]));
|
|
188
|
+
rows = parseRoutePrintWin(r.stdout).map((x) => ({ ...x, iface: byIp.get(x.ifaceIp) || x.ifaceIp }));
|
|
189
|
+
}
|
|
190
|
+
const primary = rows.find((x) => x.split) || rows.find((x) => !x.split);
|
|
191
|
+
const phys = rows.find((x) => !x.split && x.gateway && !isVpnName(x.iface));
|
|
192
|
+
out.primaryIface = primary?.iface || null;
|
|
193
|
+
out.routerIface = phys?.iface || null;
|
|
194
|
+
} catch {
|
|
195
|
+
/* without a route table the report simply says nothing about VPNs */
|
|
196
|
+
}
|
|
197
|
+
out.viaVpn = Boolean(out.primaryIface && isVpnName(out.primaryIface));
|
|
198
|
+
if (out.viaVpn && !out.vpnIfaces.includes(out.primaryIface)) out.vpnIfaces = [...out.vpnIfaces, out.primaryIface];
|
|
199
|
+
return out;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ---------- reaching a printer ----------------------------------------------------------------
|
|
203
|
+
|
|
204
|
+
/** One TCP connection attempt, closed straight away. A refusal still proves the device answered. */
|
|
205
|
+
export function tcpConnect(host, port, timeoutMs = 2000) {
|
|
206
|
+
return new Promise((resolve) => {
|
|
207
|
+
const t0 = now();
|
|
208
|
+
const sock = net.connect({ host, port });
|
|
209
|
+
const done = (answered, state) => {
|
|
210
|
+
sock.destroy();
|
|
211
|
+
resolve({ port, answered, state, ms: answered ? Math.round(now() - t0) : null });
|
|
212
|
+
};
|
|
213
|
+
sock.setTimeout(timeoutMs, () => done(false, "timeout"));
|
|
214
|
+
sock.once("connect", () => done(true, "open"));
|
|
215
|
+
sock.once("error", (e) => (e.code === "ECONNREFUSED" ? done(true, "refused") : done(false, e.code || "error")));
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Looks a printer's network name up through the system (which also understands .local names on
|
|
221
|
+
* most computers) and returns only private addresses, IPv4 first. Never throws.
|
|
222
|
+
*/
|
|
223
|
+
export async function resolvePrivate(host) {
|
|
224
|
+
if (net.isIP(host)) return isPrivateAddress(host) ? { addresses: [host], publicOnly: false } : { addresses: [], publicOnly: true };
|
|
225
|
+
try {
|
|
226
|
+
const all = await Promise.race([
|
|
227
|
+
dns.promises.lookup(host, { all: true }),
|
|
228
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 4000).unref?.()),
|
|
229
|
+
]);
|
|
230
|
+
const priv = all.filter((a) => isPrivateAddress(a.address) && !/^fe80/i.test(a.address));
|
|
231
|
+
priv.sort((a, b) => a.family - b.family);
|
|
232
|
+
return { addresses: priv.map((a) => a.address), publicOnly: all.length > 0 && priv.length === 0 };
|
|
233
|
+
} catch {
|
|
234
|
+
return { addresses: [], publicOnly: false };
|
|
235
|
+
}
|
|
236
|
+
}
|