Skip to content

feat: add device discovery (subnet TCP sweep + mDNS) - #18

Merged
Shinrai merged 11 commits into
nextfrom
feat/device-discovery
Sep 3, 2026
Merged

Shinrai merged 11 commits into
nextfrom
feat/device-discovery

Conversation

@cldmv-bot

@cldmv-bot cldmv-bot Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

🚀 What's Changed

💥 Breaking Changes

No breaking changes

✨ Features

🐛 Bug Fixes

📦 Dependencies

No dependency updates

🔧 Other Changes

No other changes

👥 Contributors

Adds src/api/discover.mjs per the two decided mechanisms on issue #5:

- subnet(cidr, port, options): a CIDR-bounded TCP-connect sweep for
  classic fixed-port devices, with bounded concurrency and a maxHosts
  safety ceiling.
- mdns(options): a hand-written mDNS client (no dependency, per the
  issue's evaluation of multicast-dns) for wireless-debugging-advertised
  devices - builds a PTR query, parses PTR/SRV/TXT/A answers including
  DNS name-compression-pointer decoding, and correlates them into
  {name, host, port, txt} entries. address/port are overridable so
  callers (and tests) can target a specific responder instead of the
  real multicast group.

Real-device validation is out of scope here, same posture as the rest
of droidsock's protocol work - tracked by #1.

Closes #5.
@cldmv-bot cldmv-bot Bot added area: core Touches core library / runtime source code area: tests Touches test files, fixtures, or test infrastructure labels Sep 2, 2026
@Shinrai
Shinrai requested a lite review from Copilot September 2, 2026 23:54

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The mDNS implementation and record-ingestion logic have correctness issues that can prevent default multicast discovery from working reliably and can yield false positives on real networks.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Adds a new discover API module to DroidSock to find ADB-capable devices either by sweeping a subnet for a reachable TCP port (classic adb connect flow) or by querying mDNS for _adb-tls-connect._tcp.local-style wireless-debugging advertisements, with accompanying Vitest coverage and API-surface assertions.

Changes:

  • Introduces src/api/discover.mjs with discover.subnet() (CIDR sweep with bounded concurrency) and discover.mdns() (PTR query + response parsing/correlation).
  • Adds a dedicated test suite for both discovery modes (tests/discover.test.vitest.mjs).
  • Extends the public API surface test to require the new discover module and its two functions.
File summaries
File Description
tests/discover.test.vitest.mjs Adds integration-style tests for subnet TCP sweep and mDNS parsing using real loopback TCP/UDP sockets.
tests/api-surface.test.vitest.mjs Updates API surface expectations to include discover and verifies subnet/mdns are functions.
src/api/discover.mjs Implements subnet sweep and mDNS discovery, including DNS name encoding/decoding and record ingestion logic.
Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 3
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/api/discover.mjs Resolved
Comment thread src/api/discover.mjs Resolved
Comment thread tests/discover.test.vitest.mjs Resolved
Three issues from Copilot review on PR #18:

- ingestDnsRecords() created a device entry from a lone SRV/TXT record
  even without a matching PTR - since joining the multicast group means
  this socket also receives every other service's mDNS traffic on the
  segment, that turned unrelated announcements into false-positive
  "devices". SRV/TXT now only update an entry a PTR record introduced.
- mdns() always bound its socket to an ephemeral port. A compliant
  responder replies via multicast back to address:port, not to the
  querier's source port, so the real multicast path now binds to that
  port; a direct-unicast target (tests, or a caller pointing at a
  specific responder) still uses an ephemeral bind to avoid a same-host
  port clash.
- tests/discover.test.vitest.mjs's afterEach() closed UDP sockets
  without awaiting completion, a source of flakiness across runs since
  dgram.Socket.close() is async - now awaited like the TCP servers
  right above it.

Adds a regression test for the SRV/TXT-without-PTR case.
@Shinrai

Shinrai commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Resolves #5 — closed when this ships to the default branch.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new discovery implementation has correctness issues in TXT record parsing and multicast address detection that can produce wrong results or miss responses for valid configurations.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (2)

Previously missed (2) — in code that hasn't changed since the last review.

src/api/discover.mjs:74

  • parseCidr() rejects a /0 prefix even though /0 is a valid CIDR; this makes the prefix-validation error message inaccurate and prevents callers from relying on standard CIDR semantics. If the intent is to guard against huge ranges, maxHosts already enforces that, so it’s better to accept /0 and compute its range explicitly (avoiding the JS bit-shift edge case for hostBits=32).
    src/api/discover.mjs:288
  • TXT record parsing treats a zero-length TXT entry (commonly used to represent an empty TXT record) as a key of "" (empty string) set to true. This produces incorrect TXT objects (e.g., { "": true }) and can leak into discovery results when a device advertises no TXT data; it should instead ignore zero-length entries and reject truncated entries.
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread src/api/discover.mjs Resolved
Follow-up Copilot review on PR #18 (1 new thread + 2 previously-suppressed
findings against the original commit):

- isMulticastAddress() now checks the whole 224.0.0.0-239.255.255.255
  range instead of just the "224." and "239." boundary prefixes -
  225.x-238.x addresses were being misdetected as unicast and bound to
  an ephemeral port, missing real responses.
- TXT record parsing now skips a zero-length entry (RFC 6763's "no TXT
  data" marker) instead of recording it as a bogus {"": true}, and stops
  at a truncated entry (a length byte claiming more bytes than remain in
  the record) instead of reading past the record's bounds.
- parseCidr() accepts /0 as valid CIDR syntax (computed directly, since
  JS's `<<` treats a shift of 32 as a no-op) rather than rejecting it as
  an invalid prefix - maxHosts already guards against actually sweeping
  it.

Adds regression tests for the /0 and TXT-parsing cases.
@Shinrai

Shinrai commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Re: the two suppressed findings on review #5096831419 (both against code unchanged since the original commit) — both addressed in 48de1a7:

  • src/api/discover.mjs (parseCidr) — /0 is now accepted as valid CIDR syntax, computed directly (JS's << treats a shift of 32 as a no-op, so the general mask math can't represent it) rather than rejected as an invalid prefix. maxHosts already guards against anyone actually trying to sweep it.
  • src/api/discover.mjs (TXT record parsing) — a zero-length entry is now skipped instead of recorded as {"": true}, and a truncated entry (length byte claiming more bytes than remain in the record) now stops parsing there instead of reading past the record's bounds.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new discovery module introduces fixable security and input-validation problems that should be addressed before merge.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (3)

Previously missed (1) — in code that hasn't changed since the last review.

src/api/discover.mjs:175

  • subnet() accepts user-provided port, timeoutMs, concurrency, and maxHosts without validation. concurrency <= 0 can silently skip all connect attempts (returning [] even when hosts are reachable) or throw on negative values; invalid ports/timeouts can also throw unexpectedly deeper in net.Socket. Add basic input validation up front.

src/api/discover.mjs:395

  • New result entries initialize txt with {}; for the same reason as TXT parsing, this should be a null-prototype object to prevent prototype pollution via TXT keys.
			results.set(instanceName, { name: instanceName, txt: {} });

src/api/discover.mjs:413

  • Merging TXT data via object spread creates a new normal object (reintroducing Object.prototype) and will treat __proto__ specially. Prefer mutating the existing null-prototype entry.txt via Object.assign to preserve safety and avoid prototype pollution.
			entry.txt = { ...entry.txt, ...record.data };
  • Files reviewed: 3/3 changed files
  • Comments generated: 2
  • Review effort level: Lite

Comment thread src/api/discover.mjs Resolved
Comment thread src/api/discover.mjs Resolved
…plit

Third Copilot review on PR #18 (2 new threads + 3 suppressed findings, 2
of which are the same underlying issue the first new thread already
cross-referenced at two other locations):

- TXT key/value objects (readDnsRecord's parsing, ingestDnsRecords' entry
  creation) are now Object.create(null) instead of {} - a plain object
  lets a TXT key like "__proto__" interact with Object.prototype's
  accessor. The TXT merge step now uses Object.assign() to mutate the
  existing null-proto object in place instead of `{...entry.txt,
  ...record.data}`, since spread always produces a normal
  Object.prototype-based object regardless of the source's prototype -
  reintroducing the exact risk the null-proto objects exist to avoid.
- parseCidr() now validates the "/"-split has exactly 2 parts and the
  prefix is a plain digit string, rejecting inputs like
  "1.2.3.4/24/extra" (extra segments silently dropped by destructuring)
  and "1.2.3.4/" (empty prefix coerced to 0 via Number("")).
- subnet() now validates port/timeoutMs/concurrency/maxHosts up front -
  concurrency <= 0 previously spawned zero sweep workers and silently
  resolved to [] even when hosts were reachable.

Adds regression tests for all three.
@Shinrai

Shinrai commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Re: the suppressed finding on review #5096927627 at src/api/discover.mjs:175 (subnet()'s unvalidated options) — addressed in bcb5063: port, timeoutMs, concurrency, and maxHosts are now all validated up front. The concurrency <= 0 case in particular was a silent-wrong-result bug, not just a missing throw — it spawned zero sweep workers and resolved to [] even when hosts were reachable. Added regression tests for all four.

(The other two suppressed findings on that same review, at lines 395/413, are the same __proto__/null-prototype issue as the open thread on line 288 — addressed together, see the reply there.)

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

mDNS host resolution can fail when A records arrive before SRV in separate messages, and mdns() lacks basic input validation for port/timeout, both of which can cause incorrect or surprising discovery behavior.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (2)

Previously missed (1) — in code that hasn't changed since the last review.

src/api/discover.mjs:434

  • ingestDnsRecords() only consults A records present in the current message when resolving an SRV target to an IP. If an A record arrives in an earlier message (common with larger mDNS payloads) and the SRV arrives later, the host will never resolve because addresses is rebuilt per-message. Keep a per-mdns-call address cache and consult it when folding SRV records so host resolution works regardless of message ordering.

This issue also appears on line 481 of the same file.

src/api/discover.mjs:483

  • mdns() needs to pass a per-call address cache into ingestDnsRecords(); otherwise SRV records can’t resolve to an IP when the A record was received in an earlier message. Add an address cache Map in mdns() and pass it to ingestDnsRecords().
	const socket = dgram.createSocket({ type: "udp4", reuseAddr: true });
	const results = new Map();
	let settled = false;
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread src/api/discover.mjs Resolved
…daries

Fourth Copilot review on PR #18 (1 new thread + 2 suppressed findings,
the latter two being the same underlying issue):

- mdns() accepted invalid port/timeoutMs with no validation, unlike
  subnet(). Now validates both up front, matching subnet()'s behavior.
  Also marks mdns() itself async so a validation throw becomes a proper
  rejected promise for non-await callers, rather than a synchronous
  throw out of a function that otherwise always returns a Promise.
- ingestDnsRecords() rebuilt its A-record address cache fresh on every
  UDP message, so an SRV record could never resolve to a host if its A
  record arrived in an earlier, separate message (a real possibility
  once a response is split across multiple packets). The cache is now
  owned by mdns() and persists for the lifetime of one discovery call,
  passed into ingestDnsRecords() instead of being rebuilt per-message.

Adds regression tests for both.
@Shinrai

Shinrai commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Re: the suppressed finding on review #5096979097 at src/api/discover.mjs:434/483 (address cache rebuilt per-message) — good catch, addressed in 33770b1: the A-record address cache is now created once in mdns() and passed into ingestDnsRecords(), persisting for the whole discovery call instead of being rebuilt from scratch on every UDP message. An SRV record now resolves correctly even when its A record arrived in an earlier, separate message. Added a regression test exercising that ordering.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The mDNS A-record parsing and caching should reject malformed rdlengths to avoid incorrect host resolution, and several tests should assert the null-prototype TXT hardening consistently to prevent regressions.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (4)

Previously missed (1) — in code that hasn't changed since the last review.

tests/discover.test.vitest.mjs:234

  • mdns() returns TXT maps as null-prototype objects for prototype-pollution hardening, but this assertion uses a plain object literal, which can let a regression back to Object.prototype-based TXT objects slip by depending on deep-equality semantics. Make the expected TXT explicitly null-prototype.

This issue also appears in the following locations of the same file:

  • line 328
  • line 419

src/api/discover.mjs:418

  • ingestDnsRecords() unconditionally caches every A record; combined with the current A parsing, a malformed A record could overwrite a previously cached valid address. Cache only when the parsed A data is a valid IPv4 string.
		if (record.type === DNS_TYPE_A) addresses.set(record.name, record.data);

tests/discover.test.vitest.mjs:328

  • This expectation uses a plain object literal for txt, but the API returns null-prototype TXT maps. Making the expected value null-prototype ensures the test will fail if the hardening regresses.
		expect(results).toEqual([{ name: instanceName, host: "10.0.0.5", port: 4321, txt: { a: "1" } }]);

tests/discover.test.vitest.mjs:419

  • This test expects txt: {} but mdns() produces an empty null-prototype TXT object when no TXT record was received. Using Object.create(null) here makes the test assert the intended hardening behavior consistently.
		expect(results).toEqual([{ name: instanceName, host: "10.0.0.7", port: 6789, txt: {} }]);
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread src/api/discover.mjs Resolved
Sixth Copilot review on PR #18 (1 new thread + 4 suppressed findings,
2 of which duplicate the new thread):

- readDnsRecord() joins whatever bytes an A record's rdata holds
  regardless of rdlength, so a malformed/hostile record (rdlength != 4)
  could produce a wrong-shaped host string and, worse, silently
  overwrite a previously-cached valid address for the same hostname.
  The address cache now only accepts A data that passes isValidIP().
- tests/discover.test.vitest.mjs's null-prototype TXT assertions
  (3 locations) used toEqual() against a plain-object literal - verified
  empirically that toEqual doesn't compare prototypes, so a regression
  back to a plain {} would still pass silently. Added an explicit
  Object.getPrototypeOf(...) === null check alongside each, which is
  what actually catches that regression (the review's literal suggestion
  of just using a null-proto expected value wouldn't have).

Adds regression tests for the malformed-A-record case, including that
it can't clobber an already-resolved valid address.
@Shinrai

Shinrai commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Re: the suppressed findings on review #5097068370 — all addressed in 34c3df4:

  • src/api/discover.mjs:418 (unvalidated A-record caching) — same root cause as the open thread on this review; see the reply there.
  • tests/discover.test.vitest.mjs:234/328/419 (null-prototype TXT assertions) — I checked this one empirically first: toEqual doesn't compare prototypes in either direction, so simply making the expected value null-prototype (the literal suggestion) wouldn't actually catch a regression back to a plain {} — a quick scratch test confirmed a plain-object actual still passes toEqual against a null-proto expected. Added an explicit Object.getPrototypeOf(results[0].txt)).toBeNull() assertion alongside each of the three instead, which does catch it.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

There are correctness/reliability issues to address (notably multicast mDNS TTL handling and a test helper’s DNS label length encoding).

Review details

Suppressed comments (2)

Previously missed (2) — in code that hasn't changed since the last review.

src/api/discover.mjs:541

  • When sending to the multicast mDNS group, the outgoing packet should be sent with an IP TTL of 255 (RFC 6762). Node's default multicast TTL is typically 1, and compliant mDNS responders may ignore queries not sent with TTL=255, making mdns() unreliable on strict networks.
    tests/discover.test.vitest.mjs:140
  • encodeName() uses label.length for the DNS label length byte, but that counts UTF-16 code units rather than the UTF-8 byte length that ends up on the wire. This can build invalid names for non-ASCII instance/service names and diverges from discover.mjs's encodeDnsName implementation.
  • Files reviewed: 3/3 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Seventh Copilot review on PR #18 (2 suppressed findings, no new threads):

- mdns() now calls socket.setMulticastTTL(255) before sending its query,
  per RFC 6762 section 11 - a querier not sending TTL 255 risks being
  ignored by strict responders. Node's platform default multicast TTL
  is typically 1. Harmless on the direct-unicast test path, since it
  only governs multicast-destined packets.
- tests/discover.test.vitest.mjs's encodeName() test helper length-
  prefixed each DNS label with the source string's .length (UTF-16 code
  units) instead of its UTF-8 byte length, diverging from discover.mjs's
  own (correct) encodeDnsName and producing a malformed encoding for any
  non-ASCII label. Fixed to match; added a regression test with a
  non-ASCII instance name round-tripping through mdns().
@Shinrai

Shinrai commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Re: the suppressed findings on review #5097317166 — both addressed in 945491a:

  • src/api/discover.mjs:541 (mDNS multicast TTL) — mdns() now calls socket.setMulticastTTL(255) before sending its query, per RFC 6762 section 11. Node's platform-default multicast TTL is typically 1, which risks being ignored by strict responders.
  • tests/discover.test.vitest.mjs:140 (encodeName()'s label length) — the test helper was length-prefixing labels with the source string's .length (UTF-16 code units) instead of the actual UTF-8 byte length, diverging from discover.mjs's own correct encodeDnsName. Fixed to match, and added a regression test with a non-ASCII instance name ("Café Device ☕...") round-tripping through mdns() — this would have failed under the old buggy helper.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The new DNS/TXT encoding helpers contain spec-level length-byte issues that can produce malformed packets for non-ASCII/long labels, which should be fixed before merging.

Review details

Suppressed comments (2)

Previously missed (2) — in code that hasn't changed since the last review.

src/api/discover.mjs:231

  • encodeDnsName() writes the label length byte directly from labelBuf.length without validating DNS label/name size limits. If a caller passes a label >63 bytes (or overall name >255 bytes), the encoded message becomes invalid (and for lengths >255 the single-byte length wraps), which can lead to hard-to-debug discovery failures.
    tests/discover.test.vitest.mjs:188
  • buildMdnsResponse() encodes TXT strings using entry.length (UTF-16 code units) for the length byte, but the DNS TXT length is a byte count of the UTF-8 payload. This makes the helper generate malformed packets when TXT keys/values contain non-ASCII characters.
  • Files reviewed: 3/3 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

…st helper

Eighth Copilot review on PR #18 (2 suppressed findings, no new threads):

- encodeDnsName() wrote a label's length byte straight from its byte
  count with no bound - a label's length byte top two bits are reserved
  for compression-pointer signaling (RFC 1035 3.1), so only 0-63 is a
  valid literal-label length, and Buffer.from([n]) silently truncates
  n>255 to a byte. A caller-controlled serviceType exceeding either
  limit would corrupt the encoded message in a way no receiver (our own
  decodeDnsName included) could recover from. Both limits are now
  enforced with a clear thrown error.
- That throw needed to happen somewhere an async caller can catch it:
  moved the buildPtrQuery() call out of the bind callback (dgram's
  event-emission machinery, outside any try/catch - a throw there could
  crash the process) to the top of mdns(), alongside the existing
  port/timeoutMs validation, so the async function wrapper turns it into
  a normal rejection.
- tests/discover.test.vitest.mjs's buildMdnsResponse() had the same
  UTF-16-vs-UTF-8 length bug as encodeName() (fixed last round) in its
  TXT-entry encoding. Fixed to match.

Adds regression tests for all three.
@Shinrai

Shinrai commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Re: the suppressed findings on review #5097416943 — both addressed in 94b1c4e:

  • src/api/discover.mjs:231 (encodeDnsName label/name limits) — a label's length byte's top two bits are reserved for compression-pointer signaling (RFC 1035 3.1), so only 0-63 is valid, and Buffer.from([n]) silently truncates n>255 to a byte. Both limits are now enforced with a clear thrown error. Also moved the buildPtrQuery() call out of the bind callback (unprotected dgram event-emission context) to the top of mdns(), so this throw — and any future one from this path — becomes a normal promise rejection instead of risking an uncaught exception.
  • tests/discover.test.vitest.mjs:188 (buildMdnsResponse()'s TXT encoding) — same UTF-16-vs-UTF-8 length bug as encodeName() fixed last round, just in the TXT-entry path. Fixed to match.

Added regression tests for all three (label >63 bytes, name >255 bytes, non-ASCII TXT value round-trip).

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The new UDP-based tests currently rely on datagram ordering, which is not guaranteed and can cause CI flakiness unless the send sequencing is made deterministic.

Review details

Suppressed comments (2)

Previously missed (1) — in code that hasn't changed since the last review.

tests/discover.test.vitest.mjs:520

  • This test relies on UDP datagrams arriving in the same order they’re sent (A cached first, then SRV). UDP does not guarantee ordering, so this can be flaky on some runners/kernels. Make the second send happen from the callback of the first (optionally scheduled with setImmediate) so the test deterministically enqueues SRV only after the first packet has been handed to the OS.

This issue also appears on line 599 of the same file.

tests/discover.test.vitest.mjs:603

  • This test assumes the ‘good A’ datagram is processed before the later malformed A datagram. UDP ordering isn’t guaranteed, so the malformed packet could arrive first and (depending on timing) make the test flaky. Send the second packet from the first send’s callback (optionally via setImmediate) to make the enqueue order deterministic.
			responder.send(Buffer.concat([header1, ptrRecord, srvRecord, goodARecord]), rinfo.port, rinfo.address);

			// Second, separate message: a malformed A record for the same
			// hostname - must not clobber the already-cached valid address.
			const badARecord = buildRecord(hostname, 1, Buffer.from([9, 9]));
  • Files reviewed: 3/3 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Ninth Copilot review on PR #18 (2 suppressed findings, no new threads,
same root cause at two test cases).

Both cross-message mDNS tests sent their two UDP packets synchronously
back-to-back, relying on delivery order UDP doesn't actually guarantee -
a CI-flakiness risk on runners/kernels where that happens to matter.
Both now send the second packet from the first send()'s own completion
callback instead, so the enqueue order is deterministic rather than
assumed.
@Shinrai

Shinrai commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Re: the suppressed findings on review #5097589560 — both addressed in ced11df:

tests/discover.test.vitest.mjs's two cross-message mDNS tests ("resolves host when the A record arrives in an earlier message than its SRV" and "a malformed A record never overwrites a previously cached valid address") sent their two UDP packets synchronously back-to-back, relying on delivery order UDP doesn't guarantee. Both now send the second packet from the first send()'s own completion callback instead, making the enqueue order deterministic.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

A new test helper can hang the test suite on bind/listen errors because it doesn’t reject on server error events.

Review details

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

tests/discover.test.vitest.mjs:54

  • listenOn() never rejects or resolves if net.Server emits an "error" event during listen (e.g. EADDRNOTAVAIL/EACCES), which can hang the entire test run until Vitest times out. Add an error handler that rejects and only push the server into openServers after a successful bind, so teardown doesn’t later try to close a never-started server.
  • Files reviewed: 3/3 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Tenth Copilot review on PR #18 (1 suppressed finding, no new threads).

listenOn() never rejected or resolved if net.Server emitted an "error"
event during listen() (e.g. EADDRNOTAVAIL/EACCES) - the promise would
hang until Vitest's own timeout. It also pushed the server into
openServers before confirming a successful bind, so teardown could try
to close a server that never actually started.

Now rejects on the server's "error" event, and only registers the
server for teardown after listen() succeeds.
@Shinrai

Shinrai commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Re: the suppressed finding on review #5097698936 at tests/discover.test.vitest.mjs:54 (listenOn() not rejecting on listen error) — addressed in 32c2b3f: the helper now attaches an "error" handler that rejects the promise, and only pushes the server into openServers after listen() actually succeeds (previously it registered the server for teardown before confirming the bind). Without this, an EADDRNOTAVAIL/EACCES during listen() would leave the promise permanently pending, hanging the whole suite until Vitest's own timeout.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The DNS record parser can read past rdata bounds for PTR/SRV records (rdlength not enforced), which can misparse malformed packets and should be fixed before approval.

Review details

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

src/api/discover.mjs:321

  • readDnsRecord() decodes PTR/SRV rdata without enforcing rdlength bounds, so a truncated/malformed record can cause decodeDnsName() and the UInt16 reads to consume bytes past rdataEnd (potentially into the next record header) and fabricate incorrect names/ports rather than treating the record as invalid. Add rdlength checks and ensure decoded name parsing stays within rdataEnd before using the values.
  • Files reviewed: 3/3 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Eleventh Copilot review on PR #18 (1 suppressed finding, no new threads).

readDnsRecord() decoded PTR/SRV rdata without checking that the decoded
name stayed within rdataEnd. decodeDnsName() has no notion of rdlength,
so a truncated/malformed record could make it walk straight into the
next record's bytes on the wire and fabricate an incorrect name (or, for
SRV, priority/weight/port off a too-short rdata) instead of the parser
treating the record as invalid.

PTR now nulls its data when the decoded name's end exceeds rdataEnd;
SRV nulls its data outright when rdlength < 6 (too small to hold
priority/weight/port), and also when its target name overruns. Both
follow the same "null data, caller skips it" pattern already used for
malformed A records. ingestDnsRecords() now guards both consumption
sites against a null record.data.
@Shinrai

Shinrai commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Re: the suppressed finding on review #5097779525 at src/api/discover.mjs:321 (readDnsRecord() not enforcing rdlength bounds on PTR/SRV) — addressed in c4a0eb5: decodeDnsName() has no notion of rdlength, so a truncated/malformed PTR or SRV record could make it walk straight into the next record's bytes on the wire and fabricate an incorrect name (or, for SRV, priority/weight/port off a too-short rdata) instead of the parser treating the record as invalid.

PTR now nulls its data when the decoded name's end exceeds rdataEnd; SRV nulls its data outright when rdlength < 6 (too small to hold priority/weight/port), and also when its target name overruns — both follow the same "null data, caller skips it" pattern already used for malformed A records. ingestDnsRecords() now guards both consumption sites against a null record.data. Added two regression tests: a malformed PTR proving no bogus entry is fabricated and the legitimate record immediately after it still resolves correctly, and a malformed SRV proving the entry it would have populated is filtered from the results.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

It introduces substantial new networking behavior and a custom mDNS parser/correlator that warrants a final human review despite strong test coverage.

Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@Shinrai
Shinrai merged commit 0c33259 into next Sep 3, 2026
24 checks passed
@cldmv-bot
cldmv-bot Bot deleted the feat/device-discovery branch September 3, 2026 12:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: core Touches core library / runtime source code area: tests Touches test files, fixtures, or test infrastructure

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants